ultimecia

A ps1 emulator in c
Log | Files | Refs

psx.txt (1891446B)


      1 Contents
      2 --------
      3 
      4 Nocash PSXSPX Playstation Specifications
      5 --> Memory Map
      6 --> I/O Map
      7 --> Graphics Processing Unit (GPU)
      8 --> Geometry Transformation Engine (GTE)
      9 --> Macroblock Decoder (MDEC)
     10 --> Sound Processing Unit (SPU)
     11 --> Interrupts
     12 --> DMA Channels
     13 --> Timers
     14 --> CDROM Drive
     15 --> CDROM File Formats
     16 --> Controllers and Memory Cards
     17 --> Pocketstation
     18 --> Serial Port (SIO)
     19 --> Expansion Port (PIO)
     20 --> Memory Control
     21 --> Unpredictable Things
     22 --> CPU Specifications
     23 --> Kernel (BIOS)
     24 --> Arcade Cabinets
     25 --> Cheat Devices
     26 --> PSX Dev-Board Chipsets
     27 --> Hardware Numbers
     28 --> Pinouts
     29 --> About & Credits
     30 
     31 Latest Research
     32 --> CDROM File Formats
     33 
     34 Nocash PSX Emulator/Debugger
     35 --> No$psx Emulation Controls
     36 --> No$psx Emulation Files
     37 --> No$psx Emulation Notes
     38 --> No$psx Debugger - Hotkeys in Debug Mode
     39 --> No$psx Debugger - Breakpoints
     40 --> No$psx Debugger - General Debug Features
     41 
     42 
     43 Memory Map
     44 ----------
     45 
     46 Memory Map
     47   KUSEG     KSEG0     KSEG1
     48   00000000h 80000000h A0000000h  2048K  Main RAM (first 64K reserved for BIOS)
     49   1F000000h 9F000000h BF000000h  8192K  Expansion Region 1 (ROM/RAM)
     50   1F800000h 9F800000h    --      1K     Scratchpad (D-Cache used as Fast RAM)
     51   1F801000h 9F801000h BF801000h  8K     I/O Ports
     52   1F802000h 9F802000h BF802000h  8K     Expansion Region 2 (I/O Ports)
     53   1FA00000h 9FA00000h BFA00000h  2048K  Expansion Region 3 (whatever purpose)
     54   1FC00000h 9FC00000h BFC00000h  512K   BIOS ROM (Kernel) (4096K max)
     55         FFFE0000h (KSEG2)        0.5K   I/O Ports (Cache Control)
     56 Additionally, there are a number of memory mirrors.
     57 
     58 Additional Memory (not mapped to the CPU bus)
     59   1024K   VRAM (Framebuffers, Textures, Palettes) (with 2KB Texture Cache)
     60   512K    Sound RAM (Capture Buffers, ADPCM Data, Reverb Workspace)
     61   0.5K    CDROM controller RAM (see CDROM Test commands)
     62   16.5K   CDROM controller ROM (Firmware and Bootstrap for MC68HC05 cpu)
     63   32K     CDROM Buffer (IC303) (32Kx8) (BUG: only two sectors accessible?)
     64   128K    External Memory Card(s) (EEPROMs)
     65 
     66 KUSEG,KSEG0,KSEG1,KSEG2 Memory Regions
     67   Address   Name   Size   Privilege    Code-Cache  Data-Cache
     68   00000000h KUSEG  2048M  Kernel/User  Yes         (Scratchpad)
     69   80000000h KSEG0  512M   Kernel       Yes         (Scratchpad)
     70   A0000000h KSEG1  512M   Kernel       No          No
     71   C0000000h KSEG2  1024M  Kernel       (No code)   No
     72 Kernel Memory: KSEG1 is the normal physical memory (uncached), KSEG0 is a
     73 mirror thereof (but with cache enabled). KSEG2 is usually intended to contain
     74 virtual kernel memory, in the PSX it's containing Cache Control I/O Ports.
     75 User Memory: KUSEG is intended to contain 2GB virtual memory (on extended MIPS
     76 processors), the PSX doesn't support virtual memory, and KUSEG simply contains
     77 a mirror of KSEG0/KSEG1 (in the first 512MB) (trying to access memory in the
     78 remaining 1.5GB causes an exception).
     79 
     80 Code Cache
     81 Works in the cached regions (KUSEG and KSEG0).
     82 There are reportedly some restrictions... not sure there... eventually it is
     83 using the LSBs of the address as cache-line number... so, for example, it
     84 couldn't simultaneously memorize opcodes at BOTH address 80001234h, AND at
     85 address 800F1234h (?)
     86 
     87 Data Cache aka Scratchpad
     88 The MIPS CPU usually have a Data Cache, but, in the PSX, Sony has misused it as
     89 "Scratchpad", that is, the "Data Cache" is mapped to a fixed memory location at
     90 1F800000h..1F8003FFh (ie. it's used as Fast RAM, rather than as cache).
     91 There <might> be a way to disable that behaviour (via Port FFFE0130h or so),
     92 but, the Kernel is accessing I/O ports via KUSEG, so activating Data Cache
     93 would cause the Kernel to access cached I/O ports.
     94 Not tested yet, but most probably the Scratchpad can be used only for Data (ie.
     95 NOT for program Code?).
     96 
     97 Memory Mirrors
     98 As described above, the 512Mbyte KUSEG, KSEG0, and KSEG1 regions are mirrors of
     99 each other. Additional mirrors within these 512MB regions are:
    100   2MB RAM can be mirrored to the first 8MB (strangely, enabled by default)
    101   512K BIOS ROM can be mirrored to the last 4MB (disabled by default)
    102   Expansion hardware (if any) may be mirrored within expansion region
    103   The seven DMA Control Registers at 1F8010x8h are mirrored to 1F8010xCh
    104 The size of the RAM, BIOS, Expansion regions can be configured by software, for
    105 Expansion Region it's also possible to change base address, see:
    106 --> Memory Control
    107 The Scratchpad is mirrored only in KUSEG and KSEG0, but not in KSEG1.
    108 
    109 Memory Exceptions
    110   Memory Error ------> Misalignments
    111                (and probably also KSEG access in User mode)
    112   Bus Error    ------> Unused Memory Regions (including Gaps in I/O Region)
    113                (unless RAM/BIOS/Expansion mirrors are mapped to "unused" area)
    114 
    115 More Memory Info
    116 For Info on Exception vectors, Unused/Garbage memory locations, I/O Ports,
    117 Expansion ROM Headers, and Memory Waitstate Control, etc. see:
    118 --> I/O Map
    119 --> Memory Control
    120 --> EXP1 Expansion ROM Header
    121 --> BIOS Memory Map
    122 --> BIOS Memory Allocation
    123 --> COP0 - Exception Handling
    124 --> Unpredictable Things
    125 
    126 I/O Map
    127 -------
    128 
    129 Expansion Region 1
    130   1F000000h 80000h Expansion Region (default 512 Kbytes, max 8 MBytes)
    131   1F000000h 100h   Expansion ROM Header (IDs and Entrypoints)
    132 Scratchpad
    133   1F800000h 400h Scratchpad (1K Fast RAM) (Data Cache mapped to fixed address)
    134 Memory Control 1
    135   1F801000h 4    Expansion 1 Base Address (usually 1F000000h)
    136   1F801004h 4    Expansion 2 Base Address (usually 1F802000h)
    137   1F801008h 4    Expansion 1 Delay/Size (usually 0013243Fh; 512Kbytes 8bit-bus)
    138   1F80100Ch 4    Expansion 3 Delay/Size (usually 00003022h; 1 byte)
    139   1F801010h 4    BIOS ROM    Delay/Size (usually 0013243Fh; 512Kbytes 8bit-bus)
    140   1F801014h 4    SPU_DELAY   Delay/Size (usually 200931E1h)
    141   1F801018h 4    CDROM_DELAY Delay/Size (usually 00020843h or 00020943h)
    142   1F80101Ch 4    Expansion 2 Delay/Size (usually 00070777h; 128-bytes 8bit-bus)
    143   1F801020h 4    COM_DELAY / COMMON_DELAY (00031125h or 0000132Ch or 00001325h)
    144 Peripheral I/O Ports
    145   1F801040h 1/4  JOY_DATA Joypad/Memory Card Data (R/W)
    146   1F801044h 4    JOY_STAT Joypad/Memory Card Status (R)
    147   1F801048h 2    JOY_MODE Joypad/Memory Card Mode (R/W)
    148   1F80104Ah 2    JOY_CTRL Joypad/Memory Card Control (R/W)
    149   1F80104Eh 2    JOY_BAUD Joypad/Memory Card Baudrate (R/W)
    150   1F801050h 1/4  SIO_DATA Serial Port Data (R/W)
    151   1F801054h 4    SIO_STAT Serial Port Status (R)
    152   1F801058h 2    SIO_MODE Serial Port Mode (R/W)
    153   1F80105Ah 2    SIO_CTRL Serial Port Control (R/W)
    154   1F80105Ch 2    SIO_MISC Serial Port Internal Register (R/W)
    155   1F80105Eh 2    SIO_BAUD Serial Port Baudrate (R/W)
    156 Memory Control 2
    157   1F801060h 4/2  RAM_SIZE (usually 00000B88h; 2MB RAM mirrored in first 8MB)
    158 Interrupt Control
    159   1F801070h 2    I_STAT - Interrupt status register
    160   1F801074h 2    I_MASK - Interrupt mask register
    161 DMA Registers
    162   1F80108xh      DMA0 channel 0 - MDECin
    163   1F80109xh      DMA1 channel 1 - MDECout
    164   1F8010Axh      DMA2 channel 2 - GPU (lists + image data)
    165   1F8010Bxh      DMA3 channel 3 - CDROM
    166   1F8010Cxh      DMA4 channel 4 - SPU
    167   1F8010Dxh      DMA5 channel 5 - PIO (Expansion Port)
    168   1F8010Exh      DMA6 channel 6 - OTC (reverse clear OT) (GPU related)
    169   1F8010F0h      DPCR - DMA Control register
    170   1F8010F4h      DICR - DMA Interrupt register
    171   1F8010F8h      unknown
    172   1F8010FCh      unknown
    173 Timers (aka Root counters)
    174   1F801100h 2    Timer 0 Current Counter Value (R/W)  ;\
    175   1F801104h 2    Timer 0 Counter Mode          (R/W)  ; Dotclock
    176   1F801108h 2    Timer 0 Counter Target Value  (R/W)  ;/
    177   1F801110h 2    Timer 1 Current Counter Value (R/W)  ;\
    178   1F801114h 2    Timer 1 Counter Mode          (R/W)  ; Horizontal Retrace
    179   1F801118h 2    Timer 1 Counter Target Value  (R/W)  ;/
    180   1F801120h 2    Timer 2 Current Counter Value (R/W)  ;\
    181   1F801124h 2    Timer 2 Counter Mode          (R/W)  ; 1/8 system clock
    182   1F801128h 2    Timer 2 Counter Target Value  (R/W)  ;/
    183 CDROM Registers (Address.Read/Write.Index)
    184   1F801800h.x.x   1   CD Index/Status Register (Bit0-1 R/W, Bit2-7 Read Only)
    185   1F801801h.R.x   1   CD Response Fifo (R) (usually with Index1)
    186   1F801802h.R.x   1/2 CD Data Fifo - 8bit/16bit (R) (usually with Index0..1)
    187   1F801803h.R.0   1   CD Interrupt Enable Register (R)
    188   1F801803h.R.1   1   CD Interrupt Flag Register (R/W)
    189   1F801803h.R.2   1   CD Interrupt Enable Register (R) (Mirror)
    190   1F801803h.R.3   1   CD Interrupt Flag Register (R/W) (Mirror)
    191   1F801801h.W.0   1   CD Command Register (W)
    192   1F801802h.W.0   1   CD Parameter Fifo (W)
    193   1F801803h.W.0   1   CD Request Register (W)
    194   1F801801h.W.1   1   Unknown/unused
    195   1F801802h.W.1   1   CD Interrupt Enable Register (W)
    196   1F801803h.W.1   1   CD Interrupt Flag Register (R/W)
    197   1F801801h.W.2   1   Unknown/unused
    198   1F801802h.W.2   1   CD Audio Volume for Left-CD-Out to Left-SPU-Input (W)
    199   1F801803h.W.2   1   CD Audio Volume for Left-CD-Out to Right-SPU-Input (W)
    200   1F801801h.W.3   1   CD Audio Volume for Right-CD-Out to Right-SPU-Input (W)
    201   1F801802h.W.3   1   CD Audio Volume for Right-CD-Out to Left-SPU-Input (W)
    202   1F801803h.W.3   1   CD Audio Volume Apply Changes (by writing bit5=1)
    203 GPU Registers
    204   1F801810h.Write 4   GP0 Send GP0 Commands/Packets (Rendering and VRAM Access)
    205   1F801814h.Write 4   GP1 Send GP1 Commands (Display Control)
    206   1F801810h.Read  4   GPUREAD Read responses to GP0(C0h) and GP1(10h) commands
    207   1F801814h.Read  4   GPUSTAT Read GPU Status Register
    208 MDEC Registers
    209   1F801820h.Write 4   MDEC Command/Parameter Register (W)
    210   1F801820h.Read  4   MDEC Data/Response Register (R)
    211   1F801824h.Write 4   MDEC Control/Reset Register (W)
    212   1F801824h.Read  4   MDEC Status Register (R)
    213 SPU Voice 0..23 Registers
    214   1F801C00h+N*10h 4   Voice 0..23 Volume Left/Right
    215   1F801C04h+N*10h 2   Voice 0..23 ADPCM Sample Rate
    216   1F801C06h+N*10h 2   Voice 0..23 ADPCM Start Address
    217   1F801C08h+N*10h 4   Voice 0..23 ADSR Attack/Decay/Sustain/Release
    218   1F801C0Ch+N*10h 2   Voice 0..23 ADSR Current Volume
    219   1F801C0Eh+N*10h 2   Voice 0..23 ADPCM Repeat Address
    220 SPU Control Registers
    221   1F801D80h 4  Main Volume Left/Right
    222   1F801D84h 4  Reverb Output Volume Left/Right
    223   1F801D88h 4  Voice 0..23 Key ON (Start Attack/Decay/Sustain) (W)
    224   1F801D8Ch 4  Voice 0..23 Key OFF (Start Release) (W)
    225   1F801D90h 4  Voice 0..23 Channel FM (pitch lfo) mode (R/W)
    226   1F801D94h 4  Voice 0..23 Channel Noise mode (R/W)
    227   1F801D98h 4  Voice 0..23 Channel Reverb mode (R/W)
    228   1F801D9Ch 4  Voice 0..23 Channel ON/OFF (status) (R)
    229   1F801DA0h 2  Unknown? (R) or (W)
    230   1F801DA2h 2  Sound RAM Reverb Work Area Start Address
    231   1F801DA4h 2  Sound RAM IRQ Address
    232   1F801DA6h 2  Sound RAM Data Transfer Address
    233   1F801DA8h 2  Sound RAM Data Transfer Fifo
    234   1F801DAAh 2  SPU Control Register (SPUCNT)
    235   1F801DACh 2  Sound RAM Data Transfer Control
    236   1F801DAEh 2  SPU Status Register (SPUSTAT) (R)
    237   1F801DB0h 4  CD Volume Left/Right
    238   1F801DB4h 4  Extern Volume Left/Right
    239   1F801DB8h 4  Current Main Volume Left/Right
    240   1F801DBCh 4  Unknown? (R/W)
    241 SPU Reverb Configuration Area
    242   1F801DC0h 2  dAPF1  Reverb APF Offset 1
    243   1F801DC2h 2  dAPF2  Reverb APF Offset 2
    244   1F801DC4h 2  vIIR   Reverb Reflection Volume 1
    245   1F801DC6h 2  vCOMB1 Reverb Comb Volume 1
    246   1F801DC8h 2  vCOMB2 Reverb Comb Volume 2
    247   1F801DCAh 2  vCOMB3 Reverb Comb Volume 3
    248   1F801DCCh 2  vCOMB4 Reverb Comb Volume 4
    249   1F801DCEh 2  vWALL  Reverb Reflection Volume 2
    250   1F801DD0h 2  vAPF1  Reverb APF Volume 1
    251   1F801DD2h 2  vAPF2  Reverb APF Volume 2
    252   1F801DD4h 4  mSAME  Reverb Same Side Reflection Address 1 Left/Right
    253   1F801DD8h 4  mCOMB1 Reverb Comb Address 1 Left/Right
    254   1F801DDCh 4  mCOMB2 Reverb Comb Address 2 Left/Right
    255   1F801DE0h 4  dSAME  Reverb Same Side Reflection Address 2 Left/Right
    256   1F801DE4h 4  mDIFF  Reverb Different Side Reflection Address 1 Left/Right
    257   1F801DE8h 4  mCOMB3 Reverb Comb Address 3 Left/Right
    258   1F801DECh 4  mCOMB4 Reverb Comb Address 4 Left/Right
    259   1F801DF0h 4  dDIFF  Reverb Different Side Reflection Address 2 Left/Right
    260   1F801DF4h 4  mAPF1  Reverb APF Address 1 Left/Right
    261   1F801DF8h 4  mAPF2  Reverb APF Address 2 Left/Right
    262   1F801DFCh 4  vIN    Reverb Input Volume Left/Right
    263 SPU Internal Registers
    264   1F801E00h+N*04h  4 Voice 0..23 Current Volume Left/Right
    265   1F801E60h      20h Unknown? (R/W)
    266   1F801E80h     180h Unknown? (Read: FFh-filled) (Unused or Write only?)
    267 Expansion Region 2 (default 128 bytes, max 8 KBytes)
    268   1F802000h      80h Expansion Region (8bit data bus, crashes on 16bit access?)
    269 Expansion Region 2 - Dual Serial Port (for TTY Debug Terminal)
    270   1F802020h/1st    DUART Mode Register 1.A (R/W)
    271   1F802020h/2nd    DUART Mode Register 2.A (R/W)
    272   1F802021h/Read   DUART Status Register A (R)
    273   1F802021h/Write  DUART Clock Select Register A (W)
    274   1F802022h/Read   DUART Toggle Baud Rate Generator Test Mode (Read=Strobe)
    275   1F802022h/Write  DUART Command Register A (W)
    276   1F802023h/Read   DUART Rx Holding Register A (FIFO) (R)
    277   1F802023h/Write  DUART Tx Holding Register A (W)
    278   1F802024h/Read   DUART Input Port Change Register (R)
    279   1F802024h/Write  DUART Aux. Control Register (W)
    280   1F802025h/Read   DUART Interrupt Status Register (R)
    281   1F802025h/Write  DUART Interrupt Mask Register (W)
    282   1F802026h/Read   DUART Counter/Timer Current Value, Upper/Bit15-8 (R)
    283   1F802026h/Write  DUART Counter/Timer Reload Value,  Upper/Bit15-8 (W)
    284   1F802027h/Read   DUART Counter/Timer Current Value, Lower/Bit7-0 (R)
    285   1F802027h/Write  DUART Counter/Timer Reload Value,  Lower/Bit7-0 (W)
    286   1F802028h/1st    DUART Mode Register 1.B (R/W)
    287   1F802028h/2nd    DUART Mode Register 2.B (R/W)
    288   1F802029h/Read   DUART Status Register B (R)
    289   1F802029h/Write  DUART Clock Select Register B (W)
    290   1F80202Ah/Read   DUART Toggle 1X/16X Test Mode (Read=Strobe)
    291   1F80202Ah/Write  DUART Command Register B (W)
    292   1F80202Bh/Read   DUART Rx Holding Register B (FIFO) (R)
    293   1F80202Bh/Write  DUART Tx Holding Register B (W)
    294   1F80202Ch/None   DUART Reserved Register (neither R nor W)
    295   1F80202Dh/Read   DUART Input Port (R)
    296   1F80202Dh/Write  DUART Output Port Configuration Register (W)
    297   1F80202Eh/Read   DUART Start Counter Command (Read=Strobe)
    298   1F80202Eh/Write  DUART Set Output Port Bits Command (Set means Out=LOW)
    299   1F80202Fh/Read   DUART Stop Counter Command (Read=Strobe)
    300   1F80202Fh/Write  DUART Reset Output Port Bits Command (Reset means Out=HIGH)
    301 Expansion Region 2 - Int/Dip/Post
    302   1F802000h 1 DTL-H2000: ATCONS STAT (R)
    303   1F802002h 1 DTL-H2000: ATCONS DATA (R and W)
    304   1F802004h 2 DTL-H2000: Whatever 16bit data ?
    305   1F802030h 1/4 DTL-H2000: Secondary IRQ10 Flags
    306   1F802032h 1 DTL-H2000: Whatever IRQ Control ?
    307   1F802040h 1 DTL-H2000: Bootmode "Dip switches" (R)
    308   1F802041h 1 PSX: POST (external 7 segment display, indicate BIOS boot status)
    309   1F802042h 1 DTL-H2000: POST/LED (similar to POST) (other addr, 2-digit wide) 
    310  1F802070h 1 PS2: POST2 (similar to POST, but PS2 BIOS uses this address)
    311 Expansion Region 2 - Nocash Emulation Expansion
    312   1F802060h Emu-Expansion ID1 "E" (R)
    313   1F802061h Emu-Expansion ID2 "X" (R)
    314   1F802062h Emu-Expansion ID3 "P" (R)
    315   1F802063h Emu-Expansion Version (01h) (R)
    316   1F802064h Emu-Expansion Enable1 "O" (R/W)
    317   1F802065h Emu-Expansion Enable2 "N" (R/W)
    318   1F802066h Emu-Expansion Halt (R)
    319   1F802067h Emu-Expansion Turbo Mode Flags (R/W)
    320 Expansion Region 3 (default 1 byte, max 2 MBytes)
    321   1FA00000h - Not used by BIOS or any PSX games
    322   1FA00000h - POST3 (similar to POST, but PS2 BIOS uses this address)
    323 BIOS Region (default 512 Kbytes, max 4 MBytes)
    324   1FC00000h 80000h   BIOS ROM (512Kbytes) (Reset Entrypoint at BFC00000h)
    325 Memory Control 3 (Cache Control)
    326   FFFE0130h 4        Cache Control
    327 
    328 Coprocessor Registers
    329   COP0 System Control Coprocessor           - 32 registers (not all used)
    330   COP1 N/A
    331   COP2 Geometry Transformation Engine (GTE) - 64 registers (most are used)
    332   COP3 N/A
    333 
    334 Graphics Processing Unit (GPU)
    335 ------------------------------
    336 
    337 The GPU can render Polygons, Lines, or Rectangles to the Drawing Buffer, and
    338 sends the Display Buffer to the Television Set. Polygons are useful for 3D
    339 graphics (or rotated/scaled 2D graphics), Rectangles are useful for 2D graphics
    340 and Text output.
    341 
    342 --> GPU I/O Ports, DMA Channels, Commands, VRAM
    343 --> GPU Render Polygon Commands
    344 --> GPU Render Line Commands
    345 --> GPU Render Rectangle Commands
    346 --> GPU Rendering Attributes
    347 --> GPU Memory Transfer Commands
    348 --> GPU Other Commands
    349 --> GPU Display Control Commands (GP1)
    350 --> GPU Status Register
    351 --> GPU Versions
    352 --> GPU Depth Ordering
    353 --> GPU Video Memory (VRAM)
    354 --> GPU Texture Caching
    355 --> GPU Timings
    356 --> GPU (MISC)
    357 
    358 GPU I/O Ports, DMA Channels, Commands, VRAM
    359 -------------------------------------------
    360 
    361 GPU I/O Ports (1F801810h and 1F801814h in Read/Write Directions)
    362   Port            Name    Expl.
    363   1F801810h-Write GP0     Send GP0 Commands/Packets (Rendering and VRAM Access)
    364   1F801814h-Write GP1     Send GP1 Commands (Display Control) (and DMA Control)
    365   1F801810h-Read  GPUREAD Receive responses to GP0(C0h) and GP1(10h) commands
    366   1F801814h-Read  GPUSTAT Receive GPU Status Register
    367 It (=GP0 only?) has a 64-byte (16-word) command FIFO buffer.
    368 Optionally, Port 1F801810h (Read/Write) can be also accessed via DMA2.
    369 
    370 GPU Timers / Synchronization
    371 Most of the Timers are bound to GPU timings, see
    372 --> Timers
    373 --> Interrupts
    374 
    375 GPU-related DMA Channels (DMA2 and DMA6)
    376   Channel                  Recommended for
    377   DMA2 in Linked Mode    - Sending rendering commands  ;GP0(20h..7Fh,E1h..E6h)
    378   DMA2 in Continous Mode - VRAM transfers to/from GPU  ;GP0(A0h,C0h)
    379   DMA6                   - Initializing the Link List  ;Main RAM
    380 Note: Before using DMA2, set up the DMA Direction in GP1(04h).
    381 DMA2 is equivalent to accessing Port 1F801810h (GP0/GPUREAD) by software.
    382 DMA6 just initializes data in Main RAM (not physically connected to the GPU).
    383 
    384 GPU Command Summary
    385 Commands/Packets consist of a 8bit command number (MSBs) and a 24bit parameter
    386 (LSBs), which are written as 32bit value to GP0 or GP1.
    387   GP0(00h)                 - Nop?
    388   GP0(01h,02h,80h,A0h,C0h) - Direct VRAM Access
    389   GP0(03h)                 - Unknown (does take up FIFO space!!!)
    390   GP0(1Fh)                 - Interrupt Request (IRQ1)
    391   GP0(20h..3Fh)            - Render Polygons
    392   GP0(40h..5Fh)            - Render Lines
    393   GP0(60h..7Fh)            - Render Rectangles
    394   GP0(E1h..E6h)            - Rendering Attributes
    395   GP1(00h..09h,10h,20h)    - Display Control (these via GP1 register)
    396 Some GP0 commands require additional parameters, which are written (following
    397 to the command) as further 32bit values to GP0. The execution of the command
    398 starts when all parameters have been received (or, in case of Polygon/Line
    399 commands, when the first 3/2 vertices have been received).
    400 
    401 VRAM Overview / VRAM Addressing
    402 VRAM is 1MByte (not mapped to the CPU bus) (it can be read/written only via I/O
    403 or DMA). The memory is used for:
    404   Framebuffer(s)      ;Usually 2 buffers (Drawing Area, and Display Area)
    405   Texture Page(s)     ;Required when using Textures
    406   Texture Palette(s)  ;Required when using 4bit/8bit Textures
    407 The 1MByte VRAM is organized as 512 lines of 2048 bytes. It is accessed via
    408 coordinates, ranging from (0,0)=Upper-Left to (N,511)=Lower-Right.
    409   Unit  = 4bit  8bit  16bit  24bit   Halfwords   | Unit   = Lines
    410   Width = 4096  2048  1024   682.66  1024        | Height = 512
    411 The horizontal coordinates are addressing memory in
    412 4bit/8bit/16bit/24bit/halfword units (depending on what data formats you are
    413 using) (or a mixup thereof, eg. a halfword-base address, plus a 4bit texture
    414 coordinate).
    415 
    416 GPU Render Polygon Commands
    417 ---------------------------
    418 
    419 GP0(20h) - Monochrome three-point polygon, opaque
    420 GP0(22h) - Monochrome three-point polygon, semi-transparent
    421 GP0(28h) - Monochrome four-point polygon, opaque
    422 GP0(2Ah) - Monochrome four-point polygon, semi-transparent
    423   1st  Color+Command     (CcBbGgRrh)
    424   2nd  Vertex1           (YyyyXxxxh)
    425   3rd  Vertex2           (YyyyXxxxh)
    426   4th  Vertex3           (YyyyXxxxh)
    427  (5th) Vertex4           (YyyyXxxxh) (if any)
    428 
    429 GP0(24h) - Textured three-point polygon, opaque, texture-blending
    430 GP0(25h) - Textured three-point polygon, opaque, raw-texture
    431 GP0(26h) - Textured three-point polygon, semi-transparent, texture-blending
    432 GP0(27h) - Textured three-point polygon, semi-transparent, raw-texture
    433 GP0(2Ch) - Textured four-point polygon, opaque, texture-blending
    434 GP0(2Dh) - Textured four-point polygon, opaque, raw-texture
    435 GP0(2Eh) - Textured four-point polygon, semi-transparent, texture-blending
    436 GP0(2Fh) - Textured four-point polygon, semi-transparent, raw-texture
    437   1st  Color+Command     (CcBbGgRrh) (color is ignored for raw-textures)
    438   2nd  Vertex1           (YyyyXxxxh)
    439   3rd  Texcoord1+Palette (ClutYyXxh)
    440   4th  Vertex2           (YyyyXxxxh)
    441   5th  Texcoord2+Texpage (PageYyXxh)
    442   6th  Vertex3           (YyyyXxxxh)
    443   7th  Texcoord3         (0000YyXxh)
    444  (8th) Vertex4           (YyyyXxxxh) (if any)
    445  (9th) Texcoord4         (0000YyXxh) (if any)
    446 
    447 GP0(30h) - Shaded three-point polygon, opaque
    448 GP0(32h) - Shaded three-point polygon, semi-transparent
    449 GP0(38h) - Shaded four-point polygon, opaque
    450 GP0(3Ah) - Shaded four-point polygon, semi-transparent
    451   1st  Color1+Command    (CcBbGgRrh)
    452   2nd  Vertex1           (YyyyXxxxh)
    453   3rd  Color2            (00BbGgRrh)
    454   4th  Vertex2           (YyyyXxxxh)
    455   5th  Color3            (00BbGgRrh)
    456   6th  Vertex3           (YyyyXxxxh)
    457  (7th) Color4            (00BbGgRrh) (if any)
    458  (8th) Vertex4           (YyyyXxxxh) (if any)
    459 
    460 GP0(34h) - Shaded Textured three-point polygon, opaque, texture-blending
    461 GP0(36h) - Shaded Textured three-point polygon, semi-transparent, tex-blend
    462 GP0(3Ch) - Shaded Textured four-point polygon, opaque, texture-blending
    463 GP0(3Eh) - Shaded Textured four-point polygon, semi-transparent, tex-blend
    464   1st  Color1+Command    (CcBbGgRrh)
    465   2nd  Vertex1           (YyyyXxxxh)
    466   3rd  Texcoord1+Palette (ClutYyXxh)
    467   4th  Color2            (00BbGgRrh)
    468   5th  Vertex2           (YyyyXxxxh)
    469   6th  Texcoord2+Texpage (PageYyXxh)
    470   7th  Color3            (00BbGgRrh)
    471   8th  Vertex3           (YyyyXxxxh)
    472   9th  Texcoord3         (0000YyXxh)
    473  (10th) Color4           (00BbGgRrh) (if any)
    474  (11th) Vertex4          (YyyyXxxxh) (if any)
    475  (12th) Texcoord4        (0000YyXxh) (if any)
    476 
    477 GP0(35h,37h,3Dh,3Fh) - Undocumented/Nonsense (Raw Texture + UNUSED shading)
    478 These are undocumented inefficient nonsense commands: Parameters are same as
    479 for GP0(34h,36h,3Ch,3Eh), ie. with colors for all vertices, but without
    480 actually using that colors. Instead, the commands are rendering raw textures
    481 without blending.
    482 In other words, the commands have same function as GP0(25h,27h,2Dh,2Fh), but
    483 with additional/unused parameters (and possible additional/unused internal
    484 gouraud shading calculations).
    485 For whatever reason, Castlevania is actually using these nonsense commands,
    486 namely GP0(3Dh) and GP0(3Fh).
    487 
    488 GP0(21h,23h,29h,2Bh,31h,33h,39h,3Bh) - Undocumented/Nonsense
    489 These commands have texture-blending disabled, which is nonsense because they
    490 are using untextured polygons anyways, ie. they are probably same as
    491 GP0(20h,22h,28h,2Ah,30h,32h,38h,3Ah).
    492 
    493 Notes
    494 Polygons are displayed up to <excluding> their lower-right coordinates.
    495 Four-point polygons are internally processed as two Three-point polygons, the
    496 first consisting of Vertices 1,2,3, and the second of  Vertices 2,3,4.
    497 Within the Three-point polygons, the ordering of the vertices is don't care at
    498 the GPU side (a front-back check, based on clockwise or anti-clockwise
    499 ordering, can be implemented at the GTE side).
    500 Dither enable (in Texpage command) affects ONLY polygons that do use Gouraud
    501 Shading or Texture Blending.
    502 
    503 GPU Render Line Commands
    504 ------------------------
    505 
    506 GP0(40h) - Monochrome line, opaque
    507 GP0(42h) - Monochrome line, semi-transparent
    508 GP0(48h) - Monochrome Poly-line, opaque
    509 GP0(4Ah) - Monochrome Poly-line, semi-transparent
    510   1st   Color+Command     (CcBbGgRrh)
    511   2nd   Vertex1           (YyyyXxxxh)
    512   3rd   Vertex2           (YyyyXxxxh)
    513  (...)  VertexN           (YyyyXxxxh) (poly-line only)
    514  (Last) Termination Code  (55555555h) (poly-line only)
    515 
    516 GP0(50h) - Shaded line, opaque
    517 GP0(52h) - Shaded line, semi-transparent
    518 GP0(58h) - Shaded Poly-line, opaque
    519 GP0(5Ah) - Shaded Poly-line, semi-transparent
    520   1st   Color1+Command    (CcBbGgRrh)
    521   2nd   Vertex1           (YyyyXxxxh)
    522   3rd   Color2            (00BbGgRrh)
    523   4th   Vertex2           (YyyyXxxxh)
    524  (...)  ColorN            (00BbGgRrh) (poly-line only)
    525  (...)  VertexN           (YyyyXxxxh) (poly-line only)
    526  (Last) Termination Code  (55555555h) (poly-line only)
    527 
    528 Note
    529 Lines are displayed up to <including> their lower-right coordinates (ie. unlike
    530 as for polygons, the lower-right coordinate is not excluded).
    531 If dithering is enabled (via Texpage command), then both monochrome and shaded
    532 lines are drawn with dithering (this differs from monochrome polygons and
    533 monochrome rectangles).
    534 
    535 Termination Codes for Poly-Lines (aka Linestrips)
    536 The termination code should be usually 55555555h, however, Wild Arms 2 uses
    537 50005000h (unknown which exact bits/values are relevant there).
    538 
    539 Wire-Frame
    540 Poly-Lines can be used (among others) to create Wire-Frame polygons (by setting
    541 the last Vertex equal to Vertex 1).
    542 
    543 GPU Render Rectangle Commands
    544 -----------------------------
    545 
    546 Rectangles are drawn much faster than polygons. Unlike for polygons, gouroud
    547 shading is not possible, dithering isn't applied, the rectangle must forcefully
    548 have horizontal and vertical edges, textures cannot be rotated or scaled, and,
    549 of course, the GPU does render Rectangles at once (without splitting them into
    550 triangles).
    551 
    552 GP0(60h) - Monochrome Rectangle (variable size) (opaque)
    553 GP0(62h) - Monochrome Rectangle (variable size) (semi-transparent)
    554 GP0(68h) - Monochrome Rectangle (1x1) (Dot) (opaque)
    555 GP0(6Ah) - Monochrome Rectangle (1x1) (Dot) (semi-transparent)
    556 GP0(70h) - Monochrome Rectangle (8x8) (opaque)
    557 GP0(72h) - Monochrome Rectangle (8x8) (semi-transparent)
    558 GP0(78h) - Monochrome Rectangle (16x16) (opaque)
    559 GP0(7Ah) - Monochrome Rectangle (16x16) (semi-transparent)
    560   1st  Color+Command     (CcBbGgRrh)
    561   2nd  Vertex            (YyyyXxxxh)
    562  (3rd) Width+Height      (YsizXsizh) (variable size only) (max 1023x511)
    563 
    564 GP0(64h) - Textured Rectangle, variable size, opaque, texture-blending
    565 GP0(65h) - Textured Rectangle, variable size, opaque, raw-texture
    566 GP0(66h) - Textured Rectangle, variable size, semi-transp, texture-blending
    567 GP0(67h) - Textured Rectangle, variable size, semi-transp, raw-texture
    568 GP0(6Ch) - Textured Rectangle, 1x1 (nonsense), opaque, texture-blending
    569 GP0(6Dh) - Textured Rectangle, 1x1 (nonsense), opaque, raw-texture
    570 GP0(6Eh) - Textured Rectangle, 1x1 (nonsense), semi-transp, texture-blending
    571 GP0(6Fh) - Textured Rectangle, 1x1 (nonsense), semi-transp, raw-texture
    572 GP0(74h) - Textured Rectangle, 8x8, opaque, texture-blending
    573 GP0(75h) - Textured Rectangle, 8x8, opaque, raw-texture
    574 GP0(76h) - Textured Rectangle, 8x8, semi-transparent, texture-blending
    575 GP0(77h) - Textured Rectangle, 8x8, semi-transparent, raw-texture
    576 GP0(7Ch) - Textured Rectangle, 16x16, opaque, texture-blending
    577 GP0(7Dh) - Textured Rectangle, 16x16, opaque, raw-texture
    578 GP0(7Eh) - Textured Rectangle, 16x16, semi-transparent, texture-blending
    579 GP0(7Fh) - Textured Rectangle, 16x16, semi-transparent, raw-texture
    580   1st  Color+Command     (CcBbGgRrh) (color is ignored for raw-textures)
    581   2nd  Vertex            (YyyyXxxxh) (upper-left edge of the rectangle)
    582   3rd  Texcoord+Palette  (ClutYyXxh) (for 4bpp Textures Xxh must be even!)
    583  (4th) Width+Height      (YsizXsizh) (variable size only) (max 1023x511)
    584 Unlike for Textured-Polygons, the "Texpage" must be set up separately for
    585 Rectangles, via GP0(E1h). Width and Height can be up to 1023x511, however, the
    586 maximum size of the texture window is 256x256 (so the source data will be
    587 repeated when trying to use sizes larger than 256x256).
    588 
    589 Texture Origin and X/Y-Flip
    590 Vertex & Texcoord specify the upper-left edge of the rectangle. And, normally,
    591 screen coords and texture coords are both incremented during rendering the
    592 rectangle pixels.
    593 Optionally, X/Y-Flip bits can be set in Texpage.Bit12/13, these bits cause the
    594 texture coordinates to be decremented (instead of incremented). The X/Y-Flip
    595 bits do affect only Rectangles (not Polygons, nor VRAM Transfers).
    596 Caution: Reportedly, the X/Y-Flip feature isn't supported on old PSX consoles
    597 (unknown which ones exactly, maybe such with PU-7 mainboards, and unknown how
    598 to detect flipping support; except of course by reading VRAM).
    599 
    600 Note
    601 There are also two VRAM Transfer commands which work similar to GP0(60h) and
    602 GP0(65h). Eventually, that commands might be even faster... although not sure
    603 if they do use the Texture Cache?
    604 The difference is that VRAM Transfers do not clip to the Drawig Area boundary,
    605 do not support fully-transparent nor semi-transparent texture pixels, and do
    606 not convert color depths (eg. without 4bit texture to 16bit framebuffer
    607 conversion).
    608 
    609 GPU Rendering Attributes
    610 ------------------------
    611 
    612 Vertex (Parameter for Polygon, Line, Rectangle commands)
    613   0-10   X-coordinate (signed, -1024..+1023)
    614   11-15  Not used (usually sign-extension, but ignored by hardware)
    615   16-26  Y-coordinate (signed, -1024..+1023)
    616   26-31  Not used (usually sign-extension, but ignored by hardware)
    617 Size Restriction: The maximum distance between two vertices is 1023
    618 horizontally, and 511 vertically. Polygons and lines that are exceeding that
    619 dimensions are NOT rendered. For example, a line from Y1=-300 to Y2=+300 is NOT
    620 rendered, a line from Y1=-100 to Y2=+400 is rendered (as far as it is within
    621 the drawing area).
    622 If portions of the polygon/line/rectangle are located outside of the drawing
    623 area, then the hardware renders only the portion that is inside of the drawing
    624 area. Not sure if the hardware is skipping all clipped pixels at once (within a
    625 single clock cycle), or if it's (slowly) processing them pixel by pixel?
    626 
    627 Color Attribute (Parameter for all Rendering commands, except Raw Texture)
    628   0-7    Red   (0..FFh)
    629   8-15   Green (0..FFh)
    630   16-23  Blue  (0..FFh)
    631   24-31  Command (in first paramter) (don't care in further parameters)
    632 Caution: For untextured graphics, 8bit RGB values of FFh are brightest.
    633 However, for texture blending, 8bit values of 80h are brightest (values
    634 81h..FFh are "brighter than bright" allowing to make textures about twice as
    635 bright as than they were originially stored in memory; of course the results
    636 can't exceed the maximum brightness, ie. the 5bit values written to the
    637 framebuffer are saturated to max 1Fh).
    638 
    639 Texpage Attribute (Parameter for Textured-Polygons commands)
    640   0-8    Same as GP0(E1h).Bit0-8 (see there)
    641   9-10   Unused (does NOT change GP0(E1h).Bit9-10)
    642   11     Same as GP0(E1h).Bit11  (see there)
    643   12-13  Unused (does NOT change GP0(E1h).Bit12-13)
    644   14-15  Unused (should be 0)
    645 This attribute is used in all Textured-Polygons commands.
    646 
    647 Clut Attribute (Color Lookup Table, aka Palette)
    648 This attribute is used in all Textured Polygon/Rectangle commands. Of course,
    649 it's relevant only for 4bit/8bit textures (don't care for 15bit textures).
    650   0-5      X coordinate X/16  (ie. in 16-halfword steps)
    651   6-14     Y coordinate 0-511 (ie. in 1-line steps)
    652   15       Unknown/unused (should be 0)
    653 Specifies the location of the CLUT data within VRAM.
    654 
    655 GP0(E1h) - Draw Mode setting (aka "Texpage")
    656   0-3   Texture page X Base   (N*64) (ie. in 64-halfword steps)    ;GPUSTAT.0-3
    657   4     Texture page Y Base   (N*256) (ie. 0 or 256)               ;GPUSTAT.4
    658   5-6   Semi Transparency     (0=B/2+F/2, 1=B+F, 2=B-F, 3=B+F/4)   ;GPUSTAT.5-6
    659   7-8   Texture page colors   (0=4bit, 1=8bit, 2=15bit, 3=Reserved);GPUSTAT.7-8
    660   9     Dither 24bit to 15bit (0=Off/strip LSBs, 1=Dither Enabled) ;GPUSTAT.9
    661   10    Drawing to display area (0=Prohibited, 1=Allowed)          ;GPUSTAT.10
    662   11    Texture Disable (0=Normal, 1=Disable if GP1(09h).Bit0=1)   ;GPUSTAT.15
    663           (Above might be chipselect for (absent) second VRAM chip?)
    664   12    Textured Rectangle X-Flip   (BIOS does set this bit on power-up...?)
    665   13    Textured Rectangle Y-Flip   (BIOS does set it equal to GPUSTAT.13...?)
    666   14-23 Not used (should be 0)
    667   24-31 Command  (E1h)
    668 The GP0(E1h) command is required only for Lines, Rectangle, and
    669 Untextured-Polygons (for Textured-Polygons, the data is specified in form of
    670 the Texpage attribute; except that, Bit9-10 can be changed only via GP0(E1h),
    671 not via the Texpage attribute).
    672 Texture page colors setting 3 (reserved) is same as setting 2 (15bit).
    673 Note: GP0(00h) seems to be often inserted between Texpage and Rectangle
    674 commands, maybe it acts as a NOP, which may be required between that commands,
    675 for timing reasons...?
    676 
    677 GP0(E2h) - Texture Window setting
    678   0-4    Texture window Mask X   (in 8 pixel steps)
    679   5-9    Texture window Mask Y   (in 8 pixel steps)
    680   10-14  Texture window Offset X (in 8 pixel steps)
    681   15-19  Texture window Offset Y (in 8 pixel steps)
    682   20-23  Not used (zero)
    683   24-31  Command  (E2h)
    684 Mask specifies the bits that are to be manipulated, and Offset contains the new
    685 values for these bits, ie. texture X/Y coordinates are adjusted as so:
    686   Texcoord = (Texcoord AND (NOT (Mask*8))) OR ((Offset AND Mask)*8)
    687 The area within a texture window is repeated throughout the texture page. The
    688 data is not actually stored all over the texture page but the GPU reads the
    689 repeated patterns as if they were there.
    690 
    691 GP0(E3h) - Set Drawing Area top left (X1,Y1)
    692 GP0(E4h) - Set Drawing Area bottom right (X2,Y2)
    693   0-9    X-coordinate (0..1023)
    694   10-18  Y-coordinate (0..511)   ;\on Old 160pin GPU (max 1MB VRAM)
    695   19-23  Not used (zero)         ;/
    696   10-19  Y-coordinate (0..1023)  ;\on New 208pin GPU (max 2MB VRAM)
    697   20-23  Not used (zero)         ;/(retail consoles have only 1MB though)
    698   24-31  Command  (Exh)
    699 Sets the drawing area corners. The Render commands GP0(20h..7Fh) are
    700 automatically clipping any pixels that are outside of this region.
    701 
    702 GP0(E5h) - Set Drawing Offset (X,Y)
    703   0-10   X-offset (-1024..+1023) (usually within X1,X2 of Drawing Area)
    704   11-21  Y-offset (-1024..+1023) (usually within Y1,Y2 of Drawing Area)
    705   22-23  Not used (zero)
    706   24-31  Command  (E5h)
    707 If you have configured the GTE to produce vertices with coordinate "0,0" being
    708 located in the center of the drawing area, then the Drawing Offset must be
    709 "X1+(X2-X1)/2, Y1+(Y2-Y1)/2". Or, if coordinate "0,0" shall be the upper-left
    710 of the Drawing Area, then Drawing Offset should be "X1,Y1". Where X1,Y1,X2,Y2
    711 are the values defined with GP0(E3h-E4h).
    712 
    713 GP0(E6h) - Mask Bit Setting
    714   0     Set mask while drawing (0=TextureBit15, 1=ForceBit15=1)   ;GPUSTAT.11
    715   1     Check mask before draw (0=Draw Always, 1=Draw if Bit15=0) ;GPUSTAT.12
    716   2-23  Not used (zero)
    717   24-31 Command  (E6h)
    718 When bit0 is off, the upper bit of the data written to the framebuffer is equal
    719 to bit15 of the texture color (ie. it is set for colors that are marked as
    720 "semi-transparent") (for untextured polygons, bit15 is set to zero).
    721 When bit1 is on, any (old) pixels in the framebuffer with bit15=1 are
    722 write-protected, and cannot be overwritten by (new) rendering commands.
    723 The mask setting affects all rendering commands, as well as CPU-to-VRAM and
    724 VRAM-to-VRAM transfer commands (where it acts on the separate halfwords, ie. as
    725 for 15bit textures). However, Mask does NOT affect the Fill-VRAM command.
    726 
    727 Note
    728 GP0(E3h..E5h) do not take up space in the FIFO, so they are probably executed
    729 immediately (even if there're still other commands in the FIFO). Best use them
    730 only if you are sure that the FIFO is empty (otherwise the new Drawing Area
    731 settings might accidently affect older Rendering Commands in the FIFO).
    732 
    733 GPU Memory Transfer Commands
    734 ----------------------------
    735 
    736 GP0(01h) - Clear Cache
    737   1st  Command           (Cc000000h)
    738 "Seems to be the same as the GP1 command." Uh, which GP1 command?
    739 Before using GP(A0h) or GP(C0h) one should reportedly send:
    740 Clear Cache       (01000000h)
    741 "Reset command buffer (write to GP1 or GP0)" Uh? Bullshit.
    742 However, there <may> be some situations in which it is neccessary to flush the
    743 texture cache.
    744 
    745 GP0(02h) - Fill Rectangle in VRAM
    746   1st  Color+Command     (CcBbGgRrh)  ;24bit RGB value (see note)
    747   2nd  Top Left Corner   (YyyyXxxxh)  ;Xpos counted in halfwords, steps of 10h
    748   3rd  Width+Height      (YsizXsizh)  ;Xsiz counted in halfwords, steps of 10h
    749 Fills the area in the frame buffer with the value in RGB. Horizontally the
    750 filling is done in 16-pixel (32-bytes) units (see below masking/rounding).
    751 The "Color" parameter is a 24bit RGB value, however, the actual fill data is
    752 16bit: The hardware automatically converts the 24bit RGB value to 15bit RGB
    753 (with bit15=0).
    754 Fill is NOT affected by the Mask settings (acts as if Mask.Bit0,1 are both
    755 zero).
    756 
    757 GP0(80h) - Copy Rectangle (VRAM to VRAM)
    758   1st  Command           (Cc000000h)
    759   2nd  Source Coord      (YyyyXxxxh)  ;Xpos counted in halfwords
    760   3rd  Destination Coord (YyyyXxxxh)  ;Xpos counted in halfwords
    761   4th  Width+Height      (YsizXsizh)  ;Xsiz counted in halfwords
    762 Copys data within framebuffer. The transfer is affected by Mask setting.
    763 
    764 GP0(A0h) - Copy Rectangle (CPU to VRAM)
    765   1st  Command           (Cc000000h)
    766   2nd  Destination Coord (YyyyXxxxh)  ;Xpos counted in halfwords
    767   3rd  Width+Height      (YsizXsizh)  ;Xsiz counted in halfwords
    768   ...  Data              (...)      <--- usually transferred via DMA
    769 Transfers data from CPU to frame buffer. If the number of halfwords to be sent
    770 is odd, an extra halfword should be sent (packets consist of 32bit units). The
    771 transfer is affected by Mask setting.
    772 
    773 GP0(C0h) - Copy Rectangle (VRAM to CPU)
    774   1st  Command           (Cc000000h) ;\
    775   2nd  Source Coord      (YyyyXxxxh) ; write to GP0 port (as usually)
    776   3rd  Width+Height      (YsizXsizh) ;/
    777   ...  Data              (...)       ;<--- read from GPUREAD port (or via DMA)
    778 Transfers data from frame buffer to CPU. Wait for bit27 of the status register
    779 to be set before reading the image data. When the number of halfwords is odd,
    780 an extra halfword is read at the end (packets consist of 32bit units).
    781 
    782 Masking and Rounding for FILL Command parameters
    783   Xpos=(Xpos AND 3F0h)                       ;range 0..3F0h, in steps of 10h
    784   Ypos=(Ypos AND 1FFh)                       ;range 0..1FFh
    785   Xsiz=((Xsiz AND 3FFh)+0Fh) AND (NOT 0Fh)   ;range 0..400h, in steps of 10h
    786   Ysiz=((Ysiz AND 1FFh))                     ;range 0..1FFh
    787 Fill does NOT occur when Xsiz=0 or Ysiz=0 (unlike as for Copy commands).
    788 Xsiz=400h works only indirectly: Param=400h is handled as Xsiz=0, however,
    789 Param=3F1h..3FFh is rounded-up and handled as Xsiz=400h.
    790 
    791 Masking for COPY Commands parameters
    792   Xpos=(Xpos AND 3FFh)                       ;range 0..3FFh
    793   Ypos=(Ypos AND 1FFh)                       ;range 0..1FFh
    794   Xsiz=((Xsiz-1) AND 3FFh)+1                 ;range 1..400h
    795   Ysiz=((Ysiz-1) AND 1FFh)+1                 ;range 1..200h
    796 Parameters are just clipped to 10bit/9bit range, the only special case is that
    797 Size=0 is handled as Size=max.
    798 
    799 Notes
    800 The coordinates for the above VRAM transfer commands are absolute framebuffer
    801 addresses (not relative to Draw Offset, and not clipped to Draw Area).
    802 Non-DMA transfers seem to be working at any time, but GPU-DMA Transfers seem to
    803 be working ONLY during V-Blank (outside of V-Blank, portions of the data appear
    804 to be skipped, and the following words arrive at wrong addresses), unknown if
    805 it's possible to change that by whatever configuration settings...? That
    806 problem appears ONLY for continous DMA aka VRAM transfers (linked-list DMA aka
    807 Ordering Table works even outside V-Blank).
    808 
    809 Wrapping
    810 If the Source/Dest starting points plus the width/height value exceed the
    811 1024x512 pixel VRAM size, then the Copy/Fill operations wrap to the opposite
    812 memory edge (without any carry-out from X to Y, nor from Y to X).
    813 
    814 GPU Other Commands
    815 ------------------
    816 
    817 GP0(1Fh) - Interrupt Request (IRQ1)
    818   1st  Command           (Cc000000h)                    ;GPUSTAT.24
    819 Requests IRQ1. Can be acknowledged via GP1(02h). This feature is rarely used.
    820 Note: The command is used by Blaze'n'Blade, but the game doesn't have IRQ1
    821 enabled, and the written value (1F801810h) looks more like an I/O address,
    822 rather than like a command, so not sure if it's done intentionally, or if it is
    823 just a bug.
    824 
    825 GP0(03h) - Unknown?
    826 Unknown. Doesn't seem to be used by any games. Unlike the "NOP" commands,
    827 GP0(03h) does take up space in FIFO, so it is apparently not a NOP.
    828 
    829 GP0(00h) - NOP (?)
    830 This command doesn't take up space in the FIFO (eg. even if a VRAM-to-VRAM
    831 transfer is still busy, one can send dozens of GP0(00h) commands, without the
    832 command FIFO becoming full. So, either the command is ignored (or, if it has a
    833 function, it is executed immediately, even while the transfer is busy).
    834 ...
    835 GP0(00h) unknown, used with parameter = 08A16Ch... or rather 08FDBCh ... the
    836 written value seems to be a bios/ram memory address, anded with 00FFFFFFh...
    837 maybe a bios bug?
    838 GP0(00h) seems to be often inserted between Texpage and Rectangle commands,
    839 maybe it acts as a NOP, which may be required between that commands, for timing
    840 reasons...?
    841 
    842 GP0(04h..1Eh,E0h,E7h..EFh) - Mirrors of GP0(00h) - NOP (?)
    843 Like GP0(00h), these commands don't take up space in the FIFO. So, maybe, they
    844 are same as GP0(00h), however, the Drawing Area/Offset commands GP0(E3h..E5h)
    845 don't take up FIFO space either, so not taking up FIFO space doesn't
    846 neccessarily mean that the command has no function.
    847 
    848 GP0(81h..9Fh) - Mirror of GP0(80h) - Copy Rectangle (VRAM to VRAM)
    849 GP0(A1h..BFh) - Mirror of GP0(A0h) - Copy Rectangle (CPU to VRAM)
    850 GP0(C1h..DFh) - Mirror of GP0(C0h) - Copy Rectangle (VRAM to CPU)
    851 Mirrors.
    852 
    853 GPU Display Control Commands (GP1)
    854 ----------------------------------
    855 
    856 GP1 Display Control Commands are sent by writing the 8bit Command number
    857 (MSBs), and 24bit parameter (LSBs) to Port 1F801814h. Unlike GP0 commands, GP1
    858 commands are passed directly to the GPU (ie. they can be sent even when the
    859 FIFO is full).
    860 
    861 GP1(00h) - Reset GPU
    862   0-23  Not used (zero)
    863 Resets the GPU to the following values:
    864   GP1(01h)      ;clear fifo
    865   GP1(02h)      ;ack irq (0)
    866   GP1(03h)      ;display off (1)
    867   GP1(04h)      ;dma off (0)
    868   GP1(05h)      ;display address (0)
    869   GP1(06h)      ;display x1,x2 (x1=200h, x2=200h+256*10)
    870   GP1(07h)      ;display y1,y2 (y1=010h, y2=010h+240)
    871   GP1(08h)      ;display mode 320x200 NTSC (0)
    872   GP0(E1h..E6h) ;rendering attributes (0)
    873 Accordingly, GPUSTAT becomes 14802000h. The x1,y1 values are too small, ie. the
    874 upper-left edge isn't visible. Note that GP1(09h) is NOT affected by the reset
    875 command.
    876 
    877 GP1(01h) - Reset Command Buffer
    878   0-23  Not used (zero)
    879 Resets the command buffer.
    880 
    881 GP1(02h) - Acknowledge GPU Interrupt (IRQ1)
    882   0-23  Not used (zero)                                        ;GPUSTAT.24
    883 Resets the IRQ flag in GPUSTAT.24. The flag can be set via GP0(1Fh).
    884 
    885 GP1(03h) - Display Enable
    886   0     Display On/Off   (0=On, 1=Off)                         ;GPUSTAT.23
    887   1-23  Not used (zero)
    888 Turns display on/off. "Note that a turned off screen still gives the flicker of
    889 NTSC on a PAL screen if NTSC mode is selected."
    890 The "Off" settings displays a black picture (and still sends /SYNC signals to
    891 the television set). (Unknown if it still generates vblank IRQs though?)
    892 
    893 GP1(04h) - DMA Direction / Data Request
    894   0-1  DMA Direction (0=Off, 1=FIFO, 2=CPUtoGP0, 3=GPUREADtoCPU) ;GPUSTAT.29-30
    895   2-23 Not used (zero)
    896 Notes: Manually sending/reading data by software (non-DMA) is ALWAYS possible,
    897 regardless of the GP1(04h) setting. The GP1(04h) setting does affect the
    898 meaning of GPUSTAT.25.
    899 
    900 Display start/end
    901 Specifies where the display area is positioned on the screen, and how much data
    902 gets sent to the screen. The screen sizes of the display area are valid only if
    903 the horizontal/vertical start/end values are default. By changing these you can
    904 get bigger/smaller display screens. On most TV's there is some black around the
    905 edge, which can be utilised by setting the start of the screen earlier and the
    906 end later. The size of the pixels is NOT changed with these settings, the GPU
    907 simply sends more data to the screen. Some monitors/TVs have a smaller display
    908 area and the extended size might not be visible on those sets. "(Mine is
    909 capable of about 330 pixels horizontal, and 272 vertical in 320*240 mode)"
    910 
    911 GP1(05h) - Start of Display area (in VRAM)
    912   0-9   X (0-1023)    (halfword address in VRAM)  (relative to begin of VRAM)
    913   10-18 Y (0-511)     (scanline number in VRAM)   (relative to begin of VRAM)
    914   19-23 Not used (zero)
    915 Upper/left Display source address in VRAM. The size and target position on
    916 screen is set via Display Range registers; target=X1,Y2;
    917 size=(X2-X1/cycles_per_pix), (Y2-Y1).
    918 
    919 GP1(06h) - Horizontal Display range (on Screen)
    920   0-11   X1 (260h+0)       ;12bit       ;\counted in 53.222400MHz units,
    921   12-23  X2 (260h+320*8)   ;12bit       ;/relative to HSYNC
    922 Specifies the horizontal range within which the display area is displayed. For
    923 resolutions other than 320 pixels it may be necessary to fine adjust the value
    924 to obtain an exact match (eg. X2=X1+pixels*cycles_per_pix).
    925 The number of displayed pixels per line is "(((X2-X1)/cycles_per_pix)+2) AND
    926 NOT 3" (ie. the hardware is rounding the width up/down to a multiple of 4
    927 pixels).
    928 Most games are using a width equal to the horizontal resolution (ie. 256, 320,
    929 368, 512, 640 pixels). A few games are using slightly smaller widths (probably
    930 due to programming bugs). Pandemonium 2 is using a bigger "overscan" width
    931 (ensuring an intact picture without borders even on mis-calibrated TV sets).
    932 The 260h value is the first visible pixel on normal TV Sets, this value is used
    933 by MOST NTSC games, and SOME PAL games (see below notes on Mis-Centered PAL
    934 games).
    935 
    936 GP1(07h) - Vertical Display range (on Screen)
    937   0-9   Y1 (NTSC=88h-(224/2), (PAL=A3h-(264/2))  ;\scanline numbers on screen,
    938   10-19 Y2 (NTSC=88h+(224/2), (PAL=A3h+(264/2))  ;/relative to VSYNC
    939   20-23 Not used (zero)
    940 Specifies the vertical range within which the display area is displayed. The
    941 number of lines is Y2-Y1 (unlike as for the width, there's no rounding applied
    942 to the height). If Y2 is set to a much too large value, then the hardware stops
    943 to generate vblank interrupts (IRQ0).
    944 The 88h/A3h values are the middle-scanlines on normal TV Sets, these values are
    945 used by MOST NTSC games, and SOME PAL games (see below notes on Mis-Centered
    946 PAL games).
    947 The 224/264 values are for fullscreen pictures. Many NTSC games display 240
    948 lines (overscan with hidden lines). Many PAL games display only 256 lines
    949 (underscan with black borders).
    950 
    951 GP1(08h) - Display mode
    952   0-1   Horizontal Resolution 1     (0=256, 1=320, 2=512, 3=640) ;GPUSTAT.17-18
    953   2     Vertical Resolution         (0=240, 1=480, when Bit5=1)  ;GPUSTAT.19
    954   3     Video Mode                  (0=NTSC/60Hz, 1=PAL/50Hz)    ;GPUSTAT.20
    955   4     Display Area Color Depth    (0=15bit, 1=24bit)           ;GPUSTAT.21
    956   5     Vertical Interlace          (0=Off, 1=On)                ;GPUSTAT.22
    957   6     Horizontal Resolution 2     (0=256/320/512/640, 1=368)   ;GPUSTAT.16
    958   7     "Reverseflag"               (0=Normal, 1=Distorted)      ;GPUSTAT.14
    959   8-23  Not used (zero)
    960 Note: Interlace must be enabled to see all lines in 480-lines mode (interlace
    961 is causing ugly flickering, so a non-interlaced low resolution image is
    962 typically having better quality than a high resolution interlaced image, a
    963 pretty bad example are the intro screens shown by the BIOS). The Display Area
    964 Color Depth does NOT affect the Drawing Area (the Drawing Area is <always>
    965 15bit).
    966 When the "Reverseflag" is set, the display scrolls down 2 lines or so, and
    967 colored regions are getting somehow hatched/distorted, but black and white
    968 regions are still looking okay. Don't know what that's good for? Probably
    969 relates to PAL/NTSC-Color Clock vs PSX-Dot Clock mismatches: Bit7=0 causes
    970 Flimmering errors (errors at different locations in each frame), and Bit7=1
    971 causes Static errors (errors at same locations in all frames)?
    972 
    973 GP1(10h) - Get GPU Info
    974 GP1(11h..1Fh) - Mirrors of GP1(10h), Get GPU Info
    975 After sending the command, the result can be immediately read from GPUREAD
    976 register (there's no NOP or other delay required) (namely GPUSTAT.Bit27 is used
    977 only for VRAM-Reads, but NOT for GPU-Info-Reads, so do not try to wait for that
    978 flag).
    979   0-23  Select Information which is to be retrieved (via following GPUREAD)
    980 On Old 180pin GPUs, following values can be selected:
    981   00h-01h = Returns Nothing (old value in GPUREAD remains unchanged)
    982   02h     = Read Texture Window setting  ;GP0(E2h) ;20bit/MSBs=Nothing
    983   03h     = Read Draw area top left      ;GP0(E3h) ;19bit/MSBs=Nothing
    984   04h     = Read Draw area bottom right  ;GP0(E4h) ;19bit/MSBs=Nothing
    985   05h     = Read Draw offset             ;GP0(E5h) ;22bit
    986   06h-07h = Returns Nothing (old value in GPUREAD remains unchanged)
    987   08h-FFFFFFh = Mirrors of 00h..07h
    988 On New 208pin GPUs, following values can be selected:
    989   00h-01h = Returns Nothing (old value in GPUREAD remains unchanged)
    990   02h     = Read Texture Window setting  ;GP0(E2h) ;20bit/MSBs=Nothing
    991   03h     = Read Draw area top left      ;GP0(E3h) ;20bit/MSBs=Nothing
    992   04h     = Read Draw area bottom right  ;GP0(E4h) ;20bit/MSBs=Nothing
    993   05h     = Read Draw offset             ;GP0(E5h) ;22bit
    994   06h     = Returns Nothing (old value in GPUREAD remains unchanged)
    995   07h     = Read GPU Type (usually 2)    ;see "GPU Versions" chapter
    996   08h     = Unknown (Returns 00000000h) (lightgun on some GPUs?)
    997   09h-0Fh = Returns Nothing (old value in GPUREAD remains unchanged)
    998   10h-FFFFFFh = Mirrors of 00h..0Fh
    999 The selected data is latched in GPUREAD, the same/latched value can be read
   1000 multiple times, but, the latch isn't automatically updated when changing GP0
   1001 registers.
   1002 
   1003 GP1(09h) - New Texture Disable
   1004   0     Texture Disable (0=Normal, 1=Allow Disable via GP0(E1h).11) ;GPUSTAT.15
   1005   1-23  Unknown (seems to have no effect)
   1006 This feature seems to be intended for debugging purposes (most released games
   1007 do contain program code for disabling textures, but do never execute it).
   1008 GP1(09h) seems to be supported only on New GPUs. Old GPUs don't support it all,
   1009 and there seem to be some Special/Prototype GPUs that use GP1(20h) instead of
   1010 GP1(09h).
   1011 
   1012 GP1(20h) - Special/Prototype Texture Disable
   1013   0-23  Unknown (501h=Texture Enable, 504h=Texture Disable, or so?)
   1014 Seems to be a used only on whatever arcade/prototype GPUs. New GPUs are using
   1015 GP1(09h) instead of GP1(20h).
   1016 
   1017 GP1(0Bh) - Unknown/Internal?
   1018   0-10  Unknown (GPU crashes after a while when set to 274h..7FFh)
   1019   11-23 Unknown (seems to have no effect)
   1020 The register doesn't seem to be used by any games.
   1021 
   1022 GP1(0Ah,0Ch..0Fh,21h..3Fh) - N/A
   1023 Not used?
   1024 
   1025 GP1(40h..FFh) - N/A (Mirrors)
   1026 Mirrors of GP1(00h..3Fh).
   1027 
   1028 Mis-Centered PAL Games (wrong GP1(06h)/GP1(07h) settings)
   1029 NTSC games are typically well centered (using X1=260h, and Y1/Y2=88h+/-N).
   1030 PAL games should be centered as X1=260h, and Y1/Y2=A3h+/-N) - these values
   1031 would be looking well on a Philips Philetta TV Set, and do also match up with
   1032 other common picture positions (eg. as used by Nintendo's SNES console).
   1033 However, most PAL games are using completely different "random" centering
   1034 values (maybe caused by different developers trying to match the centering to
   1035 the different TV Sets) (although it looks more as if the PAL developers just
   1036 went amok: Many PAL games are even using different centerings for their Intro,
   1037 Movie, and actual Game sequences).
   1038 In result, most PAL games are looking like crap when playing them on a real
   1039 PSX. For PSX emulators it may be recommended to ignore the GP1(06h)/GP1(07h)
   1040 centering, and instead, apply auto-centering to PAL games.
   1041 For PAL game developers, it may be recommended to add a screen centering option
   1042 (as found in Tomb Raider 3, for example). Unknown if this is really required...
   1043 or if X1=260h, and Y1/Y2=A3h+/-N would work fine on most or all PAL TV Sets?
   1044 
   1045 GPU Status Register
   1046 -------------------
   1047 
   1048 1F801814h - GPUSTAT - GPU Status Register (R)
   1049   0-3   Texture page X Base   (N*64)                              ;GP0(E1h).0-3
   1050   4     Texture page Y Base   (N*256) (ie. 0 or 256)              ;GP0(E1h).4
   1051   5-6   Semi Transparency     (0=B/2+F/2, 1=B+F, 2=B-F, 3=B+F/4)  ;GP0(E1h).5-6
   1052   7-8   Texture page colors   (0=4bit, 1=8bit, 2=15bit, 3=Reserved)GP0(E1h).7-8
   1053   9     Dither 24bit to 15bit (0=Off/strip LSBs, 1=Dither Enabled);GP0(E1h).9
   1054   10    Drawing to display area (0=Prohibited, 1=Allowed)         ;GP0(E1h).10
   1055   11    Set Mask-bit when drawing pixels (0=No, 1=Yes/Mask)       ;GP0(E6h).0
   1056   12    Draw Pixels           (0=Always, 1=Not to Masked areas)   ;GP0(E6h).1
   1057   13    Interlace Field       (or, always 1 when GP1(08h).5=0)
   1058   14    "Reverseflag"         (0=Normal, 1=Distorted)             ;GP1(08h).7
   1059   15    Texture Disable       (0=Normal, 1=Disable Textures)      ;GP0(E1h).11
   1060   16    Horizontal Resolution 2     (0=256/320/512/640, 1=368)    ;GP1(08h).6
   1061   17-18 Horizontal Resolution 1     (0=256, 1=320, 2=512, 3=640)  ;GP1(08h).0-1
   1062   19    Vertical Resolution         (0=240, 1=480, when Bit22=1)  ;GP1(08h).2
   1063   20    Video Mode                  (0=NTSC/60Hz, 1=PAL/50Hz)     ;GP1(08h).3
   1064   21    Display Area Color Depth    (0=15bit, 1=24bit)            ;GP1(08h).4
   1065   22    Vertical Interlace          (0=Off, 1=On)                 ;GP1(08h).5
   1066   23    Display Enable              (0=Enabled, 1=Disabled)       ;GP1(03h).0
   1067   24    Interrupt Request (IRQ1)    (0=Off, 1=IRQ)       ;GP0(1Fh)/GP1(02h)
   1068   25    DMA / Data Request, meaning depends on GP1(04h) DMA Direction:
   1069           When GP1(04h)=0 ---> Always zero (0)
   1070           When GP1(04h)=1 ---> FIFO State  (0=Full, 1=Not Full)
   1071           When GP1(04h)=2 ---> Same as GPUSTAT.28
   1072           When GP1(04h)=3 ---> Same as GPUSTAT.27
   1073   26    Ready to receive Cmd Word   (0=No, 1=Ready)  ;GP0(...) ;via GP0
   1074   27    Ready to send VRAM to CPU   (0=No, 1=Ready)  ;GP0(C0h) ;via GPUREAD
   1075   28    Ready to receive DMA Block  (0=No, 1=Ready)  ;GP0(...) ;via GP0
   1076   29-30 DMA Direction (0=Off, 1=?, 2=CPUtoGP0, 3=GPUREADtoCPU)    ;GP1(04h).0-1
   1077   31    Drawing even/odd lines in interlace mode (0=Even or Vblank, 1=Odd)
   1078 In 480-lines mode, bit31 changes per frame. And in 240-lines mode, the bit
   1079 changes per scanline. The bit is always zero during Vblank (vertical retrace
   1080 and upper/lower screen border).
   1081 
   1082 Note
   1083 Further GPU status information can be retrieved via GP1(10h) and GP0(C0h).
   1084 
   1085 Ready Bits
   1086 Bit28: Normally, this bit gets cleared when the command execution is busy (ie.
   1087 once when the command and all of its parameters are received), however, for
   1088 Polygon and Line Rendering commands, the bit gets cleared immediately after
   1089 receiving the command word (ie. before receiving the vertex parameters). The
   1090 bit is used as DMA request in DMA Mode 2, accordingly, the DMA would probably
   1091 hang if the Polygon/Line parameters are transferred in a separate DMA block
   1092 (ie. the DMA probably starts ONLY on command words).
   1093 Bit27: Gets set after sending GP0(C0h) and its parameters, and stays set until
   1094 all data words are received; used as DMA request in DMA Mode 3.
   1095 Bit26: Gets set when the GPU wants to receive a command. If the bit is cleared,
   1096 then the GPU does either want to receive data, or it is busy with a command
   1097 execution (and doesn't want to receive anything).
   1098 Bit25: This is the DMA Request bit, however, the bit is also useful for non-DMA
   1099 transfers, especially in the FIFO State mode.
   1100 
   1101 GPU Versions
   1102 ------------
   1103 
   1104 Summary of GPU Differences
   1105   Differences...                Old 160pin GPU          New 208pin GPU
   1106   GPU Chip                      CXD8514Q                CXD8561Q/BQ/CQ/CXD9500Q
   1107   Mainboard                     EARLY-PU-8 and below    LATE-PU-8 and up
   1108   Memory Type                   Dual-ported VRAM        Normal DRAM
   1109   GPUSTAT.13 when interlace=off always 0                always 1
   1110   GPUSTAT.14                    always 0                reverseflag
   1111   GPUSTAT.15                    always 0                texture_disable
   1112   GP1(10h:index3..4)            19bit (1MB VRAM)        20bit (2MB VRAM)
   1113   GP1(10h:index7)               N/A                     00000002h version
   1114   GP1(10h:index8)               mirror of index0        00000000h zero
   1115   GP1(10h:index9..F)            mirror of index1..7     N/A
   1116   GP1(20h)                      whatever? used for detecting old gpu
   1117   GP0(E1h).bit12/13             without x/y-flip        with x/y-flip
   1118   GP0(03h)                      N/A (no stored in fifo) unknown/unused command
   1119   Shaded Textures               ((color/8)*texel)/2     (color*texel)/16
   1120   GP0(02h) FillVram             xpos.bit0-3=0Fh=bugged  xpos.bit0-3=ignored
   1121   dma-to-vram: doesn't work with blksiz>10h (new gpu works with blksiz=8C0h!)
   1122   dma-to-vram: MAYBE also needs extra software-handshake to confirm DMA done?
   1123    320*224 pix = 11800h pix = 8C00h words
   1124   GP0(80h) VramToVram           works                   Freeze on large moves?
   1125 
   1126 Shaded Textures
   1127 The Old GPU crops 8:8:8 bit gouraud shading color to 5:5:5 bit before
   1128 multiplying it with the texture color, resulting in rather poor graphics. For
   1129 example, the snow scence in the first level of Tomb Raider I looks a lot
   1130 smoother on New GPUs.
   1131 The cropped colors are looking a bit as if dithering would be disabled
   1132 (although, technically dithering works fine, but due to the crippled color
   1133 input, it's always using the same dither pattern per 8 intensities, instead of
   1134 using 8 different dither patterns).
   1135 
   1136 Memory/Rendering Timings
   1137 The Old GPU uses two Dual-ported VRAM chips (each with two 16bit databusses,
   1138 one for CPU/DMA/rendering access, and one for output to the video DAC). The New
   1139 GPU uses s normal DRAM chip (with single 32bit databus).
   1140 The exact timing differences are unknown, but the different memory types should
   1141 result in quite different timings:
   1142 The Old GPU might perform better on non-32bit aligned accesses, and on memory
   1143 accesses performed simultaneously with DAC output.
   1144 On the other hand, the New GPU's DRAM seems to be faster in some cases (for
   1145 example, during Vblank, it's fast enough to perform DMA's with blksiz>10h,
   1146 which exceeds the GPU's FIFO size, and causes lost data on Old GPUs).
   1147 
   1148 X/Y-Flip and 2MB Video RAM
   1149 The X/Y-flipping feature may be used by arcade games (provided that the arcade
   1150 board is fitted with New GPUs). The flipping feature does also work on retail
   1151 consoles with New GPUs, but PSX games should never use that feature (for
   1152 maintaining compatiblity with older PSX consoles).
   1153 2Mbyte Video RAM is used on some arcade boards. Whilst PSX retail consoles are
   1154 always containing only 1MByte RAM, so the feature cannot be used even if the
   1155 console contains a New GPU. There's one special case: Some PSone consoles are
   1156 actually fitted with 2MB chips (maybe because smaller chips haven't been in
   1157 production anymore), but the chips are wired so that only half of the memory is
   1158 accessible (the extra memory could be theoretically unlocked with some minimal
   1159 hardware modification).
   1160 
   1161 GPU Detection (and optional texture disable)
   1162 Below is slightly customized GPU Detection function taken from Perfect Assassin
   1163 (the index7 latching works ONLY on New GPUs, whilst old GPUs would leave the
   1164 latched value unchanged; as a workaround, the index4 latching is used to ensure
   1165 that the latch won't contain 000002h on old GPUs, assuming that index4 is never
   1166 set to 000002h).
   1167   [1F801814h]=10000004h       ;GP1(10h).index4 (latch draw area bottom right)
   1168   [1F801814h]=10000007h       ;GP1(10h).index7 (latch GPU version, if any)
   1169   if ([1F801810h] AND 00FFFFFFh)=00000002h then goto @@gpu_v2
   1170   [1F801810h]=([1F801814h] AND 3FFFh) OR E1001000h ;change GPUSTAT via GP0(E1h)
   1171   dummy=[1F801810h]           ;dummy read (unknown purpose)
   1172   if ([1F801814h] AND 00001000h) then goto @@gpu_v1 else goto @@gpu_v0
   1173  ;---
   1174  @@gpu_v0:  ;Old 160pin GPU (EARLY-PU-8)
   1175   return 0
   1176  ;---
   1177  @@gpu_v1:  ;unknown GPU type, maybe some custom arcade/prototype version ?
   1178   if want_tex_dis then [1F801814h]=20000504h  ;GP1(20h)
   1179   return 1
   1180  ;---
   1181  @@gpu_v2:  ;New 208pin GPU (LATE-PU-8 and up)
   1182   if want_tex_dis then [1F801814h]=09000001h  ;GP1(09h)
   1183   return 2
   1184 
   1185 GP0(02h) FillVram
   1186 The FillVram command does normally ignore the lower 4bit of the x-coordinate
   1187 (and software should always set those bits to zero). However, if the 4bits are
   1188 all set, then the Old GPU does write each 2nd pixel to wrong memory address.
   1189 For example, a 32x4 pixel fill produces following results for x=0..1Fh:
   1190   0h              10h             20h             30h             40h
   1191   |               |               |               |               |
   1192   ################################                                 ;\x=00h..0Eh
   1193   ################################                                 ; and, x=0Fh
   1194   ################################                                 ; on NEW GPU
   1195   ################################                                 ;/
   1196    # # # # # # # ################## # # # # # # #                  ;\
   1197    # # # # # # # ################## # # # # # # #                  ; x=0Fh
   1198    # # # # # # # ################## # # # # # # #                  ; on OLD GPU
   1199    # # # # # # # ################## # # # # # # #                  ;/
   1200                   ################################                 ;\x=10h..1Eh
   1201                   ################################                 ; and, x=1Fh
   1202                   ################################                 ; on NEW GPU
   1203                   ################################                 ;/
   1204                    # # # # # # # ################## # # # # # # #  ;\
   1205                    # # # # # # # ################## # # # # # # #  ; x=1Fh
   1206                    # # # # # # # ################## # # # # # # #  ; on OLD GPU
   1207                    # # # # # # # ################## # # # # # # #  ;/
   1208 
   1209 Arcade GPUs
   1210 Some arcade boards are using normal retail GPUs, however, there are also two
   1211 special non-retail 208pin GPUs which seem to be solely used on arcade boards:
   1212   IC21  - 208pin - "SONY CXD8538Q"   ;seen on GP-11 (namco System 11) boards
   1213   IC103 - 208pin - "SONY CXD8654Q"   ;seen on GP-15 (namco System 12) boards
   1214 The exact differences to retail GPUs are unknown. One of the special GPUs is
   1215 said to use entierly different command numbers for rendering commands (maybe
   1216 some old prototype variant, or maybe some protection against cloning arcade
   1217 boards with retail chips).
   1218 
   1219 GPU Depth Ordering
   1220 ------------------
   1221 
   1222 Absent Depth Buffer
   1223 The PlayStation's GPU stores only RGB colors in the framebuffer (ie. unlike
   1224 modern 3D processors, it's NOT buffering Depth values; leaving apart the Mask
   1225 bit, which could be considered as a tiny 1bit "Depth" or "Priority" value). In
   1226 fact, the GPU supports only X,Y coordinates, and it's totally unaware of Z
   1227 coordinates. So, when rendering a polygon, the hardware CANNOT determine which
   1228 of the new pixels are in front/behind of the old pixels in the buffer.
   1229 
   1230 Simple Ordering
   1231 The rendering simply takes place in the ordering as the data is sent to the GPU
   1232 (ie. the most distant objects should be sent first). For 2D graphics, it's
   1233 fairly easy follow that order (eg. even multi-layer 2D graphics can be using
   1234 DMA2-continous mode).
   1235 
   1236 Depth Ordering Table (OT)
   1237 For 3D graphics, the ordering of the polygons may change more or less randomly
   1238 (eg. when rotating/moving the camera). To solve that problem, the whole
   1239 rendering data is usually first stored in a Depth Ordering Table (OT) in Main
   1240 RAM, and, once when all polygons have been stored in the OT, the OT is sent to
   1241 the GPU via "DMA2-linked-list" mode.
   1242 
   1243 Initializing an empty OT (via DMA6)
   1244 DMA channel 6 can be used to set up an empty linked list, in which each entry
   1245 points to the previous:
   1246   DPCR    - enable bits                                 ;Example=x8xxxxxxh
   1247   D6_MADR - pointer to the LAST table entry             ;Example=8012300Ch
   1248   D6_BCR  - number of list entries                      ;Example=00000004h
   1249   D6_CHCR - control bits (should be 11000002h)          ;Example=11000002h
   1250 Each entry has a size of 00h words (upper 8bit), and a pointer to the previous
   1251 entry (lower 24bit). With the above Example values, the generated table would
   1252 look like so:
   1253   [80123000h]=00FFFFFFh  ;1st entry, points to end code (xxFFFFFFh)
   1254   [80123004h]=00123000h  ;2nd entry, points to 1st entry
   1255   [80123008h]=00123004h  ;3rd entry, points to 2nd entry
   1256   [8012300Ch]=00123008h  ;last entry, points to 3rd entry (table entrypoint)
   1257 
   1258 Inserting Entries (Passing GTE data to the OT) (by software)
   1259 The GTE commands AVSZ3 and AVSZ4 can be used to calculate the Average Z
   1260 coordinates of a polygon (based on its three or four Z coordinates). The result
   1261 is returned as a 16bit Z value in GTE register OTZ, the commands do also allow
   1262 to divide the result, to make it less than 16bit (the full 16bit would require
   1263 an OT of 256KBytes - for the EMPTY table, which would be a waste of memory, and
   1264 which would slowdown the DMA2/DMA6 operations) (on the other hand, a smaller
   1265 table means less depth resolution).
   1266   [PacketAddr+0]      = [80123000h+OTZ*4] + (N SHL 24)   <--internal link chain
   1267   [PacketAddr+4..N*4] = GP0 Command(s) and Parameters    <--data (send to GP0)
   1268   [80123000h+OTZ*4]   = PacketAddr AND FFFFFFh           <--internal link chain
   1269 If there's been already an entry (at the same OTZ index), then the new polygon
   1270 will be processed first (ie. it will appear "behind" of the old entry).
   1271 Not sure if the packet size must be limited to max N=16 words (ie. as for the
   1272 DMA2-continous block size) (due to GP0 FIFO size limits)?
   1273 
   1274 Sending the OT to the CPU (via DMA2-linked-list mode)
   1275   1 - Wait until GPU is ready to receive commands ;GPUSTAT.28
   1276   2 - Enable DMA channel 2                  ;DPCR
   1277   3 - Set GPU to DMA cpu->gpu mode          ;[GP1]=04000002h aka GP1(04h)
   1278   3 - Set D2_MADR to the start of the list  ;(LAST Entry) ;Example=80123010h
   1279   4 - Set D2_BCR to zero                    ;(length unused, end at END-CODE)
   1280   5 - Set D2_CHCR to link mode, mem->GPU and dma enable   ;=01000401h
   1281 
   1282 GPU Video Memory (VRAM)
   1283 -----------------------
   1284 
   1285 Framebuffer
   1286 The framebuffer contains the image that is to be output to the Television Set.
   1287 The GPU supports 10 resolutions, with 16bit or 24bit per pixel.
   1288   Resolution  16bit      24bit      |  Resolution  16bit      24bit
   1289   256x240     120Kbytes  180Kbytes  |  256x480     240Kbytes  360Kbytes
   1290   320x240     150Kbytes  225Kbytes  |  320x480     300Kbytes  450Kbytes
   1291   368x240     xx0Kbytes  xx0Kbytes  |  368x480     xx0Kbytes  xx0Kbytes
   1292   512x240     240Kbytes  360Kbytes  |  512x480     480Kbytes  720Kbytes
   1293   640x240     300Kbytes  450Kbytes  |  640x480     600Kbytes  900Kbytes
   1294 Note: In most cases, you'll need TWO framebuffers (one being displayed, and
   1295 used as rendering target) (unless you are able to draw the whole new image
   1296 during vblank, or unless when using single-layer 2D graphics). So, resolutions
   1297 that occupy more than 512K would exceed the available 1MB VRAM when using 2
   1298 buffers. Also, high resolutions mean higher rendering load, and less texture
   1299 memory.
   1300   15bit Direct Display (default) (works with polygons, lines, rectangles)
   1301   0-4   Red       (0..31)
   1302   5-9   Green     (0..31)
   1303   10-14 Blue      (0..31)
   1304   15    Mask flag (0=Normal, 1=Do not allow to overwrite this pixel)
   1305   24bit Direct Display (works ONLY with direct vram transfers)
   1306   0-7    Red      (0..255)
   1307   8-15   Green    (0..255)
   1308   16-23  Blue     (0..255)
   1309 Note: The 24bit pixels occupy 3 bytes (not 4 bytes with unused MSBs), so each 6
   1310 bytes contain two 24bit pixels. The 24bit display mode works only with VRAM
   1311 transfer commands like GP0(A0h); the rendering commands GP0(20h..7Fh) cannot
   1312 output 24bit data. Ie. 24bit mode is used mostly for MDEC videos (and some 2D
   1313 games like Heart of Darkness).
   1314 
   1315 Texture Bitmaps
   1316 A texture is an image put on a polygon or sprite. The data of a texture can be
   1317 stored in 3 different modes:
   1318   16bit Texture (Direct Color)             ;(One 256x256 page = 128Kbytes)
   1319   0-4   Red       (0..31)         ;\Color 0000h        = Fully-Transparent
   1320   5-9   Green     (0..31)         ; Color 0001h..7FFFh = Non-Transparent
   1321   10-14 Blue      (0..31)         ; Color 8000h..FFFFh = Semi-Transparent (*)
   1322   15    Semi Transparency Flag    ;/(*) or Non-Transparent for opaque commands
   1323   8bit Texture (256 Color Palette)         ;(One 256x256 page = 64Kbytes)
   1324   0-7   Palette index for 1st pixel (left)
   1325   8-15  Palette index for 2nd pixel (right)
   1326   4bit Texture (16 Color Palette)          ;(One 256x256 page = 32Kbytes)
   1327   0-3   Palette index for 1st pixel (left)
   1328   4-7   Palette index for 2nd pixel (middle/left)
   1329   8-11  Palette index for 3rd pixel (middle/right)
   1330   12-15 Palette index for 4th pixel (right)
   1331 A Texture Page is a 256x256 texel region in VRAM (the Polygon rendering
   1332 commands are using Texcoords with 8bit X,Y coordinates, so polygons cannot use
   1333 textures bigger than 256x256) (the Rectangle rendering commands with
   1334 width/height parameters could theoretically use larger textures, but the
   1335 hardware clips their texture coordinates to 8bit, too).
   1336 The GP0(E2h) Texture Window (aka Texture Repeat) command can be used to reduce
   1337 the texture size to less than 256x256 texels.
   1338 The Texture Pages can be located in the frame buffer on X multiples of 64
   1339 halfwords and Y multiples of 256 lines.
   1340 
   1341 Texture Palettes - CLUT (Color Lookup Table)
   1342 The clut is a the table where the colors are stored for the image data in the
   1343 CLUT modes. The pixels of those images are used as indexes to this table. The
   1344 clut is arranged in the frame buffer as a 256x1 image for the 8bit clut mode,
   1345 and a 16x1 image for the 4bit clut mode.
   1346   0-4   Red       (0..31)         ;\Color 0000h        = Fully-Transparent
   1347   5-9   Green     (0..31)         ; Color 0001h..7FFFh = Non-Transparent
   1348   10-14 Blue      (0..31)         ; Color 8000h..FFFFh = Semi-Transparent (*)
   1349   15    Semi Transparency Flag    ;/(*) or Non-Transparent for opaque commands
   1350 The clut data can be arranged in the frame buffer at X multiples of 16
   1351 (X=0,16,32,48,etc) and anywhere in the Y range of 0-511.
   1352 
   1353 Texture Color Black Limitations
   1354 On the PSX, texture color 0000h is fully-transparent, that means textures
   1355 cannot contain Black pixels. However, in some cases, Color 8000h (Black with
   1356 semi-transparent flag) can be used, depending on the rendering command:
   1357   opaque command, eg. GP0(24h)      --> 8000h = Non-Transparent Black
   1358   semi-transp command, eg. GP0(26h) --> 8000h = Semi-Transparent Black
   1359 So, with semi-transparent rendering commands, it isn't possible to use
   1360 Non-Transparent Black pixels in textures, the only workaround is to use colors
   1361 like 0001h (dark red) or 0400h (dark blue). However, due to the PSX's rather
   1362 steeply increasing intensity ramp, these colors are clearly visible to be
   1363 brighter than black.
   1364 
   1365 RGB Intensity Notes
   1366 The Playstations RGB values aren't linear to normal RGB values (as used on
   1367 PCs). The min/max values are of course the same, but the medium values differ:
   1368   Intensity        PC      PSX
   1369   Minimum          0       0
   1370   Medium (circa)   16      8
   1371   Maximum          31      31
   1372 Ie. on the PSX, the intensity increases steeply from 0 to 15, and less steeply
   1373 from 16 to 31.
   1374 
   1375 GPU Texture Caching
   1376 -------------------
   1377 
   1378 The GPU has 2 Kbyte Texture Cache
   1379 The Texture Cache is (maybe) also used for CLUT data - or is there a separate
   1380 CLUT Cache - or is the CLUT uncached - but that'd be trash?
   1381 
   1382 If polygons with texture are displayed, the GPU needs to read these from the
   1383 frame buffer. This slows down the drawing process, and as a result the number
   1384 of polygons that can be drawn in a given timespan. To speed up this process the
   1385 GPU is equipped with a texture cache, so a given piece of texture needs not to
   1386 be read multiple times in succession.
   1387 The texture cache size depends on the color mode used for the textures.
   1388 In 4 bit CLUT mode it has a size of 64x64, in 8 bit CLUT it's 32x64 and in
   1389 15bitDirect is 32x32. A general speed up can be achieved by setting up textures
   1390 according to these sizes. For further speed gain a more precise knowledge of
   1391 how the cache works is necessary.
   1392 
   1393 Cache blocks
   1394 The texture page is divided into non-overlapping cache blocks, each of a unit
   1395 size according to color mode. These cache blocks are tiled within the texture
   1396 page.
   1397   +-----+-----+-----+--
   1398   |cache|     |     |
   1399   |block|     |
   1400   |    0|   1 |    2   ..
   1401   +-----+-----+--
   1402   |..   |     |
   1403 
   1404 Cache entries
   1405 Each cache block is divided into 256 cache entries, which are numbered
   1406 sequentially, and are 8 bytes wide. So a cache entry holds 16 4bit clut pixels
   1407 8 8bit clut pixels, or 4 15bitdirect pixels.
   1408   4bit and 8bit clut:        15bitdirect:
   1409   +----+----+----+----+     +----+----+----+----+----+----+----+----+
   1410   |   0|   1|   2|   3|     |   0|   1|   2|   3|   4|   5|   6|   7|
   1411   +----+----+----+----+     +----+----+----+----+----+----+----+----+
   1412   |   4|   5|   6|   7|     |   8|   9|   a|   b|   c|   d|   e|   f|
   1413   +----+----+----+----+     +----+----+----+----+----+----+----+----+
   1414   |   8|   9|  ..           |  10|  11|  ..
   1415   +----+----+--             +----+----+--
   1416   |   c|  ..|               |  18|  ..|
   1417   +----+--                  +----+--
   1418   |  ..                     |  ..
   1419 The cache can hold only one cache entry by the same number, so if f.e. a piece
   1420 of texture spans multiple cache blocks and it has data on entry 9 of block 1,
   1421 but also on entry 9 of block 2, these cannot be in the cache at once.
   1422 
   1423 GPU Timings
   1424 -----------
   1425 
   1426 Video Clock
   1427 The PSone/PAL video clock is the cpu clock multiplied by 11/7.
   1428   CPU Clock   =  33.868800MHz (44100Hz*300h)
   1429   Video Clock =  53.222400MHz (44100Hz*300h*11/7)
   1430 For other PSX/PSone PAL/NTSC variants, see:
   1431 --> Pinouts - CLK Pinouts
   1432 
   1433 Vertical Timings
   1434   PAL:  314 scanlines per frame (13Ah)
   1435   NTSC: 263 scanlines per frame (107h)
   1436 Timer1 can use the hblank signal as input, allowing to count scanlines (unless
   1437 the display is configured to 0 pixels width, which would cause an endless
   1438 hblank). The hblank signal is generated even during vertical blanking/retrace.
   1439 
   1440 Horizontal Timings
   1441   PAL:  3406 video cycles per scanline (or 3406.1 or so?)
   1442   NTSC: 3413 video cycles per scanline (or 3413.6 or so?)
   1443 Dotclocks:
   1444   PSX.256-pix Dotclock =  5.322240MHz (44100Hz*300h*11/7/10)
   1445   PSX.320-pix Dotclock =  6.652800MHz (44100Hz*300h*11/7/8)
   1446   PSX.368-pix Dotclock =  7.603200MHz (44100Hz*300h*11/7/7)
   1447   PSX.512-pix Dotclock = 10.644480MHz (44100Hz*300h*11/7/5)
   1448   PSX.640-pix Dotclock = 13.305600MHz (44100Hz*300h*11/7/4)
   1449   Namco GunCon 385-pix =  8.000000MHz (from 8.00MHz on lightgun PCB)
   1450 Dots per scanline are, depending on horizontal resolution, and on PAL/NTSC:
   1451   320pix/PAL: 3406/8  = 425.75 dots     320pix/NTSC: 3413/8  = 426.625 dots
   1452   640pix/PAL: 3406/4  = 851.5 dots      640pix/NTSC: 3413/4  = 853.25 dots
   1453   256pix/PAL: 3406/10 = 340.6 dots      256pix/NTSC: 3413/10 = 341.3 dots
   1454   512pix/PAL: 3406/5  = 681.2 dots      512pix/NTSC: 3413/5  = 682.6 dots
   1455   368pix/PAL: 3406/7  = 486.5714 dots   368pix/NTSC: 3413/7  = 487.5714 dots
   1456 Timer0 can use the dotclock as input, however, the Timer0 input "ignores" the
   1457 fractional portions (in most cases, the values are rounded down, ie. with 340.6
   1458 dots/line, the timer increments only 340 times/line; the only value that is
   1459 rounded up is 425.75 dots/line) (for example, due to the rounding, the timer
   1460 isn't running exactly twice as fast in 512pix/PAL mode than in 256pix/PAL
   1461 mode). The dotclock signal is generated even during horizontal/vertical
   1462 blanking/retrace.
   1463 
   1464 Frame Rates
   1465   PAL:  53.222400MHz/314/3406 = ca. 49.76 Hz (ie. almost 50Hz)
   1466   NTSC: 53.222400MHz/263/3413 = ca. 59.29 Hz (ie. almost 60Hz)
   1467 
   1468 Note
   1469 Above values include "hidden" dots and scanlines (during horizontal and
   1470 vertical blanking/retrace).
   1471 
   1472 GPU (MISC)
   1473 ----------
   1474 
   1475 GP0(20h..7Fh) - Render Command Bits
   1476   0-23  Color for (first) Vertex                   (Not for Raw-Texture)
   1477   24    Texture Mode      (0=Blended, 1=Raw)       (Textured-Polygon/Rect only)
   1478   25    Semi Transparency (0=Off, 1=On)            (All Render Types)
   1479   26    Texture Mapping   (0=Off, 1=On)            (Polygon/Rectangle only)
   1480   27-28 Rect Size   (0=Var, 1=1x1, 2=8x8, 3=16x16) (Rectangle only)
   1481   27    Num Vertices      (0=Triple, 1=Quad)       (Polygon only)
   1482   27    Num Lines         (0=Single, 1=Poly)       (Line only)
   1483   28    Shading           (0=Flat, 1=Gouroud)      (Polygon/Line only)
   1484   29-31 Primitive Type    (1=Polygon, 2=Line, 3=Rectangle)
   1485 
   1486 Perspective (in-)correct Rendering
   1487 The PSX doesn't support perspective correct rendering: Assume a polygon to be
   1488 rotated so that it's right half becomes more distant to the camera, and it's
   1489 left half becomes closer. Due to the GTE's perspective division, the right half
   1490 should appear smaller than the left half.
   1491 The GPU supports only linear interpolations for rendering - that is correct
   1492 concerning the X and Y screen coordinates (which are still linear to each
   1493 other, even after perspective division, since both are divided by the same
   1494 value).
   1495 However, texture coordinates (and Gouraud shaded colors) are NOT linear to the
   1496 screen coordinates, and so, the linear interpolated PSX graphics are often
   1497 looking rather distorted, that especially for textures that contain straight
   1498 lines. For color shading the problem is less obvious (since shading is kinda
   1499 blurry anyways).
   1500 
   1501 Perspective correct Rendering
   1502 For perspective correct rendering, the polygon's Z-coordinates would be needed
   1503 to be passed from the GTE to the GPU, and, the GPU would then need to use that
   1504 Z-coordinates to "undo" the perspective division for each pixel (that'd require
   1505 some additional memory, and especially a powerful division unit, which isn't
   1506 implemented in the hardware).
   1507 As a workaround, you can try to reduce the size of your polygons (the
   1508 interpolation errors increase in the center region of larger polygons).
   1509 Reducing the size would be only required for polygons that occupy a larger
   1510 screen region (which may vary depending on the distance to the camera).
   1511 Ie. you may check the size AFTER perspective division, if it's too large, then
   1512 break it into smaller parts (using the original coordinates, NOT the screen
   1513 coordinates), and then pass the fragments to the GTE another time.
   1514 Again, perspective correction would be relevant only for certain textures (not
   1515 for randomly dithered textures like sand, water, fire, grass, and not for
   1516 untextured polygons, and of course not for 2D graphics, so you may exclude
   1517 those from size reduction).
   1518 
   1519 24bit RGB to 15bit RGB Dithering (enabled in Texpage attribute)
   1520 For dithering, VRAM is broken to 4x4 pixel blocks, depending on the location in
   1521 that 4x4 pixel region, the corresponding dither offset is added to the 8bit
   1522 R/G/B values, the result is saturated to +00h..+FFh, and then divided by 8,
   1523 resulting in the final 5bit R/G/B values.
   1524   -4  +0  -3  +1   ;\dither offsets for first two scanlines
   1525   +2  -2  +3  -1   ;/
   1526   -3  +1  -4  +0   ;\dither offsets for next two scanlines
   1527   +3  -1  +2  -2   ;/(same as above, but shifted two pixels horizontally)
   1528 POLYGONs (triangles/quads) are dithered ONLY if they do use gouraud shading or
   1529 texture blending.
   1530 LINEs are dithered (no matter if they are mono or do use gouraud shading).
   1531 RECTs are NOT dithered (no matter if they do use texture blending).
   1532 
   1533 Shading information
   1534 "Texture RGB values control the brightness of the individual colors ($00-$7f).
   1535 A value of $80 in a color will take the former value as data." (What...?
   1536 probably means the "double brightness" effect... or does it want to tell that
   1537 ALL colors of 80h..FFh have only single brightness.. rather than reaching
   1538 double brightness at FFh...?)
   1539 
   1540 Shading
   1541 The GPU has a shading function, which will scale the color of a primitive to a
   1542 specified brightness. There are 2 shading modes: Flat shading, and gouraud
   1543 shading. Flat shading is the mode in which one brightness value is specified
   1544 for the entire primitive. In Gouraud shading mode, a different brightness value
   1545 can be given for each vertex of a primitive, and the brightness between these
   1546 points is automatically interpolated.
   1547 
   1548 Semi Transparency
   1549 When semi transparency is set for a pixel, the GPU first reads the pixel it
   1550 wants to write to, and then calculates the color it will write from the 2
   1551 pixels according to the semitransparency mode selected. Processing speed is
   1552 lower in this mode because additional reading and calculating are necessary.
   1553 There are 4 semitransparency modes in the GPU.
   1554   B=Back  (the old pixel read from the image in the frame buffer)
   1555   F=Front (the new halftransparent pixel)
   1556   * 0.5 x B + 0.5 x F    ;aka B/2+F/2
   1557   * 1.0 x B + 1.0 x F    ;aka B+F
   1558   * 1.0 x B - 1.0 x F    ;aka B-F
   1559   * 1.0 x B +0.25 x F    ;aka B+F/4
   1560 
   1561 Draw to display enable
   1562 This will enable/disable any drawing to the area that is currently displayed.
   1563 Not sure yet WHY one should want to disable that?
   1564 Also not sure HOW and IF it works... the SIZE of the display area is implied by
   1565 the screen size - which is horizontally counted in CLOCK CYCLES, so, to obtain
   1566 the size in PIXELS, the hardware would require to divide that value by the
   1567 number of cycles per pixel, depending on the current resolution...?
   1568 
   1569 Geometry Transformation Engine (GTE)
   1570 ------------------------------------
   1571 
   1572 --> GTE Overview
   1573 --> GTE Registers
   1574 --> GTE Saturation
   1575 --> GTE Opcode Summary
   1576 --> GTE Coordinate Calculation Commands
   1577 --> GTE General Purpose Calculation Commands
   1578 --> GTE Color Calculation Commands
   1579 --> GTE Division Inaccuracy
   1580 
   1581 GTE Overview
   1582 ------------
   1583 
   1584 GTE Operation
   1585 The GTE doesn't have any memory or I/O ports mapped to the CPU memory bus,
   1586 instead, it's solely accessed via coprocessor opcodes:
   1587   mov  cop0r12,rt          ;-enable/disable COP2 (GTE) via COP0 status register
   1588   mov  cop2r0-63,rt        ;\write parameters to GTE registers
   1589   mov  cop2r0-31,[rs+imm]  ;/
   1590   mov  cop2cmd,imm25       ;-issue GTE command
   1591   mov  rt,cop2r0-63        ;\read results from GTE registers
   1592   mov  [rs+imm],cop2r0-31  ;/
   1593   jt   cop2flg,dest        ;-jump never  ;\implemented (no exception), but,
   1594   jf   cop2flg,dest        ;-jump always ;/flag seems to be always "false"
   1595 GTE (memory-?) load and store instructions have a delay of 2 instructions, for
   1596 any GTE commands or operations accessing that register. Any? That's wrong!
   1597 GTE instructions and functions should not be used in
   1598   - Delay slots of jumps and branches
   1599   - Event handlers or interrupts (sounds like nonsense?) (need push/pop though)
   1600 If an instruction that reads a GTE register or a GTE command is executed before
   1601 the current GTE command is finished, the CPU will hold until the instruction
   1602 has finished. The number of cycles each GTE instruction takes is shown in the
   1603 command list.
   1604 
   1605 GTE Command Encoding (COP2 imm25 opcodes)
   1606   31-25  Must be 0100101b for "COP2 imm25" instructions
   1607   20-24  Fake GTE Command Number (00h..1Fh) (ignored by hardware)
   1608   19     sf - Shift Fraction in IR registers (0=No fraction, 1=12bit fraction)
   1609   17-18  MVMVA Multiply Matrix    (0=Rotation. 1=Light, 2=Color, 3=Reserved)
   1610   15-16  MVMVA Multiply Vector    (0=V0, 1=V1, 2=V2, 3=IR/long)
   1611   13-14  MVMVA Translation Vector (0=TR, 1=BK, 2=FC/Bugged, 3=None)
   1612   11-12  Always zero                        (ignored by hardware)
   1613   10     lm - Saturate IR1,IR2,IR3 result (0=To -8000h..+7FFFh, 1=To 0..+7FFFh)
   1614   6-9    Always zero                        (ignored by hardware)
   1615   0-5    Real GTE Command Number (00h..3Fh) (used by hardware)
   1616 The MVMVA bits are used only by the MVMVA opcode (the bits are zero for all
   1617 other opcodes).
   1618 The "sf" and "lm" bits are usually fixed (either set, or cleared, depending on
   1619 the command) (for MVMVA, the bits are variable) (also, "sf" can be changed for
   1620 some commands like SQR) (although they are usually fixed for most other
   1621 opcodes, changing them might have some effect on some/all opcodes)?
   1622 
   1623 GTE Data Register Summary (cop2r0-31)
   1624   cop2r0-1   3xS16 VXY0,VZ0              Vector 0 (X,Y,Z)
   1625   cop2r2-3   3xS16 VXY1,VZ1              Vector 1 (X,Y,Z)
   1626   cop2r4-5   3xS16 VXY2,VZ2              Vector 2 (X,Y,Z)
   1627   cop2r6     4xU8  RGBC                  Color/code value
   1628   cop2r7     1xU16 OTZ                   Average Z value (for Ordering Table)
   1629   cop2r8     1xS16 IR0                   16bit Accumulator (Interpolate)
   1630   cop2r9-11  3xS16 IR1,IR2,IR3           16bit Accumulator (Vector)
   1631   cop2r12-15 6xS16 SXY0,SXY1,SXY2,SXYP   Screen XY-coordinate FIFO  (3 stages)
   1632   cop2r16-19 4xU16 SZ0,SZ1,SZ2,SZ3       Screen Z-coordinate FIFO   (4 stages)
   1633   cop2r20-22 12xU8 RGB0,RGB1,RGB2        Color CRGB-code/color FIFO (3 stages)
   1634   cop2r23    4xU8  (RES1)                Prohibited
   1635   cop2r24    1xS32 MAC0                  32bit Maths Accumulators (Value)
   1636   cop2r25-27 3xS32 MAC1,MAC2,MAC3        32bit Maths Accumulators (Vector)
   1637   cop2r28-29 1xU15 IRGB,ORGB             Convert RGB Color (48bit vs 15bit)
   1638   cop2r30-31 2xS32 LZCS,LZCR             Count Leading-Zeroes/Ones (sign bits)
   1639 
   1640 GTE Control Register Summary (cop2r32-63)
   1641   cop2r32-36 9xS16 RT11RT12,..,RT33 Rotation matrix     (3x3)        ;cnt0-4
   1642   cop2r37-39 3x 32 TRX,TRY,TRZ      Translation vector  (X,Y,Z)      ;cnt5-7
   1643   cop2r40-44 9xS16 L11L12,..,L33    Light source matrix (3x3)        ;cnt8-12
   1644   cop2r45-47 3x 32 RBK,GBK,BBK      Background color    (R,G,B)      ;cnt13-15
   1645   cop2r48-52 9xS16 LR1LR2,..,LB3    Light color matrix source (3x3)  ;cnt16-20
   1646   cop2r53-55 3x 32 RFC,GFC,BFC      Far color           (R,G,B)      ;cnt21-23
   1647   cop2r56-57 2x 32 OFX,OFY          Screen offset       (X,Y)        ;cnt24-25
   1648   cop2r58 BuggyU16 H                Projection plane distance.       ;cnt26
   1649   cop2r59      S16 DQA              Depth queing parameter A (coeff) ;cnt27
   1650   cop2r60       32 DQB              Depth queing parameter B (offset);cnt28
   1651   cop2r61-62 2xS16 ZSF3,ZSF4        Average Z scale factors          ;cnt29-30
   1652   cop2r63      U20 FLAG             Returns any calculation errors   ;cnt31
   1653 
   1654 GTE Registers
   1655 -------------
   1656 
   1657 Note in some functions format is different from the one that's given here.
   1658 
   1659 Matrix Registers
   1660   Rotation matrix (RT)   Light matrix (LLM)     Light Color matrix (LCM)
   1661   cop2r32.lsbs=RT11      cop2r40.lsbs=L11       cop2r48.lsbs=LR1
   1662   cop2r32.msbs=RT12      cop2r40.msbs=L12       cop2r48.msbs=LR2
   1663   cop2r33.lsbs=RT13      cop2r41.lsbs=L13       cop2r49.lsbs=LR3
   1664   cop2r33.msbs=RT21      cop2r41.msbs=L21       cop2r49.msbs=LG1
   1665   cop2r34.lsbs=RT22      cop2r42.lsbs=L22       cop2r50.lsbs=LG2
   1666   cop2r34.msbs=RT23      cop2r42.msbs=L23       cop2r50.msbs=LG3
   1667   cop2r35.lsbs=RT31      cop2r43.lsbs=L31       cop2r51.lsbs=LB1
   1668   cop2r35.msbs=RT32      cop2r43.msbs=L32       cop2r51.msbs=LB2
   1669   cop2r36     =RT33      cop2r44     =L33       cop2r52     =LB3
   1670 Each element is 16bit (1bit sign, 3bit integer, 12bit fraction). Reading the
   1671 last elements (RT33,L33,LB3) returns the 16bit value sign-expanded to 32bit.
   1672 
   1673 Translation Vector (TR) (Input, R/W?)
   1674   cop2r37 (cnt5) - TRX - Translation vector X (R/W?)
   1675   cop2r38 (cnt6) - TRY - Translation vector Y (R/W?)
   1676   cop2r39 (cnt7) - TRZ - Translation vector Z (R/W?)
   1677 Each element is 32bit (1bit sign, 31bit integer).
   1678 Used only for MVMVA, RTPS, RTPT commands.
   1679 
   1680 Background Color (BK) (Input?, R/W?)
   1681   cop2r45 (cnt13) - RBK - Background color red component
   1682   cop2r46 (cnt14) - GBK - Background color green component
   1683   cop2r47 (cnt15) - BBK - Background color blue component
   1684 Each element is 32bit (1bit sign, 19bit integer, 12bit fraction).
   1685 
   1686 Far Color (FC) (Input?) (R/W?)
   1687   cop2r53 (cnt21) - RFC - Far color red component
   1688   cop2r54 (cnt22) - GFC - Far color green component
   1689   cop2r55 (cnt23) - BFC - Far color blue component
   1690 Each element is 32bit (1bit sign, 27bit integer, 4bit fraction).
   1691 
   1692 Screen Offset and Distance (Input, R/W?)
   1693   cop2r56 (cnt24) - OFX - Screen offset X
   1694   cop2r57 (cnt25) - OFY - Screen offset Y
   1695   cop2r58 (cnt26) - H   - Projection plane distance
   1696   cop2r59 (cnt27) - DQA - Depth queing parameter A.(coeff.)
   1697   cop2r60 (cnt28) - DQB - Depth queing parameter B.(offset.)
   1698 The X and Y values are each 32bit (1bit sign, 15bit integer, 16bit fraction).
   1699 The H value is 16bit unsigned (0bit sign, 16bit integer, 0bit fraction). BUG:
   1700 When reading the H register, the hardware does accidently <sign-expand> the
   1701 <unsigned> 16bit value (ie. values +8000h..+FFFFh are returned as
   1702 FFFF8000h..FFFFFFFFh) (this bug applies only to "mov rd,cop2r58" opcodes; the
   1703 actual calculations via RTPS/RTPT opcodes are working okay).
   1704 The DQA value is only 16bit (1bit sign, 7bit integer, 8bit fraction).
   1705 The DQB value is 32bit (1bit sign, 7bit integer, 24bit? fraction).
   1706 Used only for RTPS/RTPT commands.
   1707 
   1708 Average Z Registers (ZSF3/ZSF4=Input, R/W?) (OTZ=Result, R)
   1709   cop2r61 (cnt29) ZSF3 |  0|ZSF3 1,3,12| Z3 average scale factor (normally 1/3)
   1710   cop2r62 (cnt30) ZSF4 |  0|ZSF4 1,3,12| Z4 average scale factor (normally 1/4)
   1711   cop2r7       OTZ (R) |   |OTZ 0,15, 0| Average Z value (for Ordering Table)
   1712 Used only for AVSZ3/AVSZ4 commands.
   1713 
   1714 Screen XYZ Coordinate FIFOs
   1715   cop2r12 - SXY0  rw|SY0 1,15, 0|SX0 1,15, 0| Screen XY fifo (older)
   1716   cop2r13 - SXY1  rw|SY1 1,15, 0|SX1 1,15, 0| Screen XY fifo (old)
   1717   cop2r14 - SXY2  rw|SY2 1,15, 0|SX2 1,15, 0| Screen XY fifo (new)
   1718   cop2r15 - SXYP  rw|SYP 1,15, 0|SXP 1,15, 0| SXY2-mirror with move-on-write
   1719   cop2r16 - SZ0   rw|          0|SZ0 0,16, 0| Screen Z fifo (oldest)
   1720   cop2r17 - SZ1   rw|          0|SZ1 0,16, 0| Screen Z fifo (older)
   1721   cop2r18 - SZ2   rw|          0|SZ2 0,16, 0| Screen Z fifo (old)
   1722   cop2r19 - SZ3   rw|          0|SZ3 0,16, 0| Screen Z fifo (new)
   1723 SX,SY,SZ are used as Output for RTPS/RTPT. Additionally, SX,SY are used as
   1724 Input for NCLIP, and SZ is used as Input for AVSZ3/AVSZ4.
   1725 The SZn Fifo has 4 stages (required for AVSZ4 command), the SXYn Fifo has only
   1726 3 stages, and a special mirrored register: SXYP is a mirror of SXY2, the
   1727 difference is that writing to SXYP moves SXY2/SXY1 to SXY1/SXY0, whilst writing
   1728 to SXY2 (or any other SXYn or SZn registers) changes only the written register,
   1729 but doesn't move any other Fifo entries.
   1730 
   1731 16bit Vectors (R/W)
   1732   Vector 0 (V0)         Vector 1 (V1)       Vector 2 (V2)       Vector 3 (IR)
   1733   cop2r0.lsbs - VX0     cop2r2.lsbs - VX1   cop2r4.lsbs - VX2   cop2r9  - IR1
   1734   cop2r0.msbs - VY0     cop2r2.msbs - VY1   cop2r4.msbs - VY2   cop2r10 - IR2
   1735   cop2r1      - VZ0     cop2r3      - VZ1   cop2r5      - VZ2   cop2r11 - IR3
   1736 All elements are signed 16bit. The IRn and VZn elements occupy a whole 32bit
   1737 register, reading these registers returns the 16bit value sign-expanded to
   1738 32bit. Note: IRn can be also indirectly accessed via IRGB/ORGB registers.
   1739 
   1740 Color Register and Color FIFO
   1741   cop2r6  - RGBC  rw|CODE |B    |G    |R    | Color/code
   1742   cop2r20 - RGB0  rw|CD0  |B0   |G0   |R0   | Characteristic color fifo.
   1743   cop2r21 - RGB1  rw|CD1  |B1   |G1   |R1   |
   1744   cop2r22 - RGB2  rw|CD2  |B2   |G2   |R2   |
   1745   cop2r23 - (RES1)  |                       | Prohibited
   1746 RES1 seems to be unused... looks like an unused Fifo stage... RES1 is
   1747 read/write-able... unlike SXYP (for SXYn Fifo) it does not mirror to RGB2, nor
   1748 does it have a move-on-write function...
   1749 
   1750 Interpolation Factor
   1751   cop2r8   IR0   rw|Sign       |IR0 1, 3,12| Intermediate value 0.
   1752 Used as Output for RTPS/RTPT, and as Input for various commands.
   1753 
   1754 XX...
   1755   cop2r24  MAC0  rw|MAC0 1,31,0            | Sum of products value 0
   1756 
   1757 XX...
   1758   cop2r25  MAC1  rw|MAC1 1,31,0            | Sum of products value 1
   1759   cop2r26  MAC2  rw|MAC2 1,31,0            | Sum of products value 2
   1760   cop2r27  MAC3  rw|MAC3 1,31,0            | Sum of products value 3
   1761 
   1762 cop2r28 - IRGB - Color conversion Input (R/W)
   1763 Expands 5:5:5 bit RGB (range 0..1Fh) to 16:16:16 bit RGB (range 0000h..0F80h).
   1764   0-4    Red   (0..1Fh) (R/W)  ;multiplied by 80h, and written to IR1
   1765   5-9    Green (0..1Fh) (R/W)  ;multiplied by 80h, and written to IR2
   1766   10-14  Blue  (0..1Fh) (R/W)  ;multiplied by 80h, and written to IR3
   1767   15-31  Not used (always zero) (Read only)
   1768 After writing to IRGB, the result can be read from IR3 after TWO nop's, and
   1769 from IR1,IR2 after THREE nop's (for uncached code, ONE nop would work). When
   1770 using IR1,IR2,IR3 as parameters for GTE commands, similar timing restrictions
   1771 might apply... depending on when the specific commands use the parameters?
   1772 
   1773 cop2r29 - ORGB - Color conversion Output (R)
   1774 Collapses 16:16:16 bit RGB (range 0000h..0F80h) to 5:5:5 bit RGB (range
   1775 0..1Fh). Negative values (8000h..FFFFh/80h) are saturated to 00h, large
   1776 positive values (1000h..7FFFh/80h) are saturated to 1Fh, there are no overflow
   1777 or saturation flags set in cop2r63 though.
   1778   0-4    Red   (0..1Fh) (R)  ;IR1 divided by 80h, saturated to +00h..+1Fh
   1779   5-9    Green (0..1Fh) (R)  ;IR2 divided by 80h, saturated to +00h..+1Fh
   1780   10-14  Blue  (0..1Fh) (R)  ;IR3 divided by 80h, saturated to +00h..+1Fh
   1781   15-31  Not used (always zero) (Read only)
   1782 Any changes to IR1,IR2,IR3 are reflected to this register (and, actually also
   1783 to IRGB) (ie. ORGB is simply a read-only mirror of IRGB).
   1784 
   1785 cop2r30 - LZCS - Count Leading Bits Source data (R/W)
   1786 cop2r31 - LZCR - Count Leading Bits Result (R)
   1787 Reading LZCR returns the leading 0 count of LZCS if LZCS is positive and the
   1788 leading 1 count of LZCS if LZCS is negative. The results are in range 1..32.
   1789 
   1790 cop2r63 (cnt31) - FLAG - Returns any calculation errors.
   1791 See GTE Saturation chapter.
   1792 
   1793 GTE Saturation
   1794 --------------
   1795 
   1796 Maths overflows are indicated in FLAG register. In most cases, the result is
   1797 saturated to MIN/MAX values (except MAC0,MAC1,MAC2,MAC3 which aren't
   1798 saturated). For IR1,IR2,IR3 many commands allow to select the MIN value via
   1799 "lm" bit of the GTE opcode (though not all commands, RTPS/RTPT always act as if
   1800 lm=0).
   1801 
   1802 cop2r63 (cnt31) - FLAG - Returns any calculation errors.
   1803   31   Error Flag (Bit30..23, and 18..13 ORed together) (Read only)
   1804   30   MAC1 Result larger than 43 bits and positive
   1805   29   MAC2 Result larger than 43 bits and positive
   1806   28   MAC3 Result larger than 43 bits and positive
   1807   27   MAC1 Result larger than 43 bits and negative
   1808   26   MAC2 Result larger than 43 bits and negative
   1809   25   MAC3 Result larger than 43 bits and negative
   1810   24   IR1 saturated to +0000h..+7FFFh (lm=1) or to -8000h..+7FFFh (lm=0)
   1811   23   IR2 saturated to +0000h..+7FFFh (lm=1) or to -8000h..+7FFFh (lm=0)
   1812   22   IR3 saturated to +0000h..+7FFFh (lm=1) or to -8000h..+7FFFh (lm=0)
   1813   21   Color-FIFO-R saturated to +00h..+FFh
   1814   20   Color-FIFO-G saturated to +00h..+FFh
   1815   19   Color-FIFO-B saturated to +00h..+FFh
   1816   18   SZ3 or OTZ saturated to +0000h..+FFFFh
   1817   17   Divide overflow. RTPS/RTPT division result saturated to max=1FFFFh
   1818   16   MAC0 Result larger than 31 bits and positive
   1819   15   MAC0 Result larger than 31 bits and negative
   1820   14   SX2 saturated to -0400h..+03FFh
   1821   13   SY2 saturated to -0400h..+03FFh
   1822   12   IR0 saturated to +0000h..+1000h
   1823   0-11 Not used (always zero) (Read only)
   1824 Bit30-12 are read/write-able, ie. they can be set/reset by software, however,
   1825 that's normally not required - all bits are automatically reset at the begin of
   1826 a new GTE command.
   1827 Bit31 is apparently intended for RTPS/RTPT commands, since it triggers only on
   1828 flags that are affected by these two commands, but even for that commands it's
   1829 totally useless since one could as well check if FLAG is nonzero.
   1830 Note: Writing 32bit values to 16bit GTE registers by software does not trigger
   1831 any overflow/saturation flags (and does not do any saturation), eg. writing
   1832 12008900h (positive 32bit) to a signed 16bit register sets that register to
   1833 FFFF8900h (negative 16bit).
   1834 
   1835 GTE Opcode Summary
   1836 ------------------
   1837 
   1838 GTE Command Summary (sorted by Real Opcode bits) (bit0-5)
   1839   Opc  Name      Clk Expl.
   1840   00h  -             N/A (modifies similar registers than RTPS...)
   1841   01h  RTPS      15  Perspective Transformation single
   1842   0xh  -             N/A
   1843   06h  NCLIP     8   Normal clipping
   1844   0xh  -             N/A
   1845   0Ch  OP(sf)    6   Outer product of 2 vectors
   1846   0xh  -             N/A
   1847   10h  DPCS      8   Depth Cueing single
   1848   11h  INTPL     8   Interpolation of a vector and far color vector
   1849   12h  MVMVA(..) 8   Multiply vector by matrix and add vector (see below)
   1850   13h  NCDS      19  Normal color depth cue single vector
   1851   14h  CDP       13  Color Depth Que
   1852   15h  -             N/A
   1853   16h  NCDT      44  Normal color depth cue triple vectors
   1854   1xh  -             N/A
   1855   1Bh  NCCS      17  Normal Color Color single vector
   1856   1Ch  CC        11  Color Color
   1857   1Dh  -             N/A
   1858   1Eh  NCS       14  Normal color single
   1859   1Fh  -             N/A
   1860   20h  NCT       30  Normal color triple
   1861   2xh  -             N/A
   1862   28h  SQR(sf)   5   Square of vector IR
   1863   29h  DCPL      8   Depth Cue Color light
   1864   2Ah  DPCT      17  Depth Cueing triple (should be fake=08h, but isn't)
   1865   2xh  -             N/A
   1866   2Dh  AVSZ3     5   Average of three Z values
   1867   2Eh  AVSZ4     6   Average of four Z values
   1868   2Fh  -             N/A
   1869   30h  RTPT      23  Perspective Transformation triple
   1870   3xh  -             N/A
   1871   3Dh  GPF(sf)   5   General purpose interpolation
   1872   3Eh  GPL(sf)   5   General purpose interpolation with base
   1873   3Fh  NCCT      39  Normal Color Color triple vector
   1874 Unknown if/what happens when using the "N/A" opcodes?
   1875 
   1876 GTE Command Summary (sorted by Fake Opcode bits) (bit20-24)
   1877 The fake opcode number in bit20-24 has absolutely no effect on the hardware, it
   1878 seems to be solely used to (or not to) confuse developers. Having the opcodes
   1879 sorted by their fake numbers gives a more or less well arranged list:
   1880   Fake Name      Clk Expl.
   1881   00h  -             N/A
   1882   01h  RTPS      15  Perspective Transformation single
   1883   02h  RTPT      23  Perspective Transformation triple
   1884   03h  -             N/A
   1885   04h  MVMVA(..) 8   Multiply vector by matrix and add vector (see below)
   1886   05h  -             N/A
   1887   06h  DCPL      8   Depth Cue Color light
   1888   07h  DPCS      8   Depth Cueing single
   1889   08h  DPCT      17  Depth Cueing triple (should be fake=08h, but isn't)
   1890   09h  INTPL     8   Interpolation of a vector and far color vector
   1891   0Ah  SQR(sf)   5   Square of vector IR
   1892   0Bh  -             N/A
   1893   0Ch  NCS       14  Normal color single
   1894   0Dh  NCT       30  Normal color triple
   1895   0Eh  NCDS      19  Normal color depth cue single vector
   1896   0Fh  NCDT      44  Normal color depth cue triple vectors
   1897   10h  NCCS      17  Normal Color Color single vector
   1898   11h  NCCT      39  Normal Color Color triple vector
   1899   12h  CDP       13  Color Depth Que
   1900   13h  CC        11  Color Color
   1901   14h  NCLIP     8   Normal clipping
   1902   15h  AVSZ3     5   Average of three Z values
   1903   16h  AVSZ4     6   Average of four Z values
   1904   17h  OP(sf)    6   Outer product of 2 vectors
   1905   18h  -             N/A
   1906   19h  GPF(sf)   5   General purpose interpolation
   1907   1Ah  GPL(sf)   5   General purpose interpolation with base
   1908   1Bh  -             N/A
   1909   1Ch  -             N/A
   1910   1Dh  -             N/A
   1911   1Eh  -             N/A
   1912   1Fh  -             N/A
   1913 For the sort-effect, DCPT should use fake=08h, but Sony seems to have
   1914 accidently numbered it fake=0Fh in their devkit (giving it the same fake number
   1915 as for NCDT). Also, "Wipeout 2097" accidently uses 0140006h (fake=01h and
   1916 distorted bit18) instead of 1400006h (fake=14h) for NCLIP.
   1917 
   1918 GTE nonsense SDK command numbers (as from SDK file INLINE_A.H)
   1919   RTPS   macro               dw   $0000007f              (01x40)
   1920   RTPT   macro               dw   $000000bf              (02x40)
   1921   DCPL   macro               dw   $00000dff              (37x40)
   1922   DPCS   macro               dw   $00000e3f              (38x40)
   1923   DPCT   macro               dw   $00000e7f              (39x40)
   1924   INTPL  macro               dw   $00000ebf              (3Ax40)
   1925   NCS    macro               dw   $00000f7f              (3Dx40)
   1926   NCT    macro               dw   $00000fbf              (3Ex40)
   1927   NCDS   macro               dw   $00000fff              (3Fx40)
   1928   NCDT   macro               dw   $0000103f              (40x40)
   1929   NCCS   macro               dw   $0000107f              (41x40)
   1930   NCCT   macro               dw   $000010bf              (42x40)
   1931   CDP    macro               dw   $000010ff              (43x40)
   1932   CC     macro               dw   $0000113f              (44x40)
   1933   NCLIP  macro               dw   $0000117f              (45x40)
   1934   AVSZ3  macro               dw   $000011bf              (46x40)
   1935   AVSZ4  macro               dw   $000011ff              (47x40)
   1936   MVMVA  macro sf,mx,v,cv,lm dw   $000013bf|sf<<25|mx<<23|v<<21|cv<<19|lm<<18
   1937   SQR    macro sf            dw   $000013ff|sf<<25       (4Fx40)
   1938   OP     macro sf            dw   $0000143f|sf<<25       (50x40)
   1939   GPF    macro sf            dw   $0000147f|sf<<25       (51x40)
   1940   GPL    macro sf            dw   $000014bf|sf<<25       (52x40)
   1941 "Be warned that the DWORD codes are actually not GTE cop2 instructions. The way
   1942 you deal with them in the official SDK is that you'd run the compiled object
   1943 file of your assembly source that uses said macros through DMPSX which
   1944 translates those DWORD codes into the correct GTE cop2 instructions. I don't
   1945 know why Sony made it this way."
   1946 
   1947 Additional Functions
   1948 The LZCS/LZCR registers offer a Count-Leading-Zeroes/Leading-Ones function.
   1949 The IRGB/ORGB registers allow to convert between 48bit and 15bit RGB colors.
   1950 These registers work without needing to send any COP2 commands. However, unlike
   1951 for commands (which do automatically halt the CPU when needed), one must insert
   1952 dummy opcodes between writing and reading the registers.
   1953 
   1954 GTE Coordinate Calculation Commands
   1955 -----------------------------------
   1956 
   1957 COP2 0180001h - 15 Cycles - RTPS - Perspective Transformation (single)
   1958 COP2 0280030h - 23 Cycles - RTPT - Perspective Transformation (triple)
   1959 RTPS performs final Rotate, translate and perspective transformation on vertex
   1960 V0. Before writing to the FIFOs, the older entries are moved one stage down.
   1961 RTPT is same as RTPS, but repeats for V1 and V2. The "sf" bit should be usually
   1962 set.
   1963   IR1 = MAC1 = (TRX*1000h + RT11*VX0 + RT12*VY0 + RT13*VZ0) SAR (sf*12)
   1964   IR2 = MAC2 = (TRY*1000h + RT21*VX0 + RT22*VY0 + RT23*VZ0) SAR (sf*12)
   1965   IR3 = MAC3 = (TRZ*1000h + RT31*VX0 + RT32*VY0 + RT33*VZ0) SAR (sf*12)
   1966   SZ3 = MAC3 SAR ((1-sf)*12)                           ;ScreenZ FIFO 0..+FFFFh
   1967   MAC0=(((H*20000h/SZ3)+1)/2)*IR1+OFX, SX2=MAC0/10000h ;ScrX FIFO -400h..+3FFh
   1968   MAC0=(((H*20000h/SZ3)+1)/2)*IR2+OFY, SY2=MAC0/10000h ;ScrY FIFO -400h..+3FFh
   1969   MAC0=(((H*20000h/SZ3)+1)/2)*DQA+DQB, IR0=MAC0/1000h  ;Depth cueing 0..+1000h
   1970 If the result of the "(((H*20000h/SZ3)+1)/2)" division is greater than 1FFFFh,
   1971 then the division result is saturated to +1FFFFh, and the divide overflow bit
   1972 in the FLAG register gets set; that happens if the vertex is exceeding the
   1973 "near clip plane", ie. if it is very close to the camera (SZ3<=H/2), exactly at
   1974 the camara position (SZ3=0), or behind the camera (negative Z coordinates are
   1975 saturated to SZ3=0). For details on the division, see:
   1976 --> GTE Division Inaccuracy
   1977 For "far plane clipping", one can use the SZ3 saturation flag (MaxZ=FFFFh), or
   1978 the IR3 saturation flag (MaxZ=7FFFh) (eg. used by Wipeout 2097), or one can
   1979 compare the SZ3 value with any desired MaxZ value by software.
   1980 Note: The command does saturate IR1,IR2,IR3 to -8000h..+7FFFh (regardless of lm
   1981 bit). When using RTP with sf=0, then the IR3 saturation flag (FLAG.22) gets set
   1982 <only> if "MAC3 SAR 12" exceeds -8000h..+7FFFh (although IR3 is saturated when
   1983 "MAC3" exceeds -8000h..+7FFFh).
   1984 
   1985 COP2 1400006h - 8 Cycles - NCLIP - Normal clipping
   1986   MAC0 =   SX0*SY1 + SX1*SY2 + SX2*SY0 - SX0*SY2 - SX1*SY0 - SX2*SY1
   1987 The sign of the result indicates whether the polygon coordinates are arranged
   1988 clockwise or anticlockwise (ie. whether the front side or backside is visible).
   1989 If the result is zero, then it's neither one (ie. the vertices are all arranged
   1990 in a straight line). Note: The GPU probably renders straight lines as invisble
   1991 0 pixel width lines?
   1992 
   1993 COP2 158002Dh - 5 Cycles - AVSZ3 - Average of three Z values (for Triangles)
   1994 COP2 168002Eh - 6 Cycles - AVSZ4 - Average of four Z values (for Quads)
   1995   MAC0 =  ZSF3*(SZ1+SZ2+SZ3)       ;for AVSZ3
   1996   MAC0 =  ZSF4*(SZ0+SZ1+SZ2+SZ3)   ;for AVSZ4
   1997   OTZ  =  MAC0/1000h               ;for both (saturated to 0..FFFFh)
   1998 Adds three or four Z values together and multplies them by a fixed point value.
   1999 The result can be used as index in the GPU's Ordering Table (OT).
   2000 --> GPU Depth Ordering
   2001 The scaling factors would be usually ZSF3=N/30h and ZSF4=N/40h, where "N" is
   2002 the number of entries in the OT (max 10000h). SZn and OTZ are unsigned 16bit
   2003 values, for whatever reason ZSFn registers are signed 16bit values (negative
   2004 values would allow a negative result in MAC0, but would saturate OTZ to zero).
   2005 
   2006 GTE General Purpose Calculation Commands
   2007 ----------------------------------------
   2008 
   2009 COP2 0400012h - 8 Cycles - MVMVA(sf,mx,v,cv,lm)
   2010 Multiply vector by matrix and vector addition.
   2011   Mx = matrix specified by mx  ;RT/LLM/LCM - Rotation, light or color matrix
   2012   Vx = vector specified by v   ;V0, V1, V2, or [IR1,IR2,IR3]
   2013   Tx = translation vector specified by cv  ;TR or BK or Bugged/FC, or None
   2014 Calculation:
   2015   MAC1 = (Tx1*1000h + Mx11*Vx1 + Mx12*Vx2 + Mx13*Vx3) SAR (sf*12)
   2016   MAC2 = (Tx2*1000h + Mx21*Vx1 + Mx22*Vx2 + Mx23*Vx3) SAR (sf*12)
   2017   MAC3 = (Tx3*1000h + Mx31*Vx1 + Mx32*Vx2 + Mx33*Vx3) SAR (sf*12)
   2018   [IR1,IR2,IR3] = [MAC1,MAC2,MAC3]
   2019 Multiplies a vector with either the rotation matrix, the light matrix or the
   2020 color matrix and then adds the translation vector or background color vector.
   2021 The GTE also allows selection of the far color vector (FC), but this vector is
   2022 not added correctly by the hardware: The return values are reduced to the last
   2023 portion of the formula, ie. MAC1=(Mx13*Vx3) SAR (sf*12), and similar for MAC2
   2024 and MAC3, nethertheless, some bits in the FLAG register seem to be adjusted as
   2025 if the full operation would have been executed. Setting Mx=3 selects a garbage
   2026 matrix (with elements -60h, +60h, IR0, RT13, RT13, RT13, RT22, RT22, RT22).
   2027 
   2028 COP2 0A00428h+sf*80000h - 5 Cycles - SQR(sf) - Square vector
   2029   [MAC1,MAC2,MAC3] = [IR1*IR1,IR2*IR2,IR3*IR3] SHR (sf*12)
   2030   [IR1,IR2,IR3]    = [MAC1,MAC2,MAC3]    ;IR1,IR2,IR3 saturated to max 7FFFh
   2031 Calculates the square of a vector. The result is, of course, always positive,
   2032 so the "lm" flag for negative saturation has no effect.
   2033 
   2034 COP2 170000Ch+sf*80000h - 6 Cycles - OP(sf,lm) - Outer product of 2 vectors
   2035   [MAC1,MAC2,MAC3] = [IR3*D2-IR2*D3, IR1*D3-IR3*D1, IR2*D1-IR1*D2] SAR (sf*12)
   2036   [IR1,IR2,IR3]    = [MAC1,MAC2,MAC3]                        ;copy result
   2037 Calculates the outer product of two signed 16bit vectors. Note: D1,D2,D3 are
   2038 meant to be the RT11,RT22,RT33 elements of the RT matrix "misused" as vector.
   2039 lm should be usually zero.
   2040 
   2041 LZCS/LZCR registers - ? Cycles - Count-Leading-Zeroes/Leading-Ones
   2042 The LZCS/LZCR registers offer a Count-Leading-Zeroes/Leading-Ones function.
   2043 
   2044 GTE Color Calculation Commands
   2045 ------------------------------
   2046 
   2047 COP2 0C8041Eh - 14 Cycles - NCS - Normal color (single)
   2048 COP2 0D80420h - 30 Cycles - NCT - Normal color (triple)
   2049 COP2 108041Bh - 17 Cycles - NCCS - Normal Color Color (single vector)
   2050 COP2 118043Fh - 39 Cycles - NCCT - Normal Color Color (triple vector)
   2051 COP2 0E80413h - 19 Cycles - NCDS - Normal color depth cue (single vector)
   2052 COP2 0F80416h - 44 Cycles - NCDT - Normal color depth cue (triple vectors)
   2053 In: V0=Normal vector (for triple variants repeated with V1 and V2),
   2054 BK=Background color, RGBC=Primary color/code, LLM=Light matrix, LCM=Color
   2055 matrix, IR0=Interpolation value.
   2056   [IR1,IR2,IR3] = [MAC1,MAC2,MAC3] = (LLM*V0) SAR (sf*12)
   2057   [IR1,IR2,IR3] = [MAC1,MAC2,MAC3] = (BK*1000h + LCM*IR) SAR (sf*12)
   2058   [MAC1,MAC2,MAC3] = [R*IR1,G*IR2,B*IR3] SHL 4          ;<--- for NCDx/NCCx
   2059   [MAC1,MAC2,MAC3] = MAC+(FC-MAC)*IR0                   ;<--- for NCDx only
   2060   [MAC1,MAC2,MAC3] = [MAC1,MAC2,MAC3] SAR (sf*12)       ;<--- for NCDx/NCCx
   2061   Color FIFO = [MAC1/16,MAC2/16,MAC3/16,CODE], [IR1,IR2,IR3] = [MAC1,MAC2,MAC3]
   2062 
   2063 COP2 138041Ch - 11 Cycles - CC(lm=1) - Color Color
   2064 COP2 1280414h - 13 Cycles - CDP(...) - Color Depth Que
   2065 In: [IR1,IR2,IR3]=Vector, RGBC=Primary color/code, LCM=Color matrix,
   2066 BK=Background color, and, for CDP, IR0=Interpolation value, FC=Far color.
   2067   [IR1,IR2,IR3] = [MAC1,MAC2,MAC3] = (BK*1000h + LCM*IR) SAR (sf*12)
   2068   [MAC1,MAC2,MAC3] = [R*IR1,G*IR2,B*IR3] SHL 4
   2069   [MAC1,MAC2,MAC3] = MAC+(FC-MAC)*IR0                   ;<--- for CDP only
   2070   [MAC1,MAC2,MAC3] = [MAC1,MAC2,MAC3] SAR (sf*12)
   2071   Color FIFO = [MAC1/16,MAC2/16,MAC3/16,CODE], [IR1,IR2,IR3] = [MAC1,MAC2,MAC3]
   2072 
   2073 COP2 0680029h - 8 Cycles - DCPL - Depth Cue Color light
   2074 COP2 0780010h - 8 Cycles - DPCS - Depth Cueing (single)
   2075 COP2 0x8002Ah - 17 Cycles - DPCT - Depth Cueing (triple)
   2076 COP2 0980011h - 8 Cycles - INTPL - Interpolation of a vector and far color
   2077 In: [IR1,IR2,IR3]=Vector, FC=Far Color, IR0=Interpolation value, CODE=MSB of
   2078 RGBC, and, for DCPL, R,G,B=LSBs of RGBC.
   2079   [MAC1,MAC2,MAC3] = [R*IR1,G*IR2,B*IR3] SHL 4          ;<--- for DCPL only
   2080   [MAC1,MAC2,MAC3] = [IR1,IR2,IR3] SHL 12               ;<--- for INTPL only
   2081   [MAC1,MAC2,MAC3] = [R,G,B] SHL 16                     ;<--- for DPCS/DPCT
   2082   [MAC1,MAC2,MAC3] = MAC+(FC-MAC)*IR0
   2083   [MAC1,MAC2,MAC3] = [MAC1,MAC2,MAC3] SAR (sf*12)
   2084   Color FIFO = [MAC1/16,MAC2/16,MAC3/16,CODE], [IR1,IR2,IR3] = [MAC1,MAC2,MAC3]
   2085 DPCT executes thrice, and reads the R,G,B values from RGB0 (ie. reads from the
   2086 Bottom of the Color FIFO, instead of from the RGBC register) (the CODE value is
   2087 kept read from RGBC as usually), so, after DPCT execution, the RGB0,RGB1,RGB2
   2088 Fifo entries are modified.
   2089 
   2090 COP2 190003Dh - 5 Cycles - GPF(sf,lm) - General purpose Interpolation
   2091 COP2 1A0003Eh - 5 Cycles - GPL(sf,?) - General Interpolation with base
   2092   [MAC1,MAC2,MAC3] = [0,0,0]                            ;<--- for GPF only
   2093   [MAC1,MAC2,MAC3] = [MAC1,MAC2,MAC3] SHL (sf*12)       ;<--- for GPL only
   2094   [MAC1,MAC2,MAC3] = (([IR1,IR2,IR3] * IR0) + [MAC1,MAC2,MAC3]) SAR (sf*12)
   2095   Color FIFO = [MAC1/16,MAC2/16,MAC3/16,CODE], [IR1,IR2,IR3] = [MAC1,MAC2,MAC3]
   2096 Note: Although the SHL in GPL is theoretically undone by the SAR, 44bit
   2097 overflows can occur internally when sf=1.
   2098 
   2099 Details on "MAC+(FC-MAC)*IR0"
   2100   [IR1,IR2,IR3] = (([RFC,GFC,BFC] SHL 12) - [MAC1,MAC2,MAC3]) SAR (sf*12)
   2101   [MAC1,MAC2,MAC3] = (([IR1,IR2,IR3] * IR0) + [MAC1,MAC2,MAC3])
   2102 Note: Above "[IR1,IR2,IR3]=(FC-MAC)" is saturated to -8000h..+7FFFh (ie. as if
   2103 lm=0), anyways, further writes to [IR1,IR2,IR3] (within the same command) are
   2104 saturated as usually (ie. depending on lm setting).
   2105 
   2106 Details on "(LLM*V0) SAR (sf*12)" and "(BK*1000h + LCM*IR) SAR (sf*12)"
   2107 Works like MVMVA command (see there), but with fixed Tx/Vx/Mx parameters, the
   2108 sf/lm bits can be changed and do affect the results (although normally both
   2109 bits should be set for use with color matrices).
   2110 
   2111 Notes
   2112 The 8bit RGB values written to the top of Color Fifo are the 32bit MACn values
   2113 divided by 16, and saturated to +00h..+FFh, and of course, the older Fifo
   2114 entries are moved downwards. Note that, at the GPU side, the meaning of the RGB
   2115 values depends on whether or not texture blending is used (for untextured
   2116 polygons FFh is max brightness) (for texture blending FFh is double brightness
   2117 and 80h is normal brightness).
   2118 The 8bit CODE value is intended to contain a GP0(20h..7Fh) Rendering command,
   2119 allowing to automatically merge the 8bit command number, with the 24bit color
   2120 value.
   2121 The IRGB/ORGB registers allow to convert between 48bit and 15bit RGB colors.
   2122 Although the result of the commands in this chapter is written to the Color
   2123 FIFO, some commands like GPF/GPL may be also used for other purposes (eg. to
   2124 scale or scale/translate single vertices).
   2125 
   2126 GTE Division Inaccuracy
   2127 -----------------------
   2128 
   2129 GTE Division Inaccuracy (for RTPS/RTPT commands)
   2130 Basically, the GTE division does (attempt to) work as so (using 33bit maths):
   2131   n = (((H*20000h/SZ3)+1)/2)
   2132 alternatly, below would give (almost) the same result (using 32bit maths):
   2133   n = ((H*10000h+SZ3/2)/SZ3)
   2134 in both cases, the result is saturated about as so:
   2135   if n>1FFFFh or division_by_zero then n=1FFFFh, FLAG.Bit17=1, FLAG.Bit31=1
   2136 However, the real GTE hardware is using a fast, but less accurate division
   2137 mechanism (based on Unsigned Newton-Raphson (UNR) algorithm):
   2138   if (H < SZ3*2) then                            ;check if overflow
   2139     z = count_leading_zeroes(SZ3)                ;z=0..0Fh (for 16bit SZ3)
   2140     n = (H SHL z)                                ;n=0..7FFF8000h
   2141     d = (SZ3 SHL z)                              ;d=8000h..FFFFh
   2142     u = unr_table[(d-7FC0h) SHR 7] + 101h        ;u=200h..101h
   2143     d = ((2000080h - (d * u)) SHR 8)             ;d=10000h..0FF01h
   2144     d = ((0000080h + (d * u)) SHR 8)             ;d=20000h..10000h
   2145     n = min(1FFFFh, (((n*d) + 8000h) SHR 16))    ;n=0..1FFFFh
   2146   else n = 1FFFFh, FLAG.Bit17=1, FLAG.Bit31=1    ;n=1FFFFh plus overflow flag
   2147 the GTE's unr_table[000h..100h] consists of following values:
   2148   FFh,FDh,FBh,F9h,F7h,F5h,F3h,F1h,EFh,EEh,ECh,EAh,E8h,E6h,E4h,E3h ;\
   2149   E1h,DFh,DDh,DCh,DAh,D8h,D6h,D5h,D3h,D1h,D0h,CEh,CDh,CBh,C9h,C8h ; 00h..3Fh
   2150   C6h,C5h,C3h,C1h,C0h,BEh,BDh,BBh,BAh,B8h,B7h,B5h,B4h,B2h,B1h,B0h ;
   2151   AEh,ADh,ABh,AAh,A9h,A7h,A6h,A4h,A3h,A2h,A0h,9Fh,9Eh,9Ch,9Bh,9Ah ;/
   2152   99h,97h,96h,95h,94h,92h,91h,90h,8Fh,8Dh,8Ch,8Bh,8Ah,89h,87h,86h ;\
   2153   85h,84h,83h,82h,81h,7Fh,7Eh,7Dh,7Ch,7Bh,7Ah,79h,78h,77h,75h,74h ; 40h..7Fh
   2154   73h,72h,71h,70h,6Fh,6Eh,6Dh,6Ch,6Bh,6Ah,69h,68h,67h,66h,65h,64h ;
   2155   63h,62h,61h,60h,5Fh,5Eh,5Dh,5Dh,5Ch,5Bh,5Ah,59h,58h,57h,56h,55h ;/
   2156   54h,53h,53h,52h,51h,50h,4Fh,4Eh,4Dh,4Dh,4Ch,4Bh,4Ah,49h,48h,48h ;\
   2157   47h,46h,45h,44h,43h,43h,42h,41h,40h,3Fh,3Fh,3Eh,3Dh,3Ch,3Ch,3Bh ; 80h..BFh
   2158   3Ah,39h,39h,38h,37h,36h,36h,35h,34h,33h,33h,32h,31h,31h,30h,2Fh ;
   2159   2Eh,2Eh,2Dh,2Ch,2Ch,2Bh,2Ah,2Ah,29h,28h,28h,27h,26h,26h,25h,24h ;/
   2160   24h,23h,22h,22h,21h,20h,20h,1Fh,1Eh,1Eh,1Dh,1Dh,1Ch,1Bh,1Bh,1Ah ;\
   2161   19h,19h,18h,18h,17h,16h,16h,15h,15h,14h,14h,13h,12h,12h,11h,11h ; C0h..FFh
   2162   10h,0Fh,0Fh,0Eh,0Eh,0Dh,0Dh,0Ch,0Ch,0Bh,0Ah,0Ah,09h,09h,08h,08h ;
   2163   07h,07h,06h,06h,05h,05h,04h,04h,03h,03h,02h,02h,01h,01h,00h,00h ;/
   2164   00h    ;<-- one extra table entry (for "(d-7FC0h)/80h"=100h)    ;-100h
   2165 Above can be generated as "unr_table[i]=min(0,(40000h/(i+100h)+1)/2-101h)".
   2166 Some special cases: NNNNh/0001h uses a big multiplier (d=20000h), in practice,
   2167 this can occur only for 0000h/0001h and 0001h/0001h (due to the H<SZ3*2
   2168 overflow check).
   2169 The min(1FFFFh) limit is needed for cases like FE3Fh/7F20h, F015h/780Bh, etc.
   2170 (these do produce UNR result 20000h, and are saturated to 1FFFFh, but without
   2171 setting overflow FLAG bits).
   2172 
   2173 Macroblock Decoder (MDEC)
   2174 -------------------------
   2175 
   2176 The MDEC is a JPEG-style Macroblock Decoder, that can decompress pictures (or a
   2177 series of pictures, for being displayed as a movie).
   2178 
   2179 --> MDEC I/O Ports
   2180 --> MDEC Commands
   2181 --> MDEC Decompression
   2182 --> MDEC Data Format
   2183 
   2184 MDEC I/O Ports
   2185 --------------
   2186 
   2187 1F801820h - MDEC0 - MDEC Command/Parameter Register (W)
   2188   31-0  Command or Parameters
   2189 Used to send command word, followed by parameter words to the MDEC (usually,
   2190 only the command word is written to this register, and the parameter words are
   2191 transferred via DMA0).
   2192 
   2193 1F801820h.Read - MDEC Data/Response Register (R)
   2194   31-0  Macroblock Data (or Garbage if there's no data available)
   2195 The data is always output as a 8x8 pixel bitmap, so, when manually reading from
   2196 this register and using colored 16x16 pixel macroblocks, the data from four 8x8
   2197 blocks must be re-ordered accordingly (usually, the data is received via DMA1,
   2198 which is doing the re-ordering automatically). For monochrome 8x8 macroblocks,
   2199 no re-ordering is needed (that works with DMA1, too).
   2200 
   2201 1F801824h - MDEC1 - MDEC Status Register (R)
   2202   31    Data-Out Fifo Empty (0=No, 1=Empty)
   2203   30    Data-In Fifo Full   (0=No, 1=Full, or Last word received)
   2204   29    Command Busy  (0=Ready, 1=Busy receiving or processing parameters)
   2205   28    Data-In Request  (set when DMA0 enabled and ready to receive data)
   2206   27    Data-Out Request (set when DMA1 enabled and ready to send data)
   2207   26-25 Data Output Depth  (0=4bit, 1=8bit, 2=24bit, 3=15bit)      ;CMD.28-27
   2208   24    Data Output Signed (0=Unsigned, 1=Signed)                  ;CMD.26
   2209   23    Data Output Bit15  (0=Clear, 1=Set) (for 15bit depth only) ;CMD.25
   2210   22-19 Not used (seems to be always zero)
   2211   18-16 Current Block (0..3=Y1..Y4, 4=Cr, 5=Cb) (or for mono: always 4=Y)
   2212   15-0  Number of Parameter Words remaining minus 1  (FFFFh=None)  ;CMD.Bit0-15
   2213 If there's data in the output fifo, then the Current Block bits are always set
   2214 to the current output block number (ie. Y1..Y4; or Y for mono) (this
   2215 information is apparently passed to the DMA1 controller, so that it knows if
   2216 and how it must re-order the data in RAM). If the output fifo is empty, then
   2217 the bits indicate the currently processsed incoming block (ie. Cr,Cb,Y1..Y4; or
   2218 Y for mono).
   2219 
   2220 1F801824h - MDEC1 - MDEC Control/Reset Register (W)
   2221   31    Reset MDEC (0=No change, 1=Abort any command, and set status=80040000h)
   2222   30    Enable Data-In Request  (0=Disable, 1=Enable DMA0 and Status.bit28)
   2223   29    Enable Data-Out Request (0=Disable, 1=Enable DMA1 and Status.bit27)
   2224   28-0  Unknown/Not used - usually zero
   2225 The data requests are required to be enabled for using DMA (and for reading the
   2226 request status flags by software). The Data-Out request acts a bit strange: It
   2227 gets set when a block is available, but, it gets cleared after reading the
   2228 first some words of that block (nethertheless, one can keep reading the whole
   2229 block, until the fifo-empty flag gets set).
   2230 
   2231 DMA
   2232 MDEC decompression uses a lot of DMA channels (and CPU processing):
   2233   1) DMA3 (CDROM)    to send Huffman compressed data from CDROM to RAM
   2234   2) CPU  (MIPS)     to convert Huffman bitstream to 16bit MDEC RLE values
   2235   3) DMA0 (MDEC.In)  to send MDEC compressed data from RAM to MDEC
   2236   4) DMA1 (MDEC.Out) to send uncompressed macroblocks from MDEC to RAM
   2237   5) DMA2 (GPU)      to send uncompressed macroblocks from RAM to GPU
   2238 DMA0 and DMA1 should be usually used with a blocksize of 20h words. If
   2239 necessary, the parameters for the MDEC(1) command should be padded with FE00h
   2240 halfwords to match the 20h words (40h halfwords) DMA blocksize.
   2241 
   2242 MDEC Commands
   2243 -------------
   2244 
   2245 MDEC(1) - Decode Macroblock(s)
   2246   31-29 Command (1=decode_macroblock)
   2247   28-27 Data Output Depth  (0=4bit, 1=8bit, 2=24bit, 3=15bit)      ;STAT.26-25
   2248   26    Data Output Signed (0=Unsigned, 1=Signed)                  ;STAT.24
   2249   25    Data Output Bit15  (0=Clear, 1=Set) (for 15bit depth only) ;STAT.23
   2250   24-16 Not used (should be zero)
   2251   15-0  Number of Parameter Words (size of compressed data)
   2252 This command is followed by one or more Macroblock parameters (usually, all
   2253 macroblocks for the whole image are sent at once).
   2254 
   2255 MDEC(2) - Set Quant Table(s)
   2256   31-29 Command (2=set_iqtab)
   2257   28-1  Not used (should be zero)  ;Bit25-28 are copied to STAT.23-26 though
   2258   0     Color   (0=Luminance only, 1=Luminance and Color)
   2259 The command word is followed by 64 unsigned parameter bytes for the Luminance
   2260 Quant Table (used for Y1..Y4), and if Command.Bit0 was set, by another 64
   2261 unsigned parameter bytes for the Color Quant Table (used for Cr and Cb).
   2262 
   2263 MDEC(3) - Set Scale Table
   2264   31-29 Command (3=set_scale)
   2265   28-0  Not used (should be zero)  ;Bit25-28 are copied to STAT.23-26 though
   2266 The command is followed by 64 signed halfwords with 14bit fractional part, the
   2267 values should be usually/always the same values (based on the standard JPEG
   2268 constants, although, MDEC(3) allows to use other values than that constants).
   2269 
   2270 MDEC(0) - No function
   2271 This command has no function. Command bits 25-28 are reflected to Status bits
   2272 23-26 as usually. Command bits 0-15 are reflected to Status bits 0-15 (similar
   2273 as the "number of parameter words" for MDEC(1), but without the "minus 1"
   2274 effect, and without actually expecting any parameters).
   2275 
   2276 MDEC(4..7) - Invalid
   2277 These commands act identical as MDEC(0).
   2278 
   2279 MDEC Decompression
   2280 ------------------
   2281 
   2282 decode_colored_macroblock ;MDEC(1) command (at 15bpp or 24bpp depth)
   2283   rl_decode_block(Crblk,src,iq_uv)                 ;Cr (low resolution)
   2284   rl_decode_block(Cbblk,src,iq_uv)                 ;Cb (low resolution)
   2285   rl_decode_block(Yblk,src,iq_y), yuv_to_rgb(0,0)  ;Y1 (and upper-left Cr,Cb)
   2286   rl_decode_block(Yblk,src,iq_y), yuv_to_rgb(0,8)  ;Y2 (and upper-right Cr,Cb)
   2287   rl_decode_block(Yblk,src,iq_y), yuv_to_rgb(8,0)  ;Y3 (and lower-left Cr,Cb)
   2288   rl_decode_block(Yblk,src,iq_y), yuv_to_rgb(8,8)  ;Y4 (and lower-right Cr,Cb)
   2289 
   2290 decode_monochrome_macroblock ;MDEC(1) command (at 4bpp or 8bpp depth)
   2291   rl_decode_block(Yblk,src,iq_y), y_to_mono        ;Y
   2292 
   2293 rl_decode_block(blk,src,qt)
   2294   for i=0 to 63, blk[i]=0, next i   ;initially zerofill all entries (for skip)
   2295  @@skip:
   2296   n=[src], src=src+2, k=0           ;get first entry, init dest addr k=0
   2297   if n=FE00h then @@skip            ;ignore padding (FE00h as first halfword)
   2298   q_scale=(n SHR 10) AND 3Fh        ;contains scale value (not "skip" value)
   2299   val=signed10bit(n AND 3FFh)*qt[k] ;calc first value (without q_scale/8) (?)
   2300  @@lop:
   2301   if q_scale=0 then val=signed10bit(n AND 3FFh)*2   ;special mode without qt[k]
   2302   val=minmax(val,-400h,+3FFh)            ;saturate to signed 11bit range
   2303   val=val*scalezag[i]                    ;<-- for "fast_idct_core" only
   2304   if q_scale>0 then blk[zagzig[k]]=val   ;store entry (normal case)
   2305   if q_scale=0 then blk[k]=val           ;store entry (special, no zigzag)
   2306   n=[src], src=src+2                     ;get next entry (or FE00h end code)
   2307   k=k+((n SHR 10) AND 3Fh)+1             ;skip zerofilled entries
   2308   val=(signed10bit(n AND 3FFh)*qt[k]*q_scale+4)/8  ;calc value for next entry
   2309   if k<=63 then jump @@lop          ;should end with n=FE00h (that sets k>63)
   2310   idct_core(blk)
   2311   return (with "src" address advanced)
   2312 
   2313 fast_idct_core(blk) ;fast "idct_core" version
   2314 Fast code with only 80 multiplications, works only if the scaletable from
   2315 MDEC(3) command contains standard values (which is the case for all known PSX
   2316 games).
   2317   src=blk, dst=temp_buffer
   2318   for pass=0 to 1
   2319     for i=0 to 7
   2320       if src[(1..7)*8+i]=0 then      ;when src[(1..7)*8+i] are all zero:
   2321         dst[i*8+(0..7)]=src[0*8+i]   ;quick fill by src[0*8+i]
   2322       else
   2323         z10=src[0*8+i]+src[4*8+i], z11=src[0*8+i]-src[4*8+i]
   2324         z13=src[2*8+i]+src[6*8+i], z12=src[2*8+i]-src[6*8+i]
   2325         z12=(1.414213562*z12)-z13          ;=sqrt(2)
   2326         tmp0=z10+z13, tmp3=z10-z13, tmp1=z11+z12, tmp2=z11-z12
   2327         z13=src[3*8+i]+src[5*8+i], z10=src[3*8+i]-src[5*8+i]
   2328         z11=src[1*8+i]+src[7*8+i], z12=src[1*8+i]-src[7*8+i]
   2329         z5  =(1.847759065*(z12-z10))       ;=sqrt(2)*scalefactor[2]
   2330         tmp7=z11+z13
   2331         tmp6=(2.613125930*(z10))+z5-tmp7   ;=scalefactor[2]*2
   2332         tmp5=(1.414213562*(z11-z13))-tmp6  ;=sqrt(2)
   2333         tmp4=(1.082392200*(z12))-z5+tmp5   ;=sqrt(2)/scalefactor[2]
   2334         dst[i*8+0]=tmp0+tmp7, dst[i*8+7]=tmp0-tmp7
   2335         dst[i*8+1]=tmp1+tmp6, dst[i*8+6]=tmp1-tmp6
   2336         dst[i*8+2]=tmp2+tmp5, dst[i*8+5]=tmp2-tmp5
   2337         dst[i*8+4]=tmp3+tmp4, dst[i*8+3]=tmp3-tmp4
   2338       endif
   2339     next i
   2340     swap(src,dst)
   2341   next pass
   2342 
   2343 real_idct_core(blk) ;low level "idct_core" version
   2344 Low level code with 1024 multiplications, using the scaletable from the MDEC(3)
   2345 command. Computes dst=src*scaletable (using normal matrix maths, but with "src"
   2346 being diagonally mirrored, ie. the matrices are processed column by column,
   2347 instead of row by column), repeated with src/dst exchanged.
   2348   src=blk, dst=temp_buffer
   2349   for pass=0 to 1
   2350     for x=0 to 7
   2351       for y=0 to 7
   2352         sum=0
   2353         for z=0 to 7
   2354           sum=sum+src[y+z*8]*(scaletable[x+z*8]/8)
   2355         next z
   2356         dst[x+y*8]=(sum+0fffh)/2000h               ;<-- or so?
   2357       next y
   2358     next x
   2359     swap(src,dst)
   2360   next pass
   2361 The "(sum+0fffh)/2000h" part is meant to strip fractional bits, and to round-up
   2362 the result if the fraction was BIGGER than 0.5. The hardware appears to be
   2363 working roughly like that, still the results aren't perfect.
   2364 Maybe the real hardware is doing further roundings in other places, possibly
   2365 stripping some fractional bits before summing up "sum", possibly stripping
   2366 different amounts of bits in the two "pass" cycles, and possibly keeping a
   2367 final fraction passed on to the y_to_mono stage.
   2368 
   2369 yuv_to_rgb(xx,yy)
   2370   for y=0 to 7
   2371     for x=0 to 7
   2372       R=[Crblk+((x+xx)/2)+((y+yy)/2)*8], B=[Cbblk+((x+xx)/2)+((y+yy)/2)*8]
   2373       G=(-0.3437*B)+(-0.7143*R), R=(1.402*R), B=(1.772*B)
   2374       Y=[Yblk+(x)+(y)*8]
   2375       R=MinMax(-128,127,(Y+R))
   2376       G=MinMax(-128,127,(Y+G))
   2377       B=MinMax(-128,127,(Y+B))
   2378       if unsigned then BGR=BGR xor 808080h  ;aka add 128 to the R,G,B values
   2379       dst[(x+xx)+(y+yy)*16]=BGR
   2380     next x
   2381   next y
   2382 Note: The exact fixed point resolution for "yuv_to_rgb" is unknown. And,
   2383 there's probably also some 9bit limit (similar as in "y_to_mono").
   2384 
   2385 y_to_mono
   2386   for i=0 to 63
   2387     Y=[Yblk+i]
   2388     Y=Y AND 1FFh                  ;clip to signed 9bit range
   2389     Y=MinMax(-128,127,Y)          ;saturate from 9bit to signed 8bit range
   2390     if unsigned then Y=Y xor 80h  ;aka add 128 to the Y value
   2391     dst[i]=Y
   2392   next i
   2393 
   2394 set_iqtab  ;MDEC(2) command
   2395   iqtab_core(iq_y,src), src=src+64       ;luminance quant table
   2396   if command_word.bit0=1
   2397     iqtab_core(iq_uv,src), src=src+64    ;color quant table (optional)
   2398   endif
   2399 
   2400 iqtab_core(iq,src)  ;src = 64 unsigned paramter bytes
   2401   for i=0 to 63, iq[i]=src[i], next i
   2402 Note: For "fast_idct_core" one could precalc "iq[i]=src[i]*scalezag[i]", but
   2403 that would conflict with the RLE saturation/rounding steps (though those steps
   2404 aren't actually required, so a very-fast decoder could omit them).
   2405 
   2406 scalefactor[0..7] = cos((0..7)*90'/8)  ;for [1..7]: multiplied by sqrt(2)
   2407   1.000000000, 1.387039845, 1.306562965, 1.175875602,
   2408   1.000000000, 0.785694958, 0.541196100, 0.275899379
   2409 
   2410 zigzag[0..63] =
   2411   0 ,1 ,5 ,6 ,14,15,27,28,
   2412   2 ,4 ,7 ,13,16,26,29,42,
   2413   3 ,8 ,12,17,25,30,41,43,
   2414   9 ,11,18,24,31,40,44,53,
   2415   10,19,23,32,39,45,52,54,
   2416   20,22,33,38,46,51,55,60,
   2417   21,34,37,47,50,56,59,61,
   2418   35,36,48,49,57,58,62,63
   2419 
   2420 scalezag[0..63] (precalulated factors, for "fast_idct_core")
   2421   for y=0 to 7
   2422    for x=0 to 7
   2423     scalezag[zigzag[x+y*8]] = scalefactor[x] * scalefactor[y] / 8
   2424    next x
   2425   next y
   2426 
   2427 zagzig[0..63] (reversed zigzag table)
   2428   for i=0 to 63, zagzig[zigzag[i]]=i, next i
   2429 
   2430 set_quant_table:  ;MDEC(2) command
   2431 This command defines the quant tables, there are two tables (one for luminance
   2432 and one for chroma). For STR movies and BS pictures both 64-byte tables should
   2433 be almost always set to following 64 bytes:
   2434   02h,10h,10h,13h,10h,13h,16h,16h
   2435   16h,16h,16h,16h,1Ah,18h,1Ah,1Bh
   2436   1Bh,1Bh,1Ah,1Ah,1Ah,1Ah,1Bh,1Bh
   2437   1Bh,1Dh,1Dh,1Dh,22h,22h,22h,1Dh
   2438   1Dh,1Dh,1Bh,1Bh,1Dh,1Dh,20h,20h
   2439   22h,22h,25h,26h,25h,23h,23h,22h
   2440   23h,26h,26h,28h,28h,28h,30h,30h
   2441   2Eh,2Eh,38h,38h,3Ah,45h,45h,53h
   2442 Note: The exception are BS fraquant movies in X-Files and Eagle One (these do
   2443 also use the above values, but do have them multiplied with a fixed point
   2444 number).
   2445 
   2446 set_scale_table:  ;MDEC(3) command
   2447 This command defines the IDCT scale matrix, which should be usually/always:
   2448   5A82 5A82 5A82 5A82 5A82 5A82 5A82 5A82
   2449   7D8A 6A6D 471C 18F8 E707 B8E3 9592 8275
   2450   7641 30FB CF04 89BE 89BE CF04 30FB 7641
   2451   6A6D E707 8275 B8E3 471C 7D8A 18F8 9592
   2452   5A82 A57D A57D 5A82 5A82 A57D A57D 5A82
   2453   471C 8275 18F8 6A6D 9592 E707 7D8A B8E3
   2454   30FB 89BE 7641 CF04 CF04 7641 89BE 30FB
   2455   18F8 B8E3 6A6D 8275 7D8A 9592 471C E707
   2456 Note that the hardware does actually use only the upper 13bit of those 16bit
   2457 values. The values are choosen like so,
   2458   +s0  +s0  +s0  +s0  +s0  +s0  +s0  +s0
   2459   +s1  +s3  +s5  +s7  -s7  -s5  -s3  -s1
   2460   +s2  +s6  -s6  -s2  -s2  -s6  +s6  +s2
   2461   +s3  -s7  -s1  -s5  +s5  +s1  +s7  -s3
   2462   +s4  -s4  -s4  +s4  +s4  -s4  -s4  +s4
   2463   +s5  -s1  +s7  +s3  -s3  -s7  +s1  -s5
   2464   +s6  -s2  +s2  -s6  -s6  +s2  -s2  +s6
   2465   +s7  -s5  +s3  -s1  +s1  -s3  +s5  -s7
   2466 whereas, s0..s7 = scalefactor[0..7], multiplied by sqrt(2) (ie. by 1.414), and
   2467 multiplied by 4000h (ie. with 14bit fractional part).
   2468 
   2469 MDEC Data Format
   2470 ----------------
   2471 
   2472 Colored Macroblocks (16x16 pixels) (in 15bpp or 24bpp depth mode)
   2473 Each macroblock consists of six blocks: Two low-resolution blocks with color
   2474 information (Cr,Cb) and four full-resolution blocks with luminance (grayscale)
   2475 information (Y1,Y2,Y3,Y4). The color blocks are zoomed from 8x8 to 16x16 pixel
   2476 size, merged with the luminance blocks, and then converted from YUV to RGB
   2477 format.
   2478    .-----.       .-----.       .-----.         .-----.
   2479    |     |       |     |       |Y1|Y2|         |     |
   2480    | Cr  |   +   | Cb  |   +   |--+--|  ---->  | RGB |
   2481    |     |       |     |       |Y3|Y4|         |     |
   2482    '-----'       '-----'       '-----'         '-----'
   2483 Native PSX files are usually containing vertically arranged Macroblocks (eg.
   2484 allowing to send them to the GPU as 16x240 portion) (JPEG-style horizontally
   2485 arranged Macroblocks would require to send the data in 16x16 pixel portions to
   2486 the GPU) (something like 320x16 won't work, since that'd require to wrap from
   2487 the bottom of the first macroblock to the top of the next macroblock).
   2488 
   2489 Monochrome Macroblocks (8x8 pixel) (in 4bpp or 8bpp depth mode)
   2490 Each macroblock consist of only one block: with luminance (grayscale)
   2491 information (Y), the data comes out as such (it isn't converted to RGB).
   2492    .--.         .--.
   2493    |Y |  ---->  |Y |
   2494    '--'         '--'
   2495 The output is an 8x8 bitmap (not 16x16), so it'd be send to the GPU as 8x8
   2496 pixel rectangle, or multiple blocks at once as 8x240 pixel rectangle. Since the
   2497 data isn't RGB, it should be written to Texture memory (and then it can be
   2498 forwarded to the frame buffer in form of a texture with monochrome 15bit
   2499 palette with 32 grayscales). Alternately, one could convert the 8bpp image to
   2500 24bpp by software (this would allow to use 256 grayscales).
   2501 
   2502 Blocks (8x8 pixels)
   2503 An (uncompressed) block consists of 64 values, representing 8x8 pixels. The
   2504 first (upper-left) value is an absolute value (called "DC" value), the
   2505 remaining 63 values are relative to the DC value (called "AC" values). After
   2506 decompression and zig-zag reordering, the data in unfiltered horizontally and
   2507 vertically (IDCT conversion, ie. the relative "AC" values are converted to
   2508 absolute "DC" values).
   2509 
   2510 .STR Files
   2511 PSX Video files are usually having file extension .STR (for "Streaming").
   2512 --> CDROM File Video STR Streaming and BS Picture Compression (Sony)
   2513 
   2514 MDEC vs JPEG
   2515 The MDEC data format is very similar to the JPEG file format, the main
   2516 difference is that JPEG uses Huffman compressed blocks, whilst MDEC uses
   2517 Run-Length (RL) compressed blocks.
   2518 The (uncompressed) blocks are same as in JPEGs, using the same zigzag ordering,
   2519 AC to DC conversion, and YUV to RGB conversion (ie. the MDEC hardware can be
   2520 also used to decompress JPEGs, when handling the file header and huffman
   2521 decompression by software).
   2522 Some other differences are that MDEC has only 2 fixed-purpose quant tables,
   2523 whilst JPEGs <can> use up to 4 general-purpose quant tables. Also, JPEGs <can>
   2524 use other color resolutions than the 8x8 color info for 16x16 pixels. Whereas,
   2525 JPEGs <can> do that stuff, but most standard JPEG files aren't actually using 4
   2526 quant tables, nor higher color resolution.
   2527 
   2528 Run-Length compressed Blocks
   2529 Within each block the DCT information and RLE compressed data is stored:
   2530   DCT               ;1 halfword
   2531   RLE,RLE,RLE,etc.  ;0..63 halfwords
   2532   EOB               ;1 halfword
   2533 
   2534 DCT (1st value)
   2535 DCT data has the quantization factor and the Direct Current (DC) reference.
   2536   15-10 Q    Quantization factor (6 bits, unsigned)
   2537   9-0   DC   Direct Current reference (10 bits, signed)
   2538 Contains the absolute DC value (the upper-left value of the 8x8 block).
   2539 
   2540 RLE (Run length data, for 2nd through 64th value)
   2541   15-10 LEN  Number of zero AC values to be inserted (6 bits, unsigned)
   2542   9-0   AC   Relative AC value (10 bits, signed)
   2543 Example: AC values "000h,000h,123h" would be compressed as "(2 shl 10)+123h".
   2544 
   2545 EOB (End Of Block)
   2546 Indicates the end of a 8x8 pixel block, causing the rest of the block to be
   2547 padded with zero AC values.
   2548   15-0  End-code (Fixed, FE00h)
   2549 EOB isn't required if the block was already fully defined (up to including
   2550 blk[63]), however, most games seem to append EOB to all blocks (although it's
   2551 just acting as dummy/padding value in case of fully defined blocks).
   2552 
   2553 Dummy halfwords
   2554 Data is sent in units of words (or, when using DMA, even in units of 32-words),
   2555 which is making it neccessary to send some dummy halfwords (unless the
   2556 compressed data size should match up the transfer unit). The value FE00h can be
   2557 used as dummy value: When FE00h appears at the begin of a new block, or after
   2558 the end of block, then it is simply ignored by the hardware (if it occurs
   2559 elsewhere, then it acts as EOB end code, as described above).
   2560 
   2561 Sound Processing Unit (SPU)
   2562 ---------------------------
   2563 
   2564 --> SPU Overview
   2565 --> SPU ADPCM Samples
   2566 --> SPU ADPCM Pitch
   2567 --> SPU Volume and ADSR Generator
   2568 --> SPU Voice Flags
   2569 --> SPU Noise Generator
   2570 --> SPU Control and Status Register
   2571 --> SPU Memory Access
   2572 --> SPU Interrupt
   2573 --> SPU Reverb Registers
   2574 --> SPU Reverb Formula
   2575 --> SPU Reverb Examples
   2576 --> SPU Unknown Registers
   2577 
   2578 SPU Overview
   2579 ------------
   2580 
   2581 SPU I/O Port Summary
   2582   1F801C00h..1F801D7Fh - Voice 0..23 Registers (eight 16bit regs per voice)
   2583   1F801D80h..1F801D87h - SPU Control (volume)
   2584   1F801D88h..1F801D9Fh - Voice 0..23 Flags (six 1bit flags per voice)
   2585   1F801DA2h..1F801DBFh - SPU Control (memory, control, etc.)
   2586   1F801DC0h..1F801DFFh - Reverb configuration area
   2587   1F801E00h..1F801E5Fh - Voice 0..23 Internal Registers
   2588   1F801E60h..1F801E7Fh - Unknown?
   2589   1F801E80h..1F801FFFh - Unused?
   2590 
   2591 SPU Memory layout (512Kbyte RAM)
   2592   00000h-003FFh  CD Audio left  (1Kbyte) ;\CD Audio before Volume processing
   2593   00400h-007FFh  CD Audio right (1Kbyte) ;/signed 16bit samples at 44.1kHz
   2594   00800h-00BFFh  Voice 1 mono   (1Kbyte) ;\Voice 1 and 3 after ADSR processing
   2595   00C00h-00FFFh  Voice 3 mono   (1Kbyte) ;/signed 16bit samples at 44.1kHz
   2596   01000h-xxxxxh  ADPCM Samples  (first 16bytes usually contain a Sine wave)
   2597   xxxxxh-7FFFFh  Reverb work area
   2598 As shown above, the first 4Kbytes are used as special capture buffers, and, if
   2599 desired, one can also use the Reverb hardware to capture output from other
   2600 voice(s).
   2601 The SPU memory is not mapped to the CPU bus, it can be accessed only via I/O,
   2602 or via DMA transfers (DMA4).
   2603 
   2604 Voices
   2605 The SPU has 24 hardware voices. These voices can be used to reproduce sample
   2606 data, noise or can be used as frequency modulator on the next voice. Each voice
   2607 has it's own programmable ADSR envelope filter. The main volume can be
   2608 programmed independently for left and right output.
   2609 
   2610 Voice Capabilities
   2611 All 24 voices are having exactly the same capabilities(?), with the exception
   2612 that Voice 1 and 3 are having a special Capture feature (see SPU Memory map).
   2613 There seems to be no way to produce square waves (without storing a square
   2614 wavefrom in memory... although, since SPU RAM isn't connected to the CPU bus,
   2615 the "useless" DMA for square wave data wouldn't slowdown the CPU bus)?
   2616 
   2617 Additional Sound Inputs
   2618 External Audio can be input (from the Expansion Port?), and the CDROM drive can
   2619 be commanded to playback normal Audio CDs (via Play command), or XA-ADPCM
   2620 sectors (via Read command), and to pass that data to the SPU.
   2621 
   2622 Unstable and Delayed I/O
   2623 The SPU occassionally seems to "miss" I/O writes (not sure if that can be fixed
   2624 by any Memory Control settings?), a stable workaround is too write all values
   2625 twice (except of course, Fifo writes). The SPU seems to process written values
   2626 at 44100Hz rate (so it may take 1/44100 seconds (300h clock cycles) until it
   2627 has actually realized the new value).
   2628 
   2629 Mono/Stereo Audio Output
   2630 The standard PSX Audio cables have separate Left/Right signals, that is good
   2631 for stereo TVs, but, when using a normal mono TV, only one of the two audio
   2632 signals (Left or Right) can be connected. PSX programs should thus offer an
   2633 option to disable stereo effects, and to output an equal volume to both cables.
   2634 
   2635 SPU Bus-Width
   2636 The SPU is connected to a 16bit databus. 8bit/16bit/32bit reads and 16bit/32bit
   2637 writes are implemented. However, 8bit writes are NOT implemented: 8bit writes
   2638 to ODD addresses are simply ignored (without causing any exceptions), 8bit
   2639 writes to EVEN addresses are executed as 16bit writes (eg. "movp r1,12345678h,
   2640 movb [spu_port],r1" will write 5678h instead of 78h).
   2641 
   2642 SPU ADPCM Samples
   2643 -----------------
   2644 
   2645 The SPU supports only ADPCM compressed samples (uncompressed samples seem to be
   2646 totally unsupported; leaving apart that one can write uncompressed 16bit PCM
   2647 samples to the Reverb Buffer, which can be then output at 22050Hz, as long as
   2648 they aren't overwritten by the hardware).
   2649 
   2650 1F801C06h+N*10h - Voice 0..23 ADPCM Start Address (R/W)
   2651 This register holds the sample start address (not the current address, ie. the
   2652 register doesn't increment during playback).
   2653   15-0   Startaddress of sound in Sound buffer (in 8-byte units)
   2654 Writing to this register has no effect on the currently playing voice.
   2655 The start address is copied to the current address upon Key On.
   2656 
   2657 1F801C0Eh+N*10h - Voice 0..23 ADPCM Repeat Address (R/W)
   2658 If the hardware finds an ADPCM header with Loop-Start-Bit, then it copies the
   2659 current address to the repeat addresss register.
   2660 If the hardware finds an ADPCM header with Loop-Stop-Bit, then it copies the
   2661 repeat addresss register setting to the current address; that, <after> playing
   2662 the current ADPCM block.
   2663   15-0  Address sample loops to at end (in 8-byte units)
   2664 Normally, repeat works automatically via the above start/stop bits, and
   2665 software doesn't need to deal with the Repeat Address Register. However,
   2666 reading from it may be useful to sense if the hardware has reached a start bit,
   2667 and writing may be also useful in some cases, eg. to redirect a one-shot sample
   2668 (with stop-bit, but without any start-bits) to a silent-loop located elsewhere
   2669 in memory.
   2670 
   2671 Sample Data (SPU-ADPCM)
   2672 Samples consist of one or more 16-byte blocks:
   2673   00h       Shift/Filter (reportedly same as for CDROM XA-ADPCM) (see there)
   2674   01h       Flag Bits (see below)
   2675   02h       Compressed Data (LSBs=1st Sample, MSBs=2nd Sample)
   2676   03h       Compressed Data (LSBs=3rd Sample, MSBs=4th Sample)
   2677   04h       Compressed Data (LSBs=5th Sample, MSBs=6th Sample)
   2678   ...       ...
   2679   0Fh       Compressed Data (LSBs=27th Sample, MSBs=28th Sample)
   2680 
   2681 Flag Bits (in 2nd byte of ADPCM Header)
   2682   0   Loop End    (0=No change, 1=Set ENDX flag and Jump to [1F801C0Eh+N*10h])
   2683   1   Loop Repeat (0=Force Release and set ADSR Level to Zero; only if Bit0=1)
   2684   2   Loop Start  (0=No change, 1=Copy current address to [1F801C0Eh+N*10h])
   2685   3-7 Unknown    (usually 0)
   2686 Possible combinations for Bit0-1 are:
   2687   Code 0 = Normal     (continue at next 16-byte block)
   2688   Code 1 = End+Mute   (jump to Loop-address, set ENDX flag, Release, Env=0000h)
   2689   Code 2 = Ignored    (same as Code 0)
   2690   Code 3 = End+Repeat (jump to Loop-address, set ENDX flag)
   2691 
   2692 Looped and One-shot Samples
   2693 The Loop Start/End flags in the ADPCM Header allow to play one or more sample
   2694 block(s) in a loop, that can be either all block(s) endless repeated, or only
   2695 the last some block(s) of the sample.
   2696 There's no way to stop the output, so a one-shot sample must be followed by
   2697 dummy block (with Loop Start/End flags both set, and all data nibbles set to
   2698 zero; so that the block gets endless repeated, but doesn't produce any sound).
   2699 
   2700 SPU-ADPCM vs XA-ADPCM
   2701 The PSX supports two ADPCM formats: SPU-ADPCM (as described above), and
   2702 XA-ADPCM. XA-ADPCM is decompressed by the CDROM Controller, and sent directly
   2703 to the sound mixer, without needing to store the data in SPU RAM, nor needing
   2704 to use a Voice channel.
   2705 The actual decompression algorithm is the same for both formats. However, the
   2706 XA nibbles are arranged in different order, and XA uses 2x28 nibbles per block
   2707 (instead of 2x14), XA blocks can contain mono or stereo data, XA supports only
   2708 two sample rates, and, XA doesn't support looping.
   2709 
   2710 SPU ADPCM Pitch
   2711 ---------------
   2712 
   2713 1F801C04h+N*10h - Voice 0..23 ADPCM Sample Rate (R/W) (VxPitch)
   2714   0-15  Sample rate (0=stop, 4000h=fastest, 4001h..FFFFh=usually same as 4000h)
   2715 Defines the ADPCM sample rate (1000h = 44100Hz). This register (and PMON) does
   2716 only affect the ADPCM sample frequency (but not the Noise frequency, which is
   2717 defined - and shared for all voices - in the SPUCNT register).
   2718 
   2719 1F801D90h - Voice 0..23 Pitch Modulation Enable Flags (PMON)
   2720 Pitch modulation allows to generate "Frequency Sweep" effects by mis-using the
   2721 amplitude from channel (x-1) as pitch factor for channel (x).
   2722   0     Unknown... Unused?
   2723   1-23  Flags for Voice 1..23 (0=Normal, 1=Modulate by Voice 0..22)
   2724   24-31 Not used
   2725 For example, output a very loud 1Hz sine-wave on channel 4 (with ADSR volume
   2726 4000h, and with Left/Right volume=0; unless you actually want to output it to
   2727 the speaker). Then additionally output a 2kHz sine wave on channel 5 with
   2728 PMON.Bit5 set. The "2kHz" sound should then repeatedly sweep within 1kHz..3kHz
   2729 range (or, for a more decent sweep in 1.8kHz..2.2kHz range, drop the ADSR
   2730 volume of channel 4).
   2731 
   2732 Pitch Counter
   2733 The pitch counter is adjusted at 44100Hz rate as follows:
   2734   Step = VxPitch                  ;range +0000h..+FFFFh (0...705.6 kHz)
   2735   IF PMON.Bit(x)=1 AND (x>0)      ;pitch modulation enable
   2736     Factor = VxOUTX(x-1)          ;range -8000h..+7FFFh (prev voice amplitude)
   2737     Factor = Factor+8000h         ;range +0000h..+FFFFh (factor = 0.00 .. 1.99)
   2738     Step=SignExpand16to32(Step)   ;hardware glitch on VxPitch>7FFFh, make sign
   2739     Step = (Step * Factor) SAR 15 ;range 0..1FFFFh (glitchy if VxPitch>7FFFh)
   2740     Step=Step AND 0000FFFFh       ;hardware glitch on VxPitch>7FFFh, kill sign
   2741   IF Step>3FFFh then Step=4000h   ;range +0000h..+3FFFh (0.. 176.4kHz)
   2742   Counter = Counter + Step
   2743 Counter.Bit12 and up indicates the current sample (within a ADPCM block).
   2744 Counter.Bit3..11 are used as 8bit gaussian interpolation index.
   2745 
   2746 Maximum Sound Frequency
   2747 The Mixer and DAC supports a 44.1kHz output rate (allowing to produce max
   2748 22.1kHz tones). The Reverb unit supports only half the frequency.
   2749 The pitch counter supports sample rates up to 176.4kHz. However, exceeding the
   2750 44.1kHz limit causes the hardware to skip samples (or actually: to apply
   2751 incomplete interpolation on the 'skipped' samples).
   2752 VxPitch can be theoretically 0..FFFFh (max 705.6kHz), normally 4000h..FFFFh are
   2753 simply clipped to max=4000h (176.4kHz). Except, 4000h..FFFFh could be used with
   2754 pitch modulation (as they are multiplied by 0.00..1.99 before clipping; in
   2755 practice this works only for 4000h..7FFFh; as values 8000h..FFFFh are mistaken
   2756 as signed values).
   2757 
   2758 4-Point Gaussian Interpolation
   2759 Interpolation is applied on the 4 most recent 16bit ADPCM samples
   2760 (new,old,older,oldest), using bit4-11 of the pitch counter as 8bit
   2761 interpolation index (i=00h..FFh):
   2762   out =       ((gauss[0FFh-i] * oldest) SAR 15)
   2763   out = out + ((gauss[1FFh-i] * older)  SAR 15)
   2764   out = out + ((gauss[100h+i] * old)    SAR 15)
   2765   out = out + ((gauss[000h+i] * new)    SAR 15)
   2766 The Gauss table contains the following values (in hex):
   2767   -001h,-001h,-001h,-001h,-001h,-001h,-001h,-001h ;\
   2768   -001h,-001h,-001h,-001h,-001h,-001h,-001h,-001h ;
   2769   0000h,0000h,0000h,0000h,0000h,0000h,0000h,0001h ;
   2770   0001h,0001h,0001h,0002h,0002h,0002h,0003h,0003h ;
   2771   0003h,0004h,0004h,0005h,0005h,0006h,0007h,0007h ;
   2772   0008h,0009h,0009h,000Ah,000Bh,000Ch,000Dh,000Eh ;
   2773   000Fh,0010h,0011h,0012h,0013h,0015h,0016h,0018h ; entry
   2774   0019h,001Bh,001Ch,001Eh,0020h,0021h,0023h,0025h ; 000h..07Fh
   2775   0027h,0029h,002Ch,002Eh,0030h,0033h,0035h,0038h ;
   2776   003Ah,003Dh,0040h,0043h,0046h,0049h,004Dh,0050h ;
   2777   0054h,0057h,005Bh,005Fh,0063h,0067h,006Bh,006Fh ;
   2778   0074h,0078h,007Dh,0082h,0087h,008Ch,0091h,0096h ;
   2779   009Ch,00A1h,00A7h,00ADh,00B3h,00BAh,00C0h,00C7h ;
   2780   00CDh,00D4h,00DBh,00E3h,00EAh,00F2h,00FAh,0101h ;
   2781   010Ah,0112h,011Bh,0123h,012Ch,0135h,013Fh,0148h ;
   2782   0152h,015Ch,0166h,0171h,017Bh,0186h,0191h,019Ch ;/
   2783   01A8h,01B4h,01C0h,01CCh,01D9h,01E5h,01F2h,0200h ;\
   2784   020Dh,021Bh,0229h,0237h,0246h,0255h,0264h,0273h ;
   2785   0283h,0293h,02A3h,02B4h,02C4h,02D6h,02E7h,02F9h ;
   2786   030Bh,031Dh,0330h,0343h,0356h,036Ah,037Eh,0392h ;
   2787   03A7h,03BCh,03D1h,03E7h,03FCh,0413h,042Ah,0441h ;
   2788   0458h,0470h,0488h,04A0h,04B9h,04D2h,04ECh,0506h ;
   2789   0520h,053Bh,0556h,0572h,058Eh,05AAh,05C7h,05E4h ; entry
   2790   0601h,061Fh,063Eh,065Ch,067Ch,069Bh,06BBh,06DCh ; 080h..0FFh
   2791   06FDh,071Eh,0740h,0762h,0784h,07A7h,07CBh,07EFh ;
   2792   0813h,0838h,085Dh,0883h,08A9h,08D0h,08F7h,091Eh ;
   2793   0946h,096Fh,0998h,09C1h,09EBh,0A16h,0A40h,0A6Ch ;
   2794   0A98h,0AC4h,0AF1h,0B1Eh,0B4Ch,0B7Ah,0BA9h,0BD8h ;
   2795   0C07h,0C38h,0C68h,0C99h,0CCBh,0CFDh,0D30h,0D63h ;
   2796   0D97h,0DCBh,0E00h,0E35h,0E6Bh,0EA1h,0ED7h,0F0Fh ;
   2797   0F46h,0F7Fh,0FB7h,0FF1h,102Ah,1065h,109Fh,10DBh ;
   2798   1116h,1153h,118Fh,11CDh,120Bh,1249h,1288h,12C7h ;/
   2799   1307h,1347h,1388h,13C9h,140Bh,144Dh,1490h,14D4h ;\
   2800   1517h,155Ch,15A0h,15E6h,162Ch,1672h,16B9h,1700h ;
   2801   1747h,1790h,17D8h,1821h,186Bh,18B5h,1900h,194Bh ;
   2802   1996h,19E2h,1A2Eh,1A7Bh,1AC8h,1B16h,1B64h,1BB3h ;
   2803   1C02h,1C51h,1CA1h,1CF1h,1D42h,1D93h,1DE5h,1E37h ;
   2804   1E89h,1EDCh,1F2Fh,1F82h,1FD6h,202Ah,207Fh,20D4h ;
   2805   2129h,217Fh,21D5h,222Ch,2282h,22DAh,2331h,2389h ; entry
   2806   23E1h,2439h,2492h,24EBh,2545h,259Eh,25F8h,2653h ; 100h..17Fh
   2807   26ADh,2708h,2763h,27BEh,281Ah,2876h,28D2h,292Eh ;
   2808   298Bh,29E7h,2A44h,2AA1h,2AFFh,2B5Ch,2BBAh,2C18h ;
   2809   2C76h,2CD4h,2D33h,2D91h,2DF0h,2E4Fh,2EAEh,2F0Dh ;
   2810   2F6Ch,2FCCh,302Bh,308Bh,30EAh,314Ah,31AAh,3209h ;
   2811   3269h,32C9h,3329h,3389h,33E9h,3449h,34A9h,3509h ;
   2812   3569h,35C9h,3629h,3689h,36E8h,3748h,37A8h,3807h ;
   2813   3867h,38C6h,3926h,3985h,39E4h,3A43h,3AA2h,3B00h ;
   2814   3B5Fh,3BBDh,3C1Bh,3C79h,3CD7h,3D35h,3D92h,3DEFh ;/
   2815   3E4Ch,3EA9h,3F05h,3F62h,3FBDh,4019h,4074h,40D0h ;\
   2816   412Ah,4185h,41DFh,4239h,4292h,42EBh,4344h,439Ch ;
   2817   43F4h,444Ch,44A3h,44FAh,4550h,45A6h,45FCh,4651h ;
   2818   46A6h,46FAh,474Eh,47A1h,47F4h,4846h,4898h,48E9h ;
   2819   493Ah,498Ah,49D9h,4A29h,4A77h,4AC5h,4B13h,4B5Fh ;
   2820   4BACh,4BF7h,4C42h,4C8Dh,4CD7h,4D20h,4D68h,4DB0h ;
   2821   4DF7h,4E3Eh,4E84h,4EC9h,4F0Eh,4F52h,4F95h,4FD7h ; entry
   2822   5019h,505Ah,509Ah,50DAh,5118h,5156h,5194h,51D0h ; 180h..1FFh
   2823   520Ch,5247h,5281h,52BAh,52F3h,532Ah,5361h,5397h ;
   2824   53CCh,5401h,5434h,5467h,5499h,54CAh,54FAh,5529h ;
   2825   5558h,5585h,55B2h,55DEh,5609h,5632h,565Bh,5684h ;
   2826   56ABh,56D1h,56F6h,571Bh,573Eh,5761h,5782h,57A3h ;
   2827   57C3h,57E2h,57FFh,581Ch,5838h,5853h,586Dh,5886h ;
   2828   589Eh,58B5h,58CBh,58E0h,58F4h,5907h,5919h,592Ah ;
   2829   593Ah,5949h,5958h,5965h,5971h,597Ch,5986h,598Fh ;
   2830   5997h,599Eh,59A4h,59A9h,59ADh,59B0h,59B2h,59B3h ;/
   2831 The PSX table is a bit different as the SNES table: Values up to 3569h are
   2832 smaller as on SNES, the remaining values are bigger as on SNES, and the width
   2833 of the PSX table entries is 4bit higher as on SNES.
   2834 The PSX table is slightly bugged: Theoretically, each four values
   2835 (gauss[000h+i], gauss[0FFh-i], gauss[100h+i], gauss[1FFh-i]) should sum up to
   2836 8000h, but in practice they do sum up to 7F7Fh..7F81h (fortunately the PSX sum
   2837 doesn't exceed the 8000h limit; meaning that the PSX interpolations won't
   2838 overflow, which has been a hardware glitch on the SNES).
   2839 
   2840 Waveform Examples
   2841   Incoming ADPCM Data ---> Interpolated Data
   2842    _   _   _   _
   2843   | | | | | | | |           .   .   .   .    Nibbles=79797979, Filter=0
   2844   | | | | | | | |     ---> / \ / \ / \ / \   HALF-volume ZIGZAG-wave
   2845   | |_| |_| |_| |_            '   '   '   '
   2846    ___     ___
   2847   |   |   |   |              .'.     .'.     Nibbles=77997799, Filter=0
   2848   |   |   |   |       --->  /   \   /   \    FULL-volume SINE-wave
   2849   |   |___|   |___         '     '.'     '.
   2850    _______                     ___
   2851   |       |                  .'   '.         Nibbles=77779999, Filter=0
   2852   |       |           --->  /       \        SQUARE wave (with rounded edges)
   2853   |       |_______         '         '.____
   2854    _____         _             __
   2855   |     |_     _|            .'  ''.    .'   Nibbles=7777CC44, Filter=0
   2856   |       |___|       --->  /       '..'     CUSTOM wave-form
   2857   |                        '
   2858    ___     __
   2859   |   |___|  |    _         \ ! /  .  \ ! /  Nibbles=77DE9HZK, Filter=V
   2860   |_     ____|  _|    --->  - + -  +  - + -  SOLAR STORM wave-form
   2861   __|   |______|___         / ! \  '  / ! \
   2862 
   2863 
   2864 SPU Volume and ADSR Generator
   2865 -----------------------------
   2866 
   2867 1F801C08h+N*10h - Voice 0..23 Attack/Decay/Sustain/Release (ADSR) (32bit)
   2868   ____lower 16bit (at 1F801C08h+N*10h)___________________________________
   2869   15    Attack Mode       (0=Linear, 1=Exponential)
   2870   -     Attack Direction  (Fixed, always Increase) (until Level 7FFFh)
   2871   14-10 Attack Shift      (0..1Fh = Fast..Slow)
   2872   9-8   Attack Step       (0..3 = "+7,+6,+5,+4")
   2873   -     Decay Mode        (Fixed, always Exponential)
   2874   -     Decay Direction   (Fixed, always Decrease) (until Sustain Level)
   2875   7-4   Decay Shift       (0..0Fh = Fast..Slow)
   2876   -     Decay Step        (Fixed, always "-8")
   2877   3-0   Sustain Level     (0..0Fh)  ;Level=(N+1)*800h
   2878   ____upper 16bit (at 1F801C0Ah+N*10h)___________________________________
   2879   31    Sustain Mode      (0=Linear, 1=Exponential)
   2880   30    Sustain Direction (0=Increase, 1=Decrease) (until Key OFF flag)
   2881   29    Not used?         (should be zero)
   2882   28-24 Sustain Shift     (0..1Fh = Fast..Slow)
   2883   23-22 Sustain Step      (0..3 = "+7,+6,+5,+4" or "-8,-7,-6,-5") (inc/dec)
   2884   21    Release Mode      (0=Linear, 1=Exponential)
   2885   -     Release Direction (Fixed, always Decrease) (until Level 0000h)
   2886   20-16 Release Shift     (0..1Fh = Fast..Slow)
   2887   -     Release Step      (Fixed, always "-8")
   2888 The Attack phase gets started when the software sets the voice ON flag (see
   2889 below), the hardware does then automatically go through Attack/Decay/Sustain,
   2890 and switches from Sustain to Release when the software sets the Key OFF flag.
   2891 
   2892 1F801D80h - Mainvolume left
   2893 1F801D82h - Mainvolume right
   2894 1F801C00h+N*10h - Voice 0..23 Volume Left
   2895 1F801C02h+N*10h - Voice 0..23 Volume Right
   2896 Fixed Volume Mode (when Bit15=0):
   2897   15    Must be zero      (0=Volume Mode)
   2898   0-14  Voice volume/2    (-4000h..+3FFFh = Volume -8000h..+7FFEh)
   2899 Sweep Volume Mode (when Bit15=1):
   2900   15    Must be set       (1=Sweep Mode)
   2901   14    Sweep Mode        (0=Linear, 1=Exponential)
   2902   13    Sweep Direction   (0=Increase, 1=Decrease)
   2903   12    Sweep Phase       (0=Positive, 1=Negative)
   2904   7-11  Not used?         (should be zero)
   2905   6-2   Sweep Shift       (0..1Fh = Fast..Slow)
   2906   1-0   Sweep Step        (0..3 = "+7,+6,+5,+4" or "-8,-7,-6,-5") (inc/dec)
   2907 Sweep is another Volume envelope, additionally to the ADSR volume envelope
   2908 (unlike ADSR, sweep can be used for stereo effects, such like blending from
   2909 left to right).
   2910 Sweep starts at the current volume (which can be set via Bit15=0, however,
   2911 caution - the Bit15=0 setting isn't applied until the next 44.1kHz cycle; so
   2912 setting the initial level with Bit15=0, followed by the sweep parameter with
   2913 Bit15=1 works only if there's a suitable delay between the two operations).
   2914 Once when sweep is started, the current volume level increases to +7FFFh, or
   2915 decreases to 0000h.
   2916 Sweep Phase should be equal to the sign of the current volume (not yet tested,
   2917 in the negative mode it does probably "increase" to -7FFFh?). The Phase bit
   2918 seems to have no effect in Exponential Decrease mode.
   2919 
   2920 1F801DB0h - CD Audio Input Volume (for normal CD-DA, and compressed XA-ADPCM)
   2921 1F801DB4h - External Audio Input Volume
   2922   0-15  Volume Left   (-8000h..+7FFFh)
   2923   16-31 Volume Right  (-8000h..+7FFFh)
   2924 Note: The CDROM controller supports additional CD volume control (including
   2925 ability to convert stereo CD output to mono, or to swap left/right channels).
   2926 
   2927 Envelope Operation depending on Shift/Step/Mode/Direction
   2928   AdsrCycles = 1 SHL Max(0,ShiftValue-11)
   2929   AdsrStep = StepValue SHL Max(0,11-ShiftValue)
   2930   IF exponential AND increase AND AdsrLevel>6000h THEN AdsrCycles=AdsrCycles*4
   2931   IF exponential AND decrease THEN AdsrStep=AdsrStep*AdsrLevel/8000h
   2932   Wait(AdsrCycles)              ;cycles counted at 44.1kHz clock
   2933   AdsrLevel=AdsrLevel+AdsrStep  ;saturated to 0..+7FFFh
   2934 Exponential Increase is a fake (simply changes to a slower linear increase rate
   2935 at higher volume levels).
   2936 
   2937 1F801C0Ch+N*10h - Voice 0..23 Current ADSR volume (R/W)
   2938   15-0  Current ADSR Volume  (0..+7FFFh) (or -8000h..+7FFFh on manual write)
   2939 Reportedly Release can go down to -1 (FFFFh), but that isn't true; and release
   2940 ends at 0... or does THAT depend on an END flag found in the sample-data?
   2941 The register is read/writeable, writing allows to let the ADSR generator to
   2942 "jump" to a specific volume level. But, ACTUALLY, the ADSR generator does
   2943 overwrite the setting (from another internal register) whenever applying a new
   2944 Step?!
   2945 
   2946 1F801DB8h - Current Main Volume Left/Right
   2947 1F801E00h+voice*04h - Voice 0..23 Current Volume Left/Right
   2948   0-15  Current Volume Left  (-8000h..+7FFFh)
   2949   16-31 Current Volume Right (-8000h..+7FFFh)
   2950 These are internal registers, normally not used by software (the Volume
   2951 settings are usually set via Ports 1F801D80h and 1F801C00h+N*10h).
   2952 
   2953 Note
   2954 Negative volumes are phase inverted, otherwise same as positive.
   2955 
   2956 SPU Voice Flags
   2957 ---------------
   2958 
   2959 1F801D88h - Voice 0..23 Key ON (Start Attack/Decay/Sustain) (KON) (W)
   2960   0-23  Voice 0..23 On  (0=No change, 1=Start Attack/Decay/Sustain)
   2961   24-31 Not used
   2962 Starts the ADSR Envelope, and automatically initializes ADSR Volume to zero,
   2963 and copies Voice Start Address to Voice Repeat Address.
   2964 
   2965 1F801D8Ch - Voice 0..23 Key OFF (Start Release) (KOFF) (W)
   2966   0-23  Voice 0..23 Off (0=No change, 1=Start Release)
   2967   24-31 Not used
   2968 For a full ADSR pattern, OFF would be usually issued in the Sustain period,
   2969 however, it can be issued at any time (eg. to abort Attack, skip the Decay and
   2970 Sustain periods, and switch immediately to Release).
   2971 
   2972 1F801D9Ch - Voice 0..23 ON/OFF (status) (ENDX) (R)
   2973   0-23  Voice 0..23 Status (0=Newly Keyed On, 1=Reached LOOP-END)
   2974   24-31 Not used
   2975 The bits get CLEARED when setting the corresponding KEY ON bits.
   2976 The bits get SET when reaching an LOOP-END flag in ADPCM header.bit0.
   2977 
   2978 R/W
   2979 Key On and Key Off should be treated as write-only (although, reading returns
   2980 the most recently 32bit value, this doesn't doesn't provide any status
   2981 information about whether sound is on or off).
   2982 The on/off (status) (ENDX) register should be treated read-only (writing is
   2983 possible in so far that the written value can be read-back for a short moment,
   2984 however, thereafter the hardware is overwriting that value).
   2985 
   2986 SPU Noise Generator
   2987 -------------------
   2988 
   2989 1F801D94h - Voice 0..23 Noise mode enable (NON)
   2990   0-23  Voice 0..23 Noise (0=ADPCM, 1=Noise)
   2991   24-31 Not used
   2992 
   2993 SPU Noise Generator
   2994 The signed 16bit output Level is calculated as so (repeated at 44.1kHz clock):
   2995   Wait(1 cycle)          ;at 44.1kHz clock
   2996   Timer=Timer-NoiseStep  ;subtract Step (4..7)
   2997   ParityBit = NoiseLevel.Bit15 xor Bit12 xor Bit11 xor Bit10 xor 1
   2998   IF Timer<0 then NoiseLevel = NoiseLevel*2 + ParityBit
   2999   IF Timer<0 then Timer=Timer+(20000h SHR NoiseShift)  ;reload timer once
   3000   IF Timer<0 then Timer=Timer+(20000h SHR NoiseShift)  ;reload again if needed
   3001 Note that the Noise frequency is solely controlled by the Shift/Step values in
   3002 SPUCNT register (the ADPCM Sample Rate has absolutely no effect on noise), so
   3003 when using noise for multiple voices, all of them are forcefully having the
   3004 same frequency; the only workaround is to store a random ADPCM pattern in SPU
   3005 RAM, which can be then used with any desired sample rate(s).
   3006 
   3007 SPU Control and Status Register
   3008 -------------------------------
   3009 
   3010 1F801DAAh - SPU Control Register (SPUCNT)
   3011   15    SPU Enable              (0=Off, 1=On)       (Don't care for CD Audio)
   3012   14    Mute SPU                (0=Mute, 1=Unmute)  (Don't care for CD Audio)
   3013   13-10 Noise Frequency Shift   (0..0Fh = Low .. High Frequency)
   3014   9-8   Noise Frequency Step    (0..03h = Step "4,5,6,7")
   3015   7     Reverb Master Enable    (0=Disabled, 1=Enabled)
   3016   6     IRQ9 Enable (0=Disabled/Acknowledge, 1=Enabled; only when Bit15=1)
   3017   5-4   Sound RAM Transfer Mode (0=Stop, 1=ManualWrite, 2=DMAwrite, 3=DMAread)
   3018   3     External Audio Reverb   (0=Off, 1=On)
   3019   2     CD Audio Reverb         (0=Off, 1=On) (for CD-DA and XA-ADPCM)
   3020   1     External Audio Enable   (0=Off, 1=On)
   3021   0     CD Audio Enable         (0=Off, 1=On) (for CD-DA and XA-ADPCM)
   3022 Changes to bit0-5 aren't applied immediately; after writing to SPUCNT, it'd be
   3023 usually recommended to wait until the LSBs of SPUSTAT are updated accordingly.
   3024 Before setting a new Transfer Mode, it'd be recommended first to set the "Stop"
   3025 mode (and, again, wait until Stop is applied in SPUSTAT).
   3026 
   3027 1F801DAEh - SPU Status Register  (SPUSTAT) (R)
   3028   15-12 Unknown/Unused (seems to be usually zero)
   3029   11    Writing to First/Second half of Capture Buffers (0=First, 1=Second)
   3030   10    Data Transfer Busy Flag          (0=Ready, 1=Busy)
   3031   9     Data Transfer DMA Read Request   (0=No, 1=Yes)
   3032   8     Data Transfer DMA Write Request  (0=No, 1=Yes)
   3033   7     Data Transfer DMA Read/Write Request ;seems to be same as SPUCNT.Bit5
   3034   6     IRQ9 Flag                        (0=No, 1=Interrupt Request)
   3035   5-0   Current SPU Mode   (same as SPUCNT.Bit5-0, but, applied a bit delayed)
   3036 When switching SPUCNT to DMA-read mode, status bit9 and bit7 aren't set
   3037 immediately (apparently the SPU is first internally collecting the data in the
   3038 Fifo, before transferring it).
   3039 Bit11 indicates if data is currently written to the first or second half of the
   3040 four 1K-byte capture buffers (for CD Audio left/right, and voice 1/3). Note:
   3041 Bit11 works only if Bit2 and/or Bit3 of Port 1F801DACh are set.
   3042 The SPUSTAT register should be treated read-only (writing is possible in so far
   3043 that the written value can be read-back for a short moment, however, thereafter
   3044 the hardware is overwriting that value).
   3045 
   3046 SPU Memory Access
   3047 -----------------
   3048 
   3049 1F801DA6h - Sound RAM Data Transfer Address
   3050   15-0  Address in sound buffer divided by eight
   3051 Used for manual write and DMA read/write SPU memory. Writing to this registers
   3052 stores the written value in 1F801DA6h, and does additional store the value
   3053 (multiplied by 8) in another internal "current address" register (that internal
   3054 register does increment during transfers, whilst the 1F801DA6h value DOESN'T
   3055 increment).
   3056 
   3057 1F801DA8h - Sound RAM Data Transfer Fifo
   3058   15-0  Data (max 32 halfwords)
   3059 Used for manual-write. Not sure if it can be also used for manual read?
   3060 
   3061 1F801DACh - Sound RAM Data Transfer Control (should be 0004h)
   3062   15-4   Unknown/no effect?                       (should be zero)
   3063   3-1    Sound RAM Data Transfer Type (see below) (should be 2)
   3064   0      Unknown/no effect?                       (should be zero)
   3065 The Transfer Type selects how data is forwarded from Fifo to SPU RAM:
   3066   __Transfer Type___Halfwords in Fifo________Halfwords written to SPU RAM__
   3067   0,1,6,7  Fill     A,B,C,D,E,F,G,H,...,X    X,X,X,X,X,X,X,X,...
   3068   2        Normal   A,B,C,D,E,F,G,H,...,X    A,B,C,D,E,F,G,H,...
   3069   3        Rep2     A,B,C,D,E,F,G,H,...,X    A,A,C,C,E,E,G,G,...
   3070   4        Rep4     A,B,C,D,E,F,G,H,...,X    A,A,A,A,E,E,E,E,...
   3071   5        Rep8     A,B,C,D,E,F,G,H,...,X    H,H,H,H,H,H,H,H,...
   3072 Rep2 skips the 2nd halfword, Rep4 skips 2nd..4th, Rep8 skips 1st..7th.
   3073 Fill uses only the LAST halfword in Fifo, that might be useful for memfill
   3074 purposes, although, the length is probably determined by the number of writes
   3075 to the Fifo (?) so one must still issue writes for ALL halfwords...?
   3076 Note:
   3077 The above rather bizarre results apply to WRITE mode. In READ mode, the
   3078 register causes the same halfword to be read 2/4/8 times (for rep2/4/8).
   3079 
   3080 SPU RAM Manual Write
   3081 - Be sure that [1F801DACh] is set to 0004h
   3082 - Set SPUCNT to "Stop" (and wait until it is applied in SPUSTAT)
   3083 - Set the transfer address
   3084 - Write 1..32 halfword(s) to the Fifo
   3085 - Set SPUCNT to "Manual Write" (and wait until it is applied in SPUSTAT)
   3086 - Wait until Transfer Busy in SPUSTAT goes off (that, AFTER above apply-wait)
   3087 For multi-block transfers: Repeat the above last three steps (that is rarely
   3088 done by any games, but it is done by the BIOS intro; observe that waiting for
   3089 SPUCNT writes being applied in SPUSTAT won't work in that case (since SPUCNT
   3090 was already in manual write mode from previous block), so one must instead use
   3091 some hardcoded delay of at least 300h cycles; the BIOS is using a much longer
   3092 bizarre delay though).
   3093 
   3094 SPU RAM DMA-Write
   3095 - Be sure that [1F801DACh] is set to 0004h
   3096 - Set SPUCNT to "Stop" (and wait until it is applied in SPUSTAT)
   3097 - Set the transfer address
   3098 - Set SPUCNT to "DMA Write" (and wait until it is applied in SPUSTAT)
   3099 - Start DMA4 at CPU Side (blocksize=10h, control=01000201h)
   3100 - Wait until DMA4 finishes (at CPU side)
   3101 
   3102 SPU RAM Manual-Read
   3103 As by now, there's no known method for reading SPU RAM without using DMA.
   3104 
   3105 SPU RAM DMA-Read (stable reading, with [1F801014h].bit24-27 = nonzero)
   3106 - Be sure that [1F801014h] is set to 220931E1h (bit24-27 MUST be nonzero)
   3107 - Be sure that [1F801DACh] is set to 0004h
   3108 - Set SPUCNT to "Stop" (and wait until it is applied in SPUSTAT)
   3109 - Set the transfer address
   3110 - Set SPUCNT to "DMA Read" (and wait until it is applied in SPUSTAT)
   3111 - Start DMA4 at CPU Side (blocksize=10h, control=01000200h)
   3112 - Wait until DMA4 finishes (at CPU side)
   3113 
   3114 SPU RAM DMA-Read (unstable reading, with [1F801014h].bit24-27 = zero)
   3115 Below describes some dirt effects and some trickery to get around those dirt
   3116 effects.
   3117   Below problems (and workarounds) apply ONLY if [1F801014h].bit24-27 = zero.
   3118   Ie. below info describes what happens when [1F801014h] is mis-initialized.
   3119   Normally one should set [1F801014h]=220931E1h (and can ignore below info).
   3120 With [1F801014h].bit24-27=zero, reading SPU RAM via DMA works glitchy:
   3121 The first received halfword within each block is FFFFh. So with a DMA blocksize
   3122 of 10h words (=20h halfwords), the following is received:
   3123   1st block:   FFFFh, halfwords[00h..1Eh]
   3124   2nd block:   FFFFh, halfwords[20h..3Eh]
   3125   etc.
   3126 that'd theoretically match the SPU Fifo Size, but, because of the inserted
   3127 FFFFh value, the last Fifo entry isn't received, ie. halfword[1Fh,3Fh] are
   3128 lost. As a workaround, one can increase the DMA blocksize to 11h words, and
   3129 then the following is received:
   3130   1st block:   FFFFh, halfwords[00h..1Eh], twice halfword[1Fh]
   3131   2nd block:   FFFFh, halfwords[20h..3Eh], twice halfword[3Fh]
   3132   etc.
   3133 this time, all data is received, but after the transfer one must still remove
   3134 the FFFFh values, and the duplicated halfwords by software. Aside from the
   3135 <inserted> FFFFh values there are occassionaly some unstable halfwords ORed by
   3136 FFFFh (or ORed by other garbage values), this can be fixed by using "rep2"
   3137 mode, which does then receive:
   3138   1st block:   FFFFh, halfwords[00h,00h,..0Eh,0Eh], triple halfword[0Fh]
   3139   2nd block:   FFFFh, halfwords[10h,10h,..1Eh,1Eh], triple halfword[1Fh]
   3140   etc.
   3141 again, remove the first halfword (FFFFh) and the last halfword, and, take the
   3142 duplicated halfwords ANDed together. Unstable values occur only every 32
   3143 halfwords or so (probably when the SPU is simultaneously reading ADPCM data),
   3144 but do never occur on two continous halfwords, so, even if one halfword was
   3145 ORed by garbage, the other halfword is always correct, and the result of the
   3146 ANDed halfwords is 100% stable.
   3147 Note: The unstable reading does NOT occur always, when resetting the PSX a
   3148 couple of times it does occassionally boot-up with totally stable reading,
   3149 since there is no known way to activate the stable "mode" via I/O ports, the
   3150 stable/unstable behaviour does eventually depend on internal clock
   3151 dividers/multipliers, and whether they are starting in sync with the CPU or
   3152 not.
   3153 Caution: The "rep2" trick cannot be used in combination with reverb (reverb
   3154 seems to be using the Port 1F801DACh Sound RAM Data Transfer Control, too).
   3155 
   3156 SPU Interrupt
   3157 -------------
   3158 
   3159 1F801DA4h - Sound RAM IRQ Address (IRQ9)
   3160   15-0  Address in sound buffer divided by eight
   3161 See also: SPUCNT (IRQ enable/disable/acknowledge) and SPUSTAT (IRQ flag).
   3162 
   3163 Voice Interrupt
   3164 Triggers an IRQ when a voice reads ADPCM data from the IRQ address.
   3165 Mind that ADPCM cannot be stopped (uh, except, probably they CAN be stopped, by
   3166 setting the sample rate to zero?), all voices are permanently reading data from
   3167 SPU RAM - even in Noise mode, even if the Voice Volume is zero, and even if the
   3168 ADSR pattern has finished the Release period - so even inaudible voices can
   3169 trigger IRQs. To prevent unwanted IRQs, best set all unused voices to an
   3170 endless looped dummy ADPCM block.
   3171 For stable IRQs, the IRQ address should be aligned to the 16-byte ADPCM blocks.
   3172 If if the IRQ address is in the middle of a 16-byte ADPCM block, then the IRQ
   3173 doesn't seem to trigger always (unknown why, but it seems to occassionally miss
   3174 IRQs, even if the block gets repeated several times).
   3175 
   3176 Capture Interrupt
   3177 Setting the IRQ address to 0000h..01FFh (aka byte address 00000h..00FFFh) will
   3178 trigger IRQs on writes to the four capture buffers. Each of the four buffers
   3179 contains 400h bytes (=200h samples), so the IRQ rate will be around 86.13Hz
   3180 (44100Hz/200h).
   3181 CD-Audio capture is always active (even CD-Audio output is disabld in SPUCNT,
   3182 and even if the drive door is open). Voice capture is (probably) also always
   3183 active (even if the corresponding voice is off).
   3184 Capture IRQs do NOT occur if 1F801DACh.bit3-2 are both zero.
   3185 
   3186 Reverb Interrupt
   3187 Reverb is also triggering interrupts if the IRQ address is located in the
   3188 reverb buffer area. Unknown <which> of the various reverb read(s) and/or reverb
   3189 write(s) are triggering interrupts.
   3190 
   3191 Data Transfers
   3192 Data Transfers (usually via DMA4) to/from SPU-RAM do also trap SPU interrupts.
   3193 
   3194 Note
   3195 IRQ Address is used by Metal Gear Solid, Legend of Mana, Tokimeki Memorial 2,
   3196 Crash Team Racing, The Misadventures of Tron Bonne, and (somewhat?) by Need For
   3197 Speed 3.
   3198 
   3199 SPU Reverb Registers
   3200 --------------------
   3201 
   3202 Reverb Volume and Address Registers (R/W)
   3203   Port      Reg   Name    Type    Expl.
   3204   1F801D84h spu   vLOUT   volume  Reverb Output Volume Left
   3205   1F801D86h spu   vROUT   volume  Reverb Output Volume Right
   3206   1F801DA2h spu   mBASE   base    Reverb Work Area Start Address in Sound RAM
   3207   1F801DC0h rev00 dAPF1   disp    Reverb APF Offset 1
   3208   1F801DC2h rev01 dAPF2   disp    Reverb APF Offset 2
   3209   1F801DC4h rev02 vIIR    volume  Reverb Reflection Volume 1
   3210   1F801DC6h rev03 vCOMB1  volume  Reverb Comb Volume 1
   3211   1F801DC8h rev04 vCOMB2  volume  Reverb Comb Volume 2
   3212   1F801DCAh rev05 vCOMB3  volume  Reverb Comb Volume 3
   3213   1F801DCCh rev06 vCOMB4  volume  Reverb Comb Volume 4
   3214   1F801DCEh rev07 vWALL   volume  Reverb Reflection Volume 2
   3215   1F801DD0h rev08 vAPF1   volume  Reverb APF Volume 1
   3216   1F801DD2h rev09 vAPF2   volume  Reverb APF Volume 2
   3217   1F801DD4h rev0A mLSAME  src/dst Reverb Same Side Reflection Address 1 Left
   3218   1F801DD6h rev0B mRSAME  src/dst Reverb Same Side Reflection Address 1 Right
   3219   1F801DD8h rev0C mLCOMB1 src     Reverb Comb Address 1 Left
   3220   1F801DDAh rev0D mRCOMB1 src     Reverb Comb Address 1 Right
   3221   1F801DDCh rev0E mLCOMB2 src     Reverb Comb Address 2 Left
   3222   1F801DDEh rev0F mRCOMB2 src     Reverb Comb Address 2 Right
   3223   1F801DE0h rev10 dLSAME  src     Reverb Same Side Reflection Address 2 Left
   3224   1F801DE2h rev11 dRSAME  src     Reverb Same Side Reflection Address 2 Right
   3225   1F801DE4h rev12 mLDIFF  src/dst Reverb Different Side Reflect Address 1 Left
   3226   1F801DE6h rev13 mRDIFF  src/dst Reverb Different Side Reflect Address 1 Right
   3227   1F801DE8h rev14 mLCOMB3 src     Reverb Comb Address 3 Left
   3228   1F801DEAh rev15 mRCOMB3 src     Reverb Comb Address 3 Right
   3229   1F801DECh rev16 mLCOMB4 src     Reverb Comb Address 4 Left
   3230   1F801DEEh rev17 mRCOMB4 src     Reverb Comb Address 4 Right
   3231   1F801DF0h rev18 dLDIFF  src     Reverb Different Side Reflect Address 2 Left
   3232   1F801DF2h rev19 dRDIFF  src     Reverb Different Side Reflect Address 2 Right
   3233   1F801DF4h rev1A mLAPF1  src/dst Reverb APF Address 1 Left
   3234   1F801DF6h rev1B mRAPF1  src/dst Reverb APF Address 1 Right
   3235   1F801DF8h rev1C mLAPF2  src/dst Reverb APF Address 2 Left
   3236   1F801DFAh rev1D mRAPF2  src/dst Reverb APF Address 2 Right
   3237   1F801DFCh rev1E vLIN    volume  Reverb Input Volume Left
   3238   1F801DFEh rev1F vRIN    volume  Reverb Input Volume Right
   3239 All volume registers are signed 16bit (range -8000h..+7FFFh).
   3240 All src/dst/disp/base registers are addresses in SPU memory (divided by 8),
   3241 src/dst are relative to the current buffer address, the disp registers are
   3242 relative to src registers, the base register defines the start address of the
   3243 reverb buffer (the end address is fixed, at 7FFFEh). Writing a value to mBASE
   3244 does additionally set the current buffer address to that value.
   3245 
   3246 1F801D98h - Voice 0..23 Reverb mode aka Echo On (EON) (R/W)
   3247   0-23  Voice 0..23 Destination (0=To Mixer, 1=To Mixer and to Reverb)
   3248   24-31 Not used
   3249 Sets reverb for the channel. As soon as the sample ends, the reverb for that
   3250 channel is turned off... that's fine, but WHEN does it end?
   3251 In Reverb mode, the voice seems to output BOTH normal (immediately) AND via
   3252 Reverb (delayed).
   3253 
   3254 Reverb Bits in SPUCNT Register (R/W)
   3255 The SPUCNT register contains a Reverb Master Enable flag, and Reverb Enable
   3256 flags for External Audio input and CD Audio input.
   3257 When the Reverb Master Enable flag is cleared, the SPU stops to write any data
   3258 to the Reverb buffer (that is useful when zero-filling the reverb buffer;
   3259 ensuring that already-zero values aren't overwritten by still-nonzero values).
   3260 However, the Reverb Master Enable flag does not disable output from Reverb
   3261 buffer to the speakers (that might be useful to output uncompressed 22050Hz
   3262 samples) (otherwise, to disable the buffer output, set the Reverb Output volume
   3263 to zero and/or zerofill the reverb buffer).
   3264 
   3265 SPU Reverb Formula
   3266 ------------------
   3267 
   3268 Reverb Formula
   3269   ___Input from Mixer (Input volume multiplied with incoming data)_____________
   3270   Lin = vLIN * LeftInput    ;from any channels that have Reverb enabled
   3271   Rin = vRIN * RightInput   ;from any channels that have Reverb enabled
   3272   ____Same Side Reflection (left-to-left and right-to-right)___________________
   3273   [mLSAME] = (Lin + [dLSAME]*vWALL - [mLSAME-2])*vIIR + [mLSAME-2]  ;L-to-L
   3274   [mRSAME] = (Rin + [dRSAME]*vWALL - [mRSAME-2])*vIIR + [mRSAME-2]  ;R-to-R
   3275   ___Different Side Reflection (left-to-right and right-to-left)_______________
   3276   [mLDIFF] = (Lin + [dRDIFF]*vWALL - [mLDIFF-2])*vIIR + [mLDIFF-2]  ;R-to-L
   3277   [mRDIFF] = (Rin + [dLDIFF]*vWALL - [mRDIFF-2])*vIIR + [mRDIFF-2]  ;L-to-R
   3278   ___Early Echo (Comb Filter, with input from buffer)__________________________
   3279   Lout=vCOMB1*[mLCOMB1]+vCOMB2*[mLCOMB2]+vCOMB3*[mLCOMB3]+vCOMB4*[mLCOMB4]
   3280   Rout=vCOMB1*[mRCOMB1]+vCOMB2*[mRCOMB2]+vCOMB3*[mRCOMB3]+vCOMB4*[mRCOMB4]
   3281   ___Late Reverb APF1 (All Pass Filter 1, with input from COMB)________________
   3282   Lout=Lout-vAPF1*[mLAPF1-dAPF1], [mLAPF1]=Lout, Lout=Lout*vAPF1+[mLAPF1-dAPF1]
   3283   Rout=Rout-vAPF1*[mRAPF1-dAPF1], [mRAPF1]=Rout, Rout=Rout*vAPF1+[mRAPF1-dAPF1]
   3284   ___Late Reverb APF2 (All Pass Filter 2, with input from APF1)________________
   3285   Lout=Lout-vAPF2*[mLAPF2-dAPF2], [mLAPF2]=Lout, Lout=Lout*vAPF2+[mLAPF2-dAPF2]
   3286   Rout=Rout-vAPF2*[mRAPF2-dAPF2], [mRAPF2]=Rout, Rout=Rout*vAPF2+[mRAPF2-dAPF2]
   3287   ___Output to Mixer (Output volume multiplied with input from APF2)___________
   3288   LeftOutput  = Lout*vLOUT
   3289   RightOutput = Rout*vROUT
   3290   ___Finally, before repeating the above steps_________________________________
   3291   BufferAddress = MAX(mBASE, (BufferAddress+2) AND 7FFFEh)
   3292   Wait one 22050Hz cycle, then repeat the above stuff
   3293 
   3294 Notes
   3295 The values written to memory are saturated to -8000h..+7FFFh.
   3296 The multiplication results are divided by +8000h, to fit them to 16bit range.
   3297 All memory addresses are relative to the current BufferAddress, and wrapped
   3298 within mBASE..7FFFEh when exceeding that region.
   3299 All data in the Reverb buffer consists of signed 16bit samples. The Left and
   3300 Right Reverb Buffer addresses should be choosen so that one half of the buffer
   3301 contains Left samples, and the other half Right samples (ie. the data is
   3302 L,L,L,L,... R,R,R,R,...; it is NOT interlaced like L,R,L,R,...), during
   3303 operation, when the buffer address increases, the Left half will overwrite the
   3304 older samples of the Right half, and vice-versa.
   3305 The reverb hardware spends one 44100h cycle on left calculations, and the next
   3306 44100h cycle on right calculations (unlike as shown in the above formula, where
   3307 left/right are shown simultaneously at 22050Hz).
   3308 
   3309 Reverb Disable
   3310 SPUCNT.bit7 disables writes to reverb buffer, but reads from reverb buffer do
   3311 still occur. If vAPF2 is zero then it does simply read "Lout=[mLAPF2-dAPF2]"
   3312 and "Rout=[mRAPF2-dAPF2]". If vAPF2 is nonzero then it does additionally use
   3313 data from APF1, if vAPF1 and vAPF2 are both nonzero then it's also using data
   3314 from COMB. However, the SAME/DIFF stages aren't used when reverb is disabled.
   3315 
   3316 Bug
   3317 vIIR works only in range -7FFFh..+7FFFh. When set to -8000h, the multiplication
   3318 by -8000h is still done correctly, but, the final result (the value written to
   3319 memory) gets negated (this is a pretty strange feature, it is NOT a simple
   3320 overflow bug, it does affect the "+[mLSAME-2]" addition; although that part
   3321 normally shouldn't be affected by the "*vIIR" multiplication). Similar effects
   3322 might (?) occur on some other volume registers when they are set to -8000h.
   3323 
   3324 Speed of Sound
   3325 The speed of sound is circa 340 meters per second (in dry air, at room
   3326 temperature). For example, a voice that travels to a wall at 17 meters
   3327 distance, and back to its origin, should have a delay of 0.1 seconds.
   3328 
   3329 SPU Reverb Examples
   3330 -------------------
   3331 
   3332 Reverb Examples
   3333 Below are some Reverb examples, showing the required memory size (ie. set Port
   3334 1F801DA2h to "(80000h-size)/8"), and the Reverb register settings for Port
   3335 1F801DC0h..1F801DFFh, ie. arranged like so:
   3336   dAPF1  dAPF2  vIIR   vCOMB1 vCOMB2  vCOMB3  vCOMB4  vWALL   ;1F801DC0h..CEh
   3337   vAPF1  vAPF2  mLSAME mRSAME mLCOMB1 mRCOMB1 mLCOMB2 mRCOMB2 ;1F801DD0h..DEh
   3338   dLSAME dRSAME mLDIFF mRDIFF mLCOMB3 mRCOMB3 mLCOMB4 mRCOMB4 ;1F801DE0h..EEh
   3339   dLDIFF dRDIFF mLAPF1 mRAPF1 mLAPF2  mRAPF2  vLIN    vRIN    ;1F801DF0h..FEh
   3340 Also, don't forget to initialize Port 1F801D84h, 1F801D86h, 1F801D98h, and
   3341 SPUCNT, and to zerofill the Reverb Buffer (so that no garbage values are output
   3342 when activating reverb). For whatever reason, one MUST also initialize Port
   3343 1F801DACh (otherwise reverb stays off).
   3344 
   3345 Room (size=26C0h bytes)
   3346   007Dh,005Bh,6D80h,54B8h,BED0h,0000h,0000h,BA80h
   3347   5800h,5300h,04D6h,0333h,03F0h,0227h,0374h,01EFh
   3348   0334h,01B5h,0000h,0000h,0000h,0000h,0000h,0000h
   3349   0000h,0000h,01B4h,0136h,00B8h,005Ch,8000h,8000h
   3350 
   3351 Studio Small (size=1F40h bytes)
   3352   0033h,0025h,70F0h,4FA8h,BCE0h,4410h,C0F0h,9C00h
   3353   5280h,4EC0h,03E4h,031Bh,03A4h,02AFh,0372h,0266h
   3354   031Ch,025Dh,025Ch,018Eh,022Fh,0135h,01D2h,00B7h
   3355   018Fh,00B5h,00B4h,0080h,004Ch,0026h,8000h,8000h
   3356 
   3357 Studio Medium (size=4840h bytes)
   3358   00B1h,007Fh,70F0h,4FA8h,BCE0h,4510h,BEF0h,B4C0h
   3359   5280h,4EC0h,0904h,076Bh,0824h,065Fh,07A2h,0616h
   3360   076Ch,05EDh,05ECh,042Eh,050Fh,0305h,0462h,02B7h
   3361   042Fh,0265h,0264h,01B2h,0100h,0080h,8000h,8000h
   3362 
   3363 Studio Large (size=6FE0h bytes)
   3364   00E3h,00A9h,6F60h,4FA8h,BCE0h,4510h,BEF0h,A680h
   3365   5680h,52C0h,0DFBh,0B58h,0D09h,0A3Ch,0BD9h,0973h
   3366   0B59h,08DAh,08D9h,05E9h,07ECh,04B0h,06EFh,03D2h
   3367   05EAh,031Dh,031Ch,0238h,0154h,00AAh,8000h,8000h
   3368 
   3369 Hall (size=ADE0h bytes)
   3370   01A5h,0139h,6000h,5000h,4C00h,B800h,BC00h,C000h
   3371   6000h,5C00h,15BAh,11BBh,14C2h,10BDh,11BCh,0DC1h
   3372   11C0h,0DC3h,0DC0h,09C1h,0BC4h,07C1h,0A00h,06CDh
   3373   09C2h,05C1h,05C0h,041Ah,0274h,013Ah,8000h,8000h
   3374 
   3375 Half Echo (size=3C00h bytes)
   3376   0017h,0013h,70F0h,4FA8h,BCE0h,4510h,BEF0h,8500h
   3377   5F80h,54C0h,0371h,02AFh,02E5h,01DFh,02B0h,01D7h
   3378   0358h,026Ah,01D6h,011Eh,012Dh,00B1h,011Fh,0059h
   3379   01A0h,00E3h,0058h,0040h,0028h,0014h,8000h,8000h
   3380 
   3381 Space Echo (size=F6C0h bytes)
   3382   033Dh,0231h,7E00h,5000h,B400h,B000h,4C00h,B000h
   3383   6000h,5400h,1ED6h,1A31h,1D14h,183Bh,1BC2h,16B2h
   3384   1A32h,15EFh,15EEh,1055h,1334h,0F2Dh,11F6h,0C5Dh
   3385   1056h,0AE1h,0AE0h,07A2h,0464h,0232h,8000h,8000h
   3386 
   3387 Chaos Echo (almost infinite) (size=18040h bytes)
   3388   0001h,0001h,7FFFh,7FFFh,0000h,0000h,0000h,8100h
   3389   0000h,0000h,1FFFh,0FFFh,1005h,0005h,0000h,0000h
   3390   1005h,0005h,0000h,0000h,0000h,0000h,0000h,0000h
   3391   0000h,0000h,1004h,1002h,0004h,0002h,8000h,8000h
   3392 
   3393 Delay (one-shot echo) (size=18040h bytes)
   3394   0001h,0001h,7FFFh,7FFFh,0000h,0000h,0000h,0000h
   3395   0000h,0000h,1FFFh,0FFFh,1005h,0005h,0000h,0000h
   3396   1005h,0005h,0000h,0000h,0000h,0000h,0000h,0000h
   3397   0000h,0000h,1004h,1002h,0004h,0002h,8000h,8000h
   3398 
   3399 Reverb off (size=10h dummy bytes)
   3400   0000h,0000h,0000h,0000h,0000h,0000h,0000h,0000h
   3401   0000h,0000h,0001h,0001h,0001h,0001h,0001h,0001h
   3402   0000h,0000h,0001h,0001h,0001h,0001h,0001h,0001h
   3403   0000h,0000h,0001h,0001h,0001h,0001h,0000h,0000h
   3404 Note that the memory offsets should be 0001h here (not 0000h), otherwise
   3405 zerofilling the reverb buffer seems to fail (maybe because zero memory offsets
   3406 somehow cause the fill-value to mixed with the old value or so; that appears
   3407 even when reverb master enable is zero). Also, when not using reverb, Port
   3408 1F801D84h, 1F801D86h, 1F801D98h, and the SPUCNT reverb bits should be set to
   3409 zero.
   3410 
   3411 SPU Unknown Registers
   3412 ---------------------
   3413 
   3414 1F801DA0h - Some kind of a read-only status register.. or just garbage..?
   3415   0-15 Unknown?
   3416 Usually 9D78h, occassionaly changes to 17DAh or 108Eh for a short moment.
   3417 Other day: Usually 9CF8h, or occassionally 9CFAh.
   3418 Another day: Usually 0000h, or occassionally 4000h.
   3419 
   3420 1F801DBCh - 4 bytes - Unknown? (R/W)
   3421   80 21 4B DF
   3422 Other day (dots = same as above):
   3423   .. 31 .. ..
   3424 
   3425 1F801E60h - 32 bytes - Unknown? (R/W)
   3426   7E 61 A9 96 47 39 F9 1E E1 E1 80 DD E8 17 7F FB
   3427   FB BF 1D 6C 8F EC F3 04 06 23 89 45 C1 6D 31 82
   3428 Other day (dots = same as above):
   3429   .. .. .. .. .. .. .. .. .. .. .. .. .. .. 7B ..
   3430   .. .. .. .. .. .. .. .. 04 .. .. .. .. .. .. 86
   3431 
   3432 The bytes at 1F801DBCh and 1F801E60h usually have the above values on
   3433 cold-boot. The registers are read/write-able, although writing any values to
   3434 them doesn't seem to have any effect on sound output. Also, the SPU doesn't
   3435 seem to modify the registers at any time during sound output, nor reverb
   3436 calculations, nor activated external audio input... the registers seem to be
   3437 just some kind of general-purpose RAM.
   3438 
   3439 Interrupts
   3440 ----------
   3441 
   3442 1F801070h I_STAT - Interrupt status register (R=Status, W=Acknowledge)
   3443 1F801074h I_MASK - Interrupt mask register (R/W)
   3444 Status: Read I_STAT (0=No IRQ, 1=IRQ)
   3445 Acknowledge: Write I_STAT (0=Clear Bit, 1=No change)
   3446 Mask: Read/Write I_MASK (0=Disabled, 1=Enabled)
   3447   0     IRQ0 VBLANK (PAL=50Hz, NTSC=60Hz)
   3448   1     IRQ1 GPU   Can be requested via GP0(1Fh) command (rarely used)
   3449   2     IRQ2 CDROM
   3450   3     IRQ3 DMA
   3451   4     IRQ4 TMR0  Timer 0 aka Root Counter 0 (Sysclk or Dotclk)
   3452   5     IRQ5 TMR1  Timer 1 aka Root Counter 1 (Sysclk or H-blank)
   3453   6     IRQ6 TMR2  Timer 2 aka Root Counter 2 (Sysclk or Sysclk/8)
   3454   7     IRQ7 Controller and Memory Card - Byte Received Interrupt
   3455   8     IRQ8 SIO
   3456   9     IRQ9 SPU
   3457   10    IRQ10 Controller - Lightpen Interrupt (reportedly also PIO...?)
   3458   11-15 Not used (always zero)
   3459   16-31 Garbage
   3460 
   3461 Secondary IRQ10 Controller (Port 1F802030h)
   3462 --> EXP2 DTL-H2000 I/O Ports
   3463 
   3464 Interrupt Request / Execution
   3465 The interrupt request bits in I_STAT are edge-triggered, ie. the get set ONLY
   3466 if the corresponding interrupt source changes from "false to true".
   3467 If one or more interrupts are requested and enabled, ie. if "(I_STAT AND
   3468 I_MASK)=nonzero", then cop0r13.bit10 gets set, and when cop0r12.bit10 and
   3469 cop0r12.bit0 are set, too, then the interrupt gets executed.
   3470 
   3471 Interrupt Acknowledge
   3472 To acknowledge an interrupt, write a "0" to the corresponding bit in I_STAT.
   3473 Most interrupts (except IRQ0,4,5,6) must be additionally acknowledged at the
   3474 I/O port that has caused them (eg. JOY_CTRL.bit4).
   3475 Observe that the I_STAT bits are edge-triggered (they get set only on
   3476 High-to-Low, or False-to-True edges). The correct acknowledge order is:
   3477   First, acknowledge I_STAT                (eg. I_STAT.bit7=0)
   3478   Then, acknowledge corresponding I/O port (eg. JOY_CTRL.bit4=1)
   3479 When doing it vice-versa, the hardware may miss further IRQs (eg. when first
   3480 setting JOY_CTRL.4=1, then a new IRQ may occur in JOY_STAT.4 within a single
   3481 clock cycle, thereafter, setting I_STAT.7=0 would successfully reset I_STAT.7,
   3482 but, since JOY_STAT.4 is already set, there'll be no further edge, so I_STAT.7
   3483 won't be ever set in future).
   3484 
   3485 COP0 Interrupt Handling
   3486 Relevant COP0 registers are cop0r13 (CAUSE, reason flags), and cop0r12 (SR,
   3487 control flags), and cop0r14 (EPC, return address), and, cop0cmd=10h (aka RFE
   3488 opcode) is used to prepare the return from interrupts. For more info, see
   3489 --> COP0 - Exception Handling
   3490 
   3491 PSX specific COP0 Notes
   3492 COP0 has six hardware interrupt bits, of which, the PSX uses only cop0r13.bit10
   3493 (the other ones, cop0r13.bit11-15 are always zero). cop0r13.bit10 is NOT a
   3494 latch, ie. it gets automatically cleared as soon as "(I_STAT AND I_MASK)=zero",
   3495 so there's no need to do an acknowledge at the cop0 side. COP0 additionally has
   3496 two software interrupt bits, cop0r13.bit8-9, which do exist in the PSX, too,
   3497 these bits are read/write-able latches which can be set/cleared manually to
   3498 request/acknowledge exceptions by software.
   3499 
   3500 Halt Function (Wait for Interrupt)
   3501 The PSX doesn't have a HALT opcode, so, even if the program is merely waiting
   3502 for an interrupt to occur, the CPU is always running at full speed, which is
   3503 resulting in high power consumption, and, in case of emulators, high CPU
   3504 emulation load. To save energy, and to make emulation smoother on slower
   3505 computers, I've added a Halt function for use in emulators:
   3506 --> EXP2 Nocash Emulation Expansion
   3507 
   3508 DMA Channels
   3509 ------------
   3510 
   3511 DMA Register Summary
   3512   1F80108xh DMA0 channel 0  MDECin  (RAM to MDEC)
   3513   1F80109xh DMA1 channel 1  MDECout (MDEC to RAM)
   3514   1F8010Axh DMA2 channel 2  GPU (lists + image data)
   3515   1F8010Bxh DMA3 channel 3  CDROM   (CDROM to RAM)
   3516   1F8010Cxh DMA4 channel 4  SPU
   3517   1F8010Dxh DMA5 channel 5  PIO (Expansion Port)
   3518   1F8010Exh DMA6 channel 6  OTC (reverse clear OT) (GPU related)
   3519   1F8010F0h DPCR - DMA Control register
   3520   1F8010F4h DICR - DMA Interrupt register
   3521 These ports control DMA at the CPU-side. In most cases, you'll additionally
   3522 need to initialize an address (and transfer direction, transfer enabled, etc.)
   3523 at the remote-side (eg. at the GPU-side for DMA2).
   3524 
   3525 1F801080h+N*10h - D#_MADR - DMA base address (Channel 0..6) (R/W)
   3526   0-23  Memory Address where the DMA will start reading from/writing to
   3527   24-31 Not used (always zero)
   3528 In SyncMode=0, the hardware doesn't update the MADR registers (it will contain
   3529 the start address even during and after the transfer) (unless Chopping is
   3530 enabled, in that case it does update MADR, same does probably also happen when
   3531 getting interrupted by a higher priority DMA channel).
   3532 In SyncMode=1 and SyncMode=2, the hardware does update MADR (it will contain
   3533 the start address of the currently transferred block; at transfer end, it'll
   3534 hold the end-address in SyncMode=1, or the 00FFFFFFh end-code in SyncMode=2)
   3535 Note: Address bit0-1 are writeable, but any updated current/end addresses are
   3536 word-aligned with bit0-1 forced to zero.
   3537 
   3538 1F801084h+N*10h - D#_BCR - DMA Block Control (Channel 0..6) (R/W)
   3539 For SyncMode=0 (ie. for OTC and CDROM):
   3540   0-15  BC    Number of words (0001h..FFFFh) (or 0=10000h words)
   3541   16-31 0     Not used (usually 0 for OTC, or 1 ("one block") for CDROM)
   3542 For SyncMode=1 (ie. for MDEC, SPU, and GPU-vram-data):
   3543   0-15  BS    Blocksize (words) ;for GPU/SPU max 10h, for MDEC max 20h
   3544   16-31 BA    Amount of blocks  ;ie. total length = BS*BA words
   3545 For SyncMode=2 (ie. for GPU-command-lists):
   3546   0-31  0     Not used (should be zero) (transfer ends at END-CODE in list)
   3547 BC/BS/BA can be in range 0001h..FFFFh (or 0=10000h). For BS, take care not to
   3548 set the blocksize larger than the buffer of the corresponding unit can hold.
   3549 (GPU and SPU both have a 16-word buffer). A larger blocksize means faster
   3550 transfer.
   3551 SyncMode=1 decrements BA to zero, SyncMode=0 with chopping enabled decrements
   3552 BC to zero (aside from that two cases, D#_BCR isn't changed during/after
   3553 transfer).
   3554 
   3555 1F801088h+N*10h - D#_CHCR - DMA Channel Control (Channel 0..6) (R/W)
   3556   0       Transfer Direction    (0=To Main RAM, 1=From Main RAM)
   3557   1       Memory Address Step   (0=Forward;+4, 1=Backward;-4)
   3558   2-7     Not used              (always zero)
   3559   8       Chopping Enable       (0=Normal, 1=Chopping; run CPU during DMA gaps)
   3560   9-10    SyncMode, Transfer Synchronisation/Mode (0-3):
   3561             0  Start immediately and transfer all at once (used for CDROM, OTC)
   3562             1  Sync blocks to DMA requests   (used for MDEC, SPU, and GPU-data)
   3563             2  Linked-List mode              (used for GPU-command-lists)
   3564             3  Reserved                      (not used)
   3565   11-15   Not used              (always zero)
   3566   16-18   Chopping DMA Window Size (1 SHL N words)
   3567   19      Not used              (always zero)
   3568   20-22   Chopping CPU Window Size (1 SHL N clks)
   3569   23      Not used              (always zero)
   3570   24      Start/Busy            (0=Stopped/Completed, 1=Start/Enable/Busy)
   3571   25-27   Not used              (always zero)
   3572   28      Start/Trigger         (0=Normal, 1=Manual Start; use for SyncMode=0)
   3573   29      Unknown (R/W) Pause?  (0=No, 1=Pause?)     (For SyncMode=0 only?)
   3574   30      Unknown (R/W)
   3575   31      Not used              (always zero)
   3576 The Start/Trigger bit is automatically cleared upon BEGIN of the transfer, this
   3577 bit needs to be set only in SyncMode=0 (setting it in other SyncModes would
   3578 force the first block to be transferred instantly without DRQ, which isn't
   3579 desired).
   3580 The Start/Busy bit is automatically cleared upon COMPLETION of the transfer,
   3581 this bit must be always set for all SyncModes when starting a transfer.
   3582 For DMA6/OTC there are some restrictions, D6_CHCR has only three
   3583 read/write-able bits: Bit24,28,30. All other bits are read-only: Bit1 is always
   3584 1 (step=backward), and the other bits are always 0.
   3585 
   3586 1F8010F0h - DPCR - DMA Control Register (R/W)
   3587   0-2   DMA0, MDECin  Priority      (0..7; 0=Highest, 7=Lowest)
   3588   3     DMA0, MDECin  Master Enable (0=Disable, 1=Enable)
   3589   4-6   DMA1, MDECout Priority      (0..7; 0=Highest, 7=Lowest)
   3590   7     DMA1, MDECout Master Enable (0=Disable, 1=Enable)
   3591   8-10  DMA2, GPU     Priority      (0..7; 0=Highest, 7=Lowest)
   3592   11    DMA2, GPU     Master Enable (0=Disable, 1=Enable)
   3593   12-14 DMA3, CDROM   Priority      (0..7; 0=Highest, 7=Lowest)
   3594   15    DMA3, CDROM   Master Enable (0=Disable, 1=Enable)
   3595   16-18 DMA4, SPU     Priority      (0..7; 0=Highest, 7=Lowest)
   3596   19    DMA4, SPU     Master Enable (0=Disable, 1=Enable)
   3597   20-22 DMA5, PIO     Priority      (0..7; 0=Highest, 7=Lowest)
   3598   23    DMA5, PIO     Master Enable (0=Disable, 1=Enable)
   3599   24-26 DMA6, OTC     Priority      (0..7; 0=Highest, 7=Lowest)
   3600   27    DMA6, OTC     Master Enable (0=Disable, 1=Enable)
   3601   28-30 Unknown, Priority Offset or so? (R/W)
   3602   31    Unknown, no effect? (R/W)
   3603 Initial value on reset is 07654321h. If two or more channels have the same
   3604 priority setting, then the priority is determined by the channel number
   3605 (DMA0=Lowest, DMA6=Highest).
   3606 
   3607 1F8010F4h - DICR - DMA Interrupt Register (R/W)
   3608   0-5   Unknown  (read/write-able)
   3609   6-14  Not used (always zero)
   3610   15    Force IRQ (sets bit31)            (0=None, 1=Force Bit31=1)
   3611   16-22 IRQ Enable for DMA0..DMA6         (0=None, 1=Enable)
   3612   23    IRQ Master Enable for DMA0..DMA6  (0=None, 1=Enable)
   3613   24-30 IRQ Flags for DMA0..DMA6          (0=None, 1=IRQ)    (Write 1 to reset)
   3614   31    IRQ Master Flag                   (0=None, 1=IRQ)    (Read only)
   3615 IRQ flags in Bit(24+n) are set upon DMAn completion - but caution - they are
   3616 set ONLY if enabled in Bit(16+n).
   3617 Bit31 is a simple readonly flag that follows the following rules:
   3618   IF b15=1 OR (b23=1 AND (b16-22 AND b24-30)>0) THEN b31=1 ELSE b31=0
   3619 Upon 0-to-1 transition of Bit31, the IRQ3 flag (in Port 1F801070h) gets set.
   3620 Bit24-30 are acknowledged (reset to zero) when writing a "1" to that bits (and,
   3621 additionally, IRQ3 must be acknowledged via Port 1F801070h).
   3622 
   3623 1F8010F8h (usually 7FFAC68Bh? or 0BFAC688h)
   3624     (changes to 7FE358D1h after DMA transfer)
   3625 1F8010FCh (usually 00FFFFF7h) (...maybe OTC fill-value)
   3626     (stays so even after DMA transfer)
   3627 Contains strange read-only values (but not the usual "Garbage").
   3628 Not yet tested during transfer, might be remaining length and address?
   3629 
   3630 Commonly used DMA Control Register values for starting DMA transfers
   3631   DMA0 MDEC.IN  01000201h (always)
   3632   DMA1 MDEC.OUT 01000200h (always)
   3633   DMA2 GPU      01000200h (VramRead), 01000201h (VramWrite), 01000401h (List)
   3634   DMA3 CDROM    11000000h (normal), 11400100h (chopped, rarely used)
   3635   DMA4 SPU      01000201h (write), 01000200h (read, rarely used)
   3636   DMA5 PIO      N/A       (not used by any known games)
   3637   DMA6 OTC      11000002h (always)
   3638 XXX: DMA2 values 01000201h (VramWrite), 01000401h (List) aren't 100% confirmed
   3639 to be used by ALL existing games. All other values are always used as listed
   3640 above.
   3641 
   3642 DMA Transfer Rates
   3643   DMA0 MDEC.IN     1 clk/word   ;0110h clks per 100h words ;\plus whatever
   3644   DMA1 MDEC.OUT    1 clk/word   ;0110h clks per 100h words ;/decompression time
   3645   DMA2 GPU         1 clk/word   ;0110h clks per 100h words ;-plus ...
   3646   DMA3 CDROM/BIOS  24 clks/word ;1800h clks per 100h words ;\plus single/double
   3647   DMA3 CDROM/GAMES 40 clks/word ;2800h clks per 100h words ;/speed sector rate
   3648   DMA4 SPU         4 clks/word  ;0420h clks per 100h words ;-plus ...
   3649   DMA5 PIO         20 clks/word ;1400h clks per 100h words ;-not actually used
   3650   DMA6 OTC         1 clk/word   ;0110h clks per 100h words ;-plus nothing
   3651 MDEC decompression time is still unknown (may vary on RLE and color/mono).
   3652 GPU polygon rendering time is unknown (may be quite slow for large polys).
   3653 GPU vram read/write time is unknown (may vary on horizontal screen resolution).
   3654 CDROM BIOS default is 24 clks, for some reason most games change it to 40 clks.
   3655 SPU transfer is unknown (may have some extra delays).
   3656 XXX is SPU really only 4 clks (theoretically SPU access should be slower)?
   3657 PIO isn't used by any games (and if used: could be configured to other rates)
   3658 OTC is just writing to RAM without extra overload.
   3659 CDROM/SPU/PIO timings can be configured via Memory Control registers.
   3660 
   3661 DRAM Hyper Page mode
   3662 DMA is using DRAM Hyper Page mode, allowing it to access DRAM rows at 1 clock
   3663 cycle per word (effectively around 17 clks per 16 words, due to required row
   3664 address loading, probably plus some further minimal overload due to refresh
   3665 cycles). This is making DMA much faster than CPU memory accesses (CPU DRAM
   3666 access takes 1 opcode cycle plus 6 waitstates, ie. 7 cycles in total)
   3667 
   3668 CPU Operation during DMA
   3669 Basically, the CPU is stopped during DMA (theoretically, the CPU could be kept
   3670 running when accessing only cache, scratchpad and on-chip I/O ports like DMA
   3671 registers, and during the CDROM/SPU/PIO waitstates it could even access Main
   3672 RAM, but these situations aren't supported).
   3673 However, the CPU operation resumes during periods when DMA gets interrupted
   3674 (ie. after SyncMode 1 blocks, after SyncMode 2 list entries) (or in SyncMode 0
   3675 with Chopping enabled).
   3676 
   3677 Timers
   3678 ------
   3679 
   3680 1F801100h+N*10h - Timer 0..2 Current Counter Value (R/W)
   3681   0-15  Current Counter value (incrementing)
   3682   16-31 Garbage
   3683 This register is automatically incrementing. It is write-able (allowing to set
   3684 it to any value). It gets forcefully reset to 0000h on any write to the Counter
   3685 Mode register, and on counter overflow (either when exceeding FFFFh, or when
   3686 exceeding the selected target value).
   3687 
   3688 1F801104h+N*10h - Timer 0..2 Counter Mode (R/W)
   3689   0     Synchronization Enable (0=Free Run, 1=Synchronize via Bit1-2)
   3690   1-2   Synchronization Mode   (0-3, see lists below)
   3691          Synchronization Modes for Counter 0:
   3692            0 = Pause counter during Hblank(s)
   3693            1 = Reset counter to 0000h at Hblank(s)
   3694            2 = Reset counter to 0000h at Hblank(s) and pause outside of Hblank
   3695            3 = Pause until Hblank occurs once, then switch to Free Run
   3696          Synchronization Modes for Counter 1:
   3697            Same as above, but using Vblank instead of Hblank
   3698          Synchronization Modes for Counter 2:
   3699            0 or 3 = Stop counter at current value (forever, no h/v-blank start)
   3700            1 or 2 = Free Run (same as when Synchronization Disabled)
   3701   3     Reset counter to 0000h  (0=After Counter=FFFFh, 1=After Counter=Target)
   3702   4     IRQ when Counter=Target (0=Disable, 1=Enable)
   3703   5     IRQ when Counter=FFFFh  (0=Disable, 1=Enable)
   3704   6     IRQ Once/Repeat Mode    (0=One-shot, 1=Repeatedly)
   3705   7     IRQ Pulse/Toggle Mode   (0=Short Bit10=0 Pulse, 1=Toggle Bit10 on/off)
   3706   8-9   Clock Source (0-3, see list below)
   3707          Counter 0:  0 or 2 = System Clock,  1 or 3 = Dotclock
   3708          Counter 1:  0 or 2 = System Clock,  1 or 3 = Hblank
   3709          Counter 2:  0 or 1 = System Clock,  2 or 3 = System Clock/8
   3710   10    Interrupt Request       (0=Yes, 1=No) (Set after Writing)    (W=1) (R)
   3711   11    Reached Target Value    (0=No, 1=Yes) (Reset after Reading)        (R)
   3712   12    Reached FFFFh Value     (0=No, 1=Yes) (Reset after Reading)        (R)
   3713   13-15 Unknown (seems to be always zero)
   3714   16-31 Garbage (next opcode)
   3715 In one-shot mode, the IRQ is pulsed/toggled only once (one-shot mode doesn't
   3716 stop the counter, it just suppresses any further IRQs until a new write to the
   3717 Mode register occurs; if both IRQ conditions are enabled in Bit4-5, then
   3718 one-shot mode triggers only one of those conditions; whichever occurs first).
   3719 Normally, Pulse mode should be used (Bit10 is permanently set, except for a few
   3720 clock cycles when an IRQ occurs). In Toggle mode, Bit10 is set after writing to
   3721 the Mode register, and becomes inverted on each IRQ (in one-shot mode, it
   3722 remains zero after the IRQ) (in repeat mode it inverts Bit10 on each IRQ, so
   3723 IRQ4/5/6 are triggered only each 2nd time, ie. when Bit10 changes from 1 to 0).
   3724 
   3725 1F801108h+N*10h - Timer 0..2 Counter Target Value (R/W)
   3726   0-15  Counter Target value
   3727   16-31 Garbage
   3728 When the Target flag is set (Bit3 of the Control register), the counter
   3729 increments up to (including) the selected target value, and does then restart
   3730 at 0000h.
   3731 
   3732 Dotclock/Hblank
   3733 For more info on dotclock and hblank timings, see:
   3734 --> GPU Timings
   3735 Caution: Reading the Current Counter Value can be a little unstable (when using
   3736 dotclk or hblank as clock source); the GPU clock isn't in sync with the CPU
   3737 clock, so the timer may get changed during the CPU read cycle. As a workaround:
   3738 repeat reading the timer until the received value is the same (or slightly
   3739 bigger) than the previous value.
   3740 
   3741 CDROM Drive
   3742 -----------
   3743 
   3744 Playstation CDROM I/O Ports
   3745 --> CDROM Controller I/O Ports
   3746 
   3747 Playstation CDROM Commands
   3748 --> CDROM Controller Command Summary
   3749 --> CDROM - Control Commands
   3750 --> CDROM - Seek Commands
   3751 --> CDROM - Read Commands
   3752 --> CDROM - Status Commands
   3753 --> CDROM - CD Audio Commands
   3754 --> CDROM - Test Commands
   3755 --> CDROM - Secret Unlock Commands
   3756 --> CDROM - Video CD Commands
   3757 --> CDROM - Mainloop/Responses
   3758 --> CDROM - Response Timings
   3759 --> CDROM - Response/Data Queueing
   3760 
   3761 General CDROM Disk Format
   3762 --> CDROM Disk Format
   3763 --> CDROM Subchannels
   3764 --> CDROM Sector Encoding
   3765 --> CDROM Scrambling
   3766 --> CDROM XA Subheader, File, Channel, Interleave
   3767 --> CDROM XA Audio ADPCM Compression
   3768 --> CDROM ISO Volume Descriptors
   3769 --> CDROM ISO File and Directory Descriptors
   3770 --> CDROM ISO Misc
   3771 --> CDROM File Formats
   3772 --> CDROM Video CDs (VCD)
   3773 
   3774 Playstation CDROM Protection
   3775 --> CDROM Protection - SCEx Strings
   3776 --> CDROM Protection - Bypassing it
   3777 --> CDROM Protection - Modchips
   3778 --> CDROM Protection - Chipless Modchips
   3779 --> CDROM Protection - LibCrypt
   3780 
   3781 General CDROM Disk Images
   3782 --> CDROM Disk Images CCD/IMG/SUB (CloneCD)
   3783 --> CDROM Disk Images CDI (DiscJuggler)
   3784 --> CDROM Disk Images CUE/BIN/CDT (Cdrwin)
   3785 --> CDROM Disk Images MDS/MDF (Alcohol 120%)
   3786 --> CDROM Disk Images NRG (Nero)
   3787 --> CDROM Disk Image/Containers CDZ
   3788 --> CDROM Disk Image/Containers ECM
   3789 --> CDROM Subchannel Images
   3790 --> CDROM Disk Images Other Formats
   3791 
   3792 Playstation CDROM Coprocessor
   3793 --> CDROM Internal Info on PSX CDROM Controller
   3794 
   3795 CDROM Controller I/O Ports
   3796 --------------------------
   3797 
   3798 1F801800h - Index/Status Register (Bit0-1 R/W) (Bit2-7 Read Only)
   3799   0-1 Index   Port 1F801801h-1F801803h index (0..3 = Index0..Index3)   (R/W)
   3800   2   ADPBUSY XA-ADPCM fifo empty  (0=Empty) ;set when playing XA-ADPCM sound
   3801   3   PRMEMPT Parameter fifo empty (1=Empty) ;triggered before writing 1st byte
   3802   4   PRMWRDY Parameter fifo full  (0=Full)  ;triggered after writing 16 bytes
   3803   5   RSLRRDY Response fifo empty  (0=Empty) ;triggered after reading LAST byte
   3804   6   DRQSTS  Data fifo empty      (0=Empty) ;triggered after reading LAST byte
   3805   7   BUSYSTS Command/parameter transmission busy  (1=Busy)
   3806 Bit3,4,5 are bound to 5bit counters; ie. the bits become true at specified
   3807 amount of reads/writes, and thereafter once on every further 32 reads/writes.
   3808 
   3809 1F801801h.Index0 - Command Register (W)
   3810   0-7  Command Byte
   3811 Writing to this address sends the command byte to the CDROM controller, which
   3812 will then read-out any Parameter byte(s) which have been previously stored in
   3813 the Parameter Fifo. It takes a while until the command/parameters are
   3814 transferred to the controller, and until the response bytes are received; once
   3815 when completed, interrupt INT3 is generated (or INT5 in case of invalid
   3816 command/parameter values), and the response (or error code) can be then read
   3817 from the Response Fifo. Some commands additionally have a second response,
   3818 which is sent with another interrupt.
   3819 
   3820 1F801802h.Index0 - Parameter Fifo (W)
   3821   0-7  Parameter Byte(s) to be used for next Command
   3822 Before sending a command, write any parameter byte(s) to this address.
   3823 
   3824 1F801803h.Index0 - Request Register (W)
   3825   0-4 0    Not used (should be zero)
   3826   5   SMEN Want Command Start Interrupt on Next Command (0=No change, 1=Yes)
   3827   6   BFWR ...
   3828   7   BFRD Want Data         (0=No/Reset Data Fifo, 1=Yes/Load Data Fifo)
   3829 
   3830 1F801802h.Index0..3 - Data Fifo - 8bit/16bit (R)
   3831 After ReadS/ReadN commands have generated INT1, software must set the Want Data
   3832 bit (1F801803h.Index0.Bit7), then wait until Data Fifo becomes not empty
   3833 (1F801800h.Bit6), the datablock (disk sector) can be then read from this
   3834 register.
   3835   0-7  Data 8bit  (one byte), or alternately,
   3836   0-15 Data 16bit (LSB=First byte, MSB=Second byte)
   3837 The PSX hardware allows to read 800h-byte or 924h-byte sectors, indexed as
   3838 [000h..7FFh] or [000h..923h], when trying to read further bytes, then the PSX
   3839 will repeat the byte at index [800h-8] or [924h-4] as padding value.
   3840 Port 1F801802h can be accessed with 8bit or 16bit reads (ie. to read a
   3841 2048-byte sector, one can use 2048 load-byte opcodes, or 1024 load halfword
   3842 opcodes, or, more conventionally, a 512 word DMA transfer; the actual CDROM
   3843 databus is only 8bits wide, so CPU/DMA are apparently breaking 16bit/32bit
   3844 reads into multiple 8bit reads from 1F801802h).
   3845 
   3846 1F801801h.Index1 - Response Fifo (R)
   3847 1F801801h.Index0,2,3 - Response Fifo (R) (Mirrors)
   3848   0-7  Response Byte(s) received after sending a Command
   3849 The response Fifo is a 16-byte buffer, most or all responses are less than 16
   3850 bytes, after reading the last used byte (or before reading anything when the
   3851 response is 0-byte long), Bit5 of the Index/Status register becomes zero to
   3852 indicate that the last byte was received.
   3853 When reading further bytes: The buffer is padded with 00h's to the end of the
   3854 16-bytes, and does then restart at the first response byte (that, without
   3855 receiving a new response, so it'll always return the same 16 bytes, until a new
   3856 command/response has been sent/received).
   3857 
   3858 1F801802h.Index1 - Interrupt Enable Register (W)
   3859 1F801803h.Index0 - Interrupt Enable Register (R)
   3860 1F801803h.Index2 - Interrupt Enable Register (R) (Mirror)
   3861   0-4  Interrupt Enable Bits (usually all set, ie. 1Fh=Enable All IRQs)
   3862   5-7  Unknown/unused (write: should be zero) (read: usually all bits set)
   3863 XXX WRITE: bit5-7 unused should be 0 // READ: bit5-7 unused
   3864 
   3865 1F801803h.Index1 - Interrupt Flag Register (R/W)
   3866 1F801803h.Index3 - Interrupt Flag Register (R) (Mirror)
   3867   0-2   Read: Response Received   Write: 7=Acknowledge   ;INT1..INT7
   3868   3     Read: Unknown (usually 0) Write: 1=Acknowledge   ;INT8  ;XXX CLRBFEMPT
   3869   4     Read: Command Start       Write: 1=Acknowledge   ;INT10h;XXX CLRBFWRDY
   3870   5     Read: Always 1 ;XXX "_"   Write: 1=Unknown              ;XXX SMADPCLR
   3871   6     Read: Always 1 ;XXX "_"   Write: 1=Reset Parameter Fifo ;XXX CLRPRM
   3872   7     Read: Always 1 ;XXX "_"   Write: 1=Unknown              ;XXX CHPRST
   3873 Writing "1" bits to bit0-4 resets the corresponding IRQ flags; normally one
   3874 should write 07h to reset the response bits, or 1Fh to reset all IRQ bits.
   3875 Writing values like 01h is possible (eg. that would change INT3 to INT2, but
   3876 doing that would be total nonsense). After acknowledge, the Response Fifo is
   3877 made empty, and if there's been a pending command, then that command gets send
   3878 to the controller.
   3879 The lower 3bit indicate the type of response received,
   3880   INT0   No response received (no interrupt request)
   3881   INT1   Received SECOND (or further) response to ReadS/ReadN (and Play+Report)
   3882   INT2   Received SECOND response (to various commands)
   3883   INT3   Received FIRST response (to any command)
   3884   INT4   DataEnd (when Play/Forward reaches end of disk) (maybe also for Read?)
   3885   INT5   Received error-code (in FIRST or SECOND response)
   3886          INT5 also occurs on SECOND GetID response, on unlicensed disks
   3887          INT5 also occurs when opening the drive door (even if no command
   3888             was sent, ie. even if no read-command or other command is active)
   3889   INT6   N/A
   3890   INT7   N/A
   3891 The other 2bit indicate something else,
   3892   INT8   Unknown (never seen that bit set yet)
   3893   INT10h Command Start (when INT10h requested via 1F801803h.Index0.Bit5)
   3894 The response interrupts are queued, for example, if the 1st response is INT3,
   3895 and the second INT5, then INT3 is delivered first, and INT5 is not delivered
   3896 until INT3 is acknowledged (ie. the response interrupts are NOT ORed together
   3897 to produce INT7 or so). The upper bits however can be ORed with the lower bits
   3898 (ie. Command Start INT10h and 1st Response INT3 would give INT13h).
   3899 Caution - Unstable IRQ Flag polling
   3900 IRQ flag changes aren't synced with the MIPS CPU clock. If more than one bit
   3901 gets set (and the CPU is reading at the same time) then the CPU does
   3902 occassionally see only one of the newly bits:
   3903   0 ----------> 3   ;99.9%  normal case INT3's
   3904   0 ----------> 5   ;99%    normal case INT5's
   3905   0 ---> 1 ---> 3   ;0.1%   glitch: occurs about once per thousands of INT3's
   3906   0 ---> 4 ---> 5   ;1%     glitch: occurs about once per hundreds of INT5's
   3907 As workaround, do something like:
   3908  @@polling_lop:
   3909   irq_flags = [1F801803h] AND 07h       ;<-- 1st read (may be still unstable)
   3910   if irq_flags = 00h then goto @@polling_lop
   3911   irq_flags = [1F801803h] AND 07h       ;<-- 2nd read (should be stable now)
   3912   handle irq_flags and acknowledge them
   3913 The problem applies only when manually polling the IRQ flags (an actual IRQ
   3914 handler will get triggered when the flags get nonzero, and the flags will have
   3915 stabilized once when the IRQ handler is reading them) (except, a combination of
   3916 IRQ10h followed by IRQ3 can also have unstable LSBs within the IRQ handler).
   3917 The problem occurs only on older consoles (like LATE-PU-8), not on newer
   3918 consoles (like PSone).
   3919 
   3920 1F801802h.Index2 - Audio Volume for Left-CD-Out to Left-SPU-Input (W)
   3921 1F801803h.Index2 - Audio Volume for Left-CD-Out to Right-SPU-Input (W)
   3922 1F801801h.Index3 - Audio Volume for Right-CD-Out to Right-SPU-Input (W)
   3923 1F801802h.Index3 - Audio Volume for Right-CD-Out to Left-SPU-Input (W)
   3924 Allows to configure the CD for mono/stereo output (eg. values "80h,0,80h,0"
   3925 produce normal stereo volume, values "40h,40h,40h,40h" produce mono output of
   3926 equivalent volume).
   3927 When using bigger values, the hardware does have some incomplete saturation
   3928 support; the saturation works up to double volume (eg. overflows that occur on
   3929 "FFh,0,FFh,0" or "80h,80h,80h,80h" are clipped to min/max levels), however, the
   3930 saturation does NOT work properly when exceeding double volume (eg. mono with
   3931 quad-volume "FFh,FFh,FFh,FFh").
   3932   0-7  Volume Level (00h..FFh) (00h=Off, FFh=Max/Double, 80h=Default/Normal)
   3933 After changing these registers, write 20h to 1F801803h.Index3.
   3934 Unknown if any existing games are actually supporting mono output. Resident
   3935 Evil 2 uses these ports to produce fade-in/fade-out effects (although, for that
   3936 purpose, it should be much easier to use Port 1F801DB0h).
   3937 
   3938 1F801803h.Index3 - Audio Volume Apply Changes (by writing bit5=1)
   3939   0    ADPMUTE Mute ADPCM                 (0=Normal, 1=Mute)
   3940   1-4  -       Unused (should be zero)
   3941   5    CHNGATV Apply Audio Volume changes (0=No change, 1=Apply)
   3942   6-7  -       Unused (should be zero)
   3943 
   3944 1F801801h.Index1 - Sound Map Data Out (W)
   3945   0-7  Data
   3946 This register seems to be restricted to 8bit bus, unknown if/how the PSX DMA
   3947 controller can write to it (it might support only 16bit data for CDROM).
   3948 
   3949 1F801801h.Index2 - Sound Map Coding Info (W)
   3950   0    Mono/Stereo     (0=Mono, 1=Stereo)
   3951   1    Reserved        (0)
   3952   2    Sample Rate     (0=37800Hz, 1=18900Hz)
   3953   3    Reserved        (0)
   3954   4    Bits per Sample (0=4bit, 1=8bit)
   3955   5    Reserved        (0)
   3956   6    Emphasis        (0=Off, 1=Emphasis)
   3957   7    Reserved        (0)
   3958 
   3959  =============================================================================
   3960 
   3961 Command Execution
   3962 Command/Parameter transmission is indicated by bit7 of 1F801800h.
   3963 When that bit gets zero, the response can be read immediately (immediately for
   3964 MOST commands, but not ALL commands; so better wait for the IRQ).
   3965 Alternately, you can wait for an IRQ (which seems to take place MUCH later),
   3966 and then read the response.
   3967 If there are any pending cdrom interrupts, these MUST be acknowledged before
   3968 sending the command (otherwise bit7 of 1F801800h will stay set forever).
   3969 
   3970 Command Busy Flag - 1F801800h.Bit7
   3971 Indicates ready-to-send-new-command,
   3972   0=Ready to send a new command
   3973   1=Busy sending a command/parameters
   3974 Trying to send a new command in the Busy-phase causes malfunction (the older
   3975 command seems to get lost, the newer command executes and returns its results
   3976 and triggers an interrupt, but, thereafter, the controller seems to hang). So,
   3977 always wait until the Busy-bit goes off before sending a command.
   3978 When the Busy-flag goes off, a new command can be send immediately (even if the
   3979 response from the previous command wasn't received yet), however, the new
   3980 command stays in the Busy-phase until the IRQ from the previous command is
   3981 acknowledged, at that point the actual transmission of the new command starts,
   3982 and the Busy-flag goes off (once when the transmission completes).
   3983 
   3984 Misc
   3985 Trying to do a 32bit read from 1F801800h returns the 8bit value at 1F801800h
   3986 multiplied by 01010101h.
   3987 
   3988 To init the CD
   3989   -Flush all IRQs
   3990   -1F801803h.Index0=0
   3991   -Com_Delay=4901 (=1325h) (Port 1F801020h) (means 16bit or 32bit write?)
   3992      (the write seems to be 32bit, clearing the upper16bit of the register)
   3993   -Send two Getstat commands
   3994   -Send Command 0Ah (Init)
   3995   -Demute
   3996 
   3997 Seek-Busy Phase
   3998 Warning: most or all of the info in the sentence below appear to incorrect
   3999 (either that, or I didn't understand that rather confusing sentence).
   4000 REPORTEDLY:
   4001 "You should not send some commands while the CD is seeking (ie. Getstat returns
   4002 with bit6 set). Thing is that stat only gets updated after a new command. I
   4003 haven't tested this for other command, but for the play command (03h) you can
   4004 just keep repeating the [which?] command and checking stat returned by that,
   4005 for bit6 to go low (and bit7 to go high in this case). If you don't and try to
   4006 do a getloc [GetlocP and/or GetlocL?] directly after the play command reports
   4007 it's done [what done? meaning sending start-to-play was "done"? or meaning play
   4008 reached end-of-disc?], the CD will stop. (I guess the CD can't get it's current
   4009 location while it's seeking, so the logic stops the seek to get an exact fix,
   4010 but never restarts..)"
   4011 
   4012 Sound Map Flowchart
   4013 Sound Map mode allows to output XA-ADPCM from Main RAM (rather than from
   4014 CDROM).
   4015   SPU: Init Master Volume Left/Right (Port 1F801D80h/1F801D82h)
   4016   SPU: Init CD Audio Volume Left/Right (Port 1F801DB0h/1F801DB2h)
   4017   SPU: Enable CD Audio (Port 1F801DAAh.Bit0=1)
   4018   CDROM/CMD: send Stop command (probably better to avoid conflicts)
   4019   CDROM/CMD: send Demute command (if muted) (but works only if disc inserted)
   4020   CDROM/HOST: init Codinginfo (Port 1F801801h.Index2)
   4021   CDROM/HOST: enable ADPCM (Port 1F801803h.Index3.Bit0=0)  ;probably needed?
   4022   ... set dummy addr/len with DISHXFRC=1 ?  <-- NOT required !
   4023   ... set SMEN ... and dummy BFWR?    <-- BOTH bits required ?
   4024   ... maybe SMADPCLR (1F801803h.Index1.bit5) does clear SoundMap ADPCM buf?
   4025   transfer 900h bytes (same format as ADPCM sectors) (Port 1F801801h.Index1)
   4026   Note: Before sending a byte, one should wait for DRQs (1F801801h.Bit6=1)
   4027   Note: ADPCM output doesn't start until the last (900h'th) byte is transferred
   4028 Sound Map mode may be very useful for testing XA-ADPCM directly from within an
   4029 exe file (without needing a cdrom with ADPCM sectors). And, Sound Map supports
   4030 both 4bit and 8bit compression (the SPU supports only 4bit).
   4031 Caution: If ADPCM wasn't playing, and one sends one 900h-byte block, then it
   4032 will get stored in one of three 900h-byte slots in SRAM, and one would expect
   4033 that slot to be played when the ADPCM output starts - however, actually, the
   4034 hardware will more or less randomly play one of the three slots; not
   4035 necessarily the slot that was updated most recently.
   4036 
   4037 CDROM Controller Command Summary
   4038 --------------------------------
   4039 
   4040 Command Summary
   4041   Command          Parameters      Response(s)
   4042   00h -            -               INT5(11h,40h)  ;reportedly "Sync" uh?
   4043   01h Getstat      -               INT3(stat)
   4044   02h Setloc     E amm,ass,asect   INT3(stat)
   4045   03h Play       E (track)         INT3(stat), optional INT1(report bytes)
   4046   04h Forward    E -               INT3(stat), optional INT1(report bytes)
   4047   05h Backward   E -               INT3(stat), optional INT1(report bytes)
   4048   06h ReadN      E -               INT3(stat), INT1(stat), datablock
   4049   07h MotorOn    E -               INT3(stat), INT2(stat)
   4050   08h Stop       E -               INT3(stat), INT2(stat)
   4051   09h Pause      E -               INT3(stat), INT2(stat)
   4052   0Ah Init         -               INT3(late-stat), INT2(stat)
   4053   0Bh Mute       E -               INT3(stat)
   4054   0Ch Demute     E -               INT3(stat)
   4055   0Dh Setfilter  E file,channel    INT3(stat)
   4056   0Eh Setmode      mode            INT3(stat)
   4057   0Fh Getparam     -               INT3(stat,mode,null,file,channel)
   4058   10h GetlocL    E -               INT3(amm,ass,asect,mode,file,channel,sm,ci)
   4059   11h GetlocP    E -               INT3(track,index,mm,ss,sect,amm,ass,asect)
   4060   12h SetSession E session         INT3(stat), INT2(stat)
   4061   13h GetTN      E -               INT3(stat,first,last)  ;BCD
   4062   14h GetTD      E track (BCD)     INT3(stat,mm,ss)       ;BCD
   4063   15h SeekL      E -               INT3(stat), INT2(stat)  ;\use prior Setloc
   4064   16h SeekP      E -               INT3(stat), INT2(stat)  ;/to set target
   4065   17h -            -               INT5(11h,40h)  ;reportedly "SetClock" uh?
   4066   18h -            -               INT5(11h,40h)  ;reportedly "GetClock" uh?
   4067   19h Test         sub_function    depends on sub_function (see below)
   4068   1Ah GetID      E -               INT3(stat), INT2/5(stat,flg,typ,atip,"SCEx")
   4069   1Bh ReadS      E?-               INT3(stat), INT1(stat), datablock
   4070   1Ch Reset        -               INT3(stat), Delay
   4071   1Dh GetQ       E adr,point       INT3(stat), INT2(10bytesSubQ,peak_lo) ;\not
   4072   1Eh ReadTOC      -               INT3(late-stat), INT2(stat)           ;/vC0
   4073   1Fh VideoCD      sub,a,b,c,d,e   INT3(stat,a,b,c,d,e)   ;<-- SCPH-5903 only
   4074   1Fh..4Fh -       -               INT5(11h,40h)  ;-Unused/invalid
   4075   50h Secret 1     -               INT5(11h,40h)  ;\
   4076   51h Secret 2     "Licensed by"   INT5(11h,40h)  ;
   4077   52h Secret 3     "Sony"          INT5(11h,40h)  ; Secret Unlock Commands
   4078   53h Secret 4     "Computer"      INT5(11h,40h)  ; (not in version vC0, and,
   4079   54h Secret 5     "Entertainment" INT5(11h,40h)  ; nonfunctional in japan)
   4080   55h Secret 6     "<region>"      INT5(11h,40h)  ;
   4081   56h Secret 7     -               INT5(11h,40h)  ;/
   4082   57h SecretLock   -               INT5(11h,40h)  ;-Secret Lock Command
   4083   58h..5Fh Crash   -               Crashes the HC05 (jumps into a data area)
   4084   6Fh..FFh -       -               INT5(11h,40h)  ;-Unused/invalid
   4085 E = Error 80h appears on some commands (02h..09h, 0Bh..0Dh, 10h..16h, 1Ah,
   4086 1Bh?, and 1Dh) when the disk is missing, or when the drive unit is disconnected
   4087 from the mainboard.
   4088 
   4089 sub_function numbers (for command 19h)
   4090 Test commands are invoked with command number 19h, followed by a sub_function
   4091 number as first parameter byte. The Kernel seems to be using only sub_function
   4092 20h (to detect the CDROM Controller version).
   4093   sub  params  response           ;Effect
   4094   00h      -   INT3(stat)         ;Force motor on, clockwise, even if door open
   4095   01h      -   INT3(stat)         ;Force motor on, anti-clockwise, super-fast
   4096   02h      -   INT3(stat)         ;Force motor on, anti-clockwise, super-fast
   4097   03h      -   INT3(stat)         ;Force motor off (ignored during spin-up)
   4098   04h      -   INT3(stat)         ;Start SCEx reading and reset counters
   4099   05h      -   INT3(total,success);Stop SCEx reading and get counters
   4100   06h *    n   INT3(old)  ;\early ;Adjust balance in RAM, send CX(30+n XOR 7)
   4101   07h *    n   INT3(old)  ; PSX   ;Adjust gain in RAM, send CX(38+n XOR 7)
   4102   08h *    n   INT3(old)  ;/only  ;Adjust balance in RAM only
   4103   06h..0Fh -   INT5(11h,10h)      ;N/A (11h,20h when NONZERO number of params)
   4104   10h      -   INT3(stat) ;CX(..) ;Force motor on, anti-clockwise, super-fast
   4105   11h      -   INT3(stat) ;CX(03) ;Move Lens Up (leave parking position)
   4106   12h      -   INT3(stat) ;CX(02) ;Move Lens Down (enter parking position)
   4107   13h      -   INT3(stat) ;CX(28) ;Move Lens Outwards
   4108   14h      -   INT3(stat) ;CX(2C) ;Move Lens Inwards
   4109   15h      -   INT3(stat) ;CX(22) ;If motor on: Move outwards,inwards,motor off
   4110   16h      -   INT3(stat) ;CX(23) ;No effect?
   4111   17h      -   INT3(stat) ;CX(E8) ;Force motor on, clockwise, super-fast
   4112   18h      -   INT3(stat) ;CX(EA) ;Force motor on, anti-clockwise, super-fast
   4113   19h      -   INT3(stat) ;CX(25) ;No effect?
   4114   1Ah      -   INT3(stat) ;CX(21) ;No effect?
   4115   1Bh..1Fh -   INT5(11h,10h)      ;N/A (11h,20h when NONZERO number of params)
   4116   20h      -   INT3(yy,mm,dd,ver) ;Get cdrom BIOS date/version (yy,mm,dd,ver)
   4117   21h      -   INT3(n)            ;Get Drive Switches (bit0=POS0, bit1=DOOR)
   4118   22h ***  -   INT3("for ...")    ;Get Region ID String
   4119   23h ***  -   INT3("CXD...")     ;Get Chip ID String for Servo Amplifier
   4120   24h ***  -   INT3("CXD...")     ;Get Chip ID String for Signal Processor
   4121   25h ***  -   INT3("CXD...")     ;Get Chip ID String for Decoder/FIFO
   4122   26h..2Fh -   INT5(11h,10h)      ;N/A (11h,20h when NONZERO number of params)
   4123   30h *    i,x,y     INT3(stat)       ;Prototype/Debug stuff   ;\supported on
   4124   31h *    x,y       INT3(stat)       ;Prototype/Debug stuff   ; early PSX only
   4125   4xh *    i         INT3(x,y)        ;Prototype/Debug stuff   ;/
   4126   30h..4Fh ..        INT5(11h,10h)    ;N/A always 11h,10h (no matter of params)
   4127   50h      a[,b[,c]] INT3(stat)       ;Servo/Signal send CX(a:b:c)
   4128   51h **   39h,xx    INT3(stat,hi,lo) ;Servo/Signal send CX(39xx) with response
   4129   51h..5Fh -         INT5(11h,10h)    ;N/A
   4130   60h      lo,hi     INT3(databyte)   ;HC05 SUB-CPU read RAM and I/O ports
   4131   61h..70h -         INT5(11h,10h)    ;N/A
   4132   71h ***  adr       INT3(databyte)   ;Decoder Read one register
   4133   72h ***  adr,dat   INT3(stat)       ;Decoder Write one register
   4134   73h ***  adr,len   INT3(databytes..);Decoder Read multiple registers, bugged
   4135   74h ***  adr,len,..INT3(stat)       ;Decoder Write multiple registers, bugged
   4136   75h ***  -         INT3(lo,hi,lo,hi);Decoder Get Host Xfer Info Remain/Addr
   4137   76h ***  a,b,c,d   INT3(stat)       ;Decoder Prepare Transfer to/from SRAM
   4138   77h..FFh -         INT5(11h,10h)    ;N/A
   4139   80h..8Fh a,b       ?                ;seem to do something on PS2
   4140 * sub_functions 06h..08h, 30h..31h, and 4xh are supported only in vC0 and vC1.
   4141 ** sub_function 51h is supported only in BIOS version vC2 and up.
   4142 *** sub_functions 22h..25h, 71h..76h supported only in BIOS version vC1 and up.
   4143 
   4144 Unsupported GetQ,VCD,SecretUnlock (command 1Dh,1Fh,5xh)
   4145 INT5 will be returned if the command is unsupported. That, WITHOUT removing the
   4146 Parameters from the FIFO, so the parameters will be accidently passed to the
   4147 NEXT command. To avoid that: clear the parameter FIFO via
   4148 [1F801803h.Index1]=40h after receiving the INT5 error.
   4149 
   4150 CDROM - Control Commands
   4151 ------------------------
   4152 
   4153 Sync - Command 00h --> INTx(stat+1,40h) (?)
   4154 Reportedly "command does not succeed until all other commands complete. This
   4155 can be used for synchronization - hence the name."
   4156 Uh, actually, returns error code 40h = Invalid Command...?
   4157 
   4158 Setfilter - Command 0Dh,file,channel --> INT3(stat)
   4159 Automatic ADPCM (CD-ROM XA) filter ignores sectors except those which have the
   4160 same channel and file numbers in their subheader. This is the mechanism used to
   4161 select which of multiple songs in a single .XA file to play.
   4162 Setfilter does not affect actual reading (sector reads still occur for all
   4163 sectors).
   4164 XXX err... that is... does not affect reading of non-ADPCM sectors (normal
   4165 "data" sectors are kept received regardless of Setfilter).
   4166 
   4167 Setmode - Command 0Eh,mode --> INT3(stat)
   4168   7   Speed       (0=Normal speed, 1=Double speed)
   4169   6   XA-ADPCM    (0=Off, 1=Send XA-ADPCM sectors to SPU Audio Input)
   4170   5   Sector Size (0=800h=DataOnly, 1=924h=WholeSectorExceptSyncBytes)
   4171   4   Ignore Bit  (0=Normal, 1=Ignore Sector Size and Setloc position)
   4172   3   XA-Filter   (0=Off, 1=Process only XA-ADPCM sectors that match Setfilter)
   4173   2   Report      (0=Off, 1=Enable Report-Interrupts for Audio Play)
   4174   1   AutoPause   (0=Off, 1=Auto Pause upon End of Track) ;for Audio Play
   4175   0   CDDA        (0=Off, 1=Allow to Read CD-DA Sectors; ignore missing EDC)
   4176 The "Ignore Bit" does reportedly force a sector size of 2328 bytes (918h),
   4177 however, that doesn't seem to be true. Instead, Bit4 seems to cause the
   4178 controller to ignore the sector size in Bit5 (instead, the size is kept from
   4179 the most recent Setmode command which didn't have Bit4 set). Also, Bit4 seems
   4180 to cause the controller to ignore the <exact> Setloc position (instead, data is
   4181 randomly returned from the "Setloc position minus 0..3 sectors"). And, Bit4
   4182 causes INT1 to return status.Bit3=set (IdError). Purpose of Bit4 is unknown?
   4183 
   4184 Init - Command 0Ah --> INT3(stat) --> INT2(stat)
   4185 Multiple effects at once. Sets mode=20h, activates drive motor, Standby, abort
   4186 all commands.
   4187 
   4188 Reset - Command 1Ch,(...) --> INT3(stat) --> Delay(1/8 seconds)
   4189 Resets the drive controller, reportedly, same as opening and closing the drive
   4190 door. The command executes no matter if/how many parameters are used (tested
   4191 with 0..7 params). INT3 indicates that the command was started, but there's no
   4192 INT that would indicate when the command is finished, so, before sending any
   4193 further commands, a delay of 1/8 seconds (or 400000h clock cycles) must be
   4194 issued by software.
   4195 Note: Executing the command produces a click sound in the drive mechanics,
   4196 maybe it's just a rapid motor on/off, but it might something more serious, like
   4197 ignoring the /POS0 signal...?
   4198 
   4199 MotorOn - Command 07h --> INT3(stat) --> INT2(stat)
   4200 Activates the drive motor, works ONLY if the motor was off (otherwise fails
   4201 with INT5(stat,20h); that error code would normally indicate "wrong number of
   4202 parameters", but means "motor already on" in this case).
   4203 Commands like Read, Seek, and Play are automatically starting the Motor when
   4204 needed (which makes the MotorOn command rather useless, and it's rarely used by
   4205 any games).
   4206 Myth: Older homebrew docs are referring to MotorOn as "Standby", claiming that
   4207 it would work similar as "Pause", that is wrong: the command does NOT pause
   4208 anything (if the motor is on, then it does simply trigger INT5, but without
   4209 pausing reading or playing).
   4210 Note: The game "Nightmare Creatures 2" does actually attempt to use MotorOn to
   4211 "pause" after reading files, but the hardware does simply ignore that attempt
   4212 (aside from doing the INT5 thing).
   4213 
   4214 Stop - Command 08h --> INT3(stat) --> INT2(stat)
   4215 Stops motor with magnetic brakes (stops within a second or so) (unlike
   4216 power-off where it'd keep spinning for about 10 seconds), and moves the drive
   4217 head to the begin of the first track. Official way to restart is command 0Ah,
   4218 but almost any command will restart it.
   4219 The first response returns the current status (this already with bit5 cleared),
   4220 the second response returns the new status (with bit1 cleared).
   4221 
   4222 Pause - Command 09h --> INT3(stat) --> INT2(stat)
   4223 Aborts Reading and Playing, the motor is kept spinning, and the drive head
   4224 maintains the current location within reasonable error.
   4225 The first response returns the current status (still with bit5 set if a Read
   4226 command was active), the second response returns the new status (with bit5
   4227 cleared).
   4228 
   4229 Data/ADPCM Sector Filtering/Delivery
   4230 The PSX CDROM BIOS is first trying to send sectors to the ADPCM decoder, and,
   4231 if that didn't work out, then it's trying to send them to the main CPU (and if
   4232 that didn't work out either, then it's silently ignoring the sector).
   4233  try_deliver_as_adpcm_sector:
   4234   reject if CD-DA AUDIO format
   4235   reject if sector isn't MODE2 format
   4236   reject if adpcm_disabled(setmode.6)
   4237   reject if filter_enabled(setmode.3) AND selected file/channel doesn't match
   4238   reject if submode isn't audio+realtime (bit2 and bit6 must be both set)
   4239   deliver: send sector to xa-adpcm decoder when passing above cases
   4240  try_deliver_as_data_sector:
   4241   reject data-delivery if "try_deliver_as_adpcm_sector" did do adpcm-delivery
   4242   reject if filter_enabled(setmode.3) AND submode is audio+realtime (bit2+bit6)
   4243   1st delivery attempt: send INT1+data, unless there's another INT pending
   4244   delay, and retry at later time... but this time with file/channel checking!
   4245   reject if filter_enabled(setmode.3) AND selected file/channel doesn't match
   4246   2nd delivery attempt: send INT1+data, unless there's another INT pending
   4247 BUG: Note that the data delivery is done in two different attempts: The first
   4248 one regardless of file/channel, and the second one only on matching
   4249 file/channel (if filtering is enabled).
   4250 
   4251 CDROM - Seek Commands
   4252 ---------------------
   4253 
   4254 Setloc - Command 02h,amm,ass,asect --> INT3(stat)
   4255 Sets the seek target - but without yet starting the seek operation. The actual
   4256 seek is invoked by certain commands: SeekL (Data) and SeekP (Audio) are doing
   4257 plain seeks (and do Pause after completion). ReadN/ReadS are similar to SeekL
   4258 (and do start reading data after the seek operation). Play is similar to SeekP
   4259 (and does start playing audio after the seek operation).
   4260 The amm,ass,asect parameters refer to the entire disk (not to the current
   4261 track). To seek to a specific location within a specific track, use GetTD to
   4262 get the start address of the track, and add the desired time offset to it.
   4263 
   4264 SeekL - Command 15h --> INT3(stat) --> INT2(stat)
   4265 Seek to Setloc's location in data mode (using data sector header position data,
   4266 which works/exists only on Data tracks, not on CD-DA Audio tracks).
   4267 After the seek, the disk stays on the seeked location forever (namely: when
   4268 seeking sector N, it does stay at around N-8..N-0 in single speed mode, or at
   4269 around N-5..N+2 in double speed mode).
   4270 Trying to use SeekL on Audio CDs passes okay on the first response, but (after
   4271 two seconds or so) the second response will return an error (stat+4,04h), and
   4272 stop the drive motor... that error doesn't appear ALWAYS though... works in
   4273 some situations... such like when previously reading data sectors or so...?
   4274 
   4275 SeekP - Command 16h --> INT3(stat) --> INT2(stat)
   4276 Seek to Setloc's location in audio mode (using the Subchannel Q position data,
   4277 which works on both Audio on Data disks).
   4278 After the seek, the disk stays on the seeked location forever (namely: when
   4279 seeking sector N, it does stay at around N-9..N-1 in single speed mode, or at
   4280 around N-2..N in double speed mode).
   4281 Note: Some older docs claim that SeekP would recurse only "MM:SS" of the
   4282 "MM:SS:FF" position from Setloc - that is wrong, it does seek to MM:SS:FF
   4283 (verified on a PSone).
   4284 After the seek, status is stat.bit7=0 (ie. audio playback off), until sending a
   4285 new Play command (without parameters) to start playback at the seeked location.
   4286 
   4287 SetSession - Command 12h,session --> INT3(stat) --> INT2(stat)
   4288 Seeks to session (ie. moves the drive head to the session, with stat bit6 set
   4289 during the seek phase).
   4290 When issued during active-play, the command returns error code 80h.
   4291 When issued during play-spin-up, play is aborted.
   4292   ___Errors___
   4293   session = 00h causes error code 10h.     ;INT5(03h,10h), no 2nd/3rd response
   4294   ___On a non-multisession-disk___
   4295   session = 01h passes okay.               ;INT3(stat), and once INT2(stat)
   4296   session = 02h or higher cause seek error ;INT3(stat), and twice INT5(06h,40h)
   4297   ___On a multisession-disk with N sessions___
   4298   session = 01h..N+1 passes okay   ;where N+1 moves to the END of LAST session
   4299   session = N+2 or higher cause seek error  ;2nd response = INT5(06h,20h)
   4300 after seek error --> disk stops spinning at 2nd response, then restarts
   4301 spinning for 1 second or so, then stops spinning forever... and following
   4302 gettn/gettd/getid/getlocl/getlocp fail with error 80h...
   4303 The command does automatically read the TOC of the new session.
   4304 There seems to be no way to determine the current sessions number (via Getparam
   4305 or so), and more important, no way to determine if the disk is a multi-session
   4306 disk or not... except by trial... which would stop the drive motor on seek
   4307 errors on single-session disks...?
   4308 For setloc, one must probably specifiy minutes within the 1st track of the new
   4309 session (the 1st track of 1st session usually/always starts at 00:02:00, but
   4310 for other sessions one would need to use GetTD)...?
   4311 
   4312 CDROM - Read Commands
   4313 ---------------------
   4314 
   4315 ReadN - Command 06h --> INT3(stat) --> INT1(stat) --> datablock
   4316 Read with retry. The command responds once with "stat,INT3", and then it's
   4317 repeatedly sending "stat,INT1 --> datablock", that is continued even after a
   4318 successful read has occured; use the Pause command to terminate the repeated
   4319 INT1 responses.
   4320 Unknown which responses are sent in case of read errors?
   4321 ====
   4322 ReadN and ReadS cause errors if you're trying to read an unlicensed CD or CD-R
   4323 without a mod chip. Sectors on Audio CDs can be read only when CDDA is enabled
   4324 via Setmode (otherwise error code 40h is returned).
   4325 ====
   4326 Actually, Read seems to work on unlicensed CD-R's, but the returned data is the
   4327 whole sector or so (the 2048 data bytes preceeded by a 12byte header, and
   4328 probably/maybe followed by error-correction info; in fact the total received
   4329 data in the Data Fifo is 4096 bytes; the last some bytes probably being
   4330 garbage) (however error correction is NOT performed by hardware, so the 2048
   4331 data bytes may be trashy) (however, if the error correction info IS received,
   4332 then error correction could be performed by software) (also Setloc doesn't seem
   4333 to work accurately on unlicensed CD-R's).
   4334 ====
   4335      ;Read occasionally returns 11h,40h ..? when TOC isn't loaded?
   4336 After receiving INT1, the Kernel does,
   4337   [1F801800h]=00h
   4338   00h=[1F801800h]
   4339   [1F801803h]=00h
   4340   00h=[1F801803h]
   4341   [1F801800h]=00h
   4342   [1F801803h]=80h
   4343 and then,
   4344   [1F801018h]=00020943h  ;cdrom_delay
   4345   [1F801020h]=0000132Ch  ;com_delay
   4346 then,
   4347   x=[1F8010F4h] AND 00FFFFFFh   ;result is 00840000h
   4348   [1F8010F4h] = x OR 00880000h
   4349   [1F8010F0h] = [1F8010F0h] OR 00008000h
   4350   [1F8010B0h] = A0010000h ;addr
   4351   [1F8010B4h] = 00010200h ;LSBs=num words, MSBs=ignored/bullshit
   4352   [1F8010B4h] = 11000000h ;DMA control
   4353 thereafter,
   4354   [1F801800h]=01h
   4355   [1F801803h]=40h    ;reset parameter fifo
   4356   [0]=00000000h
   4357   [0]=00000001h
   4358   [0]=00000002h
   4359   [0]=00000003h
   4360   [1F801800h]=00h
   4361   [1F801801h]=09h    ;command9 (pause)
   4362 
   4363 ReadS - Command 1Bh --> INT3(stat) --> INT1(stat) --> datablock
   4364 Read without automatic retry. Not sure what that means... does WHAT on errors?
   4365 Maybe intended for continous streaming video output (to skip bad frames, rather
   4366 than to interrupt the stream by performing read-retrys).
   4367 
   4368 ReadN/ReadS
   4369 Both ReadN/ReadS are reading data sequentially, starting at the sector
   4370 specified with Setloc, and then automatically reading the following sectors.
   4371 
   4372 CDROM Incoming Data / Buffer Overrun Timings
   4373 The Read commands are continously receiving 75 sectors per second (or 150
   4374 sectors at double speed), and, basically, the software must be fast enough to
   4375 process that amount of incoming data. However, the PSX hardware includes a
   4376 buffer that can hold up to a handful (exact number is unknown?) of sectors, so,
   4377 occasional delays of more than 1/75 seconds between processing two sectors
   4378 aren't causing lost sectors, unless the delay(s) are summing up too much. The
   4379 relevant steps for receiving data are:
   4380   Wait for Interrupt Request (INT1)          ;indicates that data is available
   4381   Send Data Request (1F801803h.Index0.Bit7=1);accept data
   4382   Acknowledge INT1                           ;
   4383   Copy Data to Main RAM (via I/O or DMA)     ;read data
   4384 The Data Request accepts the data for the currently pending interrupt, it
   4385 should be usually issued between receiving/acknowledging INT1 (however, it can
   4386 be also issued shortly after the acknowledge; even if there are further sectors
   4387 in the buffer, there seems to be a small delay between the acknowledge and the
   4388 next interrupt, and Data Requests during that period are still treated to
   4389 belong to the old interrupt).
   4390 If a buffer overrun has occured <before> issuing the Data Request, then wrong
   4391 data will be received, ie. some sectors will be skipped (the hardware doesn't
   4392 seem to support a buffer-overrun error flag? Anyways, see GetlocL description
   4393 for a possible way to detect buffer-overruns).
   4394 If a buffer overrun occurs <after> issuing the Data Request, then the requested
   4395 data can be still read via I/O or DMA intactly, ie. the requested data is
   4396 "locked", and the overrun will affect only the following sectors.
   4397 
   4398 ReadTOC - Command 1Eh --> INT3(stat) --> INT2(stat)
   4399   Caution: Supported only in BIOS version vC1 and up. Not supported in vC0.
   4400 Reread the Table of Contents of current session without reset. The command is
   4401 rather slow, the second response appears after about 1 second delay. The
   4402 command itself returns only status information (to get the actual TOC info, use
   4403 GetTD and GetTN commands).
   4404 Note: The TOC contains information about the tracks on the disk (not file names
   4405 or so, that kind of information is obtained via Read commands). The TOC is read
   4406 automatically on power-up, when opening/closing the drive door, and when
   4407 changing sessions (so, normally, it isn't required to use this command).
   4408 
   4409 Setloc, Read, Pause
   4410 A normal CDROM access (such like reading a file) consists of three commands:
   4411   Setloc, Read, Pause
   4412 Normally one shouldn't mess up the ordering of those commands, but if one does,
   4413 following rules do apply:
   4414 Setloc is memorizing the wanted target, and marks it as unprocessed, and has no
   4415 other effect (it doesn't start reading or seeking, and doesn't interrupt or
   4416 redirect any active reads).
   4417 If Read is issued with an unprocessed Setloc, then the drive is automatically
   4418 seeking the Setloc location (and marks Setloc as processed).
   4419 If Read is issued without an unprocessed Setloc, the following happens: If
   4420 reading is already in progress then it just continues reading. If Reading was
   4421 Paused, then reading resumes at the most recently received sector (ie.
   4422 returning that sector once another time).
   4423 
   4424 CDROM - Status Commands
   4425 -----------------------
   4426 
   4427 Status code (stat)
   4428 The 8bit status code is returned by Getstat command (and many other commands),
   4429 the meaning of the separate stat bits is:
   4430   7  Play          Playing CD-DA         ;\only ONE of these bits can be set
   4431   6  Seek          Seeking               ; at a time (ie. Read/Play won't get
   4432   5  Read          Reading data sectors  ;/set until after Seek completion)
   4433   4  ShellOpen     Once shell open (0=Closed, 1=Is/was Open)
   4434   3  IdError       (0=Okay, 1=GetID denied) (also set when Setmode.Bit4=1)
   4435   2  SeekError     (0=Okay, 1=Seek error)     (followed by Error Byte)
   4436   1  Spindle Motor (0=Motor off, or in spin-up phase, 1=Motor on)
   4437   0  Error         Invalid Command/parameters (followed by Error Byte)
   4438 If the shell is closed, then bit4 is automatically reset to zero after reading
   4439 stat with the Getstat command (most or all other commands do not reset that bit
   4440 after reading). If stat bit0 or bit2 is set, then the normal respons(es) and
   4441 interrupt(s) are not send, and, instead, INT5 occurs, and an error-byte is send
   4442 as second response byte, with the following values:
   4443   ___These values appear in the FIRST response; with stat.bit0 set___
   4444   10h - Invalid Sub_function (for command 19h), or invalid parameter value
   4445   20h - Wrong number of parameters
   4446   40h - Invalid command
   4447   80h - Cannot respond yet (eg. required info was not yet read from disk yet)
   4448            (namely, TOC not-yet-read or so)
   4449            (also appears if no disk inserted at all)
   4450   ___These values appear in the SECOND response; with stat.bit2 set___
   4451   04h - Seek failed (when trying to use SeekL on Audio CDs)
   4452   ___These values appear even if no command was sent; with stat.bit2 set___
   4453   08h - Drive door became opened
   4454 80h appears on some commands (02h..09h, 0Bh..0Dh, 10h..16h, 1Ah, 1Bh?, and 1Dh)
   4455 when the disk is missing, or when the drive unit is disconnected from the
   4456 mainboard.
   4457 
   4458 Stat Seek/Play/Read bits
   4459 There's is only max ONE of the three Seek/Play/Read bits set at a time, ie.
   4460 during Seek, ONLY the seek bit is set (and Read or Play doesn't get until seek
   4461 completion), that is important for Gran Turismo 1, which checks for seek
   4462 completion by waiting for READ getting set (rather than waiting for SEEK
   4463 getting cleared).
   4464 
   4465 Getstat - Command 01h --> INT3(stat)
   4466 Returns stat (like many other commands), and additionally does reset the shell
   4467 open flag (for the following commands; unless the shell is still opened). This
   4468 is different as for most or all other commands (which may return stat, but
   4469 which do not reset the shell open flag).
   4470 In other docs, the command is eventually referred to as "Nop", believing that
   4471 it does nothing than returning stat (ignoring the fact that it's having the
   4472 special shell open reset feature).
   4473 
   4474 Getparam - Command 0Fh --> INT3(stat,mode,null,file,channel)
   4475 Returns stat (see Getstat above), mode (see Setmode), a null byte (always 00h),
   4476 and file/channel filter values (see Setfilter).
   4477 
   4478 GetlocL - Command 10h --> INT3(amm,ass,asect,mode,file,channel,sm,ci)
   4479 Retrieves 4-byte sector header, plus 4-byte subheader of the current sector.
   4480 GetlocL can be send during active Read commands (but, mind that the
   4481 GetlocL-INT3-response can't be received until any pending Read-INT1's are
   4482 acknowledged).
   4483 The PSX hardware can buffer a handful of sectors, the INT1 handler receives the
   4484 <oldest> buffered sector, the GetlocL command returns the header and subheader
   4485 of the <newest> buffered sector. Note: If the returned <newest> sector number
   4486 is much bigger than the expected <oldest> sector number, then it's likely that
   4487 a buffer overrun has occured.
   4488 GetlocL fails (with error code 80h) when playing Audio CDs (or Audio Tracks on
   4489 Data CDs). These errors occur because Audio sectors don't have any
   4490 header/subheader (instead, equivalent data is stored in Subchannel Q, which can
   4491 be read with GetlocP).
   4492 GetlocL also fails (with error code 80h) when the drive is in Seek phase (such
   4493 like shortly after a new ReadN/ReadS command). In that case one can retry
   4494 issuing GetlocL (until it passes okay, ie. until the seek has completed).
   4495 During Seek, the drive seems to decode only Subchannel position data (but no
   4496 header/subheader data), accordingly GetlocL won't work during seek (however,
   4497 GetlocP does work during Seek).
   4498 
   4499 GetlocP - Command 11h - INT3(track,index,mm,ss,sect,amm,ass,asect)
   4500 Retrieves 8 bytes of position information from Subchannel Q with ADR=1. Mainly
   4501 intended for displaying the current audio position during Play. All results are
   4502 in BCD.
   4503   track:  track number (AAh=Lead-out area) (FFh=unknown, toc, none?)
   4504   index:  index number (Usually 01h)
   4505   mm:     minute number within track (00h and up)
   4506   ss:     second number within track (00h to 59h)
   4507   sect:   sector number within track (00h to 74h)
   4508   amm:    minute number on entire disk (00h and up)
   4509   ass:    second number on entire disk (00h to 59h)
   4510   asect:  sector number on entire disk (00h to 74h)
   4511 Note: GetlocP is also used for reading the LibCrypt protection data:
   4512 --> CDROM Protection - LibCrypt
   4513 
   4514 GetTN - Command 13h --> INT3(stat,first,last) ;BCD
   4515 Get first track number, and last track number in the TOC of the current
   4516 Session. The number of tracks in the current session can be calculated as
   4517 (last-first+1). The first track number is usually 01h in the first (or only)
   4518 session, and "last track of previous session plus 1" in further sessions.
   4519 
   4520 GetTD - Command 14h,track --> INT3(stat,mm,ss) ;BCD
   4521 For a disk with NN tracks, parameter values 01h..NNh return the start of the
   4522 specified track, parameter value 00h returns the end of the last track, and
   4523 parameter values bigger than NNh return error code 10h.
   4524 The GetTD values are relative to Index=1 and are rounded down to second
   4525 boundaries (eg. if track=N Index=0 starts at 12:34:56, and Track=N Index=1
   4526 starts at 12:36:56, then GetTD(N) will return 12:36, ie. the sector number is
   4527 truncated, and the Index=0 region is skipped).
   4528 
   4529 GetQ - Command 1Dh,adr,point --> INT3(stat) --> INT2(10bytesSubQ,peak_lo)
   4530   Caution: Supported only in BIOS version vC1 and up. Not supported in vC0.
   4531   Caution: When unsupported, Parameter Fifo isn't cleared after the command.
   4532 Allows to read 10 bytes from Subchannel Q in Lead-In (see CDROM Subchannels
   4533 chapter for details). Unlike GetTD, this command allows to receive the exact
   4534 MM:SS:FF address of the point'ed Track (GetTD reads a memorized MM:SS value
   4535 from RAM, whilst GetQ reads the full MM:SS:FF from the disk, which is slower
   4536 than GetTD, due to the disk-access).
   4537 With ADR=1, point can be a any point number for ADR=1 in Lead-in (eg.
   4538 01h..99h=Track N, A2h=Lead-Out). The returned 10 bytes are raw SubQ data
   4539 (starting with the ADR/Control value; of which the lower 4bits are always
   4540 ADR=1).
   4541 The 11th returned byte is the Peak LSB (similar as in Play+Report, but in this
   4542 case only the LSB is transferred, which is apparently a bug in CDROM BIOS, the
   4543 programmer probably wanted to send 10 bytes without peak, or 12 bytes with full
   4544 peak; although peak wouldn't be too useful, as it should always zero during
   4545 Lead-In... but some discs do seem return non-zero values for whatever reason).
   4546 Aside from ADR=1, a value of ADR=5 can be used on multisession disks (eg. with
   4547 point B0h, C0h). Not sure if any other ADR values can be used (ADR=3, ISRC is
   4548 usually not in the Lead-In, ADR=2, EAN may be in the lead-in, but one may need
   4549 to specify point equal to the first EAN byte).
   4550 If the ADR/Point combination isn't found, then a timeout occurs after circa 6
   4551 seconds (to avoid this, use GetTN to see which tracks/points exist). After the
   4552 timeout, the command starts playing track 1. If the controller wasn't already
   4553 in audio mode before sending the command, then it does switch off the drive
   4554 motor for a moment (that, after the timeout, and before starting playback).
   4555 In case of timeout, the normal INT3/INT2 responses are replaced by
   4556 INT3/INT5/INT5 (INT3 at command start, 1st INT5 at timeout/stop, and 2nd INT5
   4557 at restart/play).
   4558 Note: GetQ sends scratch noise to the SPU while seeking to the Lead-In area.
   4559 
   4560 GetID - Command 1Ah --> INT3(stat) --> INT2/5 (stat,flags,type,atip,"SCEx")
   4561   Drive Status           1st Response   2nd Response
   4562   Door Open              INT5(11h,80h)  N/A
   4563   Spin-up                INT5(01h,80h)  N/A
   4564   Detect busy            INT5(03h,80h)  N/A
   4565   No Disk                INT3(stat)     INT5(08h,40h, 00h,00h, 00h,00h,00h,00h)
   4566   Audio Disk             INT3(stat)     INT5(0Ah,90h, 00h,00h, 00h,00h,00h,00h)
   4567   Unlicensed:Mode1       INT3(stat)     INT5(0Ah,80h, 00h,00h, 00h,00h,00h,00h)
   4568   Unlicensed:Mode2       INT3(stat)     INT5(0Ah,80h, 20h,00h, 00h,00h,00h,00h)
   4569   Unlicensed:Mode2+Audio INT3(stat)     INT5(0Ah,90h, 20h,00h, 00h,00h,00h,00h)
   4570   Debug/Yaroze:Mode2     INT3(stat)     INT2(02h,00h, 20h,00h, 20h,20h,20h,20h)
   4571   Licensed:Mode2         INT3(stat)     INT2(02h,00h, 20h,00h, 53h,43h,45h,4xh)
   4572   Modchip:Audio/Mode1    INT3(stat)     INT2(02h,00h, 00h,00h, 53h,43h,45h,4xh)
   4573 The status byte (ie. the first byte in the responses), may differ in some
   4574 cases; values shown above are typically received when issuing GetID shortly
   4575 after power-up; however, shortly after the detect-busy phase, seek-busy flag
   4576 (bit6) bit may be set, and, after issuing commands like Play/Read/Stop,
   4577 bit7,6,5,1 may differ. The meaning of the separate 2nd response bytes is:
   4578   1st byte: stat  (as usually, but with bit3 same as bit7 in 2nd byte)
   4579   2nd byte: flags (bit7=denied, bit4=audio... or reportedly import, uh?)
   4580     bit7: Licensed (0=Licensed Data CD, 1=Denied Data CD or Audio CD)
   4581     bit6: Missing  (0=Disk Present, 1=Disk Missing)
   4582     bit4: Audio CD (0=Data CD, 1=Audio CD) (always 0 when Modchip installed)
   4583   3rd byte: Disk type (from TOC Point=A0h) (eg. 00h=Audio or Mode1, 20h=Mode2)
   4584   4th byte: Usually 00h (or 8bit ATIP from Point=C0h, if session info exists)
   4585     that 8bit ATIP value is taken form the middle 8bit of the 24bit ATIP value
   4586   5th-8th byte: SCEx region (eg. ASCII "SCEE" = Europe) (0,0,0,0 = Unlicensed)
   4587 The fourth letter of the "SCEx" string contains region information: "SCEI"
   4588 (Japan/NTSC), "SCEA" (America/NTSC), "SCEE" (Europe/PAL). The "SCEx" string is
   4589 displayed in the intro, and the PSX refuses to boot if it doesn't match up for
   4590 the local region.
   4591 With a modchip installed, the same response is sent for Mode1 and Audio disks
   4592 (except for Audio disks with very short TOCs (eg. singles) because SCEX reading
   4593 is aborted immediately after reading all TOC entries on Audio disks); whether
   4594 it is Audio or Mode1 can be checked by examining Subchannel Q ADR/Control.Bit6
   4595 (eg. via command 19h,60h,50h,00h).
   4596 Yaroze does return "SCEA" for SCEA discs, but, for SCEI,SCEE,SCEW discs it does
   4597 return four ASCII spaces (20h).
   4598 
   4599 CDROM - CD Audio Commands
   4600 -------------------------
   4601 
   4602 To play CD-DA Audio CDs, init the following SPU Registers: CD Audio Volume,
   4603 Main Volume, and SPU Control Bit0. Then send Demute command, and Play command.
   4604 
   4605 Mute - Command 0Bh --> INT3(stat)
   4606 Turn off audio streaming to SPU (affects both CD-DA and XA-ADPCM).
   4607 Even when muted, the CDROM controller is internally processing audio sectors
   4608 (as seen in 1F801800h.Bit2, which works as usually for XA-ADPCM), muting is
   4609 just forcing the CD output volume to zero.
   4610 Mute is used by Dino Crisis 1 to mute noise during modchip detection.
   4611 
   4612 Demute - Command 0Ch --> INT3(stat)
   4613 Turn on audio streaming to SPU (affects both CD-DA and XA-ADPCM). The Demute
   4614 command is needed only if one has formerly used the Mute command (by default,
   4615 the PSX is demuted after power-up (...and/or after Init command?), and is
   4616 demuted after cdrom-booting).
   4617 
   4618 Play - Command 03h (,track) --> INT3(stat) --> optional INT1(report bytes)
   4619 Starts CD Audio Playback. The parameter is optional, if there's no parameter
   4620 given (or if it is 00h), then play either starts at Setloc position (if there
   4621 was a pending unprocessed Setloc), or otherwise starts at the current location
   4622 (eg. the last point seeked, or the current location of the current song; if it
   4623 was already playing). For a disk with N songs, Parameters 1..N are starting the
   4624 selected track. Parameters N+1..99h are restarting the begin of current track.
   4625 The motor is switched off automatically when Play reaches the end of the disk,
   4626 and INT4(stat) is generated (with stat.bit7 cleared).
   4627 The track parameter seems to be ignored when sending Play shortly after
   4628 power-up (ie. when the drive hasn't yet read the TOC).
   4629 ===
   4630 "Play is almost identical to CdlReadS, believe it or not. The main difference
   4631 is that this does not trigger a completed read IRQ. CdlPlay may be used on data
   4632 sectors. However, all sectors from data tracks are treated as 00, so no sound
   4633 is played. As CdlPlay is reading, the audio data appears in the sector buffer,
   4634 but is not reliable. Game Shark "enhancement CDs" for the 2.x and 3.x versions
   4635 used this to get around the PSX copy protection."
   4636 Hmmm, what/where is the sector buffer... in the SPU?
   4637 And, what/who are the 2.x and 3.x versions?
   4638 
   4639 Forward - Command 04h --> INT3(stat) --> optional INT1(report bytes)
   4640 Backward - Command 05h --> INT3(stat) --> optional INT1(report bytes)
   4641 After sending the command, the drive is in fast forward/backward mode, skipping
   4642 every some sectors. The skipping rate is fixed (it doesn't increase after some
   4643 seconds) (however, it increases when (as long as) sending the command again and
   4644 again). The sound becomes (obviously) non-continous, and also rather very
   4645 silent, muffled, and almost inaudible (that's making it rather useless; unless
   4646 it's combined with a track/minute/second display). To terminate
   4647 forward/backward, send a new Play command (with no parameters, so play starts
   4648 at the "searched" location). Backward automatically switches to Play when
   4649 reaching the begin of Track 1. Forward automatically Stops the drive motor with
   4650 INT4(stat) when reaching the end of the last track.
   4651 Forward/Backwards work only if the drive was in Play state, and only if Play
   4652 had already started (ie. not shortly/immediately after a Play command); if the
   4653 drive was not in Play state, then INT5(stat+1,80h) occurs.
   4654 
   4655 Setmode bits used for Play command
   4656 During Play, only bit 7,2,1 of Setmode are used, all other Setmode bits are
   4657 ignored (that, including bit0, ie. during Play the drive is always in CD-DA
   4658 mode, regardless of that bit).
   4659 Bit7 (double speed) should be usually off, although it can be used for a fast
   4660 forward effect (with audible output). Bit2 (report) activates an optional
   4661 interrupt for Play, Forward, and Backward commands (see below). Bit1
   4662 (autopause) pauses play at the end of the track.
   4663 
   4664 Report --> INT1(stat,track,index,mm/amm,ss+80h/ass,sect/asect,peaklo,peakhi)
   4665 With report enabled via Setmode, the Play, Forward, and Backward commands do
   4666 repeatedly generate INT1 interrupts, with eight bytes response length. The
   4667 interrupt isn't generated on ALL sectors, and the response changes between
   4668 absolute time, and time within current track (the latter one indicated by bit7
   4669 of ss):
   4670   amm/ass/asect are returned on asect=00h,20h,40h,60h   ;-absolute time
   4671   mm/ss+80h/sect are returned on asect=10h,30h,50h,70h  ;-within current track
   4672   (or, in case of read errors, report may be returned on other asect's)
   4673 The last two response bytes (peaklo,peakhi) contain the Peak value, as received
   4674 from the CXD2510Q Signal Processor. That is: An unsigned absolute peak level in
   4675 lower 15bit, and an L/R flag in upper bit. The L/R bit is toggled after each
   4676 SUBQ read, however the PSX Report mode does usually forward SUBQ only every 10
   4677 frames (but does read SUBQ in <every> frame), so L/R will stay stuck in one
   4678 setting (but may toggle after one second; ie. after 75 frames). And, peak is
   4679 reset after each read, so 9 of the 10 frames are lost.
   4680 Note: Report mode affects only CD Audio (not Data, nor XA-ADPCM sectors).
   4681 
   4682 AutoPause --> INT4(stat)
   4683 Autopause can be enabled/disabled via Setmode.bit1:
   4684   Setmode.bit1=1: AutoPause=On  --> Issue INT4(stat) and PAUSE at end of TRACK
   4685   Setmode.bit1=0: AutoPause=Off --> Issue INT4(stat) and STOP at end of DISC
   4686 End of Track is determined by sensing a track number transition in SubQ
   4687 position info. After autopause, the disc stays at the <end> of the old track,
   4688 NOT at the <begin> of the next track (so trying to resume playing by sending a
   4689 new Play command without new Seek/Setloc command will instantly pause again).
   4690 Caution: SubQ track transitions may pause instantly when accidently starting to
   4691 play at the end of the previous track rather than at begin of desired track
   4692 (this <might> happen due to seek inaccuracies, for example, GetTD does round
   4693 down TOC entries from MM:SS:FF to MM:SS:00, which may be off by 0.99 seconds,
   4694 although this error should be usually compensated by the leading 2-second
   4695 pregap/index0 region at the begin of each track, unfortunately there are a few
   4696 .CUE sheet files that do lack both PREGAP and INDEX 00 entries on audio tracks,
   4697 which might cause problems with autopause).
   4698 AutoPause is used by Rayman and Tactics Ogre.
   4699 
   4700 Playing XA-ADPCM Sectors (compressed audio data)
   4701 Aside from normal uncompressed CD Audio disks, the PSX can also play XA-ADPCM
   4702 compressed sectors. XA-ADPCM sectors are organized in Files (not in tracks),
   4703 and are "played" with Read command (not Play command).
   4704 To play XA-ADPCM, initialize the SPU for CD Audio input (as described above),
   4705 enable ADPCM via Setmode, then select the sector via Setloc, and issue a Read
   4706 command (typically ReadS).
   4707 XA-ADPCM sectors are interleaved, ie. only each Nth sector should be played
   4708 (where "N" depends on the Motor Speed, mono/stereo format, and sample rate). If
   4709 the "other" sectors do contain XA-ADPCM data too, then the Setfilter command
   4710 (and XA-Filter enable flag in Setmode) must be used to select the desired
   4711 sectors. If the "other" sectors do contain code or data (eg. MDEC video data)
   4712 which is wanted to be send to the CPU, then SetFilter isn't required to be
   4713 enabled (although it shouldn't disturb reading even if it is enabled).
   4714 If XA-ADPCM (and/or XA-Filter) is enabled via Setmode, then INT1 is generated
   4715 only for non-ADPCM sectors.
   4716 The Setmode sector-size selection is don't care for forwarding XA-ADPCM sectors
   4717 to the SPU (the hardware does always decompress all 900h bytes).
   4718 
   4719 CDROM - Test Commands
   4720 ---------------------
   4721 
   4722 --> CDROM - Test Commands - Version, Switches, Region, Chipset, SCEx
   4723 --> CDROM - Test Commands - Test Drive Mechanics
   4724 --> CDROM - Test Commands - Prototype Debug Transmission
   4725 --> CDROM - Test Commands - Read/Write Decoder RAM and I/O Ports
   4726 --> CDROM - Test Commands - Read HC05 SUB-CPU RAM and I/O Ports
   4727 
   4728 CDROM - Test Commands - Version, Switches, Region, Chipset, SCEx
   4729 ----------------------------------------------------------------
   4730 
   4731 19h,20h --> INT3(yy,mm,dd,ver)
   4732 Indicates the date (Year-month-day, in BCD format) and version of the HC05
   4733 CDROM controller BIOS. Known/existing values are:
   4734   (unknown)        ;DTL-H2000 (with SPC700 instead HC05)
   4735   94h,09h,19h,C0h  ;PSX (PU-7)               19 Sep 1994, version vC0 (a)
   4736   94h,11h,18h,C0h  ;PSX (PU-7)               18 Nov 1994, version vC0 (b)
   4737   95h,05h,16h,C1h  ;PSX (LATE-PU-8)          16 May 1995, version vC1 (a)
   4738   95h,07h,24h,C1h  ;PSX (LATE-PU-8)          24 Jul 1995, version vC1 (b)
   4739   95h,07h,24h,D1h  ;PSX (LATE-PU-8,debug ver)24 Jul 1995, version vD1 (debug)
   4740   96h,08h,15h,C2h  ;PSX (PU-16, Video CD)    15 Aug 1996, version vC2 (VCD)
   4741   96h,08h,18h,C1h  ;PSX (LATE-PU-8,yaroze)   18 Aug 1996, version vC1 (yaroze)
   4742   96h,09h,12h,C2h  ;PSX (PU-18) (japan)      12 Sep 1996, version vC2 (a.jap)
   4743   97h,01h,10h,C2h  ;PSX (PU-18) (us/eur)     10 Jan 1997, version vC2 (a)
   4744   97h,08h,14h,C2h  ;PSX (PU-20)              14 Aug 1997, version vC2 (b)
   4745   98h,06h,10h,C3h  ;PSX (PU-22)              10 Jun 1998, version vC3 (a)
   4746   99h,02h,01h,C3h  ;PSX/PSone (PU-23, PM-41) 01 Feb 1999, version vC3 (b)
   4747   A1h,03h,06h,C3h  ;PSone/late (PM-41(2))    06 Jun 2001, version vC3 (c)
   4748   (unknown)        ;PS2,   xx xxx xxxx, late PS2 models...?
   4749 
   4750 19h,21h --> INT3(flags)
   4751 Returns the current status of the POS0 and DOOR switches. Bit0=HeadIsAtPos0,
   4752 Bit1=DoorIsOpen, Bit2-7=AlwaysZero.
   4753 
   4754 19h,22h --> INT3("for Europe")
   4755   Caution: Supported only in BIOS version vC1 and up. Not supported in vC0.
   4756 Indicates the region that console is to be used in:
   4757   INT5(11h,10h)      --> NTSC, Japan (vC0)         --> requires "SCEI" discs
   4758   INT3("for Europe") --> PAL, Europe               --> requires "SCEE" discs
   4759   INT3("for U/C")    --> NTSC, North America       --> requires "SCEA" discs
   4760   INT3("for Japan")  --> NTSC, Japan / NTSC, Asia  --> requires "SCEI" discs
   4761   INT3("for NETNA")  --> Region-free yaroze version--> requires "SCEx" discs
   4762   INT3("for US/AEP") --> Region-free debug version --> accepts unlicensed CDRs
   4763 The CDROMs must contain a matching SCEx string accordingly.
   4764 The string "for Europe" does also suggest 50Hz PAL/SECAM video hardware.
   4765 The Yaroze accepts any normal SCEE,SCEA,SCEI discs, plus special SCEW discs.
   4766 
   4767 19h,23h --> INT3("CXD2940Q/CXD1817Q/CXD2545Q/CXD1782BR") ;Servo Amplifier
   4768 19h,24h --> INT3("CXD2940Q/CXD1817Q/CXD2545Q/CXD2510Q")  ;Signal Processor
   4769 19h,25h --> INT3("CXD2940Q/CXD1817Q/CXD1815Q/CXD1199BQ") ;Decoder/FIFO
   4770   Caution: Supported only in BIOS version vC1 and up. Not supported in vC0.
   4771 Indicates the chipset that the CDROM controller is intended to be used with.
   4772 The strings aren't always precisely correct (CXD1782BR is actually CXA1782BR,
   4773 ie. CXA, not CXD) (and CXD1199BQ chips exist on PU-7 boards, but later PU-8
   4774 boards do actually use CXD1815Q) (and CXD1817Q is actually CXD1817R) (and newer
   4775 PSones are using CXD2938Q or possibly CXD2941R chips, but nothing called
   4776 CXD2940Q).
   4777 Note: Yaroze responds by CXD1815BQ instead of CXD1199BQ (but not by CXD1815Q).
   4778 
   4779 19h,04h --> INT3(stat) ;Read SCEx string (and force motor on)
   4780 Resets the total/success counters to zero, and does then try to read the SCEx
   4781 string from the current location (the SCEx is stored only in the Lead-In area,
   4782 so, if the drive head is elsewhere, it will usually not find any strings,
   4783 unless a modchip is permanently simulating SCEx strings).
   4784 This is a raw test command (the successful or unsuccessful results do not
   4785 lock/unlock the disk). The results can be read with command 19h,05h (which will
   4786 terminate the SCEx reading), or they can be read from RAM with command
   4787 19h,60h,lo,hi (which doesn't stop reading). Wait 1-2 seconds before expecting
   4788 any results.
   4789 Note: Like 19h,00h, this command forces the drive motor to spin at standard
   4790 speed (synchronized with the data on the disk), works even if the shell is open
   4791 (but stops spinning after a while if the drive is empty).
   4792 
   4793 19h,05h --> INT3(total,success)  ;Get SCEx Counters
   4794 Returns the total number of "Sxxx" strings received (where at least the first
   4795 byte did match), and the number of full "SCEx" strings (where all bytes did
   4796 match). Typically, the values are "01h,01h" for Licensed PSX Data CDs, or
   4797 "00h,00h" for disk missing, unlicensed data CDs, Audio CDs.
   4798 The counters are reset to zero, and SCEx receive mode is active for a few
   4799 seconds after booting a new disk (on power up, on closing the drive door, on
   4800 sending a Reset command, and on sub_function 04h). The disk is unlocked if the
   4801 "success" counter is nonzero, the only exception is sub_function 04h which does
   4802 update the counters, but does not lock/unlock the disk.
   4803 
   4804 CDROM - Test Commands - Test Drive Mechanics
   4805 --------------------------------------------
   4806 
   4807 Signal Processor and Servo Amplifier
   4808 
   4809 19h,50h,msb[,mid,[lsb[,xlo]]] --> INT3(stat)
   4810 Sends an 8bit/16bit/24bit command to the hardware, depending on number of
   4811 parameters:
   4812   1 byte  --> send CX(Xx)       ;short 8bit command
   4813   2 bytes --> send CX(Xxxx)     ;longer 16bit command
   4814   3 bytes --> send CX(Xxxxxx)   ;full 24bit command
   4815   4 bytes --> send CX(Xxxxxxxx) ;extended 32bit command (BIOS vC3 only)
   4816   4..15 bytes: acts same as max (3 or 4 bytes) (extra bytes are ignored)
   4817   0 bytes or more than 15 bytes: generates an error
   4818 
   4819 19h,51h,msb[,mid,[lsb]] --> INT3(stat,hi,lo)  ;BIOS vC2/vC3 only
   4820 Supported by newer CDROM BIOSes only (such that use CXD2545Q or newer chips).
   4821 Works same as 19h,50h, but does additionally receive a response.
   4822 The command is always sending a 24bit CX(Xxxxxx) command, but it doesn't verify
   4823 the number of parameter bytes (when using more than 3 bytes: extra bytes are
   4824 ignored, when using less than 3 bytes: garbage is appended, which is somewhat
   4825 valid because 8bit/16bit commands can be padded to 24bit size by appending
   4826 "don't care" bits).
   4827 The command can be used to send any CX(..) command, but actually it does make
   4828 sense only for the get-status commands, see below "19h,51h,39h,xxh"
   4829 description.
   4830 
   4831 19h,51h,39h,xxh --> INT3(stat,hi,lo)  ;BIOS vC2/vC3 only
   4832 Supported by newer CDROM BIOSes only (such that use CXD2545Q or newer chips).
   4833 Sends CX(39xx) to the hardware, and receives a response (the response.hi byte
   4834 is usually 00h for 8bit responses, or 00h..01h for 9bit responses). For
   4835 example, this can be used to dump the Coefficient RAM.
   4836 
   4837 19h,03h --> INT3(stat) ;force motor off
   4838 Forces the motor to stop spinning (ignored during spin-up phase).
   4839 
   4840 19h,17h --> INT3(stat) ;force motor on, clockwise, super-fast
   4841 19h,01h --> INT3(stat) ;force motor on, anti-clockwise, super-fast
   4842 19h,02h --> INT3(stat) ;force motor on, anti-clockwise, super-fast
   4843 19h,10h --> INT3(stat) ;force motor on, anti-clockwise, super-fast
   4844 19h,18h --> INT3(stat) ;force motor on, anti-clockwise, super-fast
   4845 Forces the drive motor to spin at maximum speed (which is much faster than
   4846 normal or double speed), in normal (clockwise), or reversed (anti-clockwise)
   4847 direction. The commands work even if the shell is open. The commands do not try
   4848 to synchronize the motor with the data on the disk (and do thus work even if no
   4849 disk is inserted).
   4850 
   4851 19h,00h --> INT3(stat) ;force motor on, clockwise (even if shell open)
   4852 This command seems to have effect only if the drive motor was off. If it was
   4853 off, it does FFh-fills the TOC entries in RAM, and seek to the begin of the TOC
   4854 at 98:30:00 or so (where minute=98 means minus two). From that location, it
   4855 follows the spiral on the disk, although it does occassionally jump back some
   4856 seconds. After clearing the TOC, the command does not write new data to the TOC
   4857 buffer in RAM.
   4858 Note: Like 19h,04h, this command forces the drive motor to spin at standard
   4859 speed (synchronized with the data on the disk), works even if the shell is open
   4860 (but stops spinning after a while if the drive is empty).
   4861 
   4862 19h,11h --> INT3(stat) ;Move Lens Up (leave parking position)
   4863 19h,12h --> INT3(stat) ;Move Lens Down (enter parking position)
   4864 19h,13h --> INT3(stat) ;Move Lens Outwards (away from center of disk)
   4865 19h,14h --> INT3(stat) ;Move Lens Inwards (towards center of disk)
   4866 Moves the laser lens. The inwards/outwards commands do move ONLY the lens (ie.
   4867 unlike as for Seek commands, the overall-laser-unit remains in place, only the
   4868 lens is moved).
   4869 
   4870 19h,15h - if motor on: move head outwards + inwards + motor off
   4871 Moves the drive head to outer-most and inner-most position. Note that the drive
   4872 doesn't have a switch that'd tell the controller when it has reached the
   4873 outer-most position (so it'll forcefully hit against the outer edge) (ie. using
   4874 this command too often may destroy the drive mechanics).
   4875 Note: The same destructive hit-outer-edge effect happens when using Setloc/Seek
   4876 with too large values (like minute=99h).
   4877 
   4878 19h,16h --> INT3(stat) ;Unknown / makes some noise if motor is on
   4879 19h,19h --> INT3(stat) ;Unknown / no effect
   4880 19h,1Ah --> INT3(stat) ;Unknown / makes some noise if motor is on
   4881 Seem to have no effect?
   4882 19h,16h seems to Move Lens Inwards, too.
   4883 
   4884 19h,06h,new --> INT3(old) ;Adjust balance in RAM, and apply it via CX(30+n)
   4885 19h,07h,new --> INT3(old) ;Adjust gain in RAM, and apply it via CX(38+n)
   4886 19h,08h,new --> INT3(old) ;Adjust balance in RAM only
   4887 These commands are supported only by older CDROM BIOS versions (those with
   4888 CXA1782BR Servo Amplifier).
   4889 Later BIOSes will respond with INT5(11h,20h) when trying to use these commands
   4890 (because CXD2545Q and later Servo Amplifiers don't support the CX(30/38+n)
   4891 commands).
   4892 
   4893 CDROM - Test Commands - Prototype Debug Transmission
   4894 ----------------------------------------------------
   4895 
   4896 Serial Debug Messages
   4897 Older CDROM BIOSes are supporting debug message transmission via serial bus,
   4898 using lower 3bit of the HC05 "databus" combined with the so-called "ROMSEL" pin
   4899 (which apparently doesn't refer to Read-Only-Memory, but rather something like
   4900 Runtime-Output-Message, or whatever).
   4901 Data is transferred in 24bit units (8bit command/index from HC05, followed by
   4902 16bit data to/from HC05), bigger messages are divided into multiple such 24bit
   4903 snippets.
   4904 There are no connectors for external debug hardware on any PSX mainboards, so
   4905 the whole stuff seems to be dating back to prototypes. And it seems to be
   4906 removed from later BIOSes (which appear to use "ROMSEL" as "SCLK"; for
   4907 receiving status info from the new CXD2545Q chips).
   4908 
   4909 19h,30h,index,dat1,dat2 --> INT3(stat) ;Prototype/Debug stuff
   4910 19h,31h,dat1,dat2 --> INT3(stat) ;Prototype/Debug stuff
   4911 19h,4xh,index --> INT3(dat1,dat2) ;Prototype/Debug stuff
   4912 These functions are supported on older CDROM BIOS only; later BIOSes respond by
   4913 INT5(11h,10h).
   4914 The functions do not affect the CDROM operation (they do simple allow to
   4915 transfer data between Main CPU and external debug hardware).
   4916 Sub functions 30h and 31h may fail with INT5(11h,80h) when receiving wrong
   4917 signals on the serial input line.
   4918 Sub function "4xh" value can be 40h..4Fh (don't care).
   4919 
   4920 INT5 Debug Messages
   4921 Alongsides to INT5 errors, the BIOS is usually also sending information via the
   4922 above serial bus (the error info is divided into multiple 8bit+16bit snippets,
   4923 and contains stat, error code, mode, current SubQ position, and most recently
   4924 issued command).
   4925 
   4926 CDROM - Test Commands - Read/Write Decoder RAM and I/O Ports
   4927 ------------------------------------------------------------
   4928 
   4929 Caution: Below commands 19h,71h..76h are supported only in BIOS version vC1 and
   4930 up. Not supported in vC0.
   4931 
   4932 19h,71h,index --> INT3(databyte) ;Read single register
   4933 index can be 00h..1Fh, bigger values seem to be mirrored to "index AND 1Fh",
   4934 with one exception: index 13h in NOT mirrored, instead, index 33h, 53h, 93h,
   4935 B3h, D3h, F3h return INT5(stat+1,10h), and index 73h returns INT5(stat+1,20h).
   4936 Aside from returning a value, the commands seem to DO something (like moving
   4937 the drive head when a disk is inserted). Return values are usually:
   4938   index     value
   4939   00h       04h      ;04h=empty, 8Eh=licensed, 24h=audio
   4940   01h       [0B1h]   ;DCh=empty/licensed, DDh=audio
   4941   02h       00h
   4942   03h       00h          ;or variable when disk inserted
   4943   04h       00h
   4944   05h       80h          ;or 86h or 89h when disk inserted
   4945   06h       C0h
   4946   07h       02h
   4947   08h       8Ah
   4948   09h       C0h
   4949   0Ah       00h
   4950   0Bh       C0h
   4951   0Ch       [1F2h]
   4952   0Dh       [1F3h]
   4953   0Eh       00h          ;or 8Eh or E6h when disk inserted    ;D4h/audio
   4954   0Fh       00h          ;or sometimes 01h when disk inserted ;50h/audio
   4955   10h       C0h
   4956   11h       E0h
   4957   12h       71h
   4958   13h       stat
   4959   14h       FFh
   4960   15h..1Fh  C0h-filled        ;or 17h --> DEh
   4961 
   4962 19h,72h,index,databyte --> INT3(stat) ;Write single register
   4963   ;other response on param xx16h,xx18h with xx>00h
   4964 
   4965 19h,73h,index,len --> INT3(databytes...) ;Read multiple registers (bugged)
   4966 19h,74h,index,len,databytes --> INT3(stat) ;Write multiple registers (bugged)
   4967 Same as read/write single register, but trying to transfer multiple registers
   4968 at once. BUG: The transfer should range from 00h to len-1, but the loop counter
   4969 is left uninitialized (set to X=48h aka "command number 19h-minus-1-mul-2"
   4970 instead of X=00h). Causing to the function to read/write garbage at index
   4971 48h..FFh, it does then wrap to 00h and do the correct intended transfer, but
   4972 the preceeding bugged part may have smashed RAM or I/O ports.
   4973 
   4974 19h,75h --> INT3(remain.lo,remain.hi,addr.lo,addr.hi) ;Get Host Xfer Info
   4975 Returns a 4-byte value. In my early tests, on the first day it returned
   4976 B1h,CEh,4Ch,01h, on the next day 2Ch,E4h,95h,D5h, and on all following days
   4977 00h,C0h,00h,00h (no idea why/where the earlier values came from).
   4978 The first byte seems to be always 00h; no matter of [1F0h].
   4979 The second byte seems to be always C0h; no matter of [1F1h].
   4980 The third,fourth bytes are [1F2h,1F3h].
   4981 That two bytes are 0Ch,08h after Read commands.
   4982   The first bytes are NOT affected by:
   4983   destroying [1F0h] via too-many-parameters in command-buffer,
   4984   changes to [1F1h] which may occur after read command (eg. may be 20h)
   4985 
   4986 19h,76h,len_lo,len_hi,addr_lo,addr_hi --> INT3(stat) ;Prepare SRAM Transfer
   4987 Prepare Transfer to/from 32K SRAM.
   4988 After INT3, data can be read (same way as sector data after INT1).
   4989 
   4990 CDROM - Test Commands - Read HC05 SUB-CPU RAM and I/O Ports
   4991 -----------------------------------------------------------
   4992 
   4993 19h,60h,addr_lo,addr_hi --> INT3(data) ;Read one byte from Drive RAM or I/O
   4994 Reads one byte from the controller's RAM or I/O area, see the memory map below
   4995 for more info. Among others, the command allows to read Subchannel Q data, eg.
   4996 at [200h..209h], including ADR=2/UPC/EAN and ADR=3/ISRC values (which are
   4997 suppressed by GetlocP). Eg. wait for ADR<>2, then for ADR=2, then read the
   4998 remaining 9 bytes (because of the delayed IRQs, this works only at single
   4999 speed) (at double speed one can read only 5 bytes before the values get
   5000 overwritten by new data). Unknown if older boards (with 4.00MHz oscillators)
   5001 are fast enough to read all 10 SubQ bytes.
   5002 
   5003 CDROM Controller I/O Area and RAM Memory Map
   5004 First 40h bytes are I/O ports (as in MC68HC05 datasheet):
   5005   000h 4        FF 7B 00 FF  (other when disk inserted)
   5006   004h 5        11 00 20 20 0C
   5007   009h 1        00 (when disk inserted: changes between 00 or 80)
   5008   00Ah 2        71 00
   5009   00Ch 1        00 (when disk inserted: changes between 00 or 80)
   5010   00Dh 3        20 20 20
   5011   010h 8        02 80 00 60 00 00 99(orBB) 98
   5012   018h 4     changes randomly (even when no disk inserted)
   5013   01Ch 3        40 00 41
   5014   01Fh 1     changes randomly (even when no disk inserted)
   5015   020h 30    20h-filled
   5016   03Eh 2        82h 20h
   5017 Next 200h bytes are RAM:
   5018   040h 4        08 00 00 00  ;or 98 07 xx 0B when disk inserted ;[40].Bit1=MUTE
   5019   044h 4     00h-filled
   5020   048h 3        40 20 00     ;or 58 71 0F when disk inserted
   5021   04Bh 1     changes randomly (nodisk: 00 or 80 / disk: BFh)
   5022   04Ch 1     Zero (or C0h)
   5023   04Dh 3     MM:SS:FF (begin of current track MM:SS:00h) (or increasing addr)
   5024   050h 10    Subchannel Q (adjusted position values)
   5025   05Ah 2        ...
   5026   05Ch 1     00h (or 64h)
   5027   05Dh 3     MM:SS:FF (current read address) (sticky address during pause)
   5028   060h 1     increments at circa 16Hz or so (or other rate when spinning)
   5029   061h 12    00h-filled ;or else when disk inserted
   5030   06Dh 1        01      ;or 0C when disk inserted
   5031   06Eh 2     SetFilter setting (file,channel)
   5032   070h 16    00h-filled ;or else when disk inserted
   5033   080h 8     00h-filled
   5034   088h 3        03:SS:FF (three, second, fraction)
   5035   08Bh 3        03:SS:FF (three, second, fraction)
   5036   08Eh 2        01 FF (or other values)
   5037   090h 1        00h (or 91h when disk inserted + spinning)
   5038   091h 13    Zero
   5039   09Eh 1        00h (or 01h when disk inserted + spinning)
   5040   09Fh 1     Zero
   5041   0A0h 1     Always 23h
   5042   0A1h 1        09h (5Dh when disk inserted)
   5043   0A2h 7     00h-filled
   5044   0A9h 1        40
   5045   0AAh 4     00h-filled
   5046   0AEh 1        00 (no disk) or 01 (disk) or so
   5047   0AFh 1        00            ;or 06 when disk inserted
   5048   0B0h 7        00 DC 00 02 00 E0 08             ;\or else when disk inserted
   5049   0B7h 1        20         ;Bit6+7=MUTE          ;
   5050   0B8h 3        DE 00 00                         ;/
   5051   0BBh 1     SetMode setting (mode)
   5052   0BCh 1     GetStat setting (stat)
   5053   0BDh 3     00h-filled
   5054   0C0h 6     FFh-filled            ;stack...                    ;\
   5055   0C6h 1     Usually DFh           ;sometimes [0EBh and up] are non-FFh, too
   5056   0C7h 15    FFh-filled            ;(depending on disk or commands or so)
   5057   0D6h 1     Usually FDh (or FFh)  ;                            ;
   5058   0D7h 24    FFh-filled                                         ; stack
   5059   0EFh 4     on power-up FFh-filled, other once when disk read  ;
   5060   0F3h 7     changes randomly (even when no disk inserted)      ;
   5061   0FAh 6       2E 3C 2A D6 10 95                                ;/
   5062   100h 2x99  TOC Entries for Start of Track 1..99 (MM:SS)
   5063   1C6h 1     TOC First Track number (usually 01h)
   5064   1C7h 1     TOC Last Track number (usually 01h or higher)
   5065   1C8h 3     TOC Entry for Start of Lead-Out (MM:SS:FF)
   5066   1CBh 2     Zero
   5067   1CDh 1     Depends on disk (01 or 02 or 06) (or 00 when no disk)
   5068   1CEh 1     Zero
   5069   1CFh 1     Depends on disk (NULL minus N*6) (or 00 when no disk)
   5070                (maybe reflection level / laser intensity or so)
   5071                 [1CDh..1CFh]
   5072                 01 00 E8 --> licensed/metalgear/kain
   5073                 01 00 EE --> licensed/alone2
   5074                 06 00 E2 or 00 00 02 00 E8 --> licensed/wipeout
   5075                 02 00 DC --> unlicensed/elo
   5076                 02 00 D6 --> unlicensed/driver
   5077                 00 00 EE --> audio/lola
   5078                 00 00 FA --> audio/marilyn
   5079                 00 00 F4 --> audio/westen
   5080                 00 00 00 --> disk missing
   5081                last byte is always in steps of 6
   5082   1D0h 4     SCEx String
   5083   1D4h 4     Zero
   5084   1D8h 2     SCEx Counters (total,success)  ;for command 19h,05h
   5085   1DAh 6       00h-filled     (or ... SS:FF)
   5086   1E0h 6     Command Buffer (usually 19h,60h,E2h,01h = Read RAM Command)
   5087   1E6h 7       00h-filled (unless destroyed by more-than-6-byte-commands)
   5088   1EDh 3     Setloc setting (MM:SS:FF)
   5089   1F0h 1       00h          (unless destroyed by more-than-6-byte-commands)
   5090   1F1h 3       C0h 00h 00h ;or 20h,0Ch,50h or C0h,0Ch,08h ;for command(19h,75h)
   5091                            ;or 00h,00h,00h for audio
   5092                            ;or 80h,00h,00h for disk missing
   5093   1F4h 4       00h-filled ... or SCEx string
   5094   1F8h 1       00h
   5095   1F9h 1     Selected Target (parameter from Play and SetSession commands)
   5096   1FAh 5       00h-filled       ;01 01 00 8B 00 00   ;or 01 02 8B 00 00
   5097                        01 00 8B 00 00 -- audio/unlicensed
   5098                        01 01 00 00 00 -- licensed
   5099   1FFh 1       00h-on power up, changes when disk inserted  ;or 01 = Playing
   5100     1FDh 3       MM:SS:FF (only during command 19h,00h) (MM=98..99=TOC)
   5101   200h 10    Subchannel Q (real values)
   5102   20Ah 2       whatever
   5103   20Ch 1     Zero
   5104   20Dh 1     Desired Session (from SetSession command)
   5105   20Eh 1     Current Session (actual location of drive head)
   5106   20Fh 1     Zero
   5107   210h 10    Subchannel Q (adjusted position values)
   5108   21Ah 6     00h-filled
   5109   220h 4     Data Sector Header (MM:SS:FF:Mode)
   5110   224h 4     Data Sector CD-XA Subheader (file,channel,sm,ci)
   5111   228h 1         00h
   5112   229h 1     Usually 00h (shortly other value on power-up, and maybe on seek)
   5113   22Ah 1         10h (or 00h when no disk)
   5114   22Bh 3     00h-filled
   5115   22Eh 2         01,03 or 0A,00 or 03,01 (or else for other disk)
   5116   230h 3     00h-filled (or other during spin-up / read-toc or so)
   5117   233h 0Dh   00h-filled (unused RAM)
   5118 Other/invalid addresses are:
   5119   240h..2FFh  - Invalid (00h-filled) (no ROM, RAM, or I/O mapped here)
   5120   300h..3FFh  - Mirror of 200h..2FFh    ;\the BIOS is doing that
   5121   400h..FFFFh - Mirrors of 000h..3FFh   ;/mirroring by software
   5122 
   5123 Writing to RAM
   5124 There is no command for writing to RAM. Except that, one can write to the
   5125 command/parameter buffer at 1E0h and up. Normally, the longest known command
   5126 should have 6 bytes (19h,76h,a,b,c,d), and longer commands results in "bad
   5127 number of parameters" response - however, despite of that error message, the
   5128 controller does still store ALL parameter bytes in RAM (at address 1E1h..2E0h,
   5129 then wrapping back to 1E1h). Whereas, writing more than 16 bytes (FIFO storage
   5130 size) will mirror the FIFO content twice, and more than 32 bytes (FIFO counter
   5131 size) will work only when feeding extra data into the FIFO during transmission.
   5132 Anyways, writing to 1E1h and up doesn't allow to do interesting things (such
   5133 like manipulating the stack and executing custom code on the CPU).
   5134 
   5135 Subchannel Q Notes
   5136 The "adjusted position values" at 050h, 210h, 310h contain only position
   5137 information (with ADR=1) (the PSX seems to check only the lower 2bit of the
   5138 4bit ADR value, so it also treats ADR=5 as ADR=1, too). Additionally, during
   5139 Lead-In, bytes 7..9 are overwritten by the position value from bytes 3..5. The
   5140 "real values" contain unadjusted data, including ADR=2 and ADR=3 etc.
   5141 
   5142 CDROM - Secret Unlock Commands
   5143 ------------------------------
   5144 
   5145 SecretUnlockPart1 - Command 50h --> INT5(11h,40h)
   5146 SecretUnlockPart2 - Command 51h,"Licensed by" --> INT5(11h,40h)
   5147 SecretUnlockPart3 - Command 52h,"Sony" --> INT5(11h,40h)
   5148 SecretUnlockPart4 - Command 53h,"Computer" --> INT5(11h,40h)
   5149 SecretUnlockPart5 - Command 54h,"Entertainment" --> INT5(11h,40h)
   5150 SecretUnlockPart6 - Command 55h,<region> --> INT5(11h,40h)
   5151 SecretUnlockPart7 - Command 56h --> INT5(11h,40h)
   5152   Caution: Supported only in BIOS version vC1 and up. Not supported in vC0.
   5153   Caution: Supported only in Europe/USA. Nonfunctional in Japan/Asia.
   5154   Caution: When unsupported, Parameter Fifo isn't cleared after the command.
   5155 Sending these commands with the correct strings (in order 50h through 56h) does
   5156 disable the "SCEx" protection. The region can be detected via test command
   5157 19h,22h, and must be translated to the following <region> string:
   5158   "of America"    ;for NTSC/US          ;\
   5159   "(Europe)"      ;for PAL/Europe       ; handled, and actually working
   5160   "World wide"    ;for Yaroze           ;/
   5161   "Inc."          ;for NTSC/JP          ;-non-functional
   5162 In the unlocked state, ReadN/ReadS are working for unlicensed CD-Rs, and for
   5163 imported CDROMs from other regions (both without needing modchips). However
   5164 there are some cases which may still cause problems: The GetID command (1Ah)
   5165 does still identify the disc as being unlicensed, same for the Get SCEx
   5166 Counters test command (19h,05h). And, if a game should happen to send the Reset
   5167 command (1Ch) for some weird reason, then the BIOS would forget the unlocking,
   5168 same for games that set the "HCRISD" I/O port bit. On the contrary,
   5169 opening/closing the drive door does not affect the unlocking state.
   5170 The commands have been discovered in September 2013, and appear to be supported
   5171 by all CDROM BIOS versions (from old PSXes up to later PSones).
   5172 Note that the commands do always respond with INT5 errors (even on successful
   5173 unlocking).
   5174 Japanese consoles are internally containing code for processing the Secret
   5175 Unlock commands, but they are not actually executing that code, and even if
   5176 they would do so: they are ignoring the resulting unlocking flag, making the
   5177 commands nonfunctional in Japan/Asia regions.
   5178 
   5179 SecretLock - Command 57h --> INT5(11h,40h)
   5180 Undoes the unlocking and restores the normal locked state (same happens when
   5181 sending the Unlocking commands in wrong order or with wrong parameters).
   5182 
   5183 SecretCrash - Command 58h..5Fh --> Crash
   5184 Jumps to a data area and executes random code. Results are more or less
   5185 unpredictable (as they involve executing undefined opcodes). Eventually the CPU
   5186 might hit a RET opcode and recover from the crash.
   5187 
   5188 CDROM - Video CD Commands
   5189 -------------------------
   5190 
   5191   Caution: Supported only on SCPH-5903, not supported on any other consoles.
   5192   Caution: When unsupported, Parameter Fifo isn't cleared after the command.
   5193 
   5194   1Fh VideoCD      sub,a,b,c,d,e   INT3(stat,a,b,c,d,e)   ;<-- SCPH-5903 only
   5195   1Fh..4Fh -       -               INT5(11h,40h)  ;-Unused/invalid
   5196 
   5197 VideoCdSio - Cmd 1Fh,01h,JoyL,JoyH,State,Task,0 --> INT3(stat,req,mm,ss,ff,x)
   5198 The JoyL/JoyH bytes contain 16bit button (and drive door) bits:
   5199   0  Drive Door  (0=Open)    (from CDROM stat bit4) ;Open
   5200   1  Button /\   (0=Pressed) (from PSX pad bit12) ;N/A       ;PBC: Back/LevelUp
   5201   2  Button []   (0=Pressed) (from PSX pad bit15) ;Enter Menu
   5202   3  Button ()   (0=Pressed) (from PSX pad bit13) ;Leave Menu     ;PBC: Confirm
   5203   4  Button ><   (0=Pressed) (from PSX pad bit14) ;N/A
   5204   5  Start       (0=Pressed) (from PSX pad bit3)  ;Play/Pause
   5205   6  Select      (0=Pressed) (from PSX pad bit0)  ;Stop (prompt restart/resume)
   5206   7  Always 0    (0)         (fixed)              ;N/A
   5207   8  DPAD Up     (0=Pressed) (from PSX pad bit4)  ;Menu Up           ;PBC: +1
   5208   9  DPAD Right  (0=Pressed) (from PSX pad bit5)  ;Menu Right/change ;PBC: +10
   5209   10 DPAD Down   (0=Pressed) (from PSX pad bit6)  ;Menu Down         ;PBC: -1
   5210   11 DPAD Left   (0=Pressed) (from PSX pad bit7)  ;Menu Left/change  ;PBC: -10
   5211   12 Button R1   (0=Pressed) (from PSX pad bit11) ;Prev Track/Restart Track
   5212   13 Button R2   (0=Pressed) (from PSX pad bit9)  ;Fast Forward (slowly)
   5213   14 Button L1   (0=Pressed) (from PSX pad bit10) ;Next Track (if any)
   5214   15 Button L2   (0=Pressed) (from PSX pad bit8)  ;Fast Backward (slowly)
   5215 The State byte can be:
   5216   00h  Motor Off (or spin-up)   (when stat.bit1=0)
   5217   01h  Playing                  (when stat.bit7=1)
   5218   02h  Paused (and not seeking) (when stat.bit6=0)
   5219   (note: State remains unchanged when seeking)
   5220 The Task byte can be:
   5221   00h = Confirms that "Tocread" (aka setsession 1) request was processed
   5222   01h = Detect VCD Disc (used on power-up, and after door open) (after spin-up)
   5223   02h = Handshake (request ack response)
   5224   0Ah = Door opened during play (int5/door error)
   5225   80h = No disc
   5226   FFh = No change (nop)
   5227 The req byte in the INT3 response can be:
   5228   00h  Normal (no special event occured and no action requested)
   5229   01h  Request CD to Seek_and_play (using mm:ss:ff response parameter bytes)
   5230   02h  Request CD to Pause                ;cmd(09h)    -->int3(stat),int2(stat)
   5231   03h  Request CD to Stop                 ;cmd(08h)    -->int3(stat),int2(stat)
   5232   04h  Request CD to Tocread (setsession1);cmd(12h,01h)-->int3(stat),int2(stat)
   5233   05h  Handshake Command was processed, and this is the "ack" response
   5234   06h  Request CD to Fast Forward         ;cmd(04h)    -->int3(stat)
   5235   07h  Request CD to Fast Backward        ;cmd(05h)    -->int3(stat)
   5236   80h  Detect Command was processed, and disc was detected as VCD
   5237   81h  Detect Command was processed, and disc was detected as Non-VCD
   5238 
   5239 VideoCdSwitch - Cmd 1Fh,02h,flag,x,x,x,x --> INT3(stat,0,0,x,x,x)
   5240   00h      = Normal PSX Mode  (PortF.3=LOW)  (Audio/Video from GPU/SPU chips)
   5241   01h..FFh = Special VCD Mode (PortF.3=HIGH) (Audio/Video from MDEC/OSD chips)
   5242 
   5243 Some findings on the SC430924 firmware...
   5244 The version/date is "15 Aug 1996, version C2h", although the "C2h" is
   5245 misleading: The firmware is nearly identical to version "C1h" from PU-8 boards
   5246 (the stuff added in normal "C2h" versions would be for PU-18 boards with
   5247 different cdrom chipset).
   5248 
   5249 Compared to the original C1h version, there are only a few changes: A
   5250 initialization function for initializing port F on power-up. And new command
   5251 (command 1Fh, inserted in the various command tables), with two subfunctions
   5252 (01h and 02h):
   5253 - Command 1Fh,01h,a,b,c,d,e --> INT3(stat,a,b,c,d,e) Serial 5-byte read-write
   5254 - Command 1Fh,02h,v,x,x,x,x --> INT3(stat,0,0,x,x,x) Toggle 1bit (port F.bit3)
   5255 Whereas,
   5256   x = don't care/garbage
   5257   v = toggle state (00h=normal=PortF.3=LOW, 01h..FFh=special=PortF.3=HIGH)
   5258       (toggle gpu vs mpeg maybe?)
   5259   a,b,c,d,e = five bytes sent serially, and five bytes response received
   5260       serially (send/receive done simultaneously)
   5261 
   5262 The Port F bits are:
   5263   Port F.Bit0 = Serial Data In
   5264   Port F.Bit1 = Serial Data Out
   5265   Port F.Bit2 = Serial Clock Out
   5266   Port F.Bit3 = Toggle (0=Normal, 1=Special)
   5267 
   5268 And that's about all. Ie. essentially, the only change is that the new command
   5269 controls Port F. There is no interaction with the remaining firmware (ie.
   5270 reading, seeking, and everything is working as usually, without any video-cd
   5271 related changes).
   5272 The SCEx stuff is also not affected (ie. Video CDs would be seen as unlicensed
   5273 discs, so the PSX couldn't read anything from those discs, aside from Sub-Q
   5274 position data, of course). The SCEx region is SCEI aka "Japan" (or actually for
   5275 Asia in this case).
   5276 
   5277 Note
   5278 The SPU MUTE Flag (SPUCNT.14) does also affect VCD Audio (mute is applied to
   5279 the final analog audio amplifier). All other SPUCNT bits can be zero for VCD.
   5280 
   5281 CDROM - Mainloop/Responses
   5282 --------------------------
   5283 
   5284 SUB-CPU Mainloop
   5285 The SUB-CPU is running a mainloop that is handling hardware events (by simple
   5286 polling, not by IRQs):
   5287   check for incoming sectors (from CDROM decoder)
   5288   check for incoming commands (from Main CPU)
   5289   do maintenance stuff on the drive mechanics
   5290 There is no fixed priority: if both incoming sector and incoming command are
   5291 present, then the SUB-CPU may handle either one, depending on which portion of
   5292 the mainloop it is currently executing.
   5293 There is no fixed timing: if the mainloop is just checking for a specific
   5294 event, then a new event may be processed immediately, otherwise it may take
   5295 whole mainloop cycle until the SUB-CPU sees the event.
   5296 Whereas, the mainloop cycle execution time isn't constant: It may vary
   5297 depending on various details. Especially, some maintenance stuff is only
   5298 handled approximately around 15 times per second (so there are 15 slow mainloop
   5299 cycles per second).
   5300 
   5301 Responses
   5302 The PSX can deliver one INT after another. Instead of using a real queue, it's
   5303 merely using some flags that do indicate which INT(s) need to be delivered.
   5304 Basically, there seem to be two flags: One for Second Response (INT2), and one
   5305 for Data/Report Response (INT1). There is no flag for First Response (INT3);
   5306 because that INT is generated immediately after executing a command.
   5307 The flag mechanism means that the SUB-CPU cannot hold more than one undelivered
   5308 INT1. That, although the CDROM Decoder does notify the SUB-CPU about all newly
   5309 received sectors, and it can hold up to eight sectors in the 32K SRAM. However,
   5310 the SUB-CPU BIOS merely sets a sector-delivery-needed flag (instead of
   5311 memorizing which/how many sectors need to be delivered, and, accordingly, the
   5312 PSX can use only three of the available eight SRAM slots: One for currently
   5313 pending INT1, one for undelivered INT1, and one for currently/incompletly
   5314 received sector).
   5315 
   5316 First Response (INT3) (or INT5 if failed)
   5317 The first response is sent immediately after processing a command. In detail:
   5318 The mainloop checks for incoming commands once every some clock cycles, and
   5319 executes commands under following condition:
   5320   Main CPU has sent a command, AND, there is no INT pending
   5321   (if an INT is pending, then the command won't be executed yet, but will be
   5322   executed in following mainloop cycles; once when INT got acknowledged)
   5323   (even if no INT is pending, the mainloop may generate INT1/INT2 before
   5324   executing the command, if so, as said above, the command won't execute yet)
   5325 Once when the command gets executed it will sent the first response immediately
   5326 after the command execution (which may only take a few clock cycles, or some
   5327 more cycles, for example Init/ReadTOC do include some time consuming
   5328 initializations). Anyways, there will be no other INTs generated during command
   5329 execution, so once when the command execution has started, it's guaranteed that
   5330 the next INT will contain the first response.
   5331 
   5332 Second Responses (INT2) (or INT5 if failed)
   5333 Some commands do send a second response after actual command execution:
   5334   07h MotorOn    E -               INT3(stat), INT2(stat)
   5335   08h Stop       E -               INT3(stat), INT2(stat)
   5336   09h Pause      E -               INT3(stat), INT2(stat)
   5337   0Ah Init         -               INT3(late-stat), INT2(stat)
   5338   12h SetSession E session         INT3(stat), INT2(stat)
   5339   15h SeekL      E -               INT3(stat), INT2(stat)  ;\use prior Setloc
   5340   16h SeekP      E -               INT3(stat), INT2(stat)  ;/to set target
   5341   1Ah GetID      E -               INT3(stat), INT2/5(stat,flg,typ,atip,"SCEx")
   5342   1Dh GetQ       E adr,point       INT3(stat), INT2(10bytesSubQ,peak_lo)
   5343   1Eh ReadTOC      -               INT3(late-stat), INT2(stat)
   5344 In some cases (like seek or spin-up), it may take more than a second until the
   5345 2nd response is sent.
   5346 It should be highly recommended to WAIT until the second response is generated
   5347 BEFORE sending a new command (it wouldn't make too much sense to send a new
   5348 command between first and second response, and results would be unknown, and
   5349 probably totally unpredictable).
   5350 Error Notes: If the command has been rejected (INT5 sent as 1st response) then
   5351 the 2nd response isn't sent (eg. on wrong number of parameters, or if disc
   5352 missing). If the command fails at a later stage (INT5 as 2nd response), then
   5353 there are cases where another INT5 occurs as 3rd response (eg. on
   5354 SetSession=02h on non-multisession-disk).
   5355 
   5356 Data/Report Responses (INT1)
   5357   03h Play       E (track)         INT3(stat), optional INT1(report bytes)
   5358   04h Forward    E -               INT3(stat), optional INT1(report bytes)
   5359   05h Backward   E -               INT3(stat), optional INT1(report bytes)
   5360   06h ReadN      E -               INT3(stat), INT1(stat), datablock
   5361   1Bh ReadS      E?-               INT3(stat), INT1(stat), datablock
   5362 
   5363 CDROM - Response Timings
   5364 ------------------------
   5365 
   5366 Here are some response timings, measured in 33MHz units on a PAL PSone. The
   5367 CDROM BIOSes mainloop is doing some maintenance stuff once and when, meaning
   5368 that the response time will be higher in such mainloop cycles (max values), and
   5369 less in normal cycles (min values). The maintenance timings do also depend on
   5370 whether the motor is on or off (and probably on various other factors like
   5371 seeking).
   5372 
   5373 First Response
   5374 The First Response interrupt is sent almost immediately after processing the
   5375 command (that is, when the mainloop sees a new command without any old
   5376 interrupt pending). For GetStat, timings are as so:
   5377   Command                Average   Min       Max
   5378   GetStat (normal)       000c4e1h  0004a73h..003115bh
   5379   GetStat (when stopped) 0005cf4h  000483bh..00093f2h
   5380 Timings for most other commands should be similar as above. One exception is
   5381 the Init command, which is doing some initialization before sending the 1st
   5382 response:
   5383   Init                   0013cceh  000f820h..00xxxxxh
   5384 The ReadTOC command is doing similar initialization, and should have similar
   5385 timing as Init command. Some (rarely used) Test commands include things like
   5386 serial data transfers, which may be also quite slow.
   5387 
   5388 Second Response
   5389   Command                Average   Min       Max
   5390   GetID                  0004a00h  0004922h..0004c2bh
   5391   Pause (single speed)   021181ch  020eaefh..0216e3ch ;\time equal to
   5392   Pause (double speed)   010bd93h  010477Ah..011B302h ;/about 5 sectors
   5393   Pause (when paused)    0001df2h  0001d25h..0001f22h
   5394   Stop (single speed)    0d38acah  0c3bc41h..0da554dh
   5395   Stop (double speed)    18a6076h  184476bh..192b306h
   5396   Stop (when stopped)    0001d7bh  0001ce8h..0001eefh
   5397 Moreover, Seek/Play/Read/SetSession/MotorOn/Init/ReadTOC are sending second
   5398 responses which depend on seek time (and spin-up time if the motor was off).
   5399 The seek timings are still unknown, and they are probably quite complicated:
   5400 The CDROM BIOS seems to split seek distance somehow into coarse steps (eg.
   5401 minutes) and fine steps (eg. seconds/sectors), so 1-minute seek distance may
   5402 have completely different timings than 59-seconds distance.
   5403 The amount of data per spiral winding increases towards ends of the disc (so
   5404 the drive head will need to be moved by shorter distance when moving from
   5405 minute 59 to 60 as than moving from 00 to 01).
   5406 The CDROM BIOS contains some seek distance table, which is probably optimized
   5407 for 72-minute discs (or whatever capacity is used on original PSX discs).
   5408 80-minute CDRs may have tighter spiral windings (the above seek table is
   5409 probably causing the drive head to be moved too far on such discs, which will
   5410 raise the seek time as the head needs to be moved backwards to compensate that
   5411 error).
   5412 
   5413 INT1 Rate
   5414   Command                Average   Min       Max
   5415   Read (single speed)    006e1cdh  00686dah..0072732h
   5416   Read (double speed)    0036cd2h  00322dfh..003ab2bh
   5417 The INT1 rate needs to be precise for CD-DA and CD-XA Audio streaming, exact
   5418 clock cycle values should be: SystemClock*930h/4/44100Hz for Single Speed (and
   5419 half as much for Double Speed) (the "Average" values are AVERAGE values, not
   5420 exact values).
   5421 
   5422 CDROM - Response/Data Queueing
   5423 ------------------------------
   5424 
   5425 [Below are some older/outdated test cases]
   5426 
   5427 Sector Buffer
   5428 The CDROM sector buffer is 32Kx8 SRAM (IC303). The buffer is apparently divided
   5429 into 8 slots, theoretically allowing to buffer up to 8 sectors.
   5430 BUG: The drive controller seems to allow only 2 of those 8 sectors (the oldest
   5431 sector, and the current/newest sector).
   5432 Ie. after processing the INT1 for the oldest sector, one would expect the
   5433 controller to generate another INT1 for next newer sector - but instead it
   5434 appears to jump directly to INT1 for the newest sector (skipping all other
   5435 unprocessed sectors). There is no known way to get around that effect.
   5436 So far, the big 32Kbyte buffer is entirely useless (the two accessible sectors
   5437 could have been as well stored in a 8Kbyte chip) (unless, maybe the 32Kbytes
   5438 have been intended for some error-correction "read-ahead" purposes, rather than
   5439 as "look-back" buffer for old sectors; one of the unused slots might be also
   5440 used for XA-ADPCM sectors).
   5441 The bottom line is that one should process INT1's as soon as possible (ie.
   5442 before the cdrom controller receives and skips further sectors). Otherwise
   5443 sectors would be lost without notice (there appear to be absolutely no overrun
   5444 status flags, nor overrun error interrupts).
   5445 
   5446 Sector Buffer Test Cases
   5447   Setloc(0:2:0)+Read
   5448   Process INT1 --> receives sector header for 0:2:0
   5449   Process INT1 --> receives sector header for 0:2:1
   5450   Process INT1 --> receives sector header for 0:2:2
   5451   Process INT1 --> receives sector header for 0:2:3
   5452 Above shows the normal flow when processing INT1's as they arise. Now,
   5453 inserting delays (and not processing INT1's during that delays):
   5454   Setloc(0:2:0)+Read
   5455   Process INT1 --> receives sector header for 0:2:0
   5456   delay(1)
   5457   Process INT1 --> receives sector header for 0:2:1 (oldest sector)
   5458   Process INT1 --> receives sector header for 0:2:6 (newest sector)
   5459   Process INT1 --> receives sector header for 0:2:7 (next sector)
   5460 Above suggests that the CDROM buffer can hold max 2 sectors (the oldest and
   5461 current one). However, using a longer delay:
   5462   Setloc(0:2:0)+Read
   5463   Process INT1 --> receives sector header for 0:2:0
   5464   delay(2)
   5465   Process INT1 --> receives sector header for 0:2:9  (oldest/overwritten)
   5466   Process INT1 --> receives sector header for 0:2:11 (newest sector)
   5467   Process INT1 --> receives sector header for 0:2:12 (next sector)
   5468 Above indicates that sector buffer can hold 8 sectors (as the sector 1 slot is
   5469 overwritten by sector 9). And, another test with even longer delay:
   5470   Setloc(0:2:0)+Read
   5471   Process INT1 --> receives sector header for 0:2:0
   5472   delay(3)
   5473   Process INT1 --> receives sector header for 0:2:17 (currently received)
   5474   Process INT1 --> receives sector header for 0:2:16 (newest full sector)
   5475   Process INT1 --> receives sector header for 0:2:17 (next sector)
   5476   Process INT1 --> receives sector header for 0:2:18 (next sector)
   5477 Above is a special case where sector 17 appears twice; the first one is the
   5478 sector 1 slot (which was overwritten by sector 9, and apparently then half
   5479 overwritten by sector 17).
   5480 
   5481 Sector Buffer VS GetlocL Response Tests
   5482   Setloc(0:2:0)+Read
   5483   Process INT1 --> receives sector header for 0:2:0
   5484   GetlocL
   5485   Process INT3 --> receives getloc info for 0:2:0
   5486   Process INT1 --> receives sector header for 0:2:1
   5487   Process INT1 --> receives sector header for 0:2:2
   5488   Process INT1 --> receives sector header for 0:2:3
   5489 Another test, with Delay BEFORE Getloc:
   5490   Setloc(0:2:0)+Read
   5491   Process INT1 --> receives sector header for 0:2:0
   5492   Delay(1)
   5493   GetlocL
   5494   Process INT1 --> receives sector header for 0:2:1
   5495   Process INT3 --> receives getloc info for 0:2:6
   5496   Process INT1 --> receives sector header for 0:2:6
   5497   Process INT1 --> receives sector header for 0:2:7
   5498 Another test, with Delay AFTER Getloc:
   5499   Setloc(0:2:0)+Read
   5500   Process INT1 --> receives sector header for 0:2:0
   5501   GetlocL
   5502   Delay(1)
   5503   Process INT3 --> receives getloc info for 0:2:0
   5504   Process INT1 --> receives sector header for 0:2:5
   5505   Process INT1 --> receives sector header for 0:2:6
   5506   Process INT1 --> receives sector header for 0:2:7
   5507 Another test, with Delay BEFORE and AFTER Getloc:
   5508   Setloc(0:2:0)+Read
   5509   Process INT1 --> receives sector header for 0:2:0
   5510   Delay(1)
   5511   GetlocL
   5512   Delay(1)
   5513   Process INT1 --> receives sector header for 0:2:9
   5514   Process INT1 --> receives sector header for 0:2:11
   5515   Process INT3 --> receives getloc info for 0:2:12
   5516   Process INT1 --> receives sector header for 0:2:12
   5517   Process INT1 --> receives sector header for 0:2:13
   5518 
   5519 Sector Buffer VS Pause Response Tests
   5520   Setloc(0:2:0)+Read
   5521   Process INT1 --> receives sector header for 0:2:0
   5522   Pause
   5523   Process INT3 --> receives stat=22h (first pause response)
   5524   Process INT2 --> receives stat=02h (second pause response)
   5525 Another test, with Delay BEFORE Pause:
   5526   Setloc(0:2:0)+Read
   5527   Process INT1 --> receives sector header for 0:2:0
   5528   Delay(1)
   5529   Pause
   5530   Process INT1 --> receives sector header for 0:2:1 (oldest)
   5531   Process INT3 --> receives stat=22h (first pause response)
   5532   Process INT2 --> receives stat=02h (second pause response)
   5533 Another test, with Delay AFTER Pause:
   5534   Setloc(0:2:0)+Read
   5535   Process INT1 --> receives sector header for 0:2:0
   5536   Pause
   5537   Delay(1)
   5538   Process INT3 --> receives stat=22h (first pause response)
   5539   Process INT2 --> receives stat=02h (second pause response)
   5540 Another test, with Delay BEFORE and AFTER Pause:
   5541   Setloc(0:2:0)+Read
   5542   Process INT1 --> receives sector header for 0:2:0
   5543   Delay(1)
   5544   Pause
   5545   Delay(1)
   5546   Process INT1 --> receives sector header for 0:2:9 (oldest/overwritten)
   5547   Process INT3 --> receives stat=22h (first pause response)
   5548   Process INT2 --> receives stat=02h (second pause response)
   5549 For above: Note that, despite of Pause, the CDROM is still writing to the
   5550 internal buffer (and overwrites slot 1 by sector 9) (this might be because the
   5551 Pause command isn't processed at all until INT1 is processed).
   5552 
   5553 Double Commands (Getloc then Pause)
   5554   Setloc(0:2:0)+Read
   5555   Process INT1 --> receives sector header for 0:2:0
   5556   GetlocL
   5557   Pause
   5558   Process INT3 --> receives stat=22h (first pause response)
   5559   Process INT2 --> receives stat=02h (second pause response)
   5560 Another test,
   5561   Setloc(0:2:0)+Read
   5562   Process INT1 --> receives sector header for 0:2:0
   5563   Delay(1)
   5564   GetlocL
   5565   Pause
   5566   Process INT1 --> receives sector header for 0:2:1
   5567   Process INT1 --> receives sector header for 0:2:6
   5568   Process INT3 --> receives stat=22h (first pause response)
   5569   Process INT2 --> receives stat=02h (second pause response)
   5570 Another test,
   5571   Setloc(0:2:0)+Read
   5572   Process INT1 --> receives sector header for 0:2:0
   5573   GetlocL
   5574   Delay(1)
   5575   Pause
   5576   Process INT3 --> receives getloc info for 0:2:0 (first getloc response)
   5577   Process INT3 --> receives stat=22h (first pause response)
   5578   Process INT2 --> receives stat=02h (second pause response)
   5579 Another test,
   5580   Setloc(0:2:0)+Read
   5581   Process INT1 --> receives sector header for 0:2:0
   5582   Delay(1)
   5583   GetlocL
   5584   Delay(1)
   5585   Pause
   5586   Process INT1 --> receives sector header for 0:2:9 (oldest/overwritten)
   5587   Process INT3 --> receives stat=22h (first pause response)
   5588   Process INT2 --> receives stat=02h (second pause response)
   5589 
   5590 Double Commands (Pause then Getloc)
   5591   Setloc(0:2:0)+Read
   5592   Process INT1 --> receives sector header for 0:2:0
   5593   Pause
   5594   GetlocL
   5595   Process INT3 --> receives getloc info for 0:2:0 (first getloc response)
   5596   Process INT1 --> receives sector header for 0:2:1
   5597   Process INT1 --> receives sector header for 0:2:2
   5598   Process INT1 --> receives sector header for 0:2:3
   5599 Another test,
   5600   Setloc(0:2:0)+Read
   5601   Process INT1 --> receives sector header for 0:2:0
   5602   Delay(1)
   5603   Pause
   5604   GetlocL
   5605   Process INT1 --> receives sector header for 0:2:1
   5606   Process INT3 --> receives getloc info for 0:2:6 (first getloc response)
   5607   Process INT1 --> receives sector header for 0:2:6
   5608   Process INT1 --> receives sector header for 0:2:7
   5609 Another test,
   5610   Setloc(0:2:0)+Read
   5611   Process INT1 --> receives sector header for 0:2:0
   5612   Pause
   5613   Delay(1)
   5614   GetlocL
   5615   Process INT3 --> receives stat=22h (first pause response)
   5616   Process INT3 --> receives getloc info for 0:2:6 (first getloc response)
   5617   (No further INT's, ie. read is paused, but second-pause-response is lost).
   5618 Another test,
   5619   Setloc(0:2:0)+Read
   5620   Process INT1 --> receives sector header for 0:2:0
   5621   Pause
   5622   Delay(1)
   5623   GetlocL
   5624   Delay(1)
   5625   Process INT3 --> receives stat=22h (first pause response)
   5626   Process INT3 --> receives getloc info for 0:2:6 (first getloc response)
   5627   Process INT2 --> receives stat=02h (second pause response)
   5628 Another test,
   5629   Setloc(0:2:0)+Read
   5630   Process INT1 --> receives sector header for 0:2:0
   5631   Delay(1)
   5632   Pause
   5633   Delay(1)
   5634   GetlocL
   5635   Process INT1 --> receives sector header for 0:2:9
   5636   Process INT1 --> receives sector header for 0:2:11
   5637   Process INT3 --> receives getloc info for 0:2:12 (first getloc response)
   5638   Process INT1 --> receives sector header for 0:2:12
   5639   Process INT1 --> receives sector header for 0:2:13
   5640 
   5641 CDROM Disk Format
   5642 -----------------
   5643 
   5644 Overview
   5645 The PSX uses a ISO 9660 filesystem, with data stored on CD-XA (Mode2) Sectors.
   5646 ISO 9660 is standard for CDROM disks, although newer CDROMs may use extended
   5647 filesystems, allowing to use long filenames and lowercase filenames, the PSX
   5648 Kernel doesn't support such stuff, and, in fact, it's putting some restrictions
   5649 on the ISO standard: it's limiting file names to MSDOS-style 8.3 format, and
   5650 it's allowing only a limited number of files and directories per disk.
   5651 
   5652 CDROM Filesystem (ISO 9660 aka ECMA-119)
   5653   Originally intended for Mode1 Sectors (but is also used for CD-XA Mode2)
   5654   Supports "FILENAME.EXT;VERSION" filenames (version is usually "1")
   5655   Supports all-uppercase filenames and directory names (0-9, A-Z, underscore)
   5656   For PSX: Max 8-character filenames with max 3-character extensions
   5657   For PSX: Max 8-character directory names, without extension
   5658   For PSX: Max one sector per directory (?)
   5659   For PSX: Max one sector (or less?) per path table (?)
   5660 
   5661 CDROM Extended Architecture (CD-ROM XA aka CD-XA)
   5662   Uses Mode2 Sectors (see Sector Encoding chapter)
   5663   Allows 800h or 914h byte data per sector (with/without error correction)
   5664   Allows to break interleaved data into separate files/channels
   5665   Supports XA-ADPCM compressed audio data
   5666   Stores "CD-XA001" at 400h Primary Volume Descriptor (?)
   5667   Stores 14 extra bytes in System Use area (LEN_SU) of Directory Entries
   5668 
   5669 Physical Audio/CDROM Disk Format (ISO/IEC 10149 aka ECMA-130)
   5670   Defines physical metrics of the CDROM and Audio disks
   5671   Defines Sub-channels and Track.Index and Minute.Second.Fraction numbering
   5672   Defines 14bit-per-byte encoding, and splits sectors into frames
   5673   Defines ECC and EDC (error correction and error detection codes)
   5674 
   5675 Available Documentation
   5676 ISO documents are commercial standards (not available for download), however,
   5677 they are based on ECMA standards (which are free for download, however, the
   5678 ECMA stuff is in PDF format, so one may treat it as commercial bullshit, too).
   5679 CD-ROM XA is commercial only (not available for download), and, CD-XA doesn't
   5680 seem to have become very popular outside of the PSX-world, so there's very
   5681 little information available, portions of CD-XA are also used in the CD-i
   5682 standard (which may be a little better or worse documented).
   5683 
   5684 Stuff
   5685   sessions  one or more sessions per disk
   5686   tracks    99 tracks per disk     (01h..99h) (usually only 01h on Data Disks)
   5687   index     99 indices per track   (01h..99h) (rarely used, usually always 01h)
   5688   minutes   74 minutes per disk    (00h..73h) (or more, with some restrictions)
   5689   seconds   60 seconds per minute  (00h..59h)
   5690   sectors   75 sectors per second  (00h..74h)
   5691   frames    98 frames per sector
   5692   bytes     33 bytes per frame (24+1+8 = data + subchannel + error correction)
   5693   bits      14 bits per byte   (256 valid combinations, and many invalid ones)
   5694 
   5695 Track.Index (stored in subchannel, in BCD format)
   5696 Multiple Tracks are usually used only on Audio Disks (one track for each song,
   5697 numbered 01h and up), a few Audio Disks may also split Tracks into separate
   5698 fragments with different Index values (numbered 01h and up, but most tracks
   5699 have only Index 01h). A simple Data Disk would usually contain only one Track
   5700 (all sectors marked Track=01h and Index=01h), although some more complex Data
   5701 Disks may have multiple Data tracks and/or Audio tracks.
   5702 
   5703 Minute.Second.Sector (stored in subchannel, and in Data sectors, BCD format)
   5704 The sectors on CDROMs and CD Audio disks are numbered in Minutes, Seconds, and
   5705 1/75 fragments of a second (where a "second" is referring to single-speed
   5706 drives, ie. the normal CD Audio playback speed).
   5707 Minute.Second.Sector is stored twice in the subchannel (once the "absolute"
   5708 time, and once the "local" time).
   5709 The "absolute" sector number (counted from the begin of the disk) is mainly
   5710 relevant for Seek purposes (telling the controller if the drive head is on the
   5711 desired location, or if it needs to move the head backwards or forwards).
   5712 The "local" sector number (counted from the begin of the track) is mainly
   5713 relevant for Audio Players, allowing to pass the data directly to the
   5714 Minute:Second display, without needing to subtract the start address of the
   5715 track.
   5716 Data disks are additionally storing the "absolute" values in their Data Areas,
   5717 basically that's just the subchannel data duplicated, but more precisely
   5718 assigned - the problem with the subchannel data is that the CD Audio standard
   5719 seems to lack a clear definition that would assign the begin of the sub-channel
   5720 block to the exact begin of a sector; so, when using only the subchannel data,
   5721 some Drive Controllers may assign the begin of a new sector to another location
   5722 as than other Controllers do, for Audio Disks that isn't too much of a problem,
   5723 but for Data Disks it'd be fatal.
   5724 
   5725 Subchannels
   5726 Each frame contains 8 subchannel bits (named P,Q,R,S,T,U,V,W). So, a sector
   5727 (with 98 frames) contains 98 bits (12.25 bytes) for each subchannel.
   5728 --> CDROM Subchannels
   5729 
   5730 Error Correction
   5731 Each Frame contains 8 bytes Error Correction information, which is mainly used
   5732 for Audio Disks, but it isn't 100% fail-proof, for that reason, Data Disks are
   5733 containing additional Error Correction in the 930h-byte data area (the audio
   5734 correction is probably focusing on repairing the MSBs of the 16bit samples, and
   5735 gives less priority on the LSBs). Error Correction is some kind of a huge
   5736 complex checksum, which allows to detect the location of faulty bytes, and to
   5737 fix them.
   5738 
   5739 930h-Byte Sectors
   5740 The "user" area for each sector is 930h bytes (2352 bytes). That region is
   5741 combined of the 24-byte data per frame (and excludes the 8-byte audio error
   5742 correction info, and the 1-byte subchannel data).
   5743 Most CDROM Controllers are only giving access to this 930h-byte region (ie.
   5744 there's no way to read the audio error correction info by software, and only
   5745 limited access to the subchannel data, such like allowing to read only the
   5746 Q-channel for showing track/minute/second in audio playback mode).
   5747 On Audio disks, the 930h bytes are plain data, on Data disks that bytes are
   5748 containing headers, error correction, and usually only 800h bytes user data
   5749 (for more info see Sector Encoding chapter).
   5750 
   5751 Sessions
   5752 Multi-Sessions are mainly used on CDR's, allowing to append newer data at the
   5753 end of the disk at a later time. First of, the old session must contain a flag
   5754 indicating that there may be a newer session, telling the CDROM Controller to
   5755 search if one such exists (and if that is equally flagged, to search for an
   5756 even newer session, and so on until reaching the last and newest session).
   5757 Each session contains a complete new ISO Volume Descriptor, and may
   5758 additionally contain new Path Tables, new Directories, and new Files. The
   5759 Driver Controller is usually recursing only the Volume Descriptor of the newest
   5760 session. However, the various Directory Records of the new session may refer to
   5761 old files or old directories from previous sessions, allowing to "import" the
   5762 older files, or to "rename" or "delete" them by assigning new names to that
   5763 files, or by removing them from the directory.
   5764 The PSX is reportedly not supporting multi-session disks, but that doesn't seem
   5765 to be correct, namely, the Setsession command is apparently intended for that
   5766 purpose... though not sure if the PSX Kernel is automatically searching the
   5767 newest session... otherwise the boot executable in the first session would need
   5768 to do that manually by software, and redirect control to the boot executable in
   5769 the last session.
   5770 
   5771 CDROM Subchannels
   5772 -----------------
   5773 
   5774 Subchannel P
   5775 Subchannel P contains some kind of a Pause flag (to indicate muted areas
   5776 between Audio Tracks). This subchannel doesn't have any checksum, so the data
   5777 cannot be trusted to be intact (unless when sensing a longer stream of
   5778 all-one's, or all zero's). Theoretically, the 98 pause bits are somehow
   5779 associated to the 98 audio frames (with 24 audio bytes each) of the sector.
   5780 However, reportedly, Subchannel P does contain two sync bits, if that is true,
   5781 then there'd be only 96 pause flags for 98 audio frames. Strange.
   5782 Note: Another way to indicate "paused" regions is to set Subchannel Q to ADR=1
   5783 and Index=00h.
   5784 
   5785 Subchannel Q
   5786 contains the following information:
   5787   Bits Expl.
   5788   2    Sub-channel synchronization field
   5789   8    ADR/Control (see below)
   5790   72   Data (content depends on ADR)
   5791   16   CRC-16-CCITT error detection code (big-endian: bytes ordered MSB, LSB)
   5792 Possible values for the ADR/Control field are:
   5793   Bit0-3 ADR (0=No data, 1..3=see below, 4..0Fh=Reserved)
   5794   Bit4   Audio Preemphasis  (0=No, 1=Yes)      (Audio only, must be 0 for Data)
   5795   Bit5   Digital Copy       (0=Prohibited, 1=Allowed)
   5796   Bit6   Data               (0=Audio, 1=Data)
   5797   Bit7   Four-Channel Audio (0=Stereo, 1=Quad) (Audio only, must be 0 for Data)
   5798 The 72bit data regions are, depending on the ADR value...
   5799 
   5800 Subchannel Q with ADR=1 during Lead-In -- Table of Contents (TOC)
   5801   8    Track number (fixed, must be 00h=Lead-in)
   5802   8    Point (01h..99h or A0h..A2h, see last three bytes for more info)
   5803   24   MSF address (incrementing address within the Lead-in area)
   5804          Note: On some disks, these values are choosen so that the lead-in
   5805          <starts> at 00:00:00, on other disks so that it <ends> at 99:59:74.
   5806   8    Reserved (00h)
   5807 When Point=01h..99h (Track 1..99) or Point=A2h (Lead-Out):
   5808   24   MSF address (absolute address, start address of the "Point" track)
   5809 When Point=A0h (First Track Number):
   5810   8    First Track number (BCD)
   5811   8    Disk Type Byte (00h=CD-DA or CD-ROM, 10h=CD-I, 20h=CD-ROM-XA)
   5812   8    Reserved (00h)
   5813 When Point=A1h (Last Track Number):
   5814   8    Last Track number (BCD)
   5815   16   Reserved (0000h)
   5816 ADR=1 should exist in 3 consecutive lead-in sectors.
   5817 
   5818 Subchannel Q with ADR=1 in Data region -- Position
   5819   8    Track number (01h..99h=Track 1..99)
   5820   8    Index number (00h=Pause, 01h..99h=Index within Track)
   5821   24   Track relative MSF address (decreasing during Pause)
   5822   8    Reserved (00h)
   5823   24   Absolute MSF address
   5824 ADR=1 is required to exist in at least 9 out of 10 consecutive data sectors.
   5825 
   5826 Subchannel Q with ADR=1 during Lead-Out -- Position
   5827   8    Track number (fixed, must be AAh=Lead-Out)
   5828   8    Index number (fixed, must be 01h) (there's no Index=00h in Lead-Out)
   5829   24   Track relative MSF address (increasing, 00:00:00 and up)
   5830   8    Reserved (00h)
   5831   24   Absolute MSF address
   5832 ADR=1 should exist in 3 consecutive lead-out sectors (and may be then followed
   5833 by ADR=5 on multisession disks).
   5834 
   5835 Subchannel Q with ADR=2 -- Catalogue number of the disc (UPC/EAN barcode)
   5836   52   EAN-13 barcode number (13-digit BCD)
   5837   12   Reserved (000h)
   5838   8    Absolute Sector number (BCD, 00h..74h) (always 00h during Lead-in)
   5839 If the first digit of the EAN-13 number is "0", then the remaining digits are a
   5840 UPC-A barcode number. Either the 13-digit EAN-13 number, or the 12-digit UPC-A
   5841 number should be printed as barcode on the rear-side of the CD package.
   5842 The first some digits contain a country code (EAN only, not UPC), followed by a
   5843 manufacturer code, followed by a serial number. The last digit contains a
   5844 checksum, which can be calculated as 250 minus the sum of the first 12 digits,
   5845 minus twice the sum of each second digit, modulated by 10.
   5846 ADR=2 isn't included on all CDs, and, many CDs do have ADR=2, but the 13 digits
   5847 are all zero. Most CDROM drives do not allow to read EAN/UPC numbers.
   5848 If present, ADR=2 should exist in at least 1 out of 100 consecutive sectors.
   5849 ADR=2 may occur also in Lead-in.
   5850 
   5851 Subchannel Q with ADR=3 -- ISRC number of the current track
   5852 (ISO 3901 and DIN-31-621):
   5853   12   Country Code      (two 6bit characters)   (ASCII minus 30h) ;eg. "US"
   5854   18   Owner Code        (three 6bit characters) (ASCII minus 30h)
   5855   2    Reserved          (zero)
   5856   8    Year of recording (2-digit BCD) ;eg. 82h for 1982
   5857   20   Serial number     (5-digit BCD) ;usually increments by 1 or 10 per track
   5858   4    Reserved          (zero)
   5859   8    Absolute Sector number (BCD, 00h..74h) (always 00h during Lead-in)
   5860 Most CDROM drives for PC's do not allow to read ISRC numbers (or even worse,
   5861 they may accidently return the same ISRC number on every two tracks).
   5862 If present, ADR=3 should exist in at least 1 out of 100 consecutive sectors.
   5863 However, reportedly, ADR=3 should not occur in Lead-in.
   5864 
   5865 Subchannel Q with ADR=5 in Lead-in -- Multisession Lead-In Info
   5866 When Point=B0h:
   5867   8    Track number (fixed, must be 00h=Lead-in)
   5868   8    POINT = B0h (multi-session disc)
   5869   24   MM:SS:FF = the start time for the next possible session's program area,
   5870        a final session is indicated by FFh:FFh:FFh,
   5871        or when the ADR=5 / Point=B0h is absent.
   5872   8    Number of different Mode-5 pointers present.
   5873   24   MM:SS:FF = the maximum possible start time of the outermost Lead-out
   5874 When Point=C0h:
   5875   8    Track number (fixed, must be 00h=Lead-in)
   5876   8    POINT = C0h (Identifies a Multisession disc, together with POINT=B0h)
   5877   24   ATIP values from Special Information 1, ID=101
   5878   8    Reserved (must be 00h)
   5879   24   MM:SS:FF = Start time of the first Lead-in area of the disc
   5880 And, optionally, when Point=C1h:
   5881   8    Track number (fixed, must be 00h=Lead-in)
   5882   8    POINT=C1h
   5883   8x7  Copy of information from A1 point in ATIP
   5884 
   5885 Subchannel Q with ADR=5 in Lead-Out -- Multisession Lead-Out Info
   5886   8    Track number (fixed, must be AAh=Lead-out)
   5887   8    POINT = D1h (Identifies a Multisession lead-out)
   5888   24   Usually zero (or maybe ATIP as in Lead-In with Point=C0h...?)
   5889   8    Seems to be the session number?
   5890   24   MM:SS:FF = Absolute address of the First data sector of the session
   5891 Present in 3 consequtive sectors (3x ADR=1, 3x ADR=5, 3x ADR=1, 3x ADR=5, etc).
   5892 
   5893 Subchannel Q with ADR=5 in Lead-in -- CDR/CDRW Skip Info (Audio Only)
   5894 When Point=01h..40h:
   5895   8    Track number (fixed, must be 00h=Lead-in)
   5896   8    POINT=01h..40h (This identifies a specific playback skip interval)
   5897   24   MM:SS:FF Skip interval stop time in 6 BCD digits
   5898   8    Reserved (must be 00h)
   5899   24   MM:SS:FF Skip interval start time in 6 BCD digits
   5900 When Point=B1h:
   5901   8    Track number (fixed, must be 00h=Lead-in)
   5902   8    POINT=B1h (Audio only: This identifies the presence of skip intervals)
   5903   8x4  Reserved (must be 00h,00h,00h,00h)
   5904   8    the number of skip interval pointers in POINT=01h..40h
   5905   8    the number of skip track assignments in POINT=B2h..B4h
   5906   8    Reserved (must be 00h)
   5907 When Point=B2h,B3h,B4h:
   5908   8    Track number (fixed, must be 00h=Lead-in)
   5909   8    POINT=B2h,B3h,B4h (This identifies tracks that should be skipped)
   5910   8    1st Track number to skip upon playback (01h..99h, must be nonzero)
   5911   8    2nd Track number to skip upon playback (01h..99h, or 00h=None)
   5912   8    3rd Track number to skip upon playback (01h..99h, or 00h=None)
   5913   8    Reserved (must be 00h)... unclear... OR... 4th (of 7) skip info's...?
   5914   8    4th Track number to skip upon playback (01h..99h, or 00h=None)
   5915   8    5th Track number to skip upon playback (01h..99h, or 00h=None)
   5916   8    6th Track number to skip upon playback (01h..99h, or 00h=None)
   5917 Note: Skip intervals are seldom written by recorders and typically ignored by
   5918 readers.
   5919 
   5920 Subchannel R..W
   5921 Subchannels R..W are usually unused, except for some extended formats:
   5922   CD-TEXT in the Lead-In area (see below)
   5923   CD-TEXT in the Data area    (rarely used)
   5924   CD plus Graphics (CD+G)     (rarely used)
   5925 Most CDROM drives do not allow to read these subchannels. CD-TEXT was designed
   5926 by Sony and Philips in 1997, so it should be found only on (some) newer discs.
   5927 Most CD/DVD players don't support it (the only exception is that CD-TEXT seems
   5928 to be popular for car hifi equipment). Most record labels don't support
   5929 CD-TEXT, even Sony seems to have discontinued it on their own records after
   5930 some years (so CD-TEXT is very rare on original disks, however, CDR software
   5931 does often allow to write CD-TEXT on CDRs).
   5932 
   5933 Subchannel R..W, when used for CD-TEXT in the Lead-In area
   5934 CD-TEXT is stored in the six Subchannels R..W. Of the 12.25 bytes (98 bits) per
   5935 subchannel, only 12 bytes are used. Together, all 6 subchannels have a capacity
   5936 of 72 bytes (6x12 bytes) per sector. These 72 bytes are divided into four
   5937 CD-TEXT fragments (of 18 bytes each). The format of these 18 bytes is:
   5938   00h 1  Header Field ID1: Pack Type Indicator
   5939   01h 1  Header Field ID2: Track Number
   5940   02h 1  Header Field ID3: Sequence Number
   5941   03h 1  Header Field ID4: Block Number and Character Position Indicator
   5942   04h 12 Text/Data Field
   5943   10h 2  CRC-16-CCITT (big-endian) (across bytes 00h..0Fh)
   5944 ID1 - Pack Type Indicator:
   5945   80h   Titel      (TEXT)
   5946   81h   Performer  (TEXT)
   5947   82h   Songwriter (TEXT)
   5948   83h   Composer   (TEXT)
   5949   84h   Arranger   (TEXT)
   5950   85h   Message    (TEXT)
   5951   86h   Disc ID    (TEXT?)  (content/format/purpose unknown?)
   5952   87h   Genre      (BINARY) (ID codes unknown?)
   5953   88h   TOC        (BINARY) (content/format/purpose unknown?)
   5954   89h   TOC2       (BINARY) (content/format/purpose unknown?)
   5955   8Ah   Reserved for future
   5956   8Bh   Reserved for future
   5957   8Ch   Reserved for future
   5958   8Dh   Reserved for "content provider" aka "closed information"
   5959   8Eh   UPC/EAN and ISRC Codes (TEXT) (content/format/purpose unknown?)
   5960   8Fh   Blocksize (BINARY) (see below)
   5961 ID2 - Track Number:
   5962   00h       Title/Performer/etc. for the Disc
   5963   01h..63h  Title/Performer/etc. for Track 1..99 (Non-BCD) (Bit7=Extension)
   5964 ID3 - Sequence Number:
   5965   00h..FFh  Incrementing Number (00h=First 18-byte fragment, 01h=Second, etc.)
   5966 ID4 - Block Number and Character Position Indicator:
   5967   Bit7      Character Set      (0=8bit, 1=16bit)
   5968   Bit6-4    Block Number       (0..7 = Language number, as set by "Blocksize")
   5969   Bit3-0    Character Position (0..0Eh=Position, 0Fh=Append to prev fragment)
   5970 Example Data (generated with CDRWIN):
   5971   ID TR SQ CH <------------Text/Data------------> -CRC-  <---Text--->
   5972   80 00 00 00 54 65 73 74 44 69 73 6B 54 69 74 6C E2 22  TestDiskTitl
   5973   80 00 01 0C 65 00 54 65 73 74 54 72 61 63 6B 54 C9 1B  e.TestTrackT
   5974   80 01 02 0A 69 74 6C 65 31 00 54 65 73 74 54 72 40 3A  itle1.TestTr
   5975   80 02 03 06 61 63 6B 54 69 74 6C 65 32 00 00 00 80 E3  ackTitle2...
   5976   81 00 04 00 54 65 73 74 44 69 73 6B 50 65 72 66 03 DF  TestDiskPerf
   5977   81 00 05 0C 6F 72 6D 65 72 00 54 65 73 74 54 72 12 A5  ormer.TestTr
   5978   81 01 06 06 61 63 6B 50 65 72 66 6F 72 6D 65 72 BC 5B  ackPerformer
   5979   81 01 07 0F 31 00 54 65 73 74 54 72 61 63 6B 50 AC 41  1.TestTrackP
   5980   81 02 08 0A 65 72 66 6F 72 6D 65 72 32 00 00 00 64 1A  erformer2...
   5981   8F 00 09 00 01 01 02 00 04 05 00 00 00 00 00 00 6D E2  ............
   5982   8F 01 0A 00 00 00 00 00 00 00 00 03 0B 00 00 00 CD 0C  ............
   5983   8F 02 0B 00 00 00 00 00 09 00 00 00 00 00 00 00 FC 8C  ............
   5984   00   ;<--- for some reason, CDRWIN stores an ending 00h byte in .CDT files
   5985 Each Text string is terminated by a 00h byte (or 0000h for 16bit character
   5986 set). If there's still room in the 12-byte data region, then first characters
   5987 for the next Text string (for the next track) are appended after the 00h byte
   5988 (if there's no further track, then the remaining bytes should be padded with
   5989 00h).
   5990 The "Blocksize" (ID1=8Fh) consists of three packs with 24h bytes of data (first
   5991 0Ch bytes stored with ID2=00h, next 0Ch bytes with ID2=01h, and last 0Ch bytes
   5992 with ID2=02h):
   5993   00h  1   Character set (00h,01h,80h,81h,82h = see below)
   5994   01h  1   First track number (usually/always 01h)
   5995   02h  1   Last track number (01h..63h)
   5996   03h  1   1bit-cd-text-in-data-area-flag, 7bit-copy-protection-flags
   5997   04h  16  Number of 18-byte packs for ID1=80h..8Fh
   5998   14h  8   Last sequence number of block 0..7 (or 00h=none)
   5999   1Ch  8   Language codes for block 0..7 (definitions are unknown)
   6000 Character Set values (for ID1=8Fh, ID2=00h, DATA[0]=charset):
   6001   00h ISO 8859-1
   6002   01h ISO 646, ASCII
   6003   80h MS-JIS
   6004   81h Korean character code
   6005   82h Mandarin (standard) Chinese character code
   6006   Other = reserved
   6007 "In case the same character stings is used for consecutive tracks, character
   6008 09h (or 0909h for 16bit charset) may be used to indicate the same as previous
   6009 track. It shall not used for the first track."
   6010 
   6011 adjust_crc_16_ccitt(addr_len)  ;for CD-TEXT and Subchannel Q
   6012   lsb=00h, msb=00h      ;-initial value (zero for both CD-TEXT and Sub-Q)
   6013   for i=0 to len-1      ;-len (10h for CD-TEXT, 0Ah for Sub-Q)
   6014     x = [addr+i] xor msb
   6015     x = x xor (x shr 4)
   6016     msb = lsb xor (x shr 3) xor (x shl 4)
   6017     lsb = x xor (x shl 5)
   6018   next i
   6019   [addr+len+0]=msb xor FFh, [addr+len+1]=lsb xor FFh   ;inverted / big-endian
   6020 
   6021 CDROM Sector Encoding
   6022 ---------------------
   6023 
   6024 Audio
   6025   000h 930h Audio Data (2352 bytes) (LeftLsb,LeftMsb,RightLsb,RightMsb)
   6026 Mode0 (Empty)
   6027   000h 0Ch  Sync   (00h,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,00h)
   6028   00Ch 4    Header (Minute,Second,Sector,Mode=00h)
   6029   010h 920h Zerofilled
   6030 Mode1 (Original CDROM)
   6031   000h 0Ch  Sync   (00h,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,00h)
   6032   00Ch 4    Header (Minute,Second,Sector,Mode=01h)
   6033   010h 800h Data (2048 bytes)
   6034   810h 4    EDC (checksum accross [000h..80Fh])
   6035   814h 8    Zerofilled
   6036   81Ch 114h ECC (error correction codes)
   6037 Mode2/Form1 (CD-XA)
   6038   000h 0Ch  Sync   (00h,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,00h)
   6039   00Ch 4    Header (Minute,Second,Sector,Mode=02h)
   6040   010h 4    Sub-Header (File, Channel, Submode AND DFh, Codinginfo)
   6041   014h 4    Copy of Sub-Header
   6042   018h 800h Data (2048 bytes)
   6043   818h 4    EDC (checksum accross [010h..817h])
   6044   81Ch 114h ECC (error correction codes)
   6045 Mode2/Form2 (CD-XA)
   6046   000h 0Ch  Sync   (00h,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,00h)
   6047   00Ch 4    Header (Minute,Second,Sector,Mode=02h)
   6048   010h 4    Sub-Header (File, Channel, Submode OR 20h, Codinginfo)
   6049   014h 4    Copy of Sub-Header
   6050   018h 914h Data (2324 bytes)
   6051   92Ch 4    EDC (checksum accross [010h..92Bh]) (or 00000000h if no EDC)
   6052 
   6053 encode_sector
   6054   sector[000h]=00h,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh,00h
   6055   sector[00ch]=bcd(adr/75/60)      ;0..7x
   6056   sector[00dh]=bcd(adr/75 MOD 60)  ;0..59
   6057   sector[00eh]=bcd(adr MOD 75)     ;0..74
   6058   sector[00fh]=mode
   6059   if mode=00h then
   6060     sector[010h..92Fh]=zerofilled
   6061   if mode=01h then
   6062     adjust_edc(sector+0, 800h+10h)
   6063     sector[814h..817h]=00h,00h,00h,00h,00h,00h,00h,00h
   6064     calc_p_parity(sector)
   6065     calc_q_parity(sector)
   6066   if mode=02h and form=1
   6067     sector[012h]=sector[012h] AND (NOT 20h)  ;indicate not form2
   6068     sector[014h..017h]=sector[010h..013h]    ;copy of sub-header
   6069     adjust_edc(sector+10h,800h+8)
   6070     push sector[00ch]           ;\temporarily clear header
   6071     sector[00ch]=00000000h      ;/
   6072     calc_p_parity(sector)
   6073     calc_q_parity(sector)
   6074     pop sector[00ch]            ;-restore header
   6075   if mode=02h and form=2
   6076     sector[012h]=sector[012h] OR 20h         ;indicate form2
   6077     sector[014h..017h]=sector[010h..013h]    ;copy of sub-header
   6078     adjust_edc(sector+10h,914h+8)            ;edc is optional for form2
   6079 
   6080 calc_parity(sector,offs,len,j0,step1,step2)
   6081   src=00ch, dst=81ch+offs, srcmax=dst
   6082   for i=0 to len-1
   6083     base=src, x=0000h, y=0000h
   6084     for j=j0 to 42
   6085       x=x xor GF8_PRODUCT[j,sector[src+0]]
   6086       y=y xor GF8_PRODUCT[j,sector[src+1]]
   6087       src=src+step1, if (step1=2*44) and (src>=srcmax) then src=src-2*1118
   6088     sector[dst+2*len+0]=x AND 0FFh, [dst+0]=x SHR 8
   6089     sector[dst+2*len+1]=y AND 0FFh, [dst+1]=y SHR 8
   6090     dst=dst+2, src=base+step2
   6091 calc_p_parity(sector) = calc_parity(sector,0,43,19,2*43,2)
   6092 calc_q_parity(sector) = calc_parity(sector,43*4,26,0,2*44,2*43)
   6093 
   6094 adjust_edc(addr,len)
   6095   x=00000000h
   6096   for i=0 to len-1
   6097     x=x xor byte[addr+i], x=(x shr 8) xor edc_table[x and FFh]
   6098   word[addr+len]=x  ;append EDC value (little endian)
   6099 
   6100 init_tables
   6101   for i=0 to FFh
   6102     x=i, for j=0 to 7, x=x shr 1, if carry then x=x xor D8018001h
   6103     edc_table[i]=x
   6104   GF8_LOG[00h]=00h, GF8_ILOG[FFh]=00h, x=01h
   6105   for i=00h to FEh
   6106     GF8_LOG[x]=i, GF8_ILOG[i]=x
   6107     x=x SHL 1, if carry8bit then x=x xor 1dh
   6108   for j=0 to 42
   6109     xx=GF8_ILOG[44-j],  yy=subfunc(xx xor 1,19h)
   6110     xx=subfunc(xx,01h), xx=subfunc(xx xor 1,18h)
   6111     xx=GF8_LOG[xx], yy = GF8_LOG[yy]
   6112     GF8_PRODUCT[j,0]=0000h
   6113     for i=01h to FFh
   6114       x=xx+GF8_LOG[i], if x>=255 then x=x-255
   6115       y=yy+GF8_LOG[i], if y>=255 then y=y-255
   6116       GF8_PRODUCT[j,i]=GF8_ILOG[x]+(GF8_ILOG[y] shl 8)
   6117 
   6118 subfunc(a,b)
   6119   if a>0 then
   6120     a=GF8_LOG[a]-b, if a<0 then a=a+255
   6121     a=GF8_ILOG[a]
   6122   return(a)
   6123 
   6124 CDROM Scrambling
   6125 ----------------
   6126 
   6127 Scrambling
   6128 Scambling does XOR the data sectors with random values (done to avoid regular
   6129 patterns). The scrambling is applied to Data sector bytes[00Ch..92Fh] (not to
   6130 CD-DA audio sectors, and not to the leading 12-byte Sync mark in Data sectors).
   6131 The (de-)scrambling is done automatically by the CDROM controller, so disc
   6132 images should usually contain unscrambled data (there are some exceptions such
   6133 like CD-i discs that have audio and data sectors mixed inside of the same
   6134 track; which may confuse the CDROM controller about whether or not to apply
   6135 scrambling to which sectors; so one may need to manually XOR the faulty sectors
   6136 in the disc image).
   6137 The scrambling pattern is derived from a 15bit polynomial counter (much like a
   6138 noise generator in sound chips). The data bits are XORed with the counters low
   6139 bit, and the counters lower 2bit are XORed with each other, and shifted in to
   6140 the counters upper bit. To compute 8 bits and once, and store them in a
   6141 924h-byte table:
   6142   poly=0001h  ;init 15bit polynomial counter
   6143   for i=0 to 924h-1
   6144     scramble_table[i]=poly AND FFh
   6145     poly=(((poly XOR poly/2) AND 0FFh)*80h) XOR (poly/100h)
   6146   next i
   6147 The resulting table content should be:
   6148   01h,80h,00h,60h,00h,28h,00h,1Eh,80h,08h,60h,06h,A8h,02h,FEh,81h,
   6149   80h,60h,60h,28h,28h,1Eh,9Eh,88h,68h,66h,AEh,AAh,FCh,7Fh,01h,E0h,
   6150   etc.
   6151 After scrambling, the data is reportedly "shuffled and byte-swapped". Unknown
   6152 what shuffling means. And unknown what/where/why byte-swapping is done (it does
   6153 reportedly swap each two bytes in the whole(?) 930h-byte (data-?) sector; which
   6154 might date back to different conventions for disc images to contain "16bit
   6155 audio samples" in big- or little-endian format).
   6156 
   6157 CDROM XA Subheader, File, Channel, Interleave
   6158 ---------------------------------------------
   6159 
   6160 The Sub-Header for normal data sectors is usually 00h,00h,08h,00h (some PSX
   6161 sectors have 09h instead 08h, indicating the end of "something" or so?
   6162 
   6163 1st Subheader byte - File Number (FN)
   6164   0-7 File Number    (00h..FFh) (for Audio/Video Interleave, see below)
   6165 
   6166 2nd Subheader byte - Channel Number (CN)
   6167   0-4 Channel Number (00h..1Fh) (for Audio/Video Interleave, see below)
   6168   5-7 Should be always zero
   6169 Whilst not officially allowed, PSX Ace Combat 3 Electrosphere does use
   6170 Channel=FFh for unused gaps in interleaved streaming sectors.
   6171 
   6172 3rd Subheader byte - Submode (SM)
   6173   0   End of Record (EOR) (all Volume Descriptors, and all sectors with EOF)
   6174   1   Video     ;\Sector Type (usually ONE of these bits should be set)
   6175   2   Audio     ; Note: PSX .STR files are declared as Data (not as Video)
   6176   3   Data      ;/
   6177   4   Trigger           (for application use)
   6178   5   Form2             (0=Form1/800h-byte data, 1=Form2, 914h-byte data)
   6179   6   Real Time (RT)
   6180   7   End of File (EOF) (or end of Directory/PathTable/VolumeTerminator)
   6181 The EOR bit is set in all Volume Descriptor sectors, the last sector (ie. the
   6182 Volume Descriptor Terminator) additionally has the EOF bit set. Moreover, EOR
   6183 and EOF are set in the last sector of each Path Table, and last sector of each
   6184 Directory, and last sector of each File.
   6185 
   6186 4th Subheader byte - Codinginfo (CI)
   6187 When used for Data sectors:
   6188   0-7 Reserved (00h)
   6189 When used for XA-ADPCM audio sectors:
   6190   0-1 Mono/Stereo     (0=Mono, 1=Stereo, 2-3=Reserved)
   6191   2-2 Sample Rate     (0=37800Hz, 1=18900Hz, 2-3=Reserved)
   6192   4-5 Bits per Sample (0=Normal/4bit, 1=8bit, 2-3=Reserved)
   6193   6   Emphasis        (0=Normal/Off, 1=Emphasis)
   6194   7   Reserved        (0)
   6195 
   6196 Audio/Video Interleave (Multiple Files/Channels)
   6197 The CDROM drive mechanics are working best when continously following the data
   6198 spiral on the disk, that works fine for uncompressed Audio Data at normal
   6199 speed, but compressed Audio Data the disk is spinning much too fast. To avoid
   6200 the drive to need to pause reading or to do permanent backwards seeking, CD-XA
   6201 allows to store data interleaved in separate files/channels. With common
   6202 interleave values like so:
   6203   Interleave   Data Format
   6204   1/1 (none)   44100Hz Stereo CD Audio at normal speed
   6205   1/8          37800Hz Stereo ADPCM compressed Audio at double speed
   6206   1/16         18900Hz Stereo ADPCM compressed Audio at double speed
   6207   1/16         37800Hz Mono   ADPCM compressed Audio at double speed
   6208   1/32         18900Hz Mono   ADPCM compressed Audio at double speed
   6209   7/8          15fps 320x224 pixel MDEC compressed Videos at double speed
   6210   Unknown if 1/16 and 1/32 interleaves are actually possible (the PSX cdrom
   6211   controller seems to overwrite the IC303 sector buffer entries once every
   6212   eight sectors, so ADPCM data may get destroyed on interleaves above 1/8).
   6213   (Crash Team Racing uses 37800Hz Mono at Double speed, so 1/16 must work).
   6214 For example, 1/8 means that the controller processes only each 8th sector (each
   6215 having the same File Number and Channel Number), and ignores the next 7 sectors
   6216 (which must have other File Number and/or other Channel Number). There are
   6217 various ways to arrange multiple files or channels, for example,
   6218   one file with eight 1/8 audio channels
   6219   one file with one 1/8 audio channels, plus one 7/8 video channel (*)
   6220   one file with one 1/8 audio channels, plus 7 unused channels
   6221   eight different files with one 1/8 audio channel each
   6222   etc.
   6223 (*) If the Audio and Video data belongs together then both should use the SAME
   6224 channel.
   6225 Note: Above interleave values are assuming that PSX Game Disks are always
   6226 running at double speed (that's fastest for normal data files, and ADPCM files
   6227 are usually using the same speed; otherwise it'd be neccessary to change the
   6228 drive speed everytime when switching between Data to ADPCM modes).
   6229 Note: The file/channel numbers can be somehow selected with the Setfilter
   6230 command. No idea if the controller is automatically switching to the next
   6231 channel or so when reaching the end of the file?
   6232 
   6233 Unused sectors in Interleave
   6234 There are different ways to mark unused sectors in interleaved streams. Ace
   6235 Combat 3 uses Channel=FFh=Invalid. Tron Bonne uses Submode=00h=Nothing
   6236 (notably, that game has a 74Mbyte XA file that leaves about 75% unused).
   6237   Subheader bytes: 01h,FFh,64h,01h   ;Ace Combat 3 Electrosphere
   6238   Subheader bytes: 01h,00h,00h,00h   ;Misadventures of Tron Bonne (XA\*.XA)
   6239 
   6240 Real Time Streaming
   6241 With the above Interleave, files can be played continously at real time - that,
   6242 unless read-errors do occur. In that case the drive controller would usually
   6243 perform time-consuming error-correction and/or read-retries. For video/audio
   6244 streaming the resulting delay would be tendencially more annoying as than
   6245 processing or skipping the incorrect data.
   6246 In such cases the drive controller is allowed to ignore read errors; that
   6247 probably on sectors that have the Real Time (RT) flag set in their subheaders.
   6248 The controller is probably doing some read-ahead buffering (so, if it has
   6249 buffered enough data, then it may still perform read retries and/or error
   6250 correction, as long as it doesn't affect real time playback).
   6251 
   6252 CDROM XA Audio ADPCM Compression
   6253 --------------------------------
   6254 
   6255 CD-ROM XA ADPCM is used for Audio data compression. Each 16bit sample is
   6256 encoded in 4bit nibbles; so the compression rate is almost 1:4 (only almost 1:4
   6257 because there are 16 header bytes within each 128-byte portion). The data is
   6258 usually/always stored on 914h-byte sectors (without error correction).
   6259 
   6260 Subheader
   6261 The Subheader (see previous chapter) contains important info for ADPCM: The
   6262 file/channel numbers for Interleaved data, and the codinginfo flags:
   6263 mono/stereo flag, 37800Hz/18900Hz sampling rate, 4bit/8bit format, and
   6264 emphasis.
   6265 
   6266 ADPCM Sectors
   6267 Each sector consists of 12h 128-byte portions (=900h bytes) (the remaining 14h
   6268 bytes of the sectors 914h-byte data region are 00h filled).
   6269 The separate 128-byte portions consist of a 16-byte header,
   6270   00h..03h  Copy of below 4 bytes (at 04h..07h)
   6271   04h       Header for 1st Block/Mono, or 1st Block/Left
   6272   05h       Header for 2nd Block/Mono, or 1st Block/Right
   6273   06h       Header for 3rd Block/Mono, or 2nd Block/Left
   6274   07h       Header for 4th Block/Mono, or 2nd Block/Right
   6275   08h       Header for 5th Block/Mono, or 3rd Block/Left  ;\unknown/unused
   6276   09h       Header for 6th Block/Mono, or 3rd Block/Right ; for 8bit ADPCM
   6277   0Ah       Header for 7th Block/Mono, or 4th Block/Left  ; (maybe 0, or maybe
   6278   0Bh       Header for 8th Block/Mono, or 4th Block/Right ;/copy of above)
   6279   0Ch..0Fh  Copy of above 4 bytes (at 08h..0Bh)
   6280 followed by twentyeight data words (4x28-bytes),
   6281   10h..13h  1st Data Word (packed 1st samples for 2-8 blocks)
   6282   14h..17h  2nd Data Word (packed 2nd samples for 2-8 blocks)
   6283   18h..1Bh  3rd Data Word (packed 3rd samples for 2-8 blocks)
   6284   ...       Nth Data Word (packed Nth samples for 2-8 blocks)
   6285   7Ch..7Fh  28th Data Word (packed 28th samples for 2-8 blocks)
   6286 and then followed by the next 128-byte portion.
   6287 The "Copy" bytes are allowing to repair faulty headers (ie. if the CDROM
   6288 controller has sensed a read-error in the header then it can eventually replace
   6289 it by the copy of the header).
   6290 
   6291 XA-ADPCM Header Bytes
   6292   0-3   Shift  (0..12) (0=Loudest) (13..15=Reserved/Same as 9)
   6293   4-5   Filter (0..3) (only four filters, unlike SPU-ADPCM which has five)
   6294   6-7   Unused (should be 0)
   6295 Note: The 4bit (or 8bit) samples are expanded to 16bit by left-shifting them by
   6296 12 (or 8), that 16bit value is then right-shifted by the selected 'shift'
   6297 amount. For 8bit ADPCM shift should be 0..8 (values 9..12 will cut-off the
   6298 LSB(s) of the 8bit value, this works, but isn't useful). For both 4bit and 8bit
   6299 ADPCM, reserved shift values 13..15 will act same as shift=9).
   6300 
   6301 XA-ADPCM Data Words (32bit, little endian)
   6302   0-3   Nibble for 1st Block/Mono, or 1st Block/Left  (-8h..+7h)
   6303   4-7   Nibble for 2nd Block/Mono, or 1st Block/Right (-8h..+7h)
   6304   8-11  Nibble for 3rd Block/Mono, or 2nd Block/Left  (-8h..+7h)
   6305   12-15 Nibble for 4th Block/Mono, or 2nd Block/Right (-8h..+7h)
   6306   16-19 Nibble for 5th Block/Mono, or 3rd Block/Left  (-8h..+7h)
   6307   20-23 Nibble for 6th Block/Mono, or 3rd Block/Right (-8h..+7h)
   6308   24-27 Nibble for 7th Block/Mono, or 4th Block/Left  (-8h..+7h)
   6309   28-31 Nibble for 8th Block/Mono, or 4th Block/Right (-8h..+7h)
   6310 or, for 8bit ADPCM format:
   6311   0-7   Byte for 1st Block/Mono, or 1st Block/Left    (-80h..+7Fh)
   6312   8-15  Byte for 2nd Block/Mono, or 1st Block/Right   (-80h..+7Fh)
   6313   16-23 Byte for 3rd Block/Mono, or 2nd Block/Left    (-80h..+7Fh)
   6314   24-31 Byte for 4th Block/Mono, or 2nd Block/Right   (-80h..+7Fh)
   6315 
   6316 decode_sector(src)
   6317   src=src+12+4+8   ;skip sync,header,subheader
   6318   for i=0 to 11h
   6319    for blk=0 to 3
   6320     IF stereo ;left-samples (LO-nibbles), plus right-samples (HI-nibbles)
   6321       decode_28_nibbles(src,blk,0,dst_left,old_left,older_left)
   6322       decode_28_nibbles(src,blk,1,dst_right,old_right,older_right)
   6323     ELSE      ;first 28 samples (LO-nibbles), plus next 28 samples (HI-nibbles)
   6324       decode_28_nibbles(src,blk,0,dst_mono,old_mono,older_mono)
   6325       decode_28_nibbles(src,blk,1,dst_mono,old_mono,older_mono)
   6326     ENDIF
   6327    next blk
   6328    src=src+128
   6329   next i
   6330   src=src+14h+4    ;skip padding,edc
   6331 
   6332 decode_28_nibbles(src,blk,nibble,dst,old,older)
   6333   shift  = 12 - (src[4+blk*2+nibble] AND 0Fh)
   6334   filter =      (src[4+blk*2+nibble] AND 30h) SHR 4
   6335   f0 = pos_xa_adpcm_table[filter]
   6336   f1 = neg_xa_adpcm_table[filter]
   6337   for j=0 to 27
   6338     t = signed4bit((src[16+blk+j*4] SHR (nibble*4)) AND 0Fh)
   6339     s = (t SHL shift) + ((old*f0 + older*f1+32)/64);
   6340     s = MinMax(s,-8000h,+7FFFh)
   6341     halfword[dst]=s, dst=dst+2, older=old, old=s
   6342   next j
   6343 
   6344 Pos/neg Tables
   6345   pos_xa_adpcm_table[0..4] = (0, +60, +115, +98, +122)
   6346   neg_xa_adpcm_table[0..4] = (0,   0,  -52, -55,  -60)
   6347 Note: XA-ADPCM supports only four filters (0..3), unlike SPU-ADPCM which
   6348 supports five filters (0..4).
   6349 
   6350 Old/Older Values
   6351 The incoming old/older values are usually that from the previous part, or
   6352 garbage (in case of decoding errors in the previous part), or whatever (in case
   6353 there was no previous part) (ie. maybe zero on power-up?) (and maybe there's
   6354 also a way to reset the values to zero at the begin of a new file, or *maybe*
   6355 it's silently done automatically when issuing seek commands?).
   6356 
   6357 25-point Zigzag Interpolation
   6358 The CDROM decoder is applying some weird 25-point zigzag interpolation when
   6359 resampling the 37800Hz XA-ADPCM output to 44100Hz. This part is different from
   6360 SPU-ADPCM (which uses 4-point gaussian pitch interpolations). For example,
   6361 XA-ADPCM interpolation applied to a square wave looks like this:
   6362                                                  .            .
   6363            .--------------.                      | |        | |
   6364            |              |                     .'.'.'----'.'.'.
   6365            |              |                     | |          | |
   6366            |              |                     |              |
   6367            | Decompressed |                     |    Final     |
   6368            |   XA-ADPCM   |                     |   XA-ADPCM   |
   6369            |   Waveform   |                     |    Output    |
   6370            |              |                   | |              | |
   6371            |              |             ---.'.'.'              '.'.'.---
   6372    --------'              '--------          | |                | |
   6373                                                '                '
   6374 The zigzagging does produce some (inaudible) 22050Hz noise, and does produce
   6375 some low-pass (?) filtering ("sinc filter"). The effect can be reproduced
   6376 somewhat like so:
   6377   Output37800Hz(sample):
   6378     ringbuf[p AND 1Fh]=sample, p=p+1, sixstep=sixstep-1
   6379     if sixstep=0
   6380       sixstep=6
   6381       Ouput44100Hz(ZigZagInterpolate(p,Table1))
   6382       Ouput44100Hz(ZigZagInterpolate(p,Table2))
   6383       Ouput44100Hz(ZigZagInterpolate(p,Table3))
   6384       Ouput44100Hz(ZigZagInterpolate(p,Table4))
   6385       Ouput44100Hz(ZigZagInterpolate(p,Table5))
   6386       Ouput44100Hz(ZigZagInterpolate(p,Table6))
   6387       Ouput44100Hz(ZigZagInterpolate(p,Table7))
   6388     endif
   6389   ZigZagInterpolate(p,TableX):
   6390     sum=0
   6391     for i=1 to 29, sum=sum+(ringbuf[(p-i) AND 1Fh]*TableX[i])/8000h, next i
   6392     return MinMax(sum,-8000h,+7FFFh)
   6393   Table1, Table2, Table3, Table4, Table5, Table6, Table7  ;Index
   6394     0     , 0     , 0     , 0     , -0001h, +0002h, -0005h  ;1
   6395     0     , 0     , 0     , -0001h, +0003h, -0008h, +0011h  ;2
   6396     0     , 0     , -0001h, +0003h, -0008h, +0010h, -0023h  ;3
   6397     0     , -0002h, +0003h, -0008h, +0011h, -0023h, +0046h  ;4
   6398     0     , 0     , -0002h, +0006h, -0010h, +002Bh, -0017h  ;5
   6399     -0002h, +0003h, -0005h, +0005h, +000Ah, +001Ah, -0044h  ;6
   6400     +000Ah, -0013h, +001Fh, -001Bh, +006Bh, -00EBh, +015Bh  ;7
   6401     -0022h, +003Ch, -004Ah, +00A6h, -016Dh, +027Bh, -0347h  ;8
   6402     +0041h, -004Bh, +00B3h, -01A8h, +0350h, -0548h, +080Eh  ;9
   6403     -0054h, +00A2h, -0192h, +0372h, -0623h, +0AFAh, -1249h  ;10
   6404     +0034h, -00E3h, +02B1h, -05BFh, +0BCDh, -16FAh, +3C07h  ;11
   6405     +0009h, +0132h, -039Eh, +09B8h, -1780h, +53E0h, +53E0h  ;12
   6406     -010Ah, -0043h, +04F8h, -11B4h, +6794h, +3C07h, -16FAh  ;13
   6407     +0400h, -0267h, -05A6h, +74BBh, +234Ch, -1249h, +0AFAh  ;14
   6408     -0A78h, +0C9Dh, +7939h, +0C9Dh, -0A78h, +080Eh, -0548h  ;15
   6409     +234Ch, +74BBh, -05A6h, -0267h, +0400h, -0347h, +027Bh  ;16
   6410     +6794h, -11B4h, +04F8h, -0043h, -010Ah, +015Bh, -00EBh  ;17
   6411     -1780h, +09B8h, -039Eh, +0132h, +0009h, -0044h, +001Ah  ;18
   6412     +0BCDh, -05BFh, +02B1h, -00E3h, +0034h, -0017h, +002Bh  ;19
   6413     -0623h, +0372h, -0192h, +00A2h, -0054h, +0046h, -0023h  ;20
   6414     +0350h, -01A8h, +00B3h, -004Bh, +0041h, -0023h, +0010h  ;21
   6415     -016Dh, +00A6h, -004Ah, +003Ch, -0022h, +0011h, -0008h  ;22
   6416     +006Bh, -001Bh, +001Fh, -0013h, +000Ah, -0005h, +0002h  ;23
   6417     +000Ah, +0005h, -0005h, +0003h, -0001h, 0     , 0       ;24
   6418     -0010h, +0006h, -0002h, 0     , 0     , 0     , 0       ;25
   6419     +0011h, -0008h, +0003h, -0002h, +0001h, 0     , 0       ;26
   6420     -0008h, +0003h, -0001h, 0     , 0     , 0     , 0       ;27
   6421     +0003h, -0001h, 0     , 0     , 0     , 0     , 0       ;28
   6422     -0001h, 0     , 0     , 0     , 0     , 0     , 0       ;29
   6423 The above formula/table gives nearly correct results, but with small rounding
   6424 errors in some cases - possibly due to actual rounding issues, or due to
   6425 factors with bigger fractional portions, or due to a completely different
   6426 formula...
   6427 Probably, the hardware does actually do the above stuff in two steps: first,
   6428 applying a zig-zag filter (with only around 21-points) to the 37800Hz output,
   6429 and then doing 44100Hz interpolation (2-point linear or 4-point gaussian or
   6430 whatever) in a second step.
   6431 That two-step theory would also match well for 18900Hz resampling (which has
   6432 lower-pitch zigzag, and gets spread accross about fifty 44100Hz samples).
   6433 
   6434 XA-ADPCM Emphasis
   6435 With XA-Emphasis enabled in Sub-header, output will appear as so:
   6436            .------------.                           ....-----.
   6437            |            |                        .''         |
   6438            |    Raw     |                       .'    XA     |
   6439            |   ADPCM    |                       |  Emphasis  '.
   6440            |  Waveform  |                       |   Output    '..
   6441    --------'            '----------     --------'                ''''---
   6442 The exact XA-Emphasis formula is unknown (maybe it's just same as for CD-DA's
   6443 SUBQ emphasis). Additionally, zig-zag interpolation is applied (somewhere
   6444 before or after applying the emphasis stuff).
   6445 Note: The Emphasis feature isn't used by any known PSX games.
   6446 
   6447 Uninitialized Six-step Counter
   6448 The hardware does contain some six-step counter (for interpolating 37800Hz to
   6449 44100Hz, ie. to insert one extra sample after each six samples). The 900h-byte
   6450 sectors contain a multiple of six samples, so the counter will be always same
   6451 before & after playing a sector. However, the initial counter value on power-up
   6452 is uninitialized random (and the counter will fallback to that initial random
   6453 setting after each 900h-byte sector).
   6454 
   6455 RIFF Headers (on PCs)
   6456 When reading files that consist of 914h-byte sectors on a PC, the PC seems to
   6457 automatically insert a 2Ch-byte RIFF fileheader. Like so, for ADPCM audio
   6458 files:
   6459   00h 4   "RIFF"
   6460   04h 4   Total Filesize (minus 8)
   6461   08h 8   "CDXAfmt "
   6462   10h 4   Size of below stuff (10h)
   6463   14h 14  Stuff (looks like the "LEN_SU" region from XA-Directory Record)
   6464   22h 2   Zero  (probably just dummy padding for 32bit alignment)
   6465   24h 4   "data"
   6466   28h 4   Size of following data (usually N*930h)
   6467 That RIFF stuff isn't stored on the CDROM (at least not in the file area)
   6468 (however, some of that info, like the "=UXA" stuff, is stored in the directory
   6469 area of the CDROM).
   6470 After the RIFF header, the normal sector data is appended, that, with the full
   6471 930h bytes per sector (ie. the 914h data bytes preceeded by sync bytes, header,
   6472 subheader, and followed by the EDC value).
   6473 The Channel Interleave doesn't seem to be resolved, ie. the Channels are kept
   6474 arranged as how they are stored on the CDROM. However, File Interleave <should>
   6475 be resolved, ie. other Files that "overlap" the file shouldn't be included in
   6476 the file.
   6477 
   6478 CDROM ISO Volume Descriptors
   6479 ----------------------------
   6480 
   6481 System Area (prior to Volume Descriptors)
   6482 The first 16 sectors on the first track are the system area, for a Playstation
   6483 disk, it contains the following:
   6484   Sector 0..3   - Zerofilled (Mode2/Form1, 4x800h bytes, plus ECC/EDC)
   6485   Sector 4      - Licence String
   6486   Sector 5..11  - Playstation Logo (3278h bytes) (remaining bytes FFh-filled)
   6487   Sector 12..15 - Zerofilled (Mode2/Form2, 4x914h bytes, plus EDC)
   6488 Of which, the Licence String in sector 4 is,
   6489   000h 32    Line 1      ("          Licensed  by          ")
   6490   020h 32+6  Line 2 (EU) ("Sony Computer Entertainment Euro"," pe   ") ;\either
   6491   020h 32+1  Line 2 (JP) ("Sony Computer Entertainment Inc.",0Ah)      ; one of
   6492   020h 32+6  Line 2 (US) ("Sony Computer Entertainment Amer","  ica ") ;/these
   6493   041h 1983  Empty (JP)    (filled by repeating pattern 62x30h,1x0Ah, 1x30h)
   6494   046h 1978  Empty (EU/US) (filled by 00h-bytes)
   6495 The Playstation Logo in sectors 5..11 contains data like so,
   6496   0000h ..   41h,00h,00h,00h,00h,00h,00h,00h,01h,00h,00h,00h,1Ch,23h,00h,00h
   6497   0010h ..   51h,01h,00h,00h,A4h,2Dh,00h,00h,99h,00h,00h,00h,1Ch,00h,00h,00h
   6498   0020h ..   ...
   6499   3278h 588h FF-filled (remaining bytes on sector 11)
   6500 the Logo contains a .TMD header, polygons, vertices and normals for the "PS"
   6501 logo (which is displayed when booting from CDROM). Some BIOS versions are
   6502 comparing these 3278h bytes against an identical copy in ROM, and refuse to
   6503 boot if the data isn't 1:1 the same:
   6504 - US/ASIA BIOS always accepts changed logos.
   6505 - PAL BIOS accepts changed logos up to v3.0E (and refuses in v4.0E and up).
   6506 - JP BIOS never accepts changed logos (and/or changed license strings?).
   6507 Note: A region-patch-modchip causes PAL BIOS to behave same as US/ASIA BIOS.
   6508 
   6509 Volume Descriptors (Sector 16 and up)
   6510 Playstation disks usually have only two Volume Descriptors,
   6511   Sector 16    - Primary Volume Descriptor
   6512   Sector 17    - Volume Descriptor Set Terminator
   6513 
   6514 Primary Volume Descriptor (sector 16 on PSX disks)
   6515   000h 1    Volume Descriptor Type        (01h=Primary Volume Descriptor)
   6516   001h 5    Standard Identifier           ("CD001")
   6517   006h 1    Volume Descriptor Version     (01h=Standard)
   6518   007h 1    Reserved                      (00h)
   6519   008h 32   System Identifier             (a-characters) ("PLAYSTATION")
   6520   028h 32   Volume Identifier             (d-characters) (max 8 chars for PSX?)
   6521   048h 8    Reserved                      (00h)
   6522   050h 8    Volume Space Size             (2x32bit, number of logical blocks)
   6523   058h 32   Reserved                      (00h)
   6524   078h 4    Volume Set Size               (2x16bit) (usually 0001h)
   6525   07Ch 4    Volume Sequence Number        (2x16bit) (usually 0001h)
   6526   080h 4    Logical Block Size in Bytes   (2x16bit) (usually 0800h) (1 sector)
   6527   084h 8    Path Table Size in Bytes      (2x32bit) (max 800h for PSX)
   6528   08Ch 4    Path Table 1 Block Number     (32bit little-endian)
   6529   090h 4    Path Table 2 Block Number     (32bit little-endian) (or 0=None)
   6530   094h 4    Path Table 3 Block Number     (32bit big-endian)
   6531   098h 4    Path Table 4 Block Number     (32bit big-endian) (or 0=None)
   6532   09Ch 34   Root Directory Record         (see next chapter)
   6533   0BEh 128  Volume Set Identifier         (d-characters) (usually empty)
   6534   13Eh 128  Publisher Identifier          (a-characters) (company name)
   6535   1BEh 128  Data Preparer Identifier      (a-characters) (empty or other)
   6536   23Eh 128  Application Identifier        (a-characters) ("PLAYSTATION")
   6537   2BEh 37   Copyright Filename            ("FILENAME.EXT;VER") (empty or text)
   6538   2E3h 37   Abstract Filename             ("FILENAME.EXT;VER") (empty)
   6539   308h 37   Bibliographic Filename        ("FILENAME.EXT;VER") (empty)
   6540   32Dh 17   Volume Creation Timestamp     ("YYYYMMDDHHMMSSFF",timezone)
   6541   33Eh 17   Volume Modification Timestamp ("0000000000000000",00h)
   6542   34Fh 17   Volume Expiration Timestamp   ("0000000000000000",00h)
   6543   360h 17   Volume Effective Timestamp    ("0000000000000000",00h)
   6544   371h 1    File Structure Version        (01h=Standard)
   6545   372h 1    Reserved for future           (00h-filled)
   6546   373h 141  Application Use Area          (00h-filled for PSX and VCD)
   6547   400h 8    CD-XA Identifying Signature   ("CD-XA001" for PSX and VCD)
   6548   408h 2    CD-XA Flags (unknown purpose) (00h-filled for PSX and VCD)
   6549   40Ah 8    CD-XA Startup Directory       (00h-filled for PSX and VCD)
   6550   412h 8    CD-XA Reserved                (00h-filled for PSX and VCD)
   6551   41Ah 345  Application Use Area          (00h-filled for PSX and VCD)
   6552   573h 653  Reserved for future           (00h-filled)
   6553 
   6554 Volume Descriptor Set Terminator (sector 17 on PSX disks)
   6555   000h 1    Volume Descriptor Type    (FFh=Terminator)
   6556   001h 5    Standard Identifier       ("CD001")
   6557   006h 1    Terminator Version        (01h=Standard)
   6558   007h 2041 Reserved                  (00h-filled)
   6559 
   6560 Boot Record (none such on PSX disks)
   6561   000h 1    Volume Descriptor Type    (00h=Boot Record)
   6562   001h 5    Standard Identifier       ("CD001")
   6563   006h 1    Boot Record Version       (01h=Standard)
   6564   007h 32   Boot System Identifier    (a-characters)
   6565   027h 32   Boot Identifier           (a-characters)
   6566   047h 1977 Boot System Use           (not specified content)
   6567 
   6568 Supplementary Volume Descriptor (none such on PSX disks)
   6569   000h 1    Volume Descriptor Type (02h=Supplementary Volume Descriptor)
   6570   001h ..   Same as for Primary Volume Descriptor (see there)
   6571   007h 1    Volume Flags           (8bit)
   6572   008h ..   Same as for Primary Volume Descriptor (see there)
   6573   058h 32   Escape Sequences       (32 bytes)
   6574   078h ..   Same as for Primary Volume Descriptor (see there)
   6575 In practice, this is used for Joliet:
   6576 --> CDROM Extension Joliet
   6577 
   6578 Volume Partition Descriptor (none such on PSX disks)
   6579   000h 1    Volume Descriptor Type      (03h=Volume Partition Descriptor)
   6580   001h 5    Standard Identifier         ("CD001")
   6581   006h 1    Volume Partition Version    (01h=Standard)
   6582   007h 1    Reserved                    (00h)
   6583   008h 32   System Identifier           (a-characters) (32 bytes)
   6584   028h 32   Volume Partition Identifier (d-characters) (32 bytes)
   6585   048h 8    Volume Partition Location   (2x32bit) Logical Block Number
   6586   050h 8    Volume Partition Size       (2x32bit) Number of Logical Blocks
   6587   058h 1960 System Use                  (not specified content)
   6588 
   6589 Reserved Volume Descriptors (none such on PSX disks)
   6590   000h 1    Volume Descriptor Type    (04h..FEh=Reserved, don't use)
   6591   001h 2047 Reserved                  (don't use)
   6592 
   6593 CDROM ISO File and Directory Descriptors
   6594 ----------------------------------------
   6595 
   6596 The location of the Root Directory is described by a 34-byte Directory Record
   6597 being located in Primary Volume Descriptor entries 09Ch..0BDh. The data therein
   6598 is: Block Number (usually 22 on PSX disks), LEN_FI=01h, Name=00h, and,
   6599 LEN_SU=00h (due to the 34-byte limit).
   6600 
   6601 Format of a Directory Record
   6602   00h 1      Length of Directory Record (LEN_DR) (33+LEN_FI+pad+LEN_SU) (0=Pad)
   6603   01h 1      Extended Attribute Record Length (usually 00h)
   6604   02h 8      Data Logical Block Number (2x32bit)
   6605   0Ah 8      Data Size in Bytes        (2x32bit)
   6606   12h 7      Recording Timestamp       (yy-1900,mm,dd,hh,mm,ss,timezone)
   6607   19h 1      File Flags 8 bits         (usually 00h=File, or 02h=Directory)
   6608   1Ah 1      File Unit Size            (usually 00h)
   6609   1Bh 1      Interleave Gap Size       (usually 00h)
   6610   1Ch 4      Volume Sequence Number    (2x16bit, usually 0001h)
   6611   20h 1      Length of Name            (LEN_FI)
   6612   21h LEN_FI File/Directory Name ("FILENAME.EXT;1" or "DIR_NAME" or 00h or 01h)
   6613   xxh 0..1   Padding Field (00h) (only if LEN_FI is even)
   6614   xxh LEN_SU System Use (LEN_SU bytes) (see below for CD-XA disks)
   6615 LEN_SU can be calculated as "LEN_DR-(33+LEN_FI+Padding)". For CD-XA disks (as
   6616 used in the PSX), LEN_SU is 14 bytes:
   6617   00h 2      Owner ID Group  (whatever, usually 0000h, big endian)
   6618   02h 2      Owner ID User   (whatever, usually 0000h, big endian)
   6619   04h 2      File Attributes (big endian):
   6620                0   Owner Read    (usually 1)
   6621                1   Reserved      (0)
   6622                2   Owner Execute (usually 1)
   6623                3   Reserved      (0)
   6624                4   Group Read    (usually 1)
   6625                5   Reserved      (0)
   6626                6   Group Execute (usually 1)
   6627                7   Reserved      (0)
   6628                8   World Read    (usually 1)
   6629                9   Reserved      (0)
   6630                10  World Execute (usually 1)
   6631                11  IS_MODE2        (0=MODE1 or CD-DA, 1=MODE2)
   6632                12  IS_MODE2_FORM2  (0=FORM1, 1=FORM2)
   6633                13  IS_INTERLEAVED  (0=No, 1=Yes...?) (by file and/or channel?)
   6634                14  IS_CDDA         (0=Data or ADPCM, 1=CD-DA Audio Track)
   6635                15  IS_DIRECTORY    (0=File or CD-DA, 1=Directory Record)
   6636              Commonly used Attributes are:
   6637                0D55h=Normal Binary File (with 800h-byte sectors)
   6638                1555h=Uncommon           (fade to black .DPS and .XA files)
   6639                2555h=Uncommon           (wipeout .AV files) (MODE1 ??)
   6640                4555h=CD-DA Audio Track  (wipeout .SWP files, alone .WAV file)
   6641                3D55h=Streaming File     (ADPCM and/or MDEC or so)
   6642                8D55h=Directory Record   (parent-, current-, or sub-directory)
   6643   06h 2      Signature     ("XA")
   6644   08h 1      File Number   (Must match Subheader's File Number)
   6645   09h 5      Reserved      (00h-filled)
   6646 Directory sectors do usually have zeropadding at the end of each sector:
   6647   - Directory sizes are always rounded up to N*800h-bytes.
   6648   - Directory entries should not cross 800h-byte sector boundaries.
   6649   There may be further directory entries on the next sector after the padding.
   6650   To deal with that, skip 00h-bytes until finding a nonzero LEN_DR value (or
   6651   slightly faster, upon a 00h-byte, directly jump to next sector instead of
   6652   doing a slow byte-by-byte skip).
   6653   Note: Padding between sectors does rarely happen on PSX discs because the
   6654   PSX kernel supports max 800h bytes per directory (one exception is PSX Hot
   6655   Shots Golf 2, which has an ISO directory with more than 800h bytes; it does
   6656   use a lookup file instead of actually parsing the while ISO directory).
   6657 Names are alphabetically sorted, no matter if the names refer to files or
   6658 directories (ie. SUBDIR would be inserted between STRFILE.EXT and SYSFILE.EXT).
   6659 The first two entries (with non-ascii names 00h and 01h) are referring to
   6660 current and parent directory.
   6661 
   6662 Path Tables
   6663 The Path Table contain a summary of the directory names (the same information
   6664 is also stored in the directory records, so programs may either use path tables
   6665 or directory records; the path tables are allowing to read the whole directory
   6666 tree quickly at once, without neeeding to seek from directory to directory).
   6667 Path Table 1 is in Little-Endian format, Path Table 3 contains the same data in
   6668 Big-Endian format. Path Table 2 and 4 are optional copies of Table 1 and 3. The
   6669 size and location of the tables is stored in Volume Descriptor entries
   6670 084h..09Bh. The format of the separate entries within a Path Table is,
   6671   00h 1       Length of Directory Name (LEN_DI) (01h..08h for PSX)
   6672   01h 1       Extended Attribute Record Length  (usually 00h)
   6673   02h 4       Directory Logical Block Number
   6674   06h 2       Parent Directory Number           (0001h and up)
   6675   08h LEN_DI  Directory Name (d-characters, d1-characters) (or 00h for Root)
   6676   xxh 0..1    Padding Field (00h) (only if LEN_FI is odd)
   6677 The first entry (directory number 0001h) is the root directory, the root
   6678 doesn't have a name, nor a parent (the name field contains a 00h byte, rather
   6679 than ASCII text, LEN_DI is 01h, and parent is 0001h, making the root it's own
   6680 parent; ignoring the fact that incest is forbidden in many countries).
   6681 The next entries (directory number 0002h and up) (if any) are sub-directories
   6682 within the root (sorted in alphabetical order, and all having parent=0001h).
   6683 The next entries are sub-directories (if any) of the first sub-directory (also
   6684 sorted in alphabetical order, and all having parent=0002h). And so on.
   6685 PSX disks usually contain all four tables (usually on sectors 18,19,20,21).
   6686 
   6687 Format of an Extended Attribute Record (none such on PSX disks)
   6688 If present, an Extended Attribute Record shall be recorded over at least one
   6689 Logical Block. It shall have the following contents.
   6690   00h 4       Owner Identification (numerical value)  ;\used only if
   6691   04h 4       Group Identification (numerical value)  ; File Flags Bit4=1
   6692   08h 2       Permission Flags (16bit, little-endian) ;/
   6693   0Ah 17      File Creation Timestamp      ("YYYYMMDDHHMMSSFF",timezone)
   6694   1Bh 17      File Modification Timestamp  ("0000000000000000",00h)
   6695   2Ch 17      File Expiration Timestamp    ("0000000000000000",00h)
   6696   3Dh 17      File Effective Timestamp     ("0000000000000000",00h)
   6697   4Eh 1       Record Format                (numerical value)
   6698   4Fh 1       Record Attributes            (numerical value)
   6699   50h 4       Record Length                (numerical value)
   6700   54h 32      System Identifier            (a-characters, a1-characters)
   6701   74h 64      System Use                   (not specified content)
   6702   B4h 1       Extended Attribute Record Version (numerical value)
   6703   B5h 1       Length of Escape Sequences   (LEN_ESC)
   6704   B6h 64      Reserved for future standardization (00h-filled)
   6705   F6h 4       Length of Application Use    (LEN_AU)
   6706   FAh LEN_AU  Application Use
   6707   xxh LEN_ESC Escape Sequences
   6708 Unknown WHERE that data is located... the Directory Records can specify the
   6709 Extended Attribute Length, but not the location... maybe it's meant to be
   6710 located in the first some bytes or blocks of the File or Directory...?
   6711 
   6712 CDROM ISO Misc
   6713 --------------
   6714 
   6715 Both Byte Order
   6716 All 16bit and 32bit numbers in the ISO region are stored twice, once in
   6717 Little-Endian order, and then in Big-Endian Order. For example,
   6718   2x16bit value 1234h     ---> stored as 34h,12h,12h,34h
   6719   2x32bit value 12345678h ---> stored as 78h,56h,34h,12h,12h,34h,56h,78h
   6720 Exceptions are the 16bit Permission Flags which are stored only in
   6721 Little-Endian format (although the flags are four 4bit groups, so that isn't a
   6722 real 16bit number), and, the Path Tables are stored in both formats, but
   6723 separately, ie. one table contains only Little-Endian numbers, and the other
   6724 only Big-Endian numbers.
   6725 
   6726 d-characters (Filenames)
   6727   "0..9", "A..Z", and "_"
   6728 
   6729 a-characters
   6730   "0..9", "A..Z", SPACE, "!"%&'()*+,-./:;<=>?_"
   6731 Ie. all ASCII characters from 20h..5Fh except "#$@[\]^"
   6732 
   6733 SEPARATOR 1 = 2Eh (aka ".") (extension; eg. "EXT")
   6734 SEPARATOR 2 = 3Bh (aka ";") (file version; "1".."32767")
   6735 
   6736 Fixed Length Strings/Filenames
   6737 The Volume Descriptors contain a number fixed-length string/filename fields
   6738 (unlike the Directory Records and Path Tables which have variable lengths).
   6739 These fields should be padded with SPACE characters if they are empty, or if
   6740 the string is shorter than the maximum length.
   6741 Filename fields in Volume Descriptors are referring to files in the Root
   6742 Directory. On PSX disks, the filename fields are usually empty, but some disks
   6743 are mis-using the Copyright Filename to store the Company Name (although no
   6744 such file exists on the disk).
   6745 
   6746 Volume Descriptor Timestamps
   6747 The various timestamps occupy 17 bytes each, in form of
   6748   "YYYYMMDDHHMMSSFF",timezone
   6749   "0000000000000000",00h         ;empty timestamp
   6750 The first 16 bytes are ASCII Date and Time digits (Year, Month, Day, Hour,
   6751 Minute, Second, and 1/100 Seconds. The last byte is Offset from Greenwich Mean
   6752 Time in number of 15-minute steps from -48 (West) to +52 (East); or actually:
   6753 to +56 when recursing Kiribati's new timezone.
   6754 Note: PSX games manufactured in year 2000 were accidently marked to be created
   6755 in year 0000.
   6756 
   6757 Recording Timestamps
   6758 Occupy only 7 bytes, in non-ascii format
   6759   year-1900,month,day,hour,minute,second,timezone
   6760   00h,00h,00h,00h,00h,00h,00h    ;empty timestamp
   6761 The year ranges from 1900+0 to 1900+255.
   6762 
   6763 File Flags
   6764 If this Directory Record identifies a directory then bit 2,3,7 shall be set to
   6765 ZERO.
   6766 If no Extended Attribute Record is associated with the File Section identified
   6767 by this Directory Record then bit positions 3 and 4 shall be set to ZERO.
   6768   0  Existence       (0=Normal, 1=Hidden)
   6769   1  Directory       (0=File, 1=Directory)
   6770   2  Associated File (0=Not an Associated File, 1=Associated File)
   6771   3  Record
   6772         If set to ZERO, shall mean that the structure of the information in
   6773         the file is not specified by the Record Format field of any associated
   6774         Extended Attribute Record (see 9.5.8).
   6775         If set to ONE, shall mean that the structure of the information in
   6776         the file has a record format specified by a number other than zero in
   6777         the Record Format Field of the Extended Attribute Record (see 9.5.8).
   6778   4  Restrictions    (0=None, 1=Restricted via Permission Flags)
   6779   5  Reserved        (0)
   6780   6  Reserved        (0)
   6781   7  Multi-Extent    (0=Final Directory Record for the file, 1=Not final)
   6782 
   6783 Permission Flags (in Extended Attribute Records)
   6784   0-3   Permissions for upper-class owners
   6785   4-7   Permissions for normal owners
   6786   8-11  Permissions for upper-class users
   6787   12-15 Permissions for normal users
   6788 This is a bit bizarre, an upper-class owner is "an owner who is a member of a
   6789 group of the System class of user". An upper-class user is "any user who is a
   6790 member of the group specified by the Group Identification field". The separate
   6791 4bit permission codes are:
   6792   Bit0  Permission to read the file    (0=Yes, 1=No)
   6793   Bit1  Must be set (1)
   6794   Bit2  Permission to execute the file (0=Yes, 1=No)
   6795   Bit3  Must be set (1)
   6796 
   6797 CDROM Extension Joliet
   6798 ----------------------
   6799 
   6800 Typical Joliet Disc Header
   6801 The discs contains two separate filesystems, the ISO one for backwards
   6802 compatibilty, and the Joliet one with longer filenames and Unicode characters.
   6803   Sector 16 - Primary Volume Descriptor (with 8bit uppercase ASCII ISO names)
   6804   Sector 17 - Secondary Volume Descriptor (with 16bit Unicode Joliet names)
   6805   Sector 18 - Volume Descriptor Set Terminator
   6806   Sector .. - Path Tables and Directory Records (for ISO)
   6807   Sector .. - Path Tables and Directory Records (for Joliet)
   6808   Sector .. - File Data Sectors (shared for ISO and Joliet)
   6809 There is no way to determine which ISO name belongs to which Joliet name
   6810 (except, filenames do usually point to the same file data sectors, but that
   6811 doesn't work for empty files, and doesn't work for folder names).
   6812 The ISO names can be max 31 chars (or shorter for compatibility with DOS short
   6813 names: Nero does truncate them to max 14 chars "FILENAME.EXT;1", all uppercase,
   6814 with underscores instead of spaces, and somehow assigning names like
   6815 "FILENAMx.EXT;1" in case of duplicated short names).
   6816 
   6817 Secondary Volume Descriptor (aka Supplementary Volume Descriptor)
   6818 This is using the same format as ISO Primary Volume Descriptor (but with some
   6819 changed entries).
   6820 --> CDROM ISO Volume Descriptors
   6821 Changed entries are:
   6822   000h 1     Volume Descriptor Type (02h=Supplementary instead of 01h=Primary)
   6823   007h 1     Volume Flags           (whatever, instead of Reserved)
   6824   008h 2x32  Identifier Strings     (16-char Unicode instead 32-char ASCII)
   6825   058h 32    Escape Sequences       (see below, instead of Reserved)
   6826   08Ch 4x4   Path Tables            (point to new tables with Unicode chars)
   6827   09Ch 34    Root Directory Record  (point to root with Unicode chars)
   6828   0BEh 4x128 Identifier Strings     (64-char Unicode instead 128-char ASCII)
   6829   2BEh 3x37  Filename Strings       (18-char Unicode instead 37-char ASCII)
   6830 The Escape Sequences entry contains three ASCII chars (plus 29-byte
   6831 zeropadding), indicating the ISO 2022 Unicode charset:
   6832   %/@   UCS-2 Level 1
   6833   %/C   UCS-2 Level 2
   6834   %/E   UCS-2 Level 3
   6835 
   6836 Directory Records and Path Tables
   6837 This is using the standard ISO format (but with 16bit Unicode characters
   6838 instead of 8bit ASCII chars).
   6839 --> CDROM ISO File and Directory Descriptors
   6840 
   6841 File and Directory Name Characters
   6842 All characters are stored in 16bit Big Endian format. The LEN_FI filename entry
   6843 contains the length in bytes (ie. numchars*2). Charaters 0000h/0001h are
   6844 current/parent directory. Characters 0020h and up can be used for
   6845 file/directory names, except six reserved characters: */:;?\
   6846 All names must be sorted by their character numbers, padded with zero (without
   6847 attempting to merge uppercase, lowercase, or umlauts to nearby locations).
   6848 
   6849 File and Directory Name Length
   6850   max 64 chars according to original Joliet specs from 1995
   6851   max 110 chars (on standard CDROMs, with LEN_SU=0)
   6852   max 103 chars (on CD-XA discs, with LEN_SU=14)
   6853 Joliet Filenames include ISO-style version suffices (usually ";1", so the
   6854 actual filename lengths are two chars less than shown above).
   6855 The original 64-char limit was perhaps intended to leave space for future
   6856 extensions in the LEN_SU region. The 64-char limit can cause problems with
   6857 verbose names (eg. "Interprete - Title (version).mp3"). Microsoft later changed
   6858 the limit to up to 110 chars.
   6859 The 110/103-char limit is caused by the 8bit "LEN_DR=(33+LEN_FI+pad+LEN_SU)"
   6860 entry in the Directory Records.
   6861 Joliet allows to exceed the 8-level ISO directory nesting limit, however, it
   6862 doesn't allow to exceed the 240-byte (120-Unicode-char) limit in ISO 9660
   6863 section 6.8.2.1 for the total "path\filename" lengths.
   6864 
   6865 Official Specs
   6866 Joliet Specification, CD-ROM Recording Spec ISO 9660:1988, Extensions for
   6867 Unicode Version 1; May 22, 1995, Copyright 1995, Microsoft Corporation
   6868   http://littlesvr.ca/isomaster/resources/JolietSpecification.html
   6869 
   6870 CDROM File Formats
   6871 ------------------
   6872 
   6873 Official PSX File Formars
   6874 --> CDROM File Official Sony File Formats
   6875 
   6876 Executables
   6877 --> CDROM File Playstation EXE and SYSTEM.CNF
   6878 --> CDROM File PsyQ .CPE Files (Debug Executables)
   6879 --> CDROM File PsyQ .SYM Files (Debug Information)
   6880 
   6881 Video Files
   6882 --> CDROM File Video Texture Image TIM/PXL/CLT (Sony)
   6883 --> CDROM File Video Texture/Bitmap (Other)
   6884 --> CDROM File Video 2D Graphics CEL/BGD/TSQ/ANM/SDF (Sony)
   6885 --> CDROM File Video 3D Graphics TMD/PMD/TOD/HMD/RSD (Sony)
   6886 --> CDROM File Video STR Streaming and BS Picture Compression (Sony)
   6887 
   6888 Audio Files
   6889 --> CDROM File Audio Single Samples VAG (Sony)
   6890 --> CDROM File Audio Sample Sets VAB and VH/VB (Sony)
   6891 --> CDROM File Audio Sequences SEQ/SEP (Sony)
   6892 --> CDROM File Audio Streaming XA-ADPCM
   6893 --> CDROM File Audio CD-DA Tracks
   6894 
   6895 Virtual Filesystem Archives
   6896 PSX titles are quite often using virtual filesystems, with numerous custom file
   6897 archive formats.
   6898 --> CDROM File Archives with Filename
   6899 --> CDROM File Archives with Offset and Size
   6900 --> CDROM File Archives with Offset
   6901 --> CDROM File Archives with Size
   6902 --> CDROM File Archives with Chunks
   6903 --> CDROM File Archives with Folders
   6904 --> CDROM File Archives in Hidden Sectors
   6905 More misc stuff...
   6906 --> CDROM File Archive HED/DAT/BNS/STR (Ape Escape)
   6907 --> CDROM File Archive WAD.WAD, BIG.BIN, JESTERS.PKG (Crash/Herc/Pandemonium)
   6908 --> CDROM File Archive BIGFILE.BIG (Gex)
   6909 --> CDROM File Archive BIGFILE.DAT (Gex - Enter the Gecko)
   6910 --> CDROM File Archive FF9 DB (Final Fantasy IX)
   6911 --> CDROM File Archive Ace Combat 2 and 3
   6912 --> CDROM File Archive NSD/NSF (Crash Bandicoot 1-3)
   6913 --> CDROM File Archive STAGE.DIR and *.DAT (Metal Gear Solid)
   6914 --> CDROM File Archive DRACULA.DAT (Dracula)
   6915 --> CDROM File Archive Croc 1 (DIR, WAD, etc.)
   6916 --> CDROM File Archive Croc 2 (DIR, WAD, etc.)
   6917 --> CDROM File Archive Headerless Archives
   6918 Using archives can avoid issues with the PSX's poorly implemented ISO
   6919 filesystem: The PSX kernel supports max 800h bytes per directory, and lacks
   6920 proper caching for most recently accessed directories (additionally, some
   6921 archives can load the whole file/directory tree from continous sectors, which
   6922 could be difficult in ISO filesystems).
   6923 
   6924 Compression
   6925 --> CDROM File Compression
   6926 
   6927 Misc
   6928 --> CDROM File XYZ and Dummy/Null Files
   6929 
   6930 FILENAME.EXT
   6931 The BIOS seems to support only (max) 8-letter filenames with 3-letter
   6932 extension, typically all uppercase, eg. "FILENAME.EXT". Eventually, once when
   6933 the executable has started, some programs might install drivers for long
   6934 filenames(?)
   6935 
   6936 The PSX uses the standard CDROM ISO9660 filesystem without any encryption (ie.
   6937 you can put an original PSX CDROM into a DOS/Windows computer, and view the
   6938 content of the files in text or hex editors without problems).
   6939 
   6940 Note
   6941 MagDemoNN is short for "Official U.S. Playstation Magazine Demo Disc NN"
   6942 
   6943 CDROM File Official Sony File Formats
   6944 -------------------------------------
   6945 
   6946 Official Sony File Formats
   6947 https://psx.arthus.net/sdk/Psy-Q/DOCS/Devrefs/Filefrmt.pdf - Sony 1998
   6948   File Formats
   6949     (c) 1998 Sony Computer Entertainment Inc.
   6950     Publication date: November 1998
   6951   Chapter 1: Streaming Audio and Video Data
   6952     STR: Streaming (Movie) Data                               1-3
   6953     BS: MDEC Bitstream Data                                   1-8
   6954     XA: CD-ROM Voice Data                                     1-31
   6955   Chapter 2: 3D Graphics
   6956     RSD: 3D Model Data [RSD,PLY,MAT,GRP,MSH,PVT,COD,MOT,OGP]  2-3
   6957     TMD: Modeling Data for OS Library                         2-24
   6958     PMD: High-Speed Modeling Data                             2-35
   6959     TOD: Animation Data                                       2-40
   6960     HMD: Hierarchical 3D Model, Animation and Other Data      2-49
   6961   Chapter 3: 2D Graphics
   6962     TIM: Screen Image Data                                    3-3
   6963     SDF: Sprite Editor Project File                           3-8
   6964     PXL: Pixel Image Data                                     3-11
   6965     CLT: Palette Data                                         3-14
   6966     ANM: Animation Information                                3-16
   6967     TSQ: Animation Time Sequence                              3-22
   6968     CEL: Cell Data                                            3-23
   6969     BGD: BG Map Data                                          3-27
   6970   Chapter 4: Sound
   6971     SEQ: PS Sequence Data                                     4-3
   6972     SEP: PS Multi-Track Sequence Data                         4-3
   6973     VAG: PS Single Waveform Data                              4-5
   6974     VAB: PS Sound Source Data [VAB and VH/VB]                 4-5
   6975     DA: CD-DA Data                                            4-7
   6976   Chapter 5: PDA and Memory Card
   6977     FAT: Memory Card File System Specification                5-3
   6978 Most games are using their own custom file formats. However, VAG, VAB/VH(VB,
   6979 STR/XA, and TIM are quite popular (because they are matched to the PSX
   6980 low-level data encoding). Obviously, EXE is also very common (although not
   6981 included in the above document).
   6982 
   6983 CDROM File Playstation EXE and SYSTEM.CNF
   6984 -----------------------------------------
   6985 
   6986 SYSTEM.CNF
   6987 Contains boot info in ASCII/TXT format, similar to the CONFIG.SYS or
   6988 AUTOEXEC.BAT files for MSDOS. A typical SYSTEM.CNF would look like so:
   6989   BOOT = cdrom:\abcd_123.45;1 arg ;boot exe (drive:\path\name.ext;version)
   6990   TCB = 4                         ;HEX (=4 decimal)   ;max number of threads
   6991   EVENT = 10                      ;HEX (=16 decimal)  ;max number of events
   6992   STACK = 801FFF00                ;HEX (=memtop-256)
   6993 The first line specifies the executable to load, from the "cdrom:" drive, "\"
   6994 root directory, filename "abcd_123.45" (case-insensitive, the real name in the
   6995 disk directory would be uppercase, ie. "ABCD_123.45"), and, finally ";1" is the
   6996 file's version number (a rather strange ISO-filesystem specific feature) (the
   6997 version number should be usually/always 1). Additionally, "arg" may contain an
   6998 optional 128-byte command line argument string, which is copied to address
   6999 00000180h, where it may be interpreted by the executable (most or all games
   7000 don't use that feature).
   7001 Each line in the file should be terminated by 0Dh,0Ah characters... not sure if
   7002 it's also working with only 0Dh, or only 0Ah...?
   7003 
   7004 ABCD_123.45
   7005 This is a normal executable (exactly as for the .EXE files, described below),
   7006 however, the filename/extension is taken from the game code (the "ABCD-12345"
   7007 text that is printed on the CD cover), but, with the minus replaced by an
   7008 underscore, and due to the 8-letter filename limit, the last two characters are
   7009 stored in the extension region.
   7010 That "XXXX_NNN.NN" naming convention seems to apply for all official licensed
   7011 PSX games. Wild Arms does unconventionally have the file in a separate folder,
   7012 "EXE\SCUS_946.06".
   7013 
   7014 PSX.EXE (Boot-Executable) (default filename when SYSTEM.CNF doesn't exist)
   7015 XXXX_NNN.NN (Boot-Executable) (with filename as specified in SYSTEM.CNF)
   7016 FILENAME.EXE (General-Purpose Executable)
   7017 PSX executables are having an 800h-byte header, followed by the code/data.
   7018   000h-007h ASCII ID "PS-X EXE"
   7019   008h-00Fh Zerofilled
   7020   010h      Initial PC                   (usually 80010000h, or higher)
   7021   014h      Initial GP/R28               (usually 0)
   7022   018h      Destination Address in RAM   (usually 80010000h, or higher)
   7023   01Ch      Filesize (must be N*800h)    (excluding 800h-byte header)
   7024   020h      Unknown/Unused ;Addr         (usually 0)  ;\optional overlay?
   7025   024h      Unknown/Unused ;Size         (usually 0)  ;/(not auto-loaded)
   7026   028h      Memfill Start Address        (usually 0) (when below Size=None)
   7027   02Ch      Memfill Size in bytes        (usually 0) (0=None)
   7028   030h      Initial SP/R29 & FP/R30 Base (usually 801FFFF0h) (or 0=None)
   7029   034h      Initial SP/R29 & FP/R30 Offs (usually 0, added to above Base)
   7030   038h-04Bh Reserved for A(43h) Function (should be zerofilled in exefile)
   7031   04Ch-xxxh ASCII marker
   7032              "Sony Computer Entertainment Inc. for Japan area"
   7033              "Sony Computer Entertainment Inc. for Europe area"
   7034              "Sony Computer Entertainment Inc. for North America area"
   7035              (or often zerofilled in some homebrew files)
   7036              (the BIOS doesn't verify this string, and boots fine without it)
   7037   xxxh-7FFh Zerofilled
   7038   800h...   Code/Data                  (loaded to entry[018h] and up)
   7039 The code/data is simply loaded to the specified destination address, ie. unlike
   7040 as in MSDOS .EXE files, there is no relocation info in the header.
   7041 Note: In bootfiles, SP is usually 801FFFF0h (ie. not 801FFF00h as in
   7042 system.cnf). When SP is 0, the unmodified caller's stack is used. In most cases
   7043 (except when manually calling DoExecute), the stack values in the exeheader
   7044 seem to be ignored though (eg. replaced by the SYSTEM.CNF value).
   7045 The memfill region is zerofilled by a "relative" fast word-by-word fill (so
   7046 address and size must be multiples of 4) (despite of the word-by-word filling,
   7047 still it's SLOW because the memfill executes in uncached slow ROM).
   7048 The reserved region at [038h-04Bh] is internally used by the BIOS to memorize
   7049 the caller's RA,SP,R30,R28,R16 registers (for some bizarre reason, this
   7050 information is saved in the exe header, rather than on the caller's stack).
   7051 Additionally to the initial PC,R28,SP,R30 values that are contained in the
   7052 header, two parameter values are passed to the executable (in R4 and R5
   7053 registers) (however, usually that values are simply R4=1 and R5=0).
   7054 Like normal functions, the executable can return control to the caller by
   7055 jumping to the incoming RA address (provided that it hasn't destroyed the stack
   7056 or other important memory locations, and that it has pushed/popped all
   7057 registers) (returning works only for non-boot executables; if the boot
   7058 executable returns to the BIOS, then the BIOS will simply lockup itself by
   7059 calling the "SystemErrorBootOrDiskFailure" function.
   7060 
   7061 Relocatable EXE
   7062 Fade to Black (CINE.EXR) contains ID "PS-X EXR" (instead "PS-X EXE") and string
   7063 "PSX Relocable File - Delphine Software Int.", this is supposedly some custom
   7064 relocatable exe file (unsupported by the PSX kernel).
   7065 
   7066 MSDOS.EXE and WINDOWS.EXE Files
   7067 Some PSX discs contain DOS or Windows .EXE files (with "MZ" headers), eg.
   7068 devkit leftovers, or demos/gimmicks.
   7069 
   7070 CDROM File PsyQ .CPE Files (Debug Executables)
   7071 ----------------------------------------------
   7072 
   7073 Fileheader
   7074   00h 4   File ID (01455043h aka "CPE",01h)
   7075 
   7076 Chunk 00h: End of File
   7077   00h 1   Chunk ID (00h)
   7078 
   7079 Chunk 01h: Load Data
   7080   00h 1   Chunk ID (01h)
   7081   01h 4   Address (usually 80010000h and up)
   7082   05h 4   Size (LEN)
   7083   09h LEN Data (binary EXE code/data)
   7084 Theoretically, this could contain the whole EXE body in a single chunk.
   7085 However, the PsyQ files are usually containing hundreds of small chunks (with
   7086 each function and each data item in a separate chunk). For converting CPE to
   7087 EXE, use "ExeOffset = (CpeAddress AND 1FFFFFFFh)-10000h+800h".
   7088 
   7089 Chunk 02h: Run Address (whatever, optional, usually not used in CPE files)
   7090   00h 1   Chunk ID (02h)
   7091   01h 4   Address
   7092 Unknown what this is. It's not the entrypoint (which is set via chunk 03h).
   7093 Maybe intended to change the default load address (usually 80010000h)?
   7094 
   7095 Chunk 03h: Set Value 32bit (LEN=4) (used for entrypoint)
   7096 Chunk 04h: Set Value 16bit (LEN=2) (unused)
   7097 Chunk 05h: Set Value 8bit  (LEN=1) (unused)
   7098 Chunk 06h: Set Value 24bit (LEN=3) (unused)
   7099   00h 1   Chunk ID (03h..06h)
   7100   01h 2   Register (usually 0090h=Initial PC, aka Entrypoint)
   7101   03h LEN Value (8bit..32bit)
   7102 
   7103 Chunk 07h: Select Workspace (whatever, optional, usually not used in CPE)
   7104   00h 1   Chunk ID (07h)
   7105   01h 4   Workspace number (usually 00000000h)
   7106 
   7107 Chunk 08h: Select Unit (whatever, usually first chunk in CPE file)
   7108   00h 1   Chunk ID (08h)
   7109   01h 1   Unit (usually 00h)
   7110 
   7111 Example from LameGuy's sample.cpe:
   7112   0000h 4    File ID ("CPE",01h)
   7113   0004h 2    Select Unit 0            (08h,00h)
   7114   0006h 7    Set Entrypoint 8001731Ch (03h,0090h,8001731Ch)
   7115   000Dh 0Dh  Load   (01h,800195F8h,00000004h,0,0,0,0)
   7116   001Ah ..   Load   (01h,80010000h,0000002Bh,...)
   7117   004Eh ..   Load   (01h,8001065Ch,00000120h,...)
   7118   0177h ...  Load   (01h,8001077Ch,0000012Ch,...)
   7119   02ACh ...  Load   (01h,800108A8h,000000A4h,...)
   7120   ...   ...  Load   (...)
   7121   98F4h ...  Load   (01h,800195F0h,00000008h,...)
   7122   9905h 1    End    (00h)
   7123 
   7124 CDROM File PsyQ .SYM Files (Debug Information)
   7125 ----------------------------------------------
   7126 
   7127 PsyQ .SYM Files contain debug info, usually bundled with PsyQ .MAP and Psy .CPE
   7128 files. Those files are generated by PsyQ tools, which appear to be still in use
   7129 for homebrew PSX titles.
   7130 The files are occassionally also found on PSX CDROMs:
   7131   Legacy of Kain PAL version (\DEGUG\NTSC\KAIN2.SYM+MAP+CPE)
   7132   RC Revenge (\RELEASE.SYM)
   7133   Twisted Metal: Small Brawl (MagDemo54: TMSB\TM.SYM)
   7134   Jackie Chan Stuntmaster (GAME_REL.SYM+CPE)
   7135   SnoCross Championship Racing (MagDemo37: SNOCROSS\SNOW.TOC\SNOW.MAP)
   7136   Sled Storm (MagDemo24: DEBUG\MAIN.MAP)
   7137   E.T. Interplanetary Mission (MagDemo54: MEGA\MEGA.CSH\* has SYM+CPE+MAP)
   7138 
   7139 Fileheader .SYM
   7140   00h 4  File ID ("MND",01h)
   7141   04h 4  Whatever (0,0,0,0)    ;TOMB5: 0,02h,0,0
   7142   08h .. Chunks (see below)
   7143 
   7144  _______________________________ Symbol Chunks ________________________________
   7145 
   7146 Chunk 01h: Symbol (Immediate, eg. memsize, or membase)
   7147 Chunk 02h: Symbol (Function Address for Internal & External Functions)
   7148 Chunk 05h: Symbol (?)
   7149 Chunk 06h: Symbol (?)
   7150   00h 4   Address/Value
   7151   04h 1   Chunk ID (01h/02h/05h/06h)
   7152   05h 1   Symbol Length (LEN)
   7153   06h LEN Symbol (eg. "VSync")
   7154 
   7155  __________________________ Source Code Line Chunks ___________________________
   7156 
   7157 Chunk 80h: Source Code Line Numbers: Address for 1 Line
   7158   00h 4   Address (for 1 line, starting at current line)
   7159   04h 1   Chunk ID (80h)
   7160 
   7161 Chunk 82h: Source Code Line Numbers: Address for N Lines (8bit)
   7162   00h 4   Address (for N lines, starting at current line)
   7163   04h 1   Chunk ID (82h)
   7164   05h 1   Number of Lines (00h=None, or 02h and up?)
   7165 
   7166 Chunk 84h: Source Code Line Numbers: Address for NN Lines (16bit)
   7167   00h 4   Address (for N lines, starting at current line)
   7168   04h 1   Chunk ID (84h)
   7169   05h 2   Number of Lines (?)
   7170 
   7171 Chunk 86h: Source Code Line Numbers: Address for Line NNN (32bit?)
   7172   00h 4   Address (for 1 line, starting at newly assigned current line)
   7173   04h 1   Chunk ID (84h)
   7174   05h 4   Absolute Line Number (rather than number of lines) (?)
   7175 
   7176 Chunk 88h: Source Code Line Numbers: Start with Filename
   7177   00h 4   Address (start address)
   7178   04h 1   Chunk ID (88h=Filename)
   7179   05h 4   First Line Number (after comments/definitions) (32bit?)
   7180   09h 1   Filename Length (LEN)
   7181   0Ah LEN Filename (eg. "C:\path\main.c")
   7182 
   7183 Chunk 8Ah: Source Code Line Numbers: End of Source Code
   7184   00h 4   Address (end address)
   7185   04h 1   Chunk ID (8Ah)
   7186 
   7187  __________________________ Internal Function Chunks __________________________
   7188 
   7189 Chunk 8Ch: Internal Function: Start with Filename
   7190   00h 4    Address
   7191   04h 1    Chunk ID (8Ch)
   7192   05h 4    Whatever (1Eh,00h,20h,00h)  ;or 1Eh,00h,18h,00h
   7193   09h 4    Whatever (00h,00h,1Fh,00h)
   7194   0Dh 4    Whatever (00h,00h,00h,C0h)
   7195   11h 4    Whatever (FCh,FFh,FFh,FFh)  ;mask? neg.offset?
   7196   15h 4    Whatever (10h,00h,00h,00h)  <-- line number (32bit?)
   7197   19h 1    Filename Length (LEN1)
   7198   1Ah LEN1 Filename (eg. "C:\path\main.c")
   7199   xxh 1    Symbol Length (LEN2)
   7200   xxh LEN2 Symbol (eg. "VSync")
   7201 
   7202 Chunk 8Eh: Internal Function: End of Function (end of chunk 8Ch)
   7203   00h 4   Address
   7204   04h 1   Chunk ID (8Eh)
   7205   05h 4   Line Number                 <-- line number (32bit?)
   7206 
   7207 Chunk 90h: Internal Function:Whatever90h... first instruction in main func?
   7208 Chunk 92h: Internal Function:Whatever92h... last instruction in main func?
   7209 Maybe line numbers? Or end of definitions for incoming parameters?
   7210   00h 4   Address
   7211   04h 1   Chunk ID (90h/92h)
   7212   05h 4   Whatever (1Fh,00h,00h,00h)  <-- line number relative to main.start?
   7213 
   7214  _____________________________ Class/Type Chunks ______________________________
   7215 
   7216 Chunk 94h: Type/Symbol (Simple Types?)
   7217   00h 4   Offset (when used within a structure, or stack-N, or otherwise zero)
   7218   04h 1   Chunk ID (94h)
   7219   05h 2   Class (000Dh=Type.alias, 000Ah=Address, 0001h=Stack, 0002h=Addr)
   7220   07h 2   Type (XX = 8bit,16bit,signed,etc.?)
   7221   09h 4   Zero, or Size in Bytes (for "memblocks")
   7222   0xh 1   Symbol Name Length (LEN)
   7223   0xh LEN Symbol Name (eg. "size_t")
   7224 
   7225 Chunk 96h: Type/Symbol (Complex Structures/Arrays?)
   7226   00h 4   Offset (when used within a structure, otherwise zero)
   7227   04h 1   Chunk ID (96h)
   7228   05h 2   Class (02h=Array,08h=RefToStruct,0Dh=DefineAlias,66h=StructEnd)
   7229   07h 2   Type (0xh=Small, 3xh=WithArrayStuff?) (same/similar as in chunk 94h)
   7230   09h 4     Struct Size in Bytes
   7231   0Dh 2     Array Dimensions (DIM) (0=none) ;eg. [3][4] --> 0002h
   7232   0Fh DIM*4 Array Entries per Dimension     ;eg. [3][4] --> 00000003h,00000004h
   7233   xxh 1     Internal Fake Name Length (LEN1) (0=none)
   7234   xxh LEN1  Internal Fake Name  (eg. ".1fake")
   7235   xxh 1     Symbol Name Length (LEN2)
   7236   xxh LEN2  Symbol Name (eg. "r")
   7237 
   7238  ______________________________ Class/Type Values _____________________________
   7239 
   7240 Class definition (in chunk 94h) (and somewhat same/similar in chunk 96h)
   7241 (looks same/similar as C_xxx class values in COFF files!)
   7242   0001h = Local variable              (with Offset = negative stack offset)
   7243   0002h = Global variable or Function (with Offset = address)
   7244   0008h = Item in Structure           (with Offser = offset within struct)
   7245   0009h = Incoming Function param     (with Offset = index; 0,4,8,etc.)
   7246   000Ah = Type address / struc start? (with Offset = zero)
   7247   000Dh = Type alias                  (with Offset = zero)
   7248 
   7249 Type definition (in chunk 94h/96h)
   7250 (maybe lower 4bit=type, and next 4bit=usage/variant?)
   7251 (looks same/similar as T_xxx type values in COFF files!)
   7252   0000h =
   7253   0001h =
   7254   0002h =
   7255   0003h =                (16bit signed?)
   7256   0004h = int            (32bit signed?)
   7257   0005h =
   7258   0006h =
   7259   0007h =
   7260   0008h = (address)      (32bit unsigned?) (with Definition=000Ah)
   7261   0009h =
   7262   000Ah =
   7263   000Bh =
   7264   000Ch = u_char         (8bit unsigned?)
   7265   000Dh = u_short,ushort (16bit unsigned?)
   7266   000Eh = u_int          (32bit unsigned?)
   7267   000Fh = u_long         (64bit unsigned?) (or rather SAME as above?)
   7268   0021h = function with 0 params, and/or return="nothing"?
   7269   0024h = main function with 2 params, and/or return="int"?
   7270   0052h = argv           (string maybe?)
   7271   0038h = GsOT           (huh?)
   7272   00F8h = GsOT_TAG       (huh?)
   7273   00FCh = PACKET         (huh?)
   7274   ??    = float,bool,string,ptr,packet,(un-)signed8/16/32/64bit,etc
   7275   ??    = custom type/struct (using value 000xh plus "fake" name, or so?)
   7276 
   7277  __________________________________ .MAP File _________________________________
   7278 
   7279 PsyQ .MAP File
   7280 The .SYM file is usually bundled with a .MAP file, which is containing a
   7281 summary of the symbolic info as ASCII text (but without info on line numbers or
   7282 data types). For example:
   7283     Start     Stop   Length      Obj Group            Section name
   7284  80010000 80012D5B 00002D5C 80010000 text             .rdata
   7285  80012D5C 800C8417 000B56BC 80012D5C text             .text
   7286  800C8418 800CDAB7 000056A0 800C8418 text             .data
   7287  800CDAB8 800CFB63 000020AC 800CDAB8 text             .sdata
   7288  800CFB64 800D5C07 000060A4 800CFB64 bss              .sbss
   7289  800D5C08 800DD33F 00007738 800D5C08 bss              .bss
   7290 
   7291   Address  Names alphabetically
   7292  800CFE80 ACE_amount
   7293  800CFB94 AIMenu
   7294  800CDE5C AXIS_LENGTH
   7295  8005E28C AddClippedTri
   7296  8005DFEC AddVertex
   7297  ...
   7298 
   7299   Address  Names in address order
   7300  00000000 _cinemax_obj
   7301  00000000 _cinemax_header_org
   7302  00000000 _cinemax_org
   7303  00000000 _mcardx_sbss_size
   7304  00000000 _mcardx_org
   7305  ...
   7306 
   7307 CDROM File Video Texture Image TIM/PXL/CLT (Sony)
   7308 -------------------------------------------------
   7309 
   7310 TIM/PXL/CLT are standard formats from Sony's devkit. TIM is used by many PSX
   7311 games.
   7312   .TIM   contains Pixel data, and (optional) CLUT data  ;-all in one file
   7313   .PXL   contains Pixel data only                       ;\in two separate files
   7314   .CLT   contains CLUT data only (if any)               ;/
   7315 
   7316 TIM Format
   7317   000h 1  File ID  (always 10h=TIM)
   7318   001h 1  Version  (always 00h)
   7319   002h 2  Reserved (always 0000h) (or 1 or 2 for Compressed TIM, see below)
   7320   004h 4  Flags (bit0-2=Type; see below, bit3=HasCLUT, bit4-31=Reserved/zero)
   7321   ...  .. Data Section for CLUT (Palette), only exists if Flags.bit3=1, HasCLUT
   7322   ...  .. Data Section for Pixels (Bitmap/Texture)
   7323 The Type in Flags.bit0-2 can be 0=4bpp, 1=8bpp, 2=16bpp, 3=24bpp, 4=Mixed.
   7324 NFL Blitz 2000 (MagDemo26: B2000\DATA\ARTD_G.BIN) does additionally use Type
   7325 5=8bit.
   7326 The Type value value is only a hint on how to view the Pixel data (the data is
   7327 copied to VRAM regardless of the type; 4=Mixed is meant to indicate that the
   7328 data contains different types, eg. both 4bpp & 8bpp textures).
   7329 Type 3=24bpp is quite rare, but does exist (eg. Colony Wars (MagDemo02:
   7330 CWARS\GAME.RSC\DEMO.TIM).
   7331 
   7332 The format of the CLUT and Pixel Data Section(s) is:
   7333   000h 4  Size of Data Section (Xsiz*2*Ysiz+0Ch)  ;maybe rounded to 4-byte?
   7334   004h 4  Destination Coord    (YyyyXxxxh)  ;Xpos counted in halfwords
   7335   008h 4  Width+Height         (YsizXsizh)  ;Xsiz counted in halfwords
   7336   00Ch .. VRAM Data (to be DMAed to frame buffer)
   7337 Note: Above is usually a multiple of 4 bytes, but not always:
   7338 Shadow Madness (MagDemo18: SHADOW\DATA\ANDY\LOADSAVE\*.TIM) contains TIM
   7339 bitmaps with 27x27 or 39x51 halfwords; those files have odd section size & odd
   7340 total filesize. Gran Turismo 2 (GT2.VOL\arcade\arc_other.tim\0000) also has odd
   7341 size. Unknown if the CLUT can also have odd size (which would misalign the
   7342 following Bitmap section).
   7343 Bust A Groove (MagDemo18: BUSTGR_A\G_COMMON.DFS\0005) has 0x0 pixel Bitmaps
   7344 (with CLUT data).
   7345 
   7346 PXL/CLT Format
   7347 PXL/CLT is very rare. And oddly, with swapped ID values (official specs say
   7348 11h=PXL, 12h=CLT, but the existing games do use 11h=CLT, 12h=PXL).
   7349 Used by Granstream Saga (MagDemo10 GS\*)
   7350 Used by Bloody Roar 1 (MagDemo06: BL\*)
   7351 Used by Bloody Roar 2 (MagDemo22: ASC,CMN,EFT,LON,SND,ST5,STU\*)
   7352 
   7353 CLT Format
   7354   000h 1  File ID  (always 11h=CLT) (although Sony's doc says 12h)
   7355   001h 1  Version  (always 00h)
   7356   002h 2  Reserved (always 0000h)
   7357   004h 4  Flags (bit0-1=Type=2; bit2-31=Reserved/zero)
   7358   ...  .. Data Section for CLUT (Palette)
   7359 The .CLT Type should be always 2 (meant to indicate 16bit CLUT entries).
   7360 
   7361 PXL Format
   7362   000h 1  File ID  (always 12h=PXL) (although Sony's doc says 11h)
   7363   001h 1  Version  (always 00h)
   7364   002h 2  Reserved (always 0000h)
   7365   004h 4  Flags (bit0-?=Type; see below, bit?-31=Reserved/zero)
   7366   ...  .. Data Section for Pixels (Bitmap/Texture)
   7367 This does probably support the same 5 types as in .TIMs (though official Sony
   7368 docs claim the .PXL type to be only 1bit wide, but netherless claim that PXL
   7369 can be 4bpp, 8bpp, or 16bpp).
   7370 
   7371  _______________________________ Compressed TIM _______________________________
   7372 
   7373 Compressed TIMs
   7374 Ape Escape (Sony 1999) is using a customized TIM format with 4bpp compression:
   7375 --> CDROM File Compression TIM-RLE4/RLE8
   7376 Other than that, TIMs can be compressed via generic compression functions (like
   7377 LZSS, GZIP), or via bitmap dedicated compression formats (like BS, JPG, GIF).
   7378 
   7379  ______________________________ Malformed Files _______________________________
   7380 
   7381 Malformed TIMs in BIGFILE.DAT
   7382   Used by Legacy of Kain: Soul Reaver (eg. BIGFILE.DAT\folder04h\file13h)
   7383   Used by Gex - Enter the Gecko (eg. BIGFILE.DAT\file0Fh\LZcompressed)
   7384 Malformed TIMs contain texture data preceeded by a dummy 14h-byte TIM header
   7385 with following constant values:
   7386   10 00 00 00  02 00 00 00  04 00 08 00  00 02 00 00  00 02 00 02  ;<-- this
   7387   10 00 00 00  02 00 00 00  04 00 08 00  00 00 00 00  00 02 00 02  ;<-- or this
   7388 The malformed entries include:
   7389   [04h]=Type should indicated the color depth, but it's always 02h=16bpp.
   7390   [08h]=Width*2*Height+0Ch should be 8000Ch, but malformed is 80004h.
   7391   Total filesize should be 80014h, but Gecko files are often MUCH smaller.
   7392 Also, destination yloc should be 0..1FFh, but PSX "Lemmings & Oh No! More
   7393 Lemmings" (FILES\GFX\*.TIM) has yloc=200h (that game also has vandalized .BMP
   7394 headers with 2-byte alignment padding after ID "BM", whilst pretending that
   7395 those extra bytes aren't there in data offset and total size entries).
   7396 
   7397 Oversized TIMs
   7398   Used by Pong (MagDemo24: LES02020\*\*.TIM)
   7399 Has 200x200h pix, but section size (and filesize) are +2 bigger than that:
   7400   10 00 00 00 02 00 00 00 0E 00 08 00 C0 01 00 00 00 02 00 02  ;Pong *.TIM
   7401   10 00 00 00 02 00 00 00 0E 00 07 00 00 02 00 00 C0 01 00 02  ;Pong WORLD.TIM
   7402   10 00 00 00 02 00 00 00 0E 80 03 00 00 02 00 01 C0 01 00 01  ;Pong ZONE*.TIM
   7403 
   7404 Miscomputed Section Size
   7405 NBA Basketball 2000 (MagDemo28: FOXBB\TIM\*.TIM) has TIMs with section size
   7406 "0Ch+Xsiz*Ysiz" instead of "0Ch+Xsiz*2*Ysiz".
   7407 
   7408 NonTIMs in Bloody Roar 1 and 2
   7409   Bloody Roar 1 (CMN\INIT.DAT\000Eh)
   7410   Bloody Roar 2 (CMN\SE00.DAT, CMD\SEL00.DAT\0030h and CMN\VS\VS.DAT\0000h)
   7411 This looks somehow TIM-inspired, but has ID=13h.
   7412   13 00 00 00 02 00 00 00 0C 20 00 00 00 00 F8 01 00 01 10 00  ;Bloody Roar 1
   7413   13 00 00 00 02 00 00 00 0C 20 00 00 00 00 00 00 00 01 10 00  ;Bloody Roar 2
   7414 
   7415 Other uncommon/malformed TIM variants
   7416 And, Heart of Darkness has a TIM with Size entry set to Xsiz*2*Ysiz+0Eh
   7417 (instead of +0Ch) (that malformed TIM is found inside of the RNC compressed
   7418 IMAGES\US.TIM file).
   7419 Also, NFL Gameday '99 (MagDemo17: GAMEDAY\PHOTOS.FIL) contains a TIM cropped to
   7420 800h-byte size (containing only the upper quarter of the photo).
   7421 Also, not directly malformed, but uncommon: Final Fantasy IX contains 14h-byte
   7422 0x0 pixel TIMs (eg. FF9.IMG\dir04\file0046\1B-0000\04-0001).
   7423 Klonoa (MagDemo08: KLONOA\FILE.IDX\3\2\0..1) has 0x0pix TIM (plus palette).
   7424 
   7425 Malformed CLTs
   7426   Used by Secret of Mana, WM\WEFF\*.CLT
   7427 ID is 10h=TIM, Flags=10101009h (should be ID=12h, Flags=02h).
   7428 
   7429 CDROM File Video Texture/Bitmap (Other)
   7430 ---------------------------------------
   7431 
   7432 Apart from Sony's TIM (and PXL/CLT) format, there are a bunch of other
   7433 texture/bitmap formats:
   7434 
   7435 Compressed Bitmaps
   7436   .BS used by several games (and also in most .STR videos)
   7437   .GIF used by Lightspan Online Connection CD
   7438   .JPG used by Lightspan Online Connection CD
   7439   .BMP with RLE4 used by Lightspan Online Connection CD (MONOFONT, PROPFONT)
   7440   .BMP with RLE8+Delta also used by Online Connection CD (PROPFONT\ARIA6.BMP)
   7441   .PCX with RLE used by Jampack Vol. 1 (MDK\CD.HED\*.pcx)
   7442 
   7443 Uncompressed Bitmaps
   7444   .BMP
   7445   .BMP used by Mat Hoffman's Pro BMX (MagDemo39: BMX\BMXCD.HED\*)
   7446   .BMP used by Mat Hoffman's Pro BMX (MagDemo48: MHPB\BMXCD.HED\*)
   7447   .BMP used by Thrasher: Skate and Destroy (MagDemo27: SKATE\ASSETS\*.ZAL)
   7448   .BMP used by Dave Mirra Freestyle BMX (MagDemo36,46: BMX\ASSETS\*.ZAL)
   7449   .VRM .IMG .TEX .TIM .RAW .256 .COL .4B .15B .R16 .TPG - raw VRAM data
   7450   "SC" memory card icons
   7451 
   7452 Targa TGA and Paintbrush PCX
   7453 --> CDROM File Video Texture/Bitmap (TGA)
   7454 --> CDROM File Video Texture/Bitmap (PCX)
   7455 
   7456 PSI bitmap - Power Spike (MagDemo43: POWER\GAME.IDX\*.BIZ\*.PSI)
   7457   000h 10h   Name 1 ("FILENAME.BMP", zeropadded)
   7458   010h 10h   Name 2 ("FILENAME.PSI", zeropadded)
   7459   020h 4     Bits per pixel (usually 4, 8, or 16)
   7460   024h 2     Bitmap VRAM Dest.X ?
   7461   026h 2     Bitmap VRAM Dest.Y ?
   7462   028h 2     Bitmap Width in pixels
   7463   02Ah 2     Bitmap Height in pixels
   7464   02Ch 2     Palette VRAM Dest.X ?   ;\zero for 16bpp
   7465   02Eh 2     Palette VRAM Dest.Y ?   ;/
   7466   030h 2     Bitmap Width in Halfwords (PixelWidth*bpp/16)
   7467   032h 2     Palette Size in Halfwords (0, 10h, 100h for 16bpp,4npp,8bpp)
   7468   034h 4     Maybe Bitmap present flag (always 1)
   7469   038h 4     Maybe Palette present flag (0=16bpp, 1=4bpp/8bpp)
   7470   03Ch ..    Bitmap pixels
   7471   ...  ..    Palette (if any, for 4bpp: 16x16bit, for 8bpp: 256x16bit)
   7472 
   7473 JumpStart Wildlife Safari Field Trip (MagDemo52: DEMO\DATA.DAT\*.DAT+*.PSX)
   7474 This game does use two different (but nearly identical) bitmap formats (with
   7475 either palette or bitmap data stored first).
   7476   000h 4     Total Filesize (Width*Height+20Ch)
   7477   004h 2     Bitmap Width
   7478   006h 2     Bitmap Height
   7479   008h 4     Unknown, always 1 (maybe 1=8bpp?)
   7480  In .DAT files (512x192 or 256x64 pix), palette first:
   7481   00Ch 200h  Palette data
   7482   20Ch ..    Bitmap data
   7483  In .PSX files (64x64 pix), bitmap first:
   7484   00Ch ..    Bitmap data
   7485   ...  200h  Palette data
   7486 To detect the "palette first" format, check for these conditions(s):
   7487   Filename extension is ".DAT"
   7488   Bitmap Width<>Height (non-square)
   7489   [00Ch..20Bh] has AllMSBs>=80h, and SomeLSBs<80h
   7490 Note: The bitmaps are vertically mirrored (starting with bottom-most scanline).
   7491 
   7492 WxH Bitmap (Width*Height)
   7493 Used by Alone in the Dark The New Nightmare (FAT.BIN\BOOK,DOC,INTRO,MENU\*)
   7494 Used by Rayman (RAY\JUN,MON,MUS\*) (but seems to contain map data, not pixels)
   7495   000h 2   Width  (W)   ;\usually 320x240 (or 512x240 or 80x13)
   7496   002h 2   Height (H)   ;/
   7497   004h ..  Bitmap 16bpp (W*H*2 bytes)
   7498 
   7499 RAWP Bitmap
   7500 Used by Championship Motocross (MagDemo25: SMX\RESHAD.BIN\*) ("RAWP")
   7501   000h 4     ID "RAWP" (this variant has BIG-ENDIAN width/height!)
   7502   004h 2     Width  (usually 280h=640pix or 140h=320pix) (big-endian!!!)
   7503   006h 2     Height (usually 1E0h=480pix or F0h=240pix)  (big-endian!!!)
   7504   008h ..    Bitmap data, 16bpp (width*height*2 bytes)
   7505 
   7506 XYWH Bitmap/Palette (X,Y,Width*Height) (.BIT and .CLT)
   7507 Used by CART World Series (MagDemo04: CART\*.BIT and *.BIN\*)
   7508 Used by NFL Gameday '98 (MagDemo04: GAMEDAY\BUILD\GRBA.FIL\*)
   7509 Used by NFL Gameday '99 (MagDemo17: GAMEDAY\*.BIT and *.FIL\*)
   7510 Used by NFL Gameday 2000 (MagDemo27: GAMEDAY\*.BIT)
   7511 Used by NCAA Gamebreaker '98 (MagDemo05: GBREAKER\*.BIT and UFLA.BIN\*)
   7512 Used by NCAA Gamebreaker 2000 (MagDemo27: GBREAKER\*.BIT and *.FIL\*)
   7513 Used by Twisted Metal 4 (MagDemo30: TM4DATA\*.MR,*.IMG\*.bit,*.clt)
   7514   000h 2   VRAM.X             (X) (0..3FFh)
   7515   002h 2   VRAM.X             (Y) (0..1FFh)
   7516   004h 2   Width in halfwords (W) (1..400h)
   7517   006h 2   Height             (H) (1..200h)
   7518   008h ..  Bitmap or Palette data (W*H*2 bytes)
   7519 
   7520 Doom (PSXDOOM\ABIN\PSXDOOM.WAD\*\*)
   7521   000h 2     Hotspot X (signed) (usually 0)
   7522   002h 2     Hotspot Y (signed) (usually 0)
   7523   004h 2     Width in bytes
   7524   006h 2     Height
   7525   008h ..    Bitmap 8bpp (Width*Height bytes)
   7526 Most files have Hotspot X=0,Y=0, WAD\LOADING has X=FF80h,Y=FF8Ah, and WAD\S\*
   7527 has X=0..Width, Y=0..Height+1Ah (eg. S\BKEY*, S\BFG*, S\PISFA0 have large Y).
   7528 The files do not contain any palette info... maybe 2800h-byte PLAYPAL does
   7529 contain the palette(s)?
   7530 
   7531 Lemmings & Oh No! More Lemmings (FILES\GFX\*.BOB, FILES\SMLMAPS\*.BOB)
   7532   000h 2       Width
   7533   002h 2       Height
   7534   004h 100h*3  Palette 24bit RGB888
   7535   304h ..      Bitmap 8bpp (Width*Height bytes)
   7536   ..   (1700h) Unknown (only in SMLMAPS\*.BOB, not in GFX\*.BOB)
   7537 Apart from .BOB, the FILES\GFX folder also has vandalized .BMP (with ID
   7538 "BM",00h,00h) and corrupted .TIM (with VRAM.Y=200h).
   7539 
   7540 One (DIRFILE.BIN\*.VCF)
   7541   000h 4     Unknown (always 1)
   7542   004h 4     Unknown (always 8)
   7543   008h 4     Unknown (always 2) (maybe 2=16bpp?)
   7544   00Ch 4     Width in pixels (3Ah, 140h, or 280h)
   7545   010h 4     Height          (3Ah, or F0h)
   7546   014h ..    Bitmap 16bpp (Width*Height*2 bytes)
   7547 
   7548 One (DIRFILE.BIN\*.VCK and DIRFILE.BIN\w*\sect*.bin\TEXTURE  001)
   7549   000h 2     Number if Files (N)
   7550   002h 2     Number of VRAM.Slots (less or equal than Number of Files)
   7551   004h 4     ID "BLK0"
   7552   008h N*10h File List
   7553   ...  ..    1st File Bitmap
   7554   ...  ..    1st File Palette (20h/200h/0 bytes for 4bpp/8bpp/16bpp)
   7555   ...  ..    2nd File Bitmap
   7556   ...  ..    2nd File Palette (only if PaletteID=FileNo=1)
   7557   ...  ..    3rd File Bitmap
   7558   ...  ..    3rd File Palette (only if PaletteID=FileNo=2)
   7559   ...  ..    etc.
   7560 File List entries:
   7561   000h 2     VRAM.X in halfwords (0..1Fh, +bit15=Blank)  ;\within current
   7562   002h 2     VRAM.Y              (0..3Fh)                ;/VRAM.Slot
   7563   004h 2     Width in pixels (max 80h/40h/20h for 4bpp/8bpp/16bpp)
   7564   006h 2     Height          (max 40h)
   7565   008h 2     VRAM.Slot       (0,1,2,3,...,NumSlots-1)
   7566   00Ah 2     Unknown         (0,1,2,4 in *.vck, 4 in sect*.bin)
   7567   00Ch 2     Color Depth     (0=4bpp, 1=8bpp, 2=16bpp)
   7568   00Eh 2     Palette ID      (0..FileNo-1=Old, FileNo=New, FFFFh=None/16bpp)
   7569   NumFiles-1, or ID of already used palette)
   7570 Note: VRAM.Slots are 20h*40h halfwords.
   7571 Bitmaps can either have newly defined palettes (when PaletteID=FileNo), or
   7572 re-use previously defined "old" palettes (when PaletteID<FileNo).
   7573 The Blank flag allows to define a blank region (for whatever purpose), the file
   7574 doesn't contain any bitmap/palette data for such blank regions.
   7575 
   7576 BMR Bitmaps
   7577 These are 16bpp bitmaps, stored either in uncompressed .BMR files, or in
   7578 compressed .RLE files:
   7579 --> CDROM File Compression RLE_16
   7580   Apocalypse (MagDemo16: APOC\CD.HED\*.RLE and *.BMR)
   7581   Spider-Man 1 older version (MagDemo31: SPIDEY\CD.HED\*.RLE)
   7582   Spider-Man 1 newer version (MagDemo40: SPIDEY\CD.HED\*.RLE and .BMR)
   7583   Spider-Man 2 (MagDemo50: HARNESS\CD.HED\*.RLE)
   7584   Tony Hawk's Pro Skater (MagDemo22: PROSKATE\CD.HED\*.BMR)
   7585 The width/height for known filesizes are:
   7586   33408h bytes --> 512x205pix, 16bpp (Apocalypse warning.rle)
   7587   3C008h bytes --> 512x240pix, 16bpp (most common)
   7588   96008h bytes --> 640x480pix, 16bpp (tony hawk's pro skater)
   7589 Most of the older BMR files (in Apocalypse) have valid 8-byte headers:
   7590   000h 2     Unknown (FFA0h) (ID for files with valid headers?)
   7591   002h 2     Dest.Y (usually 0) (11h=(240-205)/2 in Apocalypse warning.rle)
   7592   004h 2     Width  (usually 200h=512pix)
   7593   006h 2     Height (usually F0h=240pix) (CDh=205pix in Apocalypse warning.rle)
   7594   008h ..    Bitmap data, 16bpp (width*height*2 bytes)
   7595 Most or all newer BMR files (in Apocalypse "loadlogo.rle", and in all files in
   7596 Spider-Man 1, Spider-Man-2, Tony Hawk's Pro Skater) have the 8-byte header
   7597 replaced by unused 8-byte at end of file:
   7598   000h ..    Bitmap data, 16bpp (width*height*2 bytes)
   7599   ..   8     Unused (garbage or extra pixels, not transferred to VRAM)
   7600 BUG: The bitmaps in all .BMR files (both with/without header) are distorted:
   7601 The last 4-byte (rightmost 2pix) of each scanline should be actually located at
   7602 the begin of the scanline, and the last scanline is shifted by an odd amount of
   7603 bytes (resulting in nonsense 16bpp pixel colors); Spider-Man is actually
   7604 displaying the bitmap in that distorted form (although it does mask off some
   7605 glitches: one of the two bad rightmost pixels is replaced by a bad black
   7606 leftmost pixel, and glitches in upper/lower lines aren't visible on 224-line
   7607 NTSC screens).
   7608 
   7609 Croc 1 (retail: *.IMG) (retail only, not in MagDemo02 demo version)
   7610 Croc 2 (MagDemo22: CROC2\CROCII.DIR\*.IMG)
   7611 Disney's The Emperor's New Groove (MagDemo39: ENG\KINGDOM.DIR\*.IMG)
   7612 Disney's Aladdin in Nasira's Rev. (MagDemo46: ALADDIN\ALADDIN.DIR\*.IMG)
   7613 Contains raw 16bpp bitmaps, with following sizes:
   7614   25800h bytes = 12C00h pixels (320x240)  ;Croc 1 (retail version)
   7615   3C000h bytes = 1E000h pixels (512x240)
   7616   96000h bytes = 4B000h pixels (640x480)
   7617 Note: The .IMG format is about same as .BMR files (but without the 8-byte
   7618 header, and without distorted scanlines).
   7619 
   7620 Mat Hoffman's Pro BMX (MagDemo39: BMX\FE.WAD+STR\*.BIN) (Activision)
   7621 Mat Hoffman's Pro BMX (MagDemo48: MHPB\FE.WAD+STR\*.BIN) (Shaba/Activision)
   7622   000h 2     Bits per pixel (4 or 8)
   7623   002h 2     Bitmap Width in pixels
   7624   004h 2     Bitmap Height in pixels
   7625   006h 2     Zero
   7626   008h N*2   Palette (with N=(1 SHL bpp))
   7627   ...  ..    Bitmap (with Width*Height*bpp/8 bytes)
   7628   ...  (..)  Zeropadding to 4-byte boundary (old version only)
   7629 The trailing alignment padding exists only in old demo version (eg. size of
   7630 78x49x8bpp "coreypp.bin" is old=10F8h, new=10F6h).
   7631 
   7632 E.T. Interplanetary Mission (MagDemo54: MEGA\MEGA.CSH\*)
   7633   000h 2     Type (0=4bpp, 1=8bpp, 2=16bpp)
   7634   002h 2     Unknown (usually 0000h, or sometimes CCCCh)
   7635   004h 2     Bitmap Width in pixels
   7636   006h 2     Bitmap Height in pixels
   7637   008h 200h  Palette (always 200h-byte, even for 4bpp or 16bpp)
   7638   208h ..    Bitmap (Width*Height*bpp/8 bytes)
   7639 Palette is 00h-or-CCh-padded when 4bpp, or CCh-filled when 16bpp.
   7640 Note: Some files contain two or more such bitmaps (of same or different sizes)
   7641 badged together.
   7642 
   7643 EA Sports: Madden NFL '98 (MagDemo02: TIBURON\*.DAT\*)
   7644 EA Sports: Madden NFL 2000 (MagDemo27: MADN00\*.DAT\*)
   7645 EA Sports: Madden NFL 2001 (MagDemo39: MADN01\*.DAT\*)
   7646 This format is used in various EA Sports Madden .DAT archives, it contains
   7647 standard TIMs with extra Headers/Footers.
   7648   000h 4     Offset to TIM (1Ch) (Hdr size)    (1Ch)               ;\
   7649   004h 4     Offset to Footer    (Hdr+TIM size)(123Ch,1A3Ch,1830h) ;
   7650   008h 2     Bitmap Width in pixels      (40h or 60h or 30h)       ;
   7651   00Ah 2     Bitmap Height in pixels     (40h)                     ;
   7652   00Ch 4     Unknown, always 01h         (01h)                     ; Header
   7653   010h 4     Unknown, always 23h         (23h)                     ; 1Ch bytes
   7654   014h 2     Unknown, always 0101h       (101h)                    ;
   7655   016h 1     Bitmap Width in pixels      (40h or 60h or 30h)       ;
   7656   017h 1     Bitmap Height in pixels     (40h)                     ;
   7657   018h 4     Unknown, always 00h         (0)                       ;/
   7658   01Ch ..    TIM (Texture, can be 4bpp, 8bpp, 16bpp)               ;-TIM
   7659   ...  4     Unknown, always C0000222h   (C0000222h)               ;\
   7660   ...  2     Unknown, always 0001h       (0001h)                   ;
   7661   ...  1     Bitmap Width in pixels      (40h or 60h or 30h)       ; Footer
   7662   ...  1     Bitmap Height in pixels     (40h)                     ; 12h bytes
   7663   ...  4     Unknown, always 78000000h   (78000000h)               ;
   7664   ...  6     Unknown                     (0,0,80h,0,0,0)           ;/
   7665 Purpose is unknown; the 8bit Width/Height entries might be TexCoords.
   7666 The PORTRAITS.DAT archives are a special case:
   7667   Madden NFL '98 (MagDemo02: TIBURON\PORTRAIT.DAT) (48x64, 16bpp)
   7668   Madden NFL 2000 (MagDemo27: MADN00\PORTRAIT.DAT) (96x64, 8bpp plus palette)
   7669   Madden NFL 2001 (MagDemo39: MADN01\PORTRAIT.DAT) (64x64, 8bpp plus palette)
   7670 Those PORTRAITS.DAT don't have any archive header, instead they do contain
   7671 several images in the above format, each one zeropadded to 2000h-byte size.
   7672 
   7673 989 Sports: NHL Faceoff '99 (MagDemo17: FO99\*.KGB\*.TEX)
   7674 989 Sports: NHL Faceoff 2000 (MagDemo28: FO2000\*.TEX)
   7675 989 Sports: NCAA Final Four 2000 (MagDemo30: FF00\*.TEX)
   7676   000h 0Ch  ID "TEX PSX ",01h,00h,00h,00h    ;used in 989 Sports games
   7677   00Ch 4    Number of Textures
   7678   010h 4    Total Filesize
   7679   014h 4    Common Palette Size    (0=200h, 1=None, 2=20h)
   7680   018h (..) Common Palette, if any (0,20h,200h bytes)
   7681   ...  ..   Texture(s)
   7682  Texture format:
   7683   000h 10h  Filename (eg. "light1", max 16 chars, zeropadded if shorter)
   7684   010h 4    Width in pixels  (eg. 40h)
   7685   014h 4    Height           (eg. 20h or 40h)
   7686   018h 4    Unknown          (always 0)
   7687   01Ch 4    Number of Colors (eg. 10h, 20h or 100h)
   7688   020h ..   Bitmap (4bpp when NumColors<=10h, 8bpp when NumColors>10h)
   7689   ...  (..) Palette (NumColors*2 bytes, only present if Common Palette=None)
   7690 The .TEX files may be in ISO folders, KGB archives, DOTLESS archives. And, some
   7691 are stored in headerless .DAT/.CAT archives (which start with ID "TEX PSX ",
   7692 but seem to have further files appended thereafter).
   7693 
   7694 Electronic Arts .PSH (SHPP)
   7695 FIFA - Road to World Cup 98 (with chunk C0h/C1h = RefPack compression)
   7696 NCAA March Madness 2000 (MagDemo32: MM2K\*.PSH)
   7697 Need for Speed 3 Hot Pursuit (*.PSH, ZLOAD*.QPS\RefPack.PSH)
   7698 ReBoot (DATA\*.PSH) (with chunk 6Bh)
   7699 Sled Storm (MagDemo24: DEBUG,ART,ART2,ART3,SOUND\*.PSH) (with Comment, Mipmap)
   7700 WCW Mayhem (MagDemo28: WCWDEMO\*.BIG\*.PSH) (with chunk C0h/C1h = RefPack)
   7701   000h 4    ID "SHPP"
   7702   004h 4    Total Filesize (or Filesize-0Ch, eg. FIFA'98 ZLEG*.PSH)
   7703   008h 4    Number of Textures (N)
   7704   00Ch 4    ID "GIMX"
   7705   010h N*8  File List
   7706   ...  ..   Data (each File contains a Bitmap chunk, and Palette chunk, if any)
   7707  File List entries:
   7708   000h 4    Name (ascii) (Mipmaps use the same name for each mipmap level)
   7709   004h 4    Offset from begin of archive to first Chunk of file
   7710   Caution: Most PSH files do have the above offsets sorted in increasing order,
   7711   but some have UNSORTED offsets, eg. Sled Storm (MagDemo24: ART3\LOAD1.PSH),
   7712   so one cannot easily compute sizes as NextOffset-CurrOffset.
   7713   Note: Mipmap textures consist of two files with same name and different
   7714   resolution, eg. in Sled Storm (MagDemo24: ART\WORLD0x.PSH)
   7715  Bitmap Chunk:
   7716   000h 1    Chunk Type (40h=PSX/4bpp, 41h=PSX/8bpp, 42h=PSX/16bpp)
   7717   001h 3    Offset from current chunk to next chunk (000000h=None)
   7718   004h 2    Bitmap Width in pixels (can be odd, pad lines to 2-byte boundary)
   7719   006h 2    Bitmap Height
   7720   008h 2    Center X   (whatever that is)
   7721   00Ah 2    Center Y   (whatever that is)
   7722   00Ch 2    Position X (whatever that is, plus bit12-15=flags?)
   7723   00Eh 2    Position Y (whatever that is, plus bit12-15=flags?)
   7724   010h ..   Bitmap data (each scanline is padded to 2-byte boundary)
   7725   ...  ..   Padding to 8-byte boundary
   7726  Compressed Bitmap Chunk:
   7727   000h 1    Chunk Type (C0h=PSX/4bpp, C1h=PSX/8bpp, and probably C2h=PSX/16bpp)
   7728   001h 0Fh  Same as in Chunk 40h/41h/42h (see there)
   7729   010h ..   Compressed Bitmap data (usually/always with Method=10FBh)
   7730   ...  ..   Padding to 8-byte boundary
   7731  Palette Chunk (if any) (only for 4bpp/8bpp bitmaps, not for 16bpp):
   7732   000h 1    Chunk Type (23h=PSX/Palette)
   7733   001h 3    Offset from current chunk to next chunk (000000h=None)
   7734   004h 2    Palette Width in halfwords (10h or 100h)
   7735   006h 2    Palette Height             (1)
   7736   008h 2    Unknown (usually same as Width) (or 80D0h or 9240h)
   7737   00Ah 2    Unknown (usually 0000h)         (or 0001h or 0002h)
   7738   00Ch 2    Unknown (usually 0000h)
   7739   00Eh 2    Unknown (usually 00F0h)
   7740   010h ..   Palette data (16bit per color)
   7741   Note: The odd 80D0h,0001h values occur in Sled Storm ART\WORKD00.PSH\TBR1)
   7742  Unknown Chunk (eg. ReBoot (DATA\AREA15.PSH\sp*))
   7743   000h 1    Chunk Type (6Bh)
   7744   001h 3    Offset from current chunk to next chunk (000000h=None)
   7745   004h 8    Unknown (2C,00,00,3C,03,00,00,00)
   7746   00Ch -    For whatever reason, there is no 8-byte padding here
   7747  Comment Chunk (eg. Sled Storm (MagDemo24: ART\WORLD0x.PSH))
   7748   000h 1    Chunk Type (6Fh=PSX/Comment)
   7749   001h 3    Offset from current chunk to next chunk (000000h=None)
   7750   004h ..   Comment ("Saved in Photoshop Plugin made by PEE00751@...",00h)
   7751   ...  ..   Zeropadding to 8-byte boundary
   7752  Unknown Chunk (eg. Sled Storm (MagDemo24: ART\WORLD09.PSH\ADAA))
   7753   000h 1    Chunk Type (7Ch)
   7754   001h 3    Offset from current chunk to next chunk (000000h=None)
   7755   004h 2Ch  Unknown (reportedly Hot spot / Pix region, but differs on PSX?)
   7756 The whole .PSH file or the bitmap chunks can be compressed:
   7757 --> CDROM File Compression EA Methods
   7758 Variants of the .PSH format are also used on PC, PS2, PSP, XBOX (with other
   7759 Chunk Types for other texture/palette formats, and for optional extra data).
   7760 For details, see: http://wiki.xentax.com/index.php/EA_SSH_FSH_Image
   7761 
   7762 Destruction Derby Raw (MagDemo35: DDRAW\*.PCK,*.FNT,*.SPR)
   7763 This format can contain one single Bitmap, or a font with several small
   7764 character bitmaps.
   7765   000h 2     ID "BC"                                        ;\
   7766   002h 1     Color Depth (1=4bpp, 2=8bpp, 4=16bpp)          ; Header
   7767   003h 1     Type        (40h=Bitmap, C0h=Font)             ;/
   7768   ...  (2)   Palette Unknown (0 or 1)                       ;\only if Bitmap
   7769   ...  (2)   Palette Unknown (1)                            ; 4bpp or 8bpp
   7770   ...  (..)  Palette data (20h or 200h bytes for 4bpp/8bpp) ;/
   7771   ...  2     Bitmap Number of Bitmaps-1 (N-1)               ;\
   7772   ...  2     Bitmap Width in pixels                         ;
   7773   ...  2     Bitmap Height in pixels                        ; Bitmap(s)
   7774   ...  N*1   Bitmap Tilenumbers (eg. "ABCDEFG..." for Fonts);
   7775   ...  N*1   Bitmap Proportional Font widths? (0xh or FFh)  ;
   7776   ...  N*BMP Bitmap(s) for all characters                   ;/
   7777   ...  (20h) Palette Data (20h bytes for 4bpp)              ;-only if Font/4bpp
   7778 All bitmap scanlines are padded to 2-byte boundary, eg. needed for:
   7779   INGAME1\BOWL2.PTH\SPRITES.PTH\ST.SPR    30x10x4bpp: 15 --> 16 bytes/line
   7780   INGAME1\BOWL2.PTH\SPRITES.PTH\STOPW.SPR 75x40x4bpp: 37.5 --> 38 bytes/line
   7781 The BC files are usually compressed (either in PCK file, or in the compressed
   7782 DAT portion of a PTH+DAT archive).
   7783 
   7784 Cool Boarders 2 (MagDemo02: CB2\DATA*\*.FBD)
   7785   000h 2    ID ("FB")                                ;\File Header
   7786   002h 2    Always 1 (version? 4bpp? num entries?)   ;/
   7787   004h 2    Palette VRAM Dest X (eg. 300h)           ;\
   7788   006h 2    Palette VRAM Dest Y (eg. 1CCh,1EDh,1FFh) ; Palette Header
   7789   008h 2    Palette Width in halfwords (eg. 100h)    ; (all zero when unused)
   7790   00Ah 2    Palette Height (eg. 1 or 0Dh)            ;/
   7791   00Ch 2    Bitmap VRAM Dest X (eg. 140h or 200h)    ;\
   7792   00Eh 2    Bitmap VRAM Dest Y (eg. 0 or 100h)       ; Bitmap Header
   7793   010h 2    Bitmap Width in halfwords                ;
   7794   012h 2    Bitmap Height                            ;/
   7795   ...  ..   Palette Data (if any)                    ;-Palette Data
   7796   ...  ..   Bitmap Data                              ;-Bitmap Data
   7797 The bitmap data seems to be 4bpp and/or 8bpp, but it's hard to know the correct
   7798 palette (some files have more than 16 or 256 palette colors, or don't have any
   7799 palette at all).
   7800 
   7801 CDROM File Video Texture/Bitmap (TGA)
   7802 -------------------------------------
   7803 
   7804 Targa TGA
   7805   000h 1   Image ID Size (00h..FFh, usually 0=None)      ;0
   7806   001h 1   Palette Present Flag (0=None, 1=Present)      ;0            iv=1
   7807   002h 1   Data Type code (0,1,2,3,9,10,11,32,33)        ;NEBULA=2     iv=1
   7808   003h 2   Palette First Color (usually 0)               ;0            iv=0
   7809   005h 2   Palette Number of Colors (usually 100h)       ;0            iv=100h
   7810   007h 1   Palette Bits per Color (16,24,32, usually 24) ;0            iv=18h
   7811   008h 2   Bitmap X origin (usually 0)                   ;0
   7812   00Ah 2   Bitmap Y origin (usually 0)                   ;0
   7813   00Ch 2   Bitmap Width                                  ;NEBULA=20h LOGO=142h
   7814   00Eh 2   Bitmap Height                                 ;NEBULA=20h
   7815   010h 1   Bitmap Bits per Pixel (8,16,24,32 exist?)     ;NEBULA=18h   iv=8
   7816   011h 1   Image Descriptor (usually 0)                  ;0
   7817   012h ..  Image ID Data (if any, len=[00h], usually 0=None)
   7818   ...  ..  Palette
   7819   ...  ..  Bitmap
   7820   ...  1Ah Footer (8x00h, "TRUEVISION-XFILE.", 00h) (not present in iview)
   7821 Data Type [02h]:
   7822   00h = No image data included  ;-Unknown purpose
   7823   01h = Color-mapped image      ;\
   7824   02h = RGB image               ; Uncompressed
   7825   03h = Black and white image   ;/
   7826   09h = Color-mapped image      ;\Runlength
   7827   0Ah = RGB image               ;/
   7828   0Bh = Black and white image   ;-Unknown compression method
   7829   20h = Color-mapped image      ;-Huffman+Delta+Runlength
   7830   21h = Color-mapped image      ;-Huffman+Delta+Runlength+FourPassQuadTree
   7831 The official specs do list the above 9 types, but do describe only 4 types in
   7832 detail (type 01h,02h,09h,0Ah).
   7833   Type 01h and 09h lack details on supported bits per pixel (8bpp with 100h
   7834     colors does exist; unknown if less (or more) than 8bpp are supported,
   7835     and if so, in which bit order.
   7836   Type 02h and 0Ah are more or less well documented.
   7837   Type 03h has unknown bit-order, also unknown if/how it differs from type
   7838     01h with 1bpp.
   7839   Type 0Bh, 20h, 21h lack any details on the compression method.
   7840 TGA's are used by a couple of PSX games/demos (all uncompressed):
   7841   16bpp: Tomb Raider 2 (MagDemo01: TOMBRAID\*.RAW)
   7842   24bpp: Tomb Raider 2 (MagDemo05: TOMB2\*.TGA)
   7843   24bpp: Colony Wars Venegance (MagDemo14: CWV\GAME.RSC\NEBULA*.TGA, *SKY.TGA)
   7844   24bpp: Colony Wars Red Sun (MagDemo31: CWREDSUN\GAME.RSC\000A\*)
   7845   16bpp: Colony Wars Venegance (MagDemo14: CWV\GAME.RSC\LOGO.DAT)
   7846   16bpp: X-Men: Mutant Academy (MagDemo50: XMEN2\*)
   7847   16bpp: Disney's Tarzan (MagDemo42: TARZAN\*)
   7848   8bpp+Wrong8bitAttr: SnoCross Championship Racing (MagDemo37: SNOCROSS\*.TGA)
   7849   16bpp+WrongYflip: SnoCross Championship Racing (MagDemo37: SNOCROSS\*.TGA)
   7850 For whatever reason, TGA is still in use on newer consoles:
   7851   32bpp: 3DS AR Games (RomFS:\i_ar\tex\hm*.lz77
   7852 
   7853 CDROM File Video Texture/Bitmap (PCX)
   7854 -------------------------------------
   7855 
   7856 PC Paintbrush .PCX files (ZSoft)
   7857 Default extension is .PCX (some tools did use .PCX for the "main" image, and
   7858 .PCC for smaller snippets that were clipped/cropped/copied from from a large
   7859 image).
   7860   000h 1    File ID (always 0Ah=PCX/ZSoft)
   7861   001h 1    Version (0,2,3,4,5)
   7862   002h 1    Compression (always 01h=RLE) (or inofficial: 00h=Uncompressed)
   7863   003h 1    Bits per Pixel (per Plane) (1, 2, 4, or 8)
   7864   004h 2    Window X1   ;\
   7865   006h 2    Window Y1   ; Width  = X2+1-X1
   7866   008h 2    Window X2   ; Height = Y2+1-Y1
   7867   00Ah 2    Window Y2   ;/
   7868   00Ch 2    Horizontal Resolution in DPI  ;\often square, but can be also zero,
   7869   00Eh 2    Vertical Resolution in DPI    ;/or screen size, or other values
   7870   010h 30h  EGA/VGA Palette (16 colors, 3-byte per color = R,G,B) (or garbage)
   7871   010h 1    CGA: Bit7-4=Background Color (supposedly IRGB1111 ?)
   7872   013h 1    CGA: Bit7:0=Color,1=Mono,Bit6:0=Yellow,1=White,Bit5:0=Dim,1=Bright
   7873   014h 1    Paintbrush IV: New CGA Color1 Green  ;\weird new way to encode CGA
   7874   015h 1    Paintbrush IV: New CGA Color1 Red    ;/palette in these two bytes
   7875   040h 1    Reserved (00h) (but is 96h in animals.pcx)
   7876   041h 1    Number of color planes (1=Palette, 3=RGB, or 4=RGBI)
   7877   042h 2    Bytes per Line (per plane) (must be N*2) (=(Width*Bits+15)/16*2)
   7878   044h 2    PaletteInfo? (0000h/xxxxh=Normal, 0001h=Color/BW, 0002h=Grayscale)
   7879   046h 2    Horizontal screen size in pixels  ;\New fields, found only
   7880   048h 2    Vertical screen size in pixels    ;/in Paintbrush IV/IV Plus
   7881   04Ah 36h  Reserved (zerofilled) (or garbage in older files, custom in MGS)
   7882   080h ..   Bitmap data (RLE compressed)
   7883   ...  1    VGA Palette ID (0Ch=256 colors)                      ;\when 8bpp
   7884   ..   300h VGA Palette (256 colors, 3-byte per color  = R,G,B)  ;/
   7885 Decoding PCX files is quite a hardcore exercise due to a vast amount of
   7886 versions, revisions, corner cases, incomplete & bugged specifications, and
   7887 inofficial third-party glitches.
   7888 
   7889 PCX Versions
   7890   00h = Version 2.5 whatever ancient stuff
   7891   02h = Version 2.8 with custom 16-color palette
   7892   03h = Version 2.8 without palette (uses fixed CGA/EGA palette)
   7893   04h = Version ?.? without palette (uses fixed CGA/EGA palette)
   7894   05h = Version 3.0 with custom 16-color or 256-color palette or truecolor
   7895 NOTE: Version[01h]=05h with PaletteInfo[44h]=0001h..0002h is Paintbrush IV?
   7896 
   7897 Known PCX Color Depths
   7898   planes=1, bits=1  P1        ;1bit, HGC 2 color (iview and paint shop pro 2)
   7899   planes=1, bits=2  P2        ;2bit, CGA 4 color (with old/new palette info)
   7900   planes=3, bits=1  RGB111    ;3bit, EGA 8 color (official samples)  ;\version
   7901   planes=4, bits=1  IRGB1111  ;4bit, EGA 16 color (paint shop pro 2) ;/03h..04h
   7902   planes=1, bits=4  P4        ;4bit, BMP 16 color (iview)
   7903   planes=1, bits=8  P8        ;8bit, VGA 256 color palette
   7904   planes=1, bits=8  I8        ;8bit, VGA 256 level grayscale (gmarbles.pcx)
   7905   planes=3, bits=8  BGR888    ;24bit, truecolor (this is official 24bit format)
   7906  ;planes=1, bits=24 BGR888 ?  ;24bit, reportedly exists? poor compression
   7907  ;planes=4, bits=4  ABGR4444  ;16bit, wikipedia-myth? unlikely to exist
   7908  ;planes=4, bits=8  ABGR8888  ;32bit, truecolor+alpha (used in abydos.dcx\*)
   7909 
   7910 Width and Height
   7911 These are normally calculated as so:
   7912   Width  = X2+1-X1      ;width for normal files
   7913   Height = Y2+1-Y1      ;height for normal files
   7914 However, a few PCX files do accidentally want them to be calculated as so:
   7915   Width  = X2-X1        ;width for bugged files
   7916   Height = Y2-Y1        ;height for bugged files
   7917 Files with bugged width can be (sometimes) detected as so:
   7918   (Width*Bits+15)/16*2) > BytesPerLine
   7919 Files with bugged height can be detected during decompression:
   7920   BeginOfLastScanline >= Filesize (or Filesize-301h for files with palette)
   7921 Bugged sample files are SAMPLE.DCX, marbles.pcx and gmarbles.pcx. RLE
   7922 decompression may crash when not taking care of such files.
   7923 
   7924 Color Planes and Palettes
   7925 The official ZSoft PCX specs are - wrongly - describing planes as:
   7926   plane0 = red         ;\
   7927   plane1 = green       ; this is WRONG, NONSENSE, does NOT exist
   7928   plane2 = blue        ;
   7929   plane3 = intensity   ;/
   7930 The 8-color and 16-color EGA images are actually using plane0,1,2,(3) as
   7931 bit0,1,2,(3) of the EGA color number; which implies plane0=blue (ie. red/blue
   7932 are opposite of the ZSoft document).
   7933 The truecolor and truecolor+alpha formats have plane0..2=red,green,blue (as
   7934 described by ZSoft), but they don't have any intensity plane (a few files are
   7935 using plane3=alpha).
   7936 
   7937 Mono 2-Color Palette
   7938 This format was intended for 640x200pix 2-color CGA graphics, it's also common
   7939 for higher resolution FAX or print images. The general rule for these files is
   7940 to use this colors:
   7941   color0=black
   7942   color1=white
   7943 There are rumours that color1 could be changed to any of the 16 CGA colors
   7944 (supposedly via [10h].bit7-4, but most older & newer 2-color files have that
   7945 byte set to 00h, so one would end up with black-on-black).
   7946 Some newer 2-color files contain RGB palette entries [10h]=000000h,
   7947 [13h]=FFFFFFh (and [16h..3Fh]=00h-filled or FFh-filled).
   7948 Iview does often display 2-color images with color1=dark green (somewhat
   7949 mysteriously; it's doing that even for files that don't contain any CGA color
   7950 numbers or RGB palette values that could qualify as dark green).
   7951 
   7952 4-Color Palettes
   7953 This format was intended for 320x200pix 4-color CGA graphics, and the palette
   7954 is closely bound to colors available in CGA graphics modes. Color0 is defined
   7955 in [10h], and Color1-3 were originally defined in [13h], and later in
   7956 [14h,15h]:
   7957   color0=[10h].bit7-4  ;(Color0 IRGB)  ;CGA Port 3D9h.bit3-0 (usually 0=black)
   7958   bright=[13h].bit5                    ;CGA Port 3D9h.bit4    ;\
   7959   palette=[13h].bit6                   ;CGA Port 3D9h.bit5    ; old method
   7960   if [13h].bit7 then palette=2         ;CGA Port 3D8h.bit2    ;/
   7961   if [01h]=05h and [44h]=0001h then                           ;\new "smart"
   7962     if [14h]>200 or [15h]>200 then bright=1, else bright=0    ; method used in
   7963     if [14h]>[15h] then palette=0 else palette=1              :/Paintbrush IV
   7964   if palette=0 and bright=0 then color1..3=02h,04h,06h  ;\green-red-yellow
   7965   if palette=0 and bright=1 then color1..3=0Ah,0Ch,0Eh  ;/
   7966   if palette=1 and bright=0 then color1..3=03h,05h,07h  ;\cyan-magenta-white
   7967   if palette=1 and bright=1 then color1..3=0Bh,0Dh,0Fh  ;/
   7968   if palette=2 and bright=0 then color1..3=03h,04h,07h  ;\cyan-red-white
   7969   if palette=2 and bright=1 then color1..3=0Bh,0Ch,0Fh  ;/
   7970 Palette=2 uses some undocumented CGA glitch, it was somewhat intended to output
   7971 grayscale by disabling color burst on CGA hardware with analog composite
   7972 output, but actually most or all CGA hardware is having digital 4bit IRGB
   7973 output, which outputs cyan-red-white.
   7974 The new "smart" method is apparently trying to detect if [13h-1Bh] contains RGB
   7975 values with Color1=Green or Cyan, and to select the corresponding CGA palette;
   7976 unfortunately such PCX files are merely setting [14h,15h] to match up with the
   7977 "smart" formula, without actually storing valid RGB values in [13h-1Bh].
   7978 
   7979 8-Color and 16-Color, with fixed EGA Palettes (version=03h or 04h)
   7980 These images have 3 or 4 planes. Plane0-3 correspond to bit0-3 of the EGA color
   7981 numbers (ie. blue=plane0, green=plane1, red=plane2, and either intensity=plane3
   7982 for 16-color, or intensity=0 for 8-color images).
   7983 Some 8-Color sample images (with version=03h and 04h) can be found bundled with
   7984 PC Paintbrush Plus 1.22 for Windows. A 16-color sample called WINSCR.PCX can be
   7985 found elsewhere in internet.
   7986 Caution 1: Official ZSoft specs are wrongly claiming plane0=red and
   7987 plane2=blue; this is wrong (although Paint Shop Pro 2 is actually implementing
   7988 it that way) (whilst MS Paint for Win95b can properly display them) (most other
   7989 tools are trying to read a palette from [10h..3Fh], which is usually garbage
   7990 filled in version=03h..04h).
   7991 Caution 2: The standard EGA palette is used for version=03h..04h (many docs
   7992 claim it to be used for version=03h only).
   7993 
   7994 16-Color, with custom EGA/VGA Palettes (version=02h or 05h)
   7995 These can have 1 plane with 4 bits, or 4 planes with 1 bit. Header[10h..3Fh]
   7996 contains a custom 16-color RGB palette with 3x8bit per R,G,B.
   7997 Classic VGA hardware did only use the upper 6bit of the 8bit values.
   7998 Classic EGA hardware did only use the upper 2bit of the 8bit values (that, only
   7999 when having a special EGA monitor with support for more than 16 colors).
   8000 
   8001 256-Color VGA Palettes (version=05h)
   8002 These have 1 plane with 8 bits. And a 256-color RGB palette with 3x8bit per
   8003 R,G,B appended at end of file.
   8004 The appended 256-color palette should normally exist only in 256-color images,
   8005 some PCX tools are reportedly always appending the extra palette to all
   8006 version=05h files (even for 2-color files).
   8007 
   8008 256-Level Grayscale Images (version=05h and [44h]=0002h)
   8009 The most obvious and reliable way is to use a palette with grayscale RGB
   8010 values. However, Paintbrush IV is explicetly implementing (or ignoring?) an
   8011 obscure grayscale format with following settings:
   8012   [01h]=version=05h, and [44h]=0002h=grayscale
   8013 That settings are used in a file called gmarbles.pcx (which does contain a
   8014 256-color RGB palette with gray RGB values, ie. one can simply ignore the
   8015 special settings, and display it as normal 256-color image).
   8016 
   8017 Default 16-color CGA/EGA Palettes
   8018   Color  Name                     IRGB1111 RGB222 RGB888   Windows
   8019   00h    dark black               0000     000    000000   000000
   8020   01h    dark blue                0001     002    0000AA   000080
   8021   02h    dark green               0010     020    00AA00   008000
   8022   03h    dark cyan                0011     022    00AAAA   008080
   8023   04h    dark red                 0100     200    AA0000   800000
   8024   05h    dark magenta             0101     202    AA00AA   800080
   8025   06h    dark yellow (brown)      0110     210!!  AA5500!! 808000
   8026   07h    dark white (light gray)  0111     222    AAAAAA   C0C0C0!!
   8027   08h    bright black (dark gray) 1000     111    555555   808080!!
   8028   09h    bright blue              1001     113    5555FF   0000FF
   8029   0Ah    bright green             1010     131    55FF55   00FF00
   8030   0Bh    bright cyan              1011     133    55FFFF   00FFFF
   8031   0Ch    bright red               1100     311    FF5555   FF0000
   8032   0Dh    bright magenta           1101     313    FF55FF   FF00FF
   8033   0Eh    bright yellow            1110     331    FFFF55   FFFF00
   8034   0Fh    bright white             1111     333    FFFFFF   FFFFFF
   8035 Some notes on number of colors:
   8036  CGA supports 16 colors in text mode (but only max 4 colors in graphics mode).
   8037  EGA supports the same 16 colors as CGA in both text and graphics mode.
   8038  EGA-with-special-EGA-monitor supports 64 colors (but only max 16 at once).
   8039  VGA supports much colors (but can mimmick CGA/EGA colors, or similar colors)
   8040 CGA is using a 4pin IRGB1111 signal for up to 16 colors in text mode (max 4
   8041 colors in graphics mode), and CGA monitors contain some circuitry to convert
   8042 "dark yellow" to "brown" (though cheap CGA clones may display it as "dark
   8043 yellow").
   8044 EGA can display CGA colors (with all 16 colors in graphics mode).
   8045 EGA-with-special-EGA-monitor uses 6pin RGB222 signals for up to 64 colors (but
   8046 not more than 16 colors at once).
   8047 Windows is also using those 16 standard colors (when not having any VGA driver
   8048 installed, and also in 256-color VGA mode, in the latter case the 16 standard
   8049 colors are held to always available (even if different tasks are trying to
   8050 simultanously display different images with different palettes).
   8051 However, Windows has dropped brown, and uses non-pastelized bright colors.
   8052 
   8053 PCX files in PSX games
   8054   .PCX with RLE used by Jampack Vol. 1 (MDK\CD.HED\*.pcx)
   8055   .PCX with RLE used by Hot Wheels Extreme Racing (MagDemo52: US_01293\MISC\*)
   8056   .PCX with RLE used by Metal Gear Solid (slightly corrupted PCX files)
   8057 
   8058 PCX files in PSX Metal Gear Solid (MGS)
   8059 MGS is storing some extra data at [4Ah..57h] (roughly resembling the info in
   8060 TIM files).
   8061   04Ah 2    Custom MGS ID (always 3039h)
   8062   04Ch 2    Display Mode? (08h/18h=4bit, 09h/19h=8bit)
   8063   04Eh 2    Bitmap X-coordinate in VRAM (reportedly "divided by 2" ???)
   8064   050h 2    Bitmap Y-coordinate in VRAM
   8065   052h 2    Palette X-coordinate in VRAM
   8066   054h 2    Palette Y-coordinate in VRAM
   8067   056h 2    Palette number of actually used colors (can be less than 16/256)
   8068   058h 28h  Reserved (zerofilled)
   8069   080h ..   Bitmap data (RLE compressed)
   8070   ...  1    VGA Palette ID (0Ch=256 colors)                      ;\when 8bpp
   8071   ..   300h VGA Palette (256 colors, 3-byte per color  = R,G,B)  ;/
   8072   ..   ..   Padding to 4-byte boundary, ie. palette isn't at filesize-301h !!!
   8073 MGS has filesize padded to 4-byte boundary. That is causing problems for files
   8074 with 256-color palette: The official way to find the palette is to stepback
   8075 301h bytes from end of file, which won't work with padding. To find the MGS
   8076 palette, one must decompress the whole bitmap, and then expect the 301h-byte
   8077 palette to be located after the compressed data.
   8078 As an extra oddity, MGS uses non-square ultra-high DPI values.
   8079 
   8080 DCX Archives
   8081 DCX archives contain multiple PCX files (eg. multi-page FAX documents). The
   8082 standard format is as so:
   8083   0000h 4     ID (3ADE68B1h) (987654321 decimal)
   8084   0004h 4000h File List (32bit offsets) (max 1023 files, plus 0=End of List)
   8085   1004h ..    File Data area (PCX files)
   8086 However, some files have the first PCX at offset 1000h (ie. the list is only
   8087 3FFCh bytes tall). Reportedly there are also files that start with yet smaller
   8088 offsets (for saving space when the file list contains fewer entries).
   8089 The PCX filesize is next-curr offset (or total-curr for last file).
   8090 
   8091 References
   8092 https://www.fileformat.info/format/pcx/egff.htm
   8093 
   8094 CDROM File Video 2D Graphics CEL/BGD/TSQ/ANM/SDF (Sony)
   8095 -------------------------------------------------------
   8096 
   8097 CEL/BGD/TSQ/ANM/SDF
   8098 
   8099 CEL: Cell Data (official format with 8bit header entries)
   8100 This does merely translate Tile Numbers to VRAM Addresses and Attributes (with
   8101 the actual VRAM bitmap data usually being stored in .TIM files).
   8102   000h 1   File ID (22h)
   8103   001h 1   Version (3)
   8104   002h 2   Flag (bit15=WithAttr, bit14=AttrDataSize:0=8bit,1=16bit, bit13-0=0)
   8105   004h 2   Number of cell data items (in cell units) (N)
   8106   006h 1   Sprite Editor Display Window Width  (in cell units)
   8107   007h 1   Sprite Editor Display Window Height (in cell units)
   8108   008h ..  Cell Data[N] (64bit entries)
   8109   ...  ..  Cell Attr[N] (0bit/8bit/16bit user data? depending on Flag)
   8110 Cell Data:
   8111   0-7   Tex Coord X (8bit)
   8112   8-15  Tex Coord Y (8bit)
   8113   16-21 Clut X      (6bit)
   8114   22-30 Clut X      (9bit)
   8115   31    Semi-transparency enable        ;-only in Version>=3
   8116   32    Vertical Reversal   (Y-Flip)    ;\only in Version=0 and Version>=2
   8117   33    Horizontal Reversal (X-Flip)    ;/
   8118   34-47 Unused
   8119   48-52 Texture Page (5bit)
   8120   53-54 Semi Transparency     (0=B/2+F/2, 1=B+F, 2=B-F, 3=B+F/4)
   8121   55-56 Texture page colors   (0=4bit, 1=8bit, 2=15bit, 3=Reserved)
   8122   57-60 Sprite Editor Color Set Number  ;\
   8123   61    Unused                          ; only in Version>=3
   8124   62-63 Sprite Editor TIM Bank          ;/     XXX else hardcoded?
   8125 This is used in R-Types, CG.1\file3Dh\file00h, but [6,7] are 16bit wide! And
   8126 there are a LOT of ZEROes appended (plus FFh-padding due to CG.1 archive size
   8127 units).
   8128 Used by R-Types (CG.1\file07h\file01h, size 08h*04h, with 8bit attr)
   8129 Used by R-Types (CG.1\file07h\file03h, size 10h*08h, with 16bit attr)
   8130 Used by R-Types (CG.1\file07h\file05h, size 04h*04h, with 16bit attr)
   8131 Used by Tiny Tank (MagDemo23: TINYTANK\TMD05.DSK\*.CEL, size 08h*05h)
   8132 
   8133 CEL16: Inofficial CEL hack with 16bit entries and more extra data (R-Types)
   8134 This is an inofficial hack used by R-Types, the game does use both the official
   8135 CEL and inofficial CEL16 format.
   8136   000h 1   File ID (22h)        ;\same as in official CEL version
   8137   001h 1   Version (3)          ;/
   8138   002h 2   Flag (...unknown meaning in this case...?)           ;<-- ?
   8139   004h 2   Number of cell data items (in cell units) (N)
   8140   006h 2   Sprite Editor Display Window Width  (in cell units)  ;<-- 16bit!
   8141   008h 2   Sprite Editor Display Window Height (in cell units)  ;<-- 16bit!
   8142   00Ah ..  Cell Data[N] (64bit entries)
   8143   ...  ..  Cell Attr[N] (16bit/192bit user data, depending on Flag or so...?)
   8144 Used by R-Types (CG.1\file12h\file00h, size 0120h*000Fh with 192bit attr)
   8145 Used by R-Types (CG.1\file15h\file00h, size 0168h*000Fh with ? attr)
   8146 Used by R-Types (CG.1\file1Ch\file00h, size 00D8h*000Fh with ? attr)
   8147 
   8148 BGD: BG Map Data (official format with 8bit header entries)
   8149   000h 1   File ID (23h)
   8150   001h 1   Version (0)
   8151   002h 2   Flag (bit15=WithAttr, bit14=AttrDataSize:0=8bit,1=16bit, bit13-0=0)
   8152   004h 1   BG Map Width  (in cell units) (W)
   8153   005h 1   BG Map Height (in cell units) (H)
   8154   006h 1   Cell Width    (in pixels)
   8155   007h 1   Cell Height   (in pixels)
   8156   008h ..  BG Map Data[W*H] (16bit cell numbers)
   8157   ...  ..  BG Map Attr[W*H] (0bit/8bit/16bit user data? depending on Flag)
   8158 Used by R-Types (CG.1\file07h\file00h, official BGD format)
   8159 Used by Cardinal Syn (MagDemo03,09: SYN\SONY\KROLOGO.WAD\*.BGD)
   8160 Used by Tiny Tank (MagDemo23: TINYTANK\TMD05.DSK\*.BGD, with 8bit entries).
   8161 
   8162 BGD16: Inofficial BGD hack with 16bit entries (R-Types)
   8163 This is an inofficial hack used by R-Types, the game does use both the official
   8164 BGD and inofficial BGD16 format. Apparently invented to support bigger BG Map
   8165 Widths for huge sidescrolling game maps.
   8166   000h 1   File ID (23h)        ;\same as in official BGD version
   8167   001h 1   Version (0)          ;/
   8168   002h 2   Flag (bit15=WithAttr, bit14=AttrDataSize:0=8bit,1=16bit, bit13-0=0)
   8169   004h 2   BG Map Width  (in cell units) (W)                    ;<-- 16bit!
   8170   006h 2   BG Map Height (in cell units) (H)                    ;<-- 16bit!
   8171   008h 2   Cell Width    (in pixels)                            ;<-- 16bit!
   8172   00Ah 2   Cell Height   (in pixels)                            ;<-- 16bit!
   8173   00Ch ..  BG Map Data[W*H] (16bit cell numbers)
   8174   ...  ..  BG Map Attr[W*H] (0bit/8bit/16bit user data? depending on Flag)
   8175   ...  ..  FFh-padding (in case being stored in R-Types' DOT1 archives)
   8176 Used by R-Types (CG.1\file3Ch\file00h, inofficial BGD16 format)
   8177 
   8178 TSQ: Animation Time Sequence
   8179   000h 1   File ID (24h)
   8180   001h 1   Version (1)
   8181   002h 2   Number of Sequence data entries (N)
   8182   004h N*8 Sequence Data (64bit entries)
   8183 Sequence Data:
   8184   0-15  Sprite Group Number to be displayed
   8185   16-23 Display Time
   8186   24-27 Unused
   8187   28-31 Attribute (user defined) (only in Version>=1)
   8188   32-47 Hotspot X Coordinate
   8189   48-63 Hotspot Y Coordinate
   8190 There aren't any known games using .TSQ files.
   8191 
   8192 ANM: Animation Information
   8193   000h 1    File ID (21h)
   8194   001h 1    Version (3=normal) (but see below notes on older versions)
   8195   002h 2    Flag (bit0-1=TPF, bit2-11=0, bit12-15=CLT)
   8196              0-1   TPF PixFmt (0=4bpp, 1=8bpp, 2/3=Reserved)   ;version>=2 only
   8197              2-11  -   Reserved (0)
   8198              12-15 CLT Number of CLUT Groups, for color animation
   8199   004h 2    Number of Sprites Groups
   8200   006h 2    Number of Sequences (N) (can be 0=None)
   8201   008h N*8  Sequence(s) (64bit per entry)  ;Num=[004h]
   8202   ...  ..   Sprite Group(s)                ;Num=[006h]
   8203   ...  ..   CLUT Group(s)                  ;Num=[002h].bit12-15
   8204 Sequence entries:
   8205   000h 2  Sprite Group Number to be displayed (range 0..AnimHdr[004h]-1)
   8206   002h 1  Display Time (can be 00h or 0Ah or whatever)
   8207   003h 1  Attribute (bit0-3=Unused/Zero, bit4-7=User defined)  ;version>=3 only
   8208   004h 2  Hotspot X Coordinate (usually 0, or maybe can be +/-NN ?)
   8209   006h 2  Hotspot Y Coordinate (usually 0, or maybe can be +/-NN ?)
   8210 Sprite Group entries:
   8211  Each "Group" seems to represent one animation frame.
   8212  Each "Group" can contain one or more sprites (aka metatiles).
   8213  Below stuff is "4+N*14h" bytes, that seems to repeat "AnmHeader[004h] times"
   8214  XXX... actually below can be "4+N*10h" or "4+N*14h" bytes
   8215  XXX... so, maybe maybe some entries like width/height are optional?
   8216   000h 4     Number of Sprites in this Sprite Group ("sprites per metatile"?)
   8217   004h 14h*N Sprite(s) (see below)
   8218  Sprites:
   8219   000h 1   Tex Coord X (8bit)
   8220   001h 1   Tex Coord Y (8bit)
   8221   002h 1   Offset X from Hotspot within frame (maybe vertex x ?)
   8222   003h 1   Offset Y from Hotspot within frame (maybe vertex y ?)
   8223   004h 2   CBA Clut Base (bit0-5=ClutX, Bit6-14=ClutY, bit15=SemiTransp)
   8224   006h 2   FLAGs (bit0-4, bit5-6, bit7-8, bit9, bit10, bit11, bit12-15)
   8225             0-4   TPN Texture Page Number
   8226             5-6   ABR Semi-Transparency Rate
   8227             7-8   TPF Pixel depth (0=4bpp, 1=8bpp, 2=16bpp)
   8228             9     -   Reserved
   8229             10    RSZ Scaling  (0=No, 1=Scaled)
   8230             11    ROT Rotation (0=No, 1=Rotated)
   8231             12-15 THW Texture Width/Height div8 (0=Other custom width/height)
   8232   008h (2) Texture Width    "of optional size" (uh?)  ;\only present if
   8233   00Ah (2) Texture Height   "of optional size" (uh?)  ;/FLAGs.bit12-15=0 ?)
   8234   00Ch 2   Angle of Rotation (in what units?)
   8235   00Eh 2   Sprite Editor info (bit0-7=Zero, bit8-13=ClutNo, bit14-15=TimBank)
   8236   010h 2   Scaling X (for Vertex?) (as whatever fixed point number) (eg. 1000h)
   8237   012h 2   Scaling Y (for Vertex?) (as whatever fixed point number) (eg. 1000h)
   8238 CLUT Group entries:
   8239   000h 4  CLUT size in bytes (Width*Height*2+0Ch)
   8240   004h 2  Clut X Coordinate
   8241   006h 2  Clut Y Coordinate
   8242   008h 2  Clut Width
   8243   00Ah 2  Clut Height
   8244   00Ch .. CLUT entries (16bit per entry, Width*Height*2 bytes)
   8245 Note: ALICE.PAC\MENU.PAC\CON00.ANM has NumSequences=0 and NumSpriteGroups=2Dh
   8246 (unknown if/how that is animated, maybe it has 2Dh static groups? or the groups
   8247 are played in order 0..2Ch with display time 1 frame each?).
   8248 Used by Alice in Cyberland (ALICE.PAC\*.ANM) (ANM v3)
   8249 Unknown if there are any other games are using that format.
   8250 
   8251 SDF: Sprite Editor Project File
   8252 This is an ASCII text file for "artist boards" with following entries:
   8253   TIM0 file0.tim             ;\
   8254   TIM1 file1.pxl file1.clt   ; four TIM banks (with TIM or PXL/CLT files)
   8255   TIM2                       ; (or no filename for empty banks)
   8256   TIM3                       ;/
   8257   CEL0 file0.cel             ;-one CEL (with CEL, or no filename if none)
   8258   MAP0 file0.bgd             ;\
   8259   MAP1 file1.bgd             ; four BG MAP banks (with BGD filenames)
   8260   MAP2                       ; (or no filename for empty banks)
   8261   MAP3                       ;/
   8262   ANM0 file0.anm             ;-one ANM (with ANM, or no filename if none)
   8263   DISPLAY n       ;0-3=256/320/512/640x240, 4-7=256/320/512/640x480
   8264   COLOR n         ;0=4bpp, 1=8bpp  ;docs are unclear, is it COLORn or COLOR n?
   8265   ADDR0 texX texY clutX clutY numColorSets ;\
   8266   ADDR1 texX texY clutX clutY numColorSets ; four texture/palette offsets
   8267   ADDR2 texX texY clutX clutY numColorSets ; for the corresponding TIM banks
   8268   ADDR3 texX texY clutX clutY numColorSets ;/ (or whatever for empty banks?)
   8269 
   8270 CDROM File Video 3D Graphics TMD/PMD/TOD/HMD/RSD (Sony)
   8271 -------------------------------------------------------
   8272 
   8273  ____________________________________ TMD _____________________________________
   8274 
   8275 TMD - Modeling Data for OS Library
   8276   000h 4     ID (00000041h)
   8277   004h 4     Flags (bit0=FIXP, bit1-31=Reserved/zero)
   8278   008h 4     Number of Objects (N)     ;"integral value" uh?
   8279   00Ch N*1Ch Object List (1Ch-byte per entry)
   8280   ...  ..    Data (Vertices, Normals, Primitives)
   8281 Object List entries:
   8282   000h 4    Start address of a Vertex     ;\Address values depend on the
   8283   004h 4    Number of Vertices            ; file header's FIXP flag:
   8284   008h 4    Start address of a Normal     ;  FIXP=0 Addr from begin of Object
   8285   00Ch 4    Number of Normals             ;  FIXP=0 Addr from begin of TMD File
   8286   010h 4    Start address of a Primitive  ;
   8287   014h 4    Number of Primitives          ;/
   8288   018h 4    Scale (signed shift value, Pos=SHL, Neg=SHR) (not used by LIBGS)
   8289 Vertex entries (8-byte):
   8290   000h 2    Vertex X (signed 16bit)
   8291   002h 2    Vertex Y (signed 16bit)
   8292   004h 2    Vertex Z (signed 16bit)
   8293   006h 2    Unused
   8294 Normal entries (8-byte) (if any, needed only for computing light directions):
   8295   000h 2    Normal X (fixed point 1.3.12)
   8296   002h 2    Normal Y (fixed point 1.3.12)
   8297   004h 2    Normal Z (fixed point 1.3.12)
   8298   006h 2    Unused
   8299 Primitive entries (variable length):
   8300   000h 1    Output Size/4 of the GPU command (after GTE conversion)
   8301   001h 1    Input Size/4 of the Packet Data in the TMD file
   8302   002h 1    Flag
   8303               0   Light source calculation (0=On, 1=Off)
   8304               1   Clip Back (0=Clip, 1=Don't clip) (for Polygons only)
   8305               2   Shading (0=Flat, 1=Gouraud)
   8306                    (Valid only for the polygon not textured,
   8307                    subjected to light source calculation)
   8308               3-7 Reserved (0)
   8309   003h 1    Mode (20h..7Fh) (same as GP0(20h..7Fh) command value in packet)
   8310   004h ..   Packet Data
   8311 Packet Data (for Polygons)
   8312   000h 4   GPU Command+Color for that packet (CcBbGgRrh), see GP0(20h..3Fh)
   8313   ... (4)  Texcoord1+Palette (ClutYyXxh)               ;\
   8314   ... (4)  Texcoord2+Texpage (PageYyXxh)               ; only if Mode.bit2=1
   8315   ... (4)  Texcoord3         (0000YyXxh)               ;
   8316   ... (4)  Texcoord4         (0000YyXxh) ;-quad only   ;/
   8317   ... (4)  Color2 (00BbGgRrh)                          ;\
   8318   ... (4)  Color3 (00BbGgRrh)                          ; only if Flag.bit2=1
   8319   ... (4)  Color4 (00BbGgRrh) ;-quad only              ;/
   8320   ... (2)  Normal1 (index in Normal list?)  ;always, unless Flag.bit0=1
   8321   ...  2   Vertex1 (index in Vertex list?)
   8322   ... (2)  Normal2 (index in Normal list?)             ;-only if Mode.bit4=1
   8323   ...  2   Vertex2 (index in Vertex list?)
   8324   ... (2)  Normal3 (index in Normal list?)             ;-only if Mode.bit4=1
   8325   ...  2   Vertex3 (index in Vertex list?)
   8326   ... (2)  Normal4 (index in Normal list?) ;\quad only ;-only if Mode.bit4=1
   8327   ...  2   Vertex4 (index in Vertex list?) ;/
   8328   ... (2)  Unused zeropadding (to 4-byte boundary)
   8329 Packet Data (for Lines)
   8330   000h 4   GPU Command+Color for that packet (CcBbGgRrh), see GP0(40h,50h)
   8331   ... (4)  Color2 (00BbGgRrh)                          ;-only if Mode.bit4=1
   8332   ...  2   Vertex1 (index in Vertex list?)
   8333   ...  2   Vertex2 (index in Vertex list?)
   8334 Packet Data (for Rectangle/Sprites)
   8335   000h 4   GPU Command+Color for that packet (CcBbGgRrh), see GP0(60h..7Fh)
   8336   ...  ..  Unknown, reportedy "with 3-D coordinates and the drawing
   8337            content is the same as a normal sprite."
   8338 Note: Objects should usually contain Primitives and Vertices (and optionally
   8339 Normals), however, N2O\SHIP.TMD does contain some dummy Objects with Number of
   8340 Vertices/Normals/Primitives all set to zero.
   8341 Used by Playstation Logo (in sector 5..11 on all PSX discs, 3278h bytes)
   8342 Used by ...???model???... (MagDemo54: MODEL\*.BIN\*.TMD)
   8343 Used by Alice in Cyberland (ALICE.PAC\xxx_TM*.FA\*.TMD)
   8344 Used by Armored Core (MagDemo02: AC10DEMP\MS\MENU_TMD.T\*)
   8345 Used by Bloody Roar 1 (MagDemo06: CMN\EFFECT.DAT\0005h)
   8346 Used by Deception III Dark Delusion (MagDemo33: DECEPT3\K3_DAT.BIN\056A,0725\*)
   8347 Used by Gundam Battle Assault 2 (DATA\*.PAC\*)
   8348 Used by Hear It Now (Playstation Developer's Demo) (*.TMD and FISH.DAT).
   8349 Used by Jersey Devil (MagDemo10: JD\*.BZZ\*)
   8350 Used by Klonoa (MagDemo08: KLONOA\FILE.IDX\*)
   8351 Used by Legend of Dragoon (MagDemo34: LOD\DRAGN0.BIN\16xxh)
   8352 Used by Macross VF-X 2 (MagDemo23: VFX2\DATA01\*.TMD)
   8353 Used by Madden NFL '98 (MagDemo02: TIBURON\MODEL01.DAT\*)
   8354 Used by No One Can Stop Mr. Domino (MagDemo18: DATA\*, .TMD and DOT1\TMD)
   8355 Used by O.D.T. (MagDemo17: ODT\*.LNK\*)
   8356 Used by Parappa (MagDemo01: PARAPPA\COMPO01.INT\3\*.TMD)
   8357 Used by Resident Evil 1 (PSX\ITEM_M1\*.DOR\0001)
   8358 Used by Starblade Alpha (FLT\SB2.DAT\* and TEX\SB2.DAT\*)
   8359 Used by Tiny Tank (MagDemo23: TINYTANK\TMD*.DSK\*.TMD)
   8360 Used by WCW/nWo Thunder (MagDemo19: THUNDER\RING\*.TMD)
   8361 Used by Witch of Salzburg (the MODELS\*.MDL\*.TMD)
   8362 Used by Scooby Doo and the Cyber Chase (MagDemo54: MODEL\*\*)
   8363 
   8364  ____________________________________ PMD _____________________________________
   8365 
   8366 PMD - High-Speed Modeling Data
   8367 This is about same as TMD, with less features, intended to work fasrer.
   8368   000h 4    ID (00000042h)
   8369   004h 4    Offset to Primitives
   8370   008h 4    Offset to Shared Vertices (or 0=None)
   8371   00Ch 4    Number of Objects
   8372   010h ..   Objects         (4+N*4 bytes each, with offsets to Primitives)
   8373   ...  ..   Primitives
   8374   ...  ..   Shared Vertices (8-bytes each, if any)
   8375 Vertex entries (8-byte):
   8376   000h 2    Vertex X (signed 16bit)
   8377   002h 2    Vertex Y (signed 16bit)
   8378   004h 2    Vertex Z (signed 16bit)
   8379   006h 2    Unused
   8380 Objects:
   8381   000h 4    Number of Primitives
   8382   004h N*4  Offsets to Primitives ... maybe relative to hdr[004h] ?
   8383 Primitives:
   8384   000h 2    Number of Packets
   8385   002h 2    Type flags
   8386              0    Polygon   (0=Triangle, 1=Quadrilateral)
   8387              1    Shading   (0=Flat, 1=Gouraud)           ;uh, with ONE color?
   8388              2    Texture   (0=Texture-On, 1=Texture-Off) ;uh, withoutTexCoord?
   8389              3    Shared    (0=Independent vertex, 1=Shared vertex)
   8390              4    Light source calculation (0=Off, 1=On)  ;uh, withoutNormal?
   8391              5    Clip      (0=Back clip, 1=No back clip)
   8392              6-15 Reserved for system
   8393   004h ...  Packet(s)
   8394 Packet entries, when Type.bit3=0 (independent vertex):
   8395   000h 4   GPU Command+Color for that packet (CcBbGgRrh), see GP0(20h..7Fh)
   8396   004h 8   Vertex1 (Xxxxh,Yyyyh,Zzzzh,0000h)
   8397   00Ch 8   Vertex2 (Xxxxh,Yyyyh,Zzzzh,0000h)
   8398   014h 8   Vertex3 (Xxxxh,Yyyyh,Zzzzh,0000h)
   8399   01Ch (8) Vertex4 (Xxxxh,Yyyyh,Zzzzh,0000h) ;<-- only when Type.bit0=1 (quad)
   8400 Packet entries, when Type.bit3=1 (shared vertex):
   8401   000h 4   GPU Command+Color for that packet (CcBbGgRrh), see GP0(20h..7Fh)
   8402   004h 4   Offset to Shared Vertex1    ;offsets are
   8403   008h 4   Offset to Shared Vertex2    ;"from the start of a row"
   8404   00Ch 4   Offset to Shared Vertex3    ;aka from "Packet+04h" ?
   8405   010h (4) Offset to Shared Vertex4          ;<-- only when Type.bit0=1(quad)
   8406 Unknown if/how Texture/Light is implemented... without TexCoords/Normals?
   8407 Unknown if/how Gouraud is implemented... with ONE color and without Normals?
   8408 Used only by a few games:
   8409   Cool Boarders 2 (MagDemo02: CB2\DATA3\*.PMD)
   8410   Cardinal Syn (MagDemo03,09: SYN\*\*.WAD\*.PMD)    (4-byte hdr plus PMD file)
   8411   Sesame Streets Sports (MagDemo52: SSS\LV*\*MRG\*) (4-byte hdr plus PMD file)
   8412 Unknown if/which other games are using the PMD format.
   8413 
   8414  ____________________________________ TOD _____________________________________
   8415 
   8416 TOD - Animation Data
   8417   000h 1    ID (50h)
   8418   001h 1    Version (0)
   8419   002h 2    Resolution (time per frame in 60Hz units, can be 0) (60Hz on PAL?)
   8420   004h 4    Number of Frames
   8421   008h ..   Frame1
   8422   ...  ..   Frame2
   8423   ...  ..   Frame3
   8424   ...  ..   etc.
   8425 Frames:
   8426   000h 2    Frame Size in words (ie. size/4)
   8427   002h 2    Number of Packets (can be 0=None, ie. do nothing this frame)
   8428   004h 4    Frame Number (increasing 0,1,2,3,..)
   8429   008h ...  Packet(s)
   8430 Packet:
   8431   000h 2    Object ID
   8432   002h 1    Type/Flag (bit0-3=Type, bit4-7=Flags)
   8433   003h 1    Packet Size ("in words (4 bytes)")
   8434   004h ...  Packet Data
   8435 XXX... in Sony's doc.
   8436 Used by Witch of Salzburg (ANIM\ANM0\ANM0.TOD) (oddly with [02h]=0000h)
   8437 Used by Parappa (MagDemo01: PARAPPA\COMPO01.INT\3\*.TOD)
   8438 Used by Macross VF-X 2 (MagDemo23: VFX2\DATA01\*.TOD and *.TOX)
   8439 Used by Alice in Cyberland (ALICE.PAC\xxx_T*.FA\*.TOD)
   8440 Unknown if/which other games are using the TOD format.
   8441 
   8442  ____________________________________ HMD _____________________________________
   8443 
   8444 HMD - Hierarchical 3D Model, Animation and Other Data
   8445   000h 4    ID (00000050h)   ;same as in TOD, which CAN ALSO have MSBs=zero(!)
   8446   004h 4    MAP FLAG (0 or 1, set when mapped via GsMapUnit() function)
   8447   008h 4    Primitive Header Section pointer (whut?)
   8448   00Ch 4    Number of Blocks
   8449   010h 4*N  Pointers to Blocks
   8450   ...       Primitive Header section    (required)
   8451   ...       Coordinate section          (optional)
   8452   ...       Primitive section           (required)
   8453 This format is very complicated, see Sony's "File Formats" document for
   8454 details.
   8455 .HMD used by Brunswick Bowling (MagDemo13: THQBOWL\*).
   8456 .HMD used by Soul of the Samurai (MagDemo22: RASETSU\0\OPT01T.BIN\0\0\*)
   8457 .HMD used by Bloody Roar 2 (MagDemo22: LON\LON*.DAT\*, ST5\ST*.DAT\02h..03h)
   8458 .HMD used by Ultimate Fighting Championship (MagDemo38: UFC\CU00.RBB\6Bh..EFh)
   8459 Unknown if/which games other are using the HMD format.
   8460 
   8461  ____________________________________ RSD _____________________________________
   8462 
   8463 RSD Files (RSD,PLY,MAT,GRP,MSH,PVT,COD,MOT,OGP)
   8464 RSD files consist of a set of several files (RSD,PLY,MAT,etc). The files
   8465 contain the "polygon source code" in ASCII text format, generated from Sony's
   8466 "SCE 3D Graphics Tool". For use on actual hardware, the "RSDLINK" utility can
   8467 be used to convert them to binary (TMD, PMD, TOD?, HMB?) files.
   8468   RSD Main project file
   8469   PLY Polygon Vertices (Vertices, Normals, Polygons)
   8470   MAT Polygon Material (Color, Blending, Texture)
   8471   GRP Polygon Grouping
   8472   MSH Polygon Linking                   ;\
   8473   PVT Pivot Rotation center offsets     ; New Extended
   8474   COD Vertex Coordinate Attributes      ; (since RSD version 3)
   8475   MOT Animation Information             ;/
   8476   OGP Vertex Object Grouping            ;-Sub-extended
   8477 All of the above files are in ASCII text format. Each file is starting with a
   8478 "@typYYMMDD" string in the first line of the file, eg. "@RSD970401" for RSD
   8479 version 3. Vertices are defined as floating point values (as ASCII strings).
   8480 There's more info in Sony's "File Formats" document, but the RSD stuff isn't
   8481 used on retail discs. Except:
   8482   RSD/GRP/MAT/PLY (and DXF=whatever?) used on Yaroze disc (DTL-S3035)
   8483 
   8484 CDROM File Video STR Streaming and BS Picture Compression (Sony)
   8485 ----------------------------------------------------------------
   8486 
   8487 STR Files (movie streams)
   8488 --> CDROM File Video Streaming STR (Sony)
   8489 --> CDROM File Video Streaming STR Variants
   8490 --> CDROM File Video Streaming Framerate
   8491 --> CDROM File Video Streaming Audio
   8492 --> CDROM File Video Streaming Chunk-based formats
   8493 --> CDROM File Video Streaming Mis-mastered files
   8494 Apart from the 20h-byte STR headers, movies basically consist of a series of BS
   8495 files (see below).
   8496 
   8497 BS Files (Huffman compressed MDEC codes)
   8498 BS stands for bitstream, which might refer to the use in STR files, or to the
   8499 Huffman bitstreams.
   8500 --> CDROM File Video BS Compression Versions
   8501 --> CDROM File Video BS Compression Headers
   8502 The header is followed by the bitstream...
   8503   v1/v2/v3/ea/iki --> first bit in bit15 of first halfword (good for psx)
   8504   v0              --> first bit in bit7 of first byte (not so good for psx)
   8505   (to use the same decoder for all version: swap each 2 bytes in v0)
   8506 For each block, the bitstream contains one DC value, up to 63 AC values,
   8507 terminated by EOB (end of block).
   8508 --> CDROM File Video BS Compression DC Values
   8509 --> CDROM File Video BS Compression AC Values
   8510 Apart from being used in STR movies, BS can be also used to store single
   8511 pictures:
   8512 --> CDROM File Video BS Picture Files
   8513 
   8514 Wacwac (similar as BS, but with completely different Huffman codes)
   8515 --> CDROM File Video Wacwac MDEC Streams
   8516 
   8517 Credits
   8518 Thanks to Michael Sabin for info on various STR and BS variants:
   8519 https://github.com/m35/jpsxdec/
   8520 
   8521 CDROM File Video Streaming STR (Sony)
   8522 -------------------------------------
   8523 
   8524 .STR Sectors (with 20h-byte headers) (for MDEC Movies, or User data)
   8525   000h 2    StStatus (0160h) (RV6Rh; R=Reserved=0, V=Version=1, 6=Fixed ID)
   8526   002h 2    StType (0000h..7FFFh=User Defined, 8000h..FFFFh=System; 8001h=MDEC)
   8527   004h 2    StSectorOffset (Sector number in the frame, 0=First)
   8528   006h 2    StSectorSize   (Number of sectors in the frame) (eg. 4 or 5)
   8529   008h 4    StFrameNo      (Frame number, 1=First) (except Viewpoint=0)
   8530   00Ch 4    StFrameSize    (in bytes, in this frame, excluding headers/padding)
   8531  When StType=0000h..7FFFh:
   8532   010h 10h  StUser         (user defined data)
   8533   020h 7E0h User data      (more user defined data)
   8534  When StType=8001h=MDEC (the only system defined type) (with StStatus=0160h):
   8535   010h 2    StMovieWidth                  (eg. 0140h)
   8536   012h 2    StMovieHeight                 (eg. 00F0h)
   8537   014h 4    StHeadM (reserved for system) (eg. 38000720h) ;\same as [020h-027h]
   8538   018h 4    StHeadV (reserved for system) (eg. 00020001h) ;/from 1st STR sector
   8539   01Ch 4    Unspecified                   (eg. 00000000h) (except Viewpoint<>0)
   8540   020h 7E0h Data (in BS format) (or padding, when image is smaller than frame)
   8541 The default file extension .STR is used by various games (though some games use
   8542 other extensions, the .FMV files in Tomb Raider do also contain standard
   8543 20h-byte .STR sector headers).
   8544 
   8545 Video Frames
   8546 The video frames consist of BS compressed images (that is, all sectors have STR
   8547 headers at 000h..01Fh, and the first sector of each frame does additionally
   8548 contain a standard BS fileheader at offset 020h..027h).
   8549   See "CDROM File Video BS Compression" chapters
   8550 Less common, there is also a format for streaming polygon animations instead of
   8551 BS compressed bitmaps:
   8552 --> CDROM File Video Polygon Streaming
   8553 
   8554 STR Resolution
   8555 The Width/Height entries are almost always multiples of 16 pixels. But there
   8556 are a few exceptions:
   8557   Height=260 (104h) in Star Wars Rebel Assault II, NTSC (S1\L01_PLAY.STR)
   8558   Height=200 (0C8h) in Perfect Assassin (DATA.JFS\CDV\*.STR)
   8559   Height=40  (028h) in Gran Turismo 1 (TITLE.DAT\*, MagDemo10 and MagDemo15)
   8560   Width=232  (0E8h) in Gran Turismo 1 (TITLE.DAT\*, MagDemo10 only)
   8561 For such videos, the width/height of MDEC decompression buffer in RAM must be
   8562 rounded up to multiples of 16 pixels (and the decompressed picture should be
   8563 cropped to the STR header width/height before forwarding it to VRAM).
   8564 Note: The extra scanlines are usually padded with the bottom-most scanline
   8565 (except, Gran Turismo 1 has gray-padding in lower/right pixels). Ideally, one
   8566 would repeat the bottom-most pixels in zigzag order.
   8567 
   8568 Subtitles
   8569 Metal Gear Solid MGS\ZMOVIE.STR contains subtitles as text strings: The first
   8570 sector of the .STR file is something custom (without STR header), the remaining
   8571 movie consists of STR sectors with StType=0001h for subtitles and StType=8001h
   8572 for picture frames.
   8573 Unknown if other games are using the same method, or other methods.
   8574 Obviously, subtitles could be also displayed as part of the compressed image,
   8575 but text strings are much smaller, have better quality, and would also allow to
   8576 support multiple languages.
   8577 
   8578 CDROM File Video Streaming STR Variants
   8579 ---------------------------------------
   8580 
   8581 STR ID Values
   8582   2-byte  0160h         ;Standard STR header
   8583   1-byte  01h           ;Ace Combat 3 Electrosphere
   8584   4-byte  "SMJ",01h     ;Final Fantasy 8, Video
   8585   4-byte  "SMN",01h     ;Final Fantasy 8, Audio/left
   8586   4-byte  "SMR",01h     ;Final Fantasy 8, Audio/righ
   8587   4-byte  0000000xh     ;Judge Dredd
   8588   4-byte  DDCCBBAAh     ;Crusader: No Remorse, older Electronic Arts
   8589   4-byte  08895574h     ;Chunk header in 1st sector only, Best Sports (demo)
   8590   4-byte  "VLC0"        ;Chunk header in 1st sector only, newer Electronic Arts
   8591   4-byte  "VMNK"        ;Chunk header in 1st sector only, Policenauts
   8592   4-byte  01h,"XSP"     ;Sentient header in 1st sector only
   8593   N-byre  zero(es)      ;Polygons? (in last 150Mbyte of PANEKIT.STR)
   8594 
   8595 STR Type values (for videos that do have STR ID=0160h):
   8596 The official definition from Sony's File Formats document is as so;
   8597   0000h..7FFFh=User Defined
   8598   8000h..FFFFh=System (with 8001h=MDEC being the only officially defined type)
   8599 In practice, the following values are used (of which, 8001h is most common).
   8600   0000h=Polygon Video, Wacwac as Polygon Stream
   8601   0000h=Polygon Video?, Army Men Air Attack 2 (MagDemo40: AMAA2\*.PMB)
   8602   0000h=MDEC Video, Alice in Cyberland
   8603   0001h=MDEC Video, Ridge Racer Type 4 (PAL version, 320x176 pix)
   8604   0001h=Whatever extra data for XA-ADPCM streams (Bits Laboratory games)
   8605   0001h=Whatever non-audio waverform? (3D Baseball)
   8606   0001h=Subtitles, Metal Gear Solid MGS\ZMOVIE.STR
   8607   0002h=Software-rendered video (without using MDEC/GTE) (Cyberia)
   8608   0002h=MDEC Video, Wacwac with IntroTableSet
   8609   0003h=MDEC Video, Wacwac with EndingTableSet
   8610   0004h=MDEC Video, Final Fantasy 9 (MODE2/FORM2)
   8611   0008h=SPU-ADPCM, AKAO audio (Final Fantasy 9)
   8612   0000h=SPU-ADPCM, AKAO audio (Chrono Cross Disc 1, Legend of Mana)
   8613   0001h=SPU-ADPCM, AKAO audio (Chrono Cross Disc 1, Legend of Mana)
   8614   0100h=SPU-ADPCM, AKAO audio (Chrono Cross Disc 2)
   8615   0101h=SPU-ADPCM, AKAO audio (Chrono Cross Disc 2)
   8616   0000h=Whatever special, channel 0 header (Nightmare Project: Yakata)
   8617   0400h=Whatever special, channel 1 header (Nightmare Project: Yakata)
   8618   0001h=Whatever special, channel 0 data   (Nightmare Project: Yakata)
   8619   0401h=Whatever special, channel 1 data   (Nightmare Project: Yakata)
   8620   5349h=MDEC Video, Gran Turismo 1 and 2 (with BS iki)
   8621   0078h=MDEC Ending Dummy  (Mat Hoffman's Pro BMX (MagDemo48: MHPB\SHORT.STR)
   8622   5673h=MDEC Leading Dummy (Mat Hoffman's Pro BMX (MagDemo48: MHPB\SHORT.STR)
   8623   8001h=MDEC Video, Standard MDEC (most common type value)
   8624   8001h=Polygon Video (Ape Escape) (same ID as standard MDEC)
   8625   8001h=Eagle One: Harrier Attack various types (MDEC and other data)
   8626   8001h=Dance series SPU-ADPCM streaming (with STR[1Ch]=DDCCBBAAh)
   8627   8101h=MDEC Video, Standard MDEC plus bit8=FlagDisc2 (Chrono Cross Disc 2)
   8628 
   8629  ______________________________________________________________________________
   8630 
   8631 Leading XA-ADPCM
   8632 Most movies start with STR video sectors. But a few games start with XA-ADPCM:
   8633   Ace Combat 3 Electrosphere (*.SPB)
   8634   Alice in Cyber Land (*.STR)
   8635   Judge Dredd (*.IXA) ;and very small 4-byte STR header
   8636   ReBoot (MOVIES\*.WXA)
   8637 Also, Aconcagua (Wacwac) has XA-ADPCM before Video (but, yet before that, it
   8638 has 150 leading zerofilled sectors).
   8639 Also, Porsche Challenge (SRC\MENU\STREAM\*.STR) starts with corrupted
   8640 Subheaders, which may appear as leading XA-ADPCM (depending on how to
   8641 interprete the corrupted header bits).
   8642 
   8643 Leading SPU-ADPCM
   8644   EA videos     ;\
   8645   Crusader      ; chunks
   8646   Policenauts   ;/
   8647   AKAO videos
   8648 
   8649 Metal Gear Solid (MGS\ZMOVIE.STR, 47Mbyte)
   8650 This is an archive dedicated to STR movies (with number of frames instead of
   8651 filesize entries). Metal Gear Solid does also have cut-scenes with polygon
   8652 animations (but those are supposedly stored elsewhere?).
   8653   000h 4    Number of entries (4)
   8654   004h N*8  File List
   8655   ...  ..   Zerofilled
   8656 File List entries:
   8657   000h 2    Unknown... decreasing values?
   8658   002h 2    Number of Frames (same as last frame number in STR header)
   8659   004h 4    Offset/800h (to begin of STR movie, with subtiltes in 1st sector)
   8660 Disc 1 has four movies: The first one has a bit more than 12.5 sectors/frame,
   8661 the other three have a bit more than 10 sectors/frame (eg. detecting the
   8662 archive format could be done checking for entries wirh 8..16 sectors/frame).
   8663 Example, from Disc 1:
   8664   04 00 00 00
   8665   ED 97 9E 01  01 00 00 00 ;num sectors=1439h ;div19Eh=C.81h ;97EDh-6137h=36B6h
   8666   37 61 86 01  3A 14 00 00 ;num sectors=0F41h ;div186h=A.03h ;6137h-38D0h=2867h
   8667   D0 38 10 03  7B 23 00 00 ;num sectors=1EA1h ;div310h=A.00h ;38D0h-2302h=15CEh
   8668   02 23 73 02  1C 42 00 00 ;num sectors=1881h ;div273h=A.01h ;2302h-0000h=2302h
   8669 The files in the ZMOVIE.STR archive start with subtitles in 1st sector (this is
   8670 usually/always only one single sector for the whole movie):
   8671   000h 2    STR ID   (0160h)                                       ;\
   8672   002h 2    STR Type (0001h=Subtitles)                             ;
   8673   004h 2    Sector number within Subtitles (0)                     ; STR
   8674   006h 2    Number of Sectors with Subtitles (1)                   ; header
   8675   008h 4    Frame number (1)                                       ;
   8676   00Ch 4    Data size counted in 4-byte units (same as [02Ch]/4)   ;
   8677   010h 10h  Zerofilled                                             ;/
   8678   020h 4    Unknown (2)                                            ;\
   8679   024h 4    Unknown (1AAh, 141h, or 204h)                          ; Data
   8680   028h 4    Unknown (00100000h)                                    ; part
   8681   02Ch 4    Size of all Subtitle entries in bytes plus 10h         ;
   8682   030h ..   Subtitle entries                                       ;/
   8683   ...  ..   Zeropadding to 800h-byte boundary                      ;-padding
   8684 Subtitle entries:
   8685   000h 4    Offset from current subtitle to next subtitle (or 0=Last subtitle)
   8686   004h 4    First Frame number when to display the subtitle?
   8687   008h 4    Number of frames when to display the subtitle?
   8688   00Ch 4    Zero
   8689   010h ..   Text string, terminated by 00h
   8690   ...  ..   Zeropadding to 4-byte boundary
   8691 The text strings are ASCII, with special 2-byte codes (80h,7Bh=Linebreak,
   8692 1Fh,20h=u-Umlaut, etc).
   8693 
   8694  ________________________ Customized STR Video Headers ________________________
   8695 
   8696 Viewpoint (with slightly modified STR header)
   8697   008h 4    Frame number (0=First)                      ;<-- instead of 1=First
   8698   01Ch 2    Unknown (always D351h)                      ;<-- instead of zero
   8699   01Eh 2    Number of Frames in this STR file           ;<-- instead of zero
   8700 
   8701 Capcom games
   8702 Resident Evil 2 (ZMOVIE\*.STR, PL0\ZMOVIE\*.STR)
   8703 Super Puzzle Fighter II Turbo (STR/CAPCOM15.STR)
   8704   01Ch 4    Sector number of 1st sector of current frame  ;<-- instead of zero
   8705 
   8706 Chrono Cross Disc 2 Video
   8707 Chrono Cross Disc 1 does have normal STR headers, but Disc 2 has Type.bit8
   8708 toggled:
   8709   002h 2    STR Type (8101h=Disc 2)                       ;<-- instead of 8001h
   8710 And, the Chrono Cross "final movie" does reportedly have "additional
   8711 properties". Unknown, what that means, it does probably refer to the last movie
   8712 on Chrono Cross Disc 2, which is quite huge (90Mbyte), and has lower resolution
   8713 (160x112), and might have whatever "additional properties"?
   8714 
   8715 Need for Speed 3
   8716 Need for Speed 3 Hot Pursuit (MOVIES\*.XA, contains videos, not raw XA-ADPCM)
   8717 Jackie Chan Stuntmaster (FE\MOVIES\*.STR)
   8718 With slightly modified STR headers:
   8719   014h 4    Number of Frames (..excluding last some frames?) ;-instead BS[0..3]
   8720   018h 4    Unlike the above modified entry, this is normal  ;-copy of BS[4..7]
   8721 
   8722 ReBoot (MOVIES\*.WXA)
   8723 This has leading XA-ADPCM, and customized STR header:
   8724   014h 2    Type (0000h=Normal, 01FFh=Empty frames at end of video)
   8725   016h 2    Number of Frames (excluding empty ones at end of video)
   8726   018h 8    Zerofilled
   8727 
   8728 Gran Turismo 1 (230Mbyte STREAM.DAT) and Gran Turismo 2 (330Mbyte STREAM.DAT)
   8729 These two games use BS iki format, and (unlike other iki videos) also special
   8730 STR headers:
   8731   002h 2    STR Type (5349h) ("IS")         ;-special (instead 8001h)
   8732   010h 2    Total number of frames in video ;-special (instead width)
   8733   012h 2    Flags (bit15=1st, bit14=last)   ;-special (instead height)
   8734   014h 8    Zero                            ;-special (instead BS header copy)
   8735   020h 7E0h Data (in BS iki format)         ;-BS iki header (with width/height)
   8736 Caution: The STR header values aren't constant throughout the frame:
   8737   Namely, flags in [012h] are toggled on first/last sector of each frame,
   8738   and of course [04h] does also increase per sector.
   8739 
   8740 PGA Tour 96, 97, 98 (VIDEO\..\*.XA and ZZBUFFER\*.STR)
   8741 Used by all movies in PGA Tour 96, 97 (and for the ZZBUFFER\BIGSPY.STR dummy
   8742 padding movie in PGA Tour 98).
   8743 The videos have normal BS v2 data, but the Frame Size entry is 8 smaller than
   8744 usually. As workaround, always load [0Ch]+8 for all movies with standard STR
   8745 headers (unless that would exceed [06h]*7E0h).
   8746   00Ch 4    Frame Size-8 (ie. excluding 8-byte BS header)  ;instead of Size-0
   8747 The padding videos in ZZBUFFER folder have additional oddities in STR header:
   8748   ZZBUFFER\SPY256.STR    [14h..1Fh]=normal copy of 8-byte BS v2 header and zero
   8749   ZZBUFFER\SPYGLASS.STR  [14h..1Fh]=zerofilled                          ;\BS v1
   8750   ZZBUFFER\SPYTEST.STR   [14h..1Fh]=00 00 10 00 00 00 00 09 00 00 07 EE ;/
   8751   ZZBUFFER\BIGSPY.STR    Used in PGA Tour 98 (instead of above three files)
   8752 SPYTEST.STR has nonsense quant values exceeding the 0000h..003Fh range (first
   8753 frame has quant=00B1h, and later frames go as high as quant=FFxxh, that kind of
   8754 junk is probably unrelated to BS fraquant). The oddities for SPYTEST.STR do
   8755 also occur in some frames in PGA Tour 98 BIGSPY.STR. Anyways, those ZZBUFFER
   8756 files seem to be only unused padding files.
   8757 
   8758 Alice in Cyber Land (*.STR)
   8759 Note: First sector contains XA-ADPCM audio (video starts in 2nd sector).
   8760  STR Sector Header:
   8761   002h 2    STR Type (0000h=Alice in Cyber Land video)            ;-special
   8762   008h 4    Frame number (1=First) (bit15 set in last frame, or FFFFh)
   8763   010h 10h  Zerofilled (instead width/height and BS header copy)  ;-special
   8764   020h 7E0h Data (in BS v2 format)
   8765 Frames are always 320x240.
   8766 The frame number of the last used frame of a movie has the bit15 set. After
   8767 that last frame, there are some empty frame(s) with frame number FFFFh.
   8768 For some reason there are "extra audio sectors in between movies" (uh?).
   8769 Many of the movies have a variable frame rate. All movies contain frames
   8770 sequences that match one of the following frame rates: 7.5 fps, 10 fps, 15 fps,
   8771 30 fps.
   8772 
   8773 Encrypted iki (Panekit - Infinitive Crafting Toy Case)
   8774   014h 8    Copy of decrypted BS header (instead of encrypted BS header)
   8775 
   8776 Princess Maker: Yumemiru Yousei (PM3.STR)
   8777 Parappa (Japanese Demo version only) (S0/GUIDE.STR)
   8778 These files do have BS ID=3000h (except, the first and last some frames have
   8779 nromal ID=3800h). The STR header is quite normal (apart from reflecting the odd
   8780 BS ID):
   8781   016h 2    Copy of BS ID, 3000h in most frames (instead of 3800h)
   8782   020h 7E0h Data (in BS format, also with BS ID 3000h, instead of 3800h)
   8783 
   8784 Starblade Alpha and Galaxian 3
   8785 These movies have Extra stuff in the data section. The STR header is quite
   8786 normal (apart from reflecting the Extra stuff):
   8787   00Ch 4    Frame Size in bytes (=size of ExtraHeader + BsData + ExtraData)
   8788   014h 4    Copy of Extra Header        ;instead of BS[0..3]
   8789   018h 4    Copy of BS[0..3]            ;instead of BS[4..7]
   8790   020h 7E0h Data (ExtraHeader + BsData + ExtraData)
   8791 The data part looks as so:
   8792   000h 2    Size of BS Data area    (S1)        ;\Extra Header
   8793   002h 2    Size of Extra Data area (S2)        ;/
   8794   004h S1   BS Data (in BS v3 format)           ;-BS Data
   8795   ..   S2   Extra Data (unknown purpose)        ;-Extra Data
   8796 Note: Starblade Alpha does use that format for GAMEn.STR and NAME.STR in FLT
   8797 and TEX folders (the other movies in that game are in normal STR format).
   8798 
   8799 Largo Winch: Commando SAR (FMV\NSPIN_W.RNG)
   8800 This is a somewhat "normal" movie, without audio, and with the STR headers
   8801 moved to the begin of the file:
   8802   000h Nx20h   STR Headers  ;size = filesize/800h*20h
   8803   ...  Nx7E0h  Data         ;size = filesize/800h*7E0h
   8804 Note: The movie contains the rotating "W" logo, which is looped in Start
   8805 screen.
   8806 
   8807 Player Manager (1996, Anco Software) (FILMS\1..3\*.STR)
   8808   006h 2    Number of Sectors in this Frame-1 (8..9 = 9..10 sectors)
   8809   00Ch 4    Frame Size in bytes               (8..9*7E0h = 3F00h or 46E0h)
   8810   010h 2    Bitmap Width                      (always F0h)
   8811   012h 2    Bitmap Width                      (always 50h)
   8812   014h 0Ch  Zerofilled (instead copy of BS header or copy of Extra header)
   8813   020h 7E0h Data (Extra Stuff, BS v2 data, plus Unused stuff)
   8814 The data part occupies 9-10 sectors, consisting of:
   8815   0000h Extra Stuff   (7E0h bytes, whatever, often starts with 00,FF,00,FF,..)
   8816   07E0h BS v2 data    (3720h or 3F00h bytes, including FFh-padding)
   8817   ...   Unused Sector (7E0h bytes, same as in previous frame or zerofilled)
   8818 The compressor tries to match the picture quality to the number of sectors per
   8819 frame, but it's accidentally leaving the last sector unused:
   8820   For 9 sectors:  Only 1..7 are used, sector 8 is same as in previous frame
   8821   For 10 sectors: Only 1..8 are used, sector 9 is zerofilled
   8822 Apart from the odd format in FILMS\1..3\*.STR, the game does also have normal
   8823 videos in FILMS\*.STR.
   8824 
   8825 Chiisana Kyojin Microman (DAT\STAGE*\*.MV)
   8826 The .MV files have 5 sectors/frame: Either 5 video sectors without audio, or
   8827 4-5 video sectors plus XA-ADPCM audio (in the latter case, audio is in each 8th
   8828 sector (07h,0Fh,17h,1Fh,etc), hence having filesize rounded up to N*8 sectors):
   8829   Filesize = 800h*((NumberOfFrames*5))             ;5 sectors, no xa-adpcm
   8830   Filesize = 800h*((NumberOfFrames*5+7) AND not 7) ;4-5 sectors, plus xa-adpcm
   8831 Caution: The STR header values aren't constant throughout the frame:
   8832   Sector 0: [10h] = Number of Frames,   [12h]=Junk
   8833   Sector 1: [10h] = Junk,               [12h]=0
   8834   Sector 2: [10h] = Junk,               [12h]=Junk
   8835   Sector 3: [10h] = Junk,               [12h]=Same as below (Bitmap Height)
   8836  Below ONLY when having 5 sectors per frame:
   8837   Sector 4: [10h] = Bitmap Width (140h) [12h]=Bitmap Height (D0h)
   8838  That is, frames with 4 sectors do NOT have any Bitmap Width entry
   8839  (the duplicated Height entry in sector 3 exists, so one could compute
   8840  Width=NumMacroBlocks*100h/Height, or assume fixed Width=320, Height=208).
   8841 The Junk values can be zero, or increase/decrease during the movie, some or all
   8842 of them seem to be sign-expanded from 12bit (eg. increasing values can wrap
   8843 from 07xxh to F8xxh).
   8844 Apart from the odd DAT\STAGE*\*.MV files, the game does also have .STR files
   8845 with normal STR headers and more sectors per frame (DAT\STAGE16,21,27\*.STR,
   8846 DAT\OTHER\*.STR, DAT\OTHER\CM\*.STR, and MAT\DAT\*.STR).
   8847 
   8848 Black Silence padding
   8849 Used by Bugriders: The Race of Kings (MOVIE\*XB.STR)
   8850 Used by Rugrats Studio Tour (MagDemo32: RUGRATS\DATA\OPEN\*B.STR)
   8851   Each movie file is followed by dummy padding file. For example, in Bugriders:
   8852   MOVIE\*XA.STR  Movie clip             (with correct size, 320x192)
   8853   MOVIE\*XB.STR  Black Silence padding  (wrong size 640x192, should be 320x192)
   8854 The names are sorted alphabetically and exist in pairs (eg. CHARMXA.STR and
   8855 CHARMXB.STR), and the disc sectors are following the same sort order.
   8856 The padding files contain only black pixels and silent XA-ADPCM sectors, with
   8857 following unique STR header entries, notably with wrong Width entry (the MDEC
   8858 data contains only 320x192 pixels).
   8859   00Ch 4    Frame Size    (087Ch)
   8860   010h 2    Bitmap Width  (wrongly set to 640, should be 320)
   8861   012h 2    Bitmap Height (192)
   8862   014h 2    MDEC Size     (05A0h)
   8863   016h 2    BS ID         (3800h)
   8864   018h 2    BS Quant      (0001h)
   8865   01Ah 2    BS Version    (0002h)
   8866   Filesize is always 44Fh sectors (about 2.2Mbyte per *XB.STR file)
   8867 The huge 7 second padding is a very crude way to avoid the next movie to be
   8868 played when not immediately pausing the CDROM at end of current movie.
   8869 
   8870 Ridge Racer Type 4 (only PAL version) (R4.STR)
   8871 The 570Mbyte R4.STR file contains XA-ADPCM in first three quarters, and two STR
   8872 movies in last quarter:
   8873   1st NTSC/US movie: 320x160 pix, 0F61h frames, 4-5 sectors/frame, normal STR
   8874   1st PAL/EUR movie: 320x176 pix, 0CD0h frames, 5-6 sectors/frame, special STR
   8875   2nd NTSC/US movie: 320x160 pix, 1D6Ah frames, 4-5 sectors/frame, normal STR
   8876   2nd PAL/EUR movie: 320x160 pix, 18B5h frames, 5-6 sectors/frame, normal STR
   8877 As seen above, the PAL movies have lower framerate. And, the 1st PAL movie has
   8878 higher resolution, plus some other customized STR header entries:
   8879   002h 2    STR Type (0001h=Custom, 176pix PAL video)         ;instead of 8001h
   8880   006h 2    Number of Sectors in this Frame (always 5..6)
   8881   00Ch 4    Frame Size (always 2760h or 2F40h, aka 7E0h*5..6)
   8882   012h 2    Bitmap Height (00B0h, aka 176 pixels)             ;instead of 00A0h
   8883   014h 8    Zerofilled                                        ;instead BS[0..7]
   8884   020h 7E0h Data (in BS v3 format, plus FFh-padding)
   8885 That is, the special video is standard MDEC, the only problem is detecting it
   8886 as such (despite of the custom STR Type entry).
   8887 
   8888 Mat Hoffman's Pro BMX (MagDemo48: MHPB\SHORT.STR)
   8889 This contains a normal MDEC movie, but with distorted "garbage" in first and
   8890 last some sectors.
   8891   1st sector          STR Type 5673h (Leading Dummy)                ;\
   8892   2nd sector          STR Type 8001h (distorted/empty MDEC)         ; junk
   8893   3rd..6th sector     STR Type 8001h (distorted/garbage MDEC)       ;/
   8894   7th sector and up   STR Type 8001h (normal MDEC, with odd [01Ch]) ;-movie
   8895   Last 96h sectors    STR Type 0078h (Ending Dummy)                 ;-junk
   8896 1st Sector:
   8897   002h 2    STR Type (5673h=Leading Dummy)
   8898   004h 4    Whatever (0004000Ch)
   8899   008h 4    Whatever (0098967Fh)
   8900   00Ch 4    Frame Size (always 100h)
   8901   010h 7F0h EAh-filled
   8902 2nd Sector:
   8903   002h 2    STR Type (8001h=Normal MDEC ID, but content is empty)
   8904   004h 4    Whatever (0004000Ch)        ;\
   8905   008h 4    Whatever (0098967Fh)        ; same as in 1st sector
   8906   00Ch 4    Frame Size (always 100h)    ; (but ID at [002h] differes)
   8907   010h 7F0h EAh-filled                  ;/
   8908 3rd-6th Sector:
   8909   002h 2    STR Type (8001h=Normal MDEC ID, but content is distorted)
   8910   004h 2    Sector number within current Frame (always 0)
   8911   006h 2    Number of Sectors in this Frame (always 1)
   8912   008h 4    Frame number (increasing, 1..4 for 3rd..6th sector)
   8913   00Ch 4    Frame Size (always 7D0h)
   8914   010h 10h  EAh-filled
   8915   020h 7D0h Unknown (random/garbage?)
   8916   7F0h 10h  EAh-filled
   8917 7th Sector and up (almost standard MDEC):
   8918  Caution: The STR header values aren't constant throughout the frame:
   8919  Entry entry [01Ch] is incremented per sector (or wraps to 0 in new section).
   8920   01Ch 4    Increasing sector number (within current movie section or so)
   8921 Last 96h Sectors:
   8922   002h 2    STR Type (0078h=Ending Dummy)
   8923   004h 2    Sector number within current Frame (always 0)
   8924   006h 2    Number of Sectors in this Frame (always 1)
   8925   008h 4    Frame number (increasing, in last 96h sectors)
   8926   00Ch 4    Frame Size (always 20h)
   8927   010h 2    Bitmap Width  (always 40h)
   8928   012h 2    Bitmap Height (always 40h)
   8929   014h 7ECh Zerofilled
   8930 
   8931 Final Fantasy VII (FF7) (MOVIE\*.MOV and MOVIE\*.STR)
   8932 These movies have Extra stuff in the data section. The STR header is quite
   8933 normal (apart from reflecting the Extra stuff):
   8934   00Ch 4    Frame Size in bytes (including 28h-byte extra stuff)
   8935   014h 8    Copy of Extra data [0..7]           :-instead of BS header[0..7]
   8936   020h 7E0h Data (ExtraData + BsData)
   8937 The data part looks as so:
   8938   000h 28h  Extra data (unknown purpose, reportedly "Camera data" ... whut?)
   8939   028h ..   BS Data (in BS v1 format)
   8940 
   8941 Final Fantasy IX (FF9) (*.STR and *.MBG)
   8942 There are several customized STR header entries:
   8943   002h 2    STR Type (0004h=FF9/Video)                      ;instead of 8001h
   8944   004h 2    Sector number within current Frame (02h..num-1) (2..9 for video)
   8945   006h 2    Total number of Audio+Video sectors in this frame (always 0Ah)
   8946   00Ch 4    Frame Size/4 (of BS data, excluding MBG extra)  ;instead of Size/1
   8947   014h 8    Copy of BS[0..7] from 8th video sector          ;instead 1st sector
   8948   01Ch 2    Usually 0000h (or 0004h in some MBG sectors)    ;inszead of 0000h
   8949   01Eh 2    Usually 0000h (or 3xxxh in some MBG sectors)    ;inszead of 0000h
   8950   020h 8F4h Data (in BS v2 format, plus MBG extra data, if any)
   8951 Caution: The STR header values aren't constant throughout the frame:
   8952   Namely, entry [1Ch..1Fh]=nonzero occurs only on the sector that does contain
   8953   the end of BS data (=and begin of MBG extra data), and of course [04h] does
   8954   also increase per sector.
   8955 Sector ordering has BS data snippets arranged backwards, for example, if BS
   8956 data does occupy 2.5 sectors:
   8957   [04h]=00h-01h 1st-2nd audio sector, SPU-ADPCM (see Audio streaming chapter)
   8958   [04h]=02h-06h 1st-5th video sector, unused, [020h..913h] is FFh-filled
   8959   [04h]=07h     6th video sector, contains end of BS data and MBG extra, if any
   8960   [04h]=08h     7th video sector, contains middle of BS data
   8961   [04h]=09h     8th video sector, contains begin of BS data
   8962 Sector type/size, very unusually with FORM2 sectors:
   8963   Audio sectors are MODE2/FORM1 (800h bytes, with error correction)
   8964   Video sectors are MODE2/FORM2 (914h bytes, without error correction)
   8965 Huffman codes are standard BS v2, with one odd exception: MDEC 001Eh/03E1h
   8966 (run=0, level=+/-1Eh) should be usually encoded as 15bit Huffman codes, FF9 is
   8967 doing that for 001Eh, but 03E1h is instead encoded as 22bit Escape code:
   8968   000000000100010         MDEC=001Eh (run=0, level=+1Eh) ;-normal (used)
   8969   000000000100011         MDEC=03E1h (run=0, level=-1Eh) ;-normal (not used)
   8970   0000010000001111100001  MDEC=03E1h (run=0, level=-1Eh) ;-escape (used)
   8971 There are two movie variants: *.STR and *.MBG. Most MBG files (except
   8972 SEQ02\MBG102.MBG) contain extra MBG info in [01Ch..01Fh] and extra MBG data
   8973 appended after the BS data. If present, the appended MBG data is
   8974 often/always(?) just these 28h-bytes:
   8975   FF FF FF FF FE FF FE 41 AD AD AD AD AD AD AD AD
   8976   AD AD AD AD AD AD AD AD AD AD AD AD AD AD AD AD
   8977   AD AD AD AD AD AD AD AD
   8978   (followed by FF's, which might be padding, or part of the extra data)
   8979 Unknown if some sectors contain more/other MBG data, perhaps compressed BG
   8980 pixel-depth values for drawing OBJs in front/behind BG pixels?
   8981 
   8982  _______________________ Non-standard STR Video Headers _______________________
   8983 
   8984 Final Fantasy VIII (FF8)
   8985 Video frames are always 320x224. The video frames are preceeded by two
   8986 SPU-ADPCM audio sectors.
   8987   000h 4    ID "SMJ",01h=Video
   8988   004h 1    Sector number within current Frame (02h..num-1) (2..9 for video)
   8989   005h 1    Total number of Audio+Video sectors in this frame, minus 1 (9)
   8990   006h 2    Frame number (0=First)
   8991   008h 7F8h Data (in BS v2 format)
   8992 
   8993 Ace Combat 3 Electrosphere (in 520Mbyte ACE.SPH/SPB archive)
   8994 The videos start with one XA-ADPCM sector, followed by the first Video sector.
   8995  STR Sector Header:
   8996   000h 1    Always 01h
   8997   001h 1    Sector number within current Frame (00h..num-1) (8bit)
   8998   002h 2    Number of Sectors in this Frame
   8999   004h 2    Unknown (1 or 3)
   9000   006h 2    Frame number (decreasing, 0=Last)
   9001   008h 2    Bitmap Width in pixels    ;\130hxE0h or 140hxB0h or 80hx60h
   9002   00Ah 2    Bitmap Height in pixels   ;/
   9003   00Ch 4    Zero
   9004   010h 2    Zero, or decreasing timer (decreases approx every 2 sectors)
   9005   012h 2    Zero, or decreasing timer (decreases approx every 1 sector)
   9006   014h 3    Zero
   9007   017h 1    Zero, or increases with step 2 every some hundred sectors
   9008   018h 2    Zero, or Timer (increments when [1Ah] wraps from 04h to 01h)
   9009   01Ah 1    Zero, or Timer (increments when [1Bh] wraps from 5Fh to 00h]
   9010   01Bh 1    Zero, or Timer (increments approx every 1 sector)
   9011   01Ch 2    Zero, or Whatever (changes to whatever every many hundred sectors)
   9012   01Eh 2    Zero, or 0204h
   9013   020h 7E0h Data (in BS v3 format)
   9014 Caution: The STR header values aren't constant throughout the frame:
   9015   Namely, entry [10h..1Fh] can change within the frame (happens in japanese
   9016   version), and of course [01h] does also increase per sector.
   9017 The Japanese version may be the only game that has two streaming videos running
   9018 in parallel on different channels.
   9019 That means, non-japanese version is different...?
   9020 
   9021 Judge Dredd (1998, Gremlin) (CUTS\*.IXA and LEVELS\*\*.IXA)
   9022 This is a lightgun-game with "interactive movies". The gameplay consists of
   9023 running on a fixed path through a scene with pre-recorded background graphics,
   9024 the only player interaction is aiming the gun at other people that show up in
   9025 that movie scene. There are two movie types:
   9026   LEVELS\*\*.IXA  - Interactive gameplay movies
   9027   CUTS\*.IXA      - Non-interactive cut-scene movies
   9028 Both CUTS and LEVELS have unusually small 4-byte STR headers:
   9029   000h 4    Sector number within current Frame (LEVELS=0..8, or CUTS=0..9)
   9030   004h 7FCh Data (see below)
   9031 Data for CUTS is 320x240pix (10 sectors per frame):
   9032   Note: CUTS videos have 2 leading XA-ADPCM sectors
   9033   000h ..   BS Data (in BS v2/v3 format)                        ;-BS picture
   9034 Data for LEVELS is 320x352pix plus extra stuff (9 sectors per frame):
   9035   Note: LEVELS videos have 1 leading XA-ADPCM sector
   9036   000h 4    Offset to BS Data (always 28h)                      ;\
   9037   004h 4*6  Offsets to Extra Stuff 1..6                         ; extra header
   9038   01Ch 0Ch  Zerofilled                                          ;/
   9039   028h ..   BS Data (in BS v2/v3 format)                        ;-BS picture
   9040   ...  ..   Extra Stuff 1..6                                    ;-extra data
   9041 The unusual 320x352pix resoltution contains a 320x240pix BG image, with
   9042 additional 320x112pix texture data appended at the bottom.
   9043 Extra Stuff 1..6 does supposedly contain info for animating enemies and/or
   9044 backgrounds.
   9045 
   9046 ______________________________________________________________________________
   9047 
   9048 iki
   9049 The .iki video format (found in files with .IKI or .IK2 extension) is used in
   9050 several games made by Sony. iki movie sectors have some different properties:
   9051   * There are only as many iki video sectors as needed to hold all the
   9052     frame's data. Remaining sectors are null.
   9053   * The first sector's Submode.Channel starts at zero, then increments for
   9054     each sector after that, and resets to zero after an audio sector.
   9055   * IK2 videos can also have variable frame rates that are very inconsistent.
   9056 
   9057 CDROM File Video Streaming Framerate
   9058 ------------------------------------
   9059 
   9060 According to Sony, BS encoded 320x240pix videos can be played at 30fps (with
   9061 cdrom running at double speed).
   9062 
   9063 STR Frame Rate
   9064 As a general rule, the frame rate is implied in CDROM rotation speed (150 or 75
   9065 sectors per second, minus the audio sectors, divided by the number of sectors
   9066 per video frame).
   9067 
   9068 Fixed/Variable Framerates
   9069 The frame can drop on video frames that contain more sectors than usually.
   9070 Video frames that require fewer sectors than often padded with zerofilled
   9071 sectors. However, some games don't have that padding, so they could end up
   9072 reeceiving up to 150 single-sector frames per second; the actual framerate is
   9073 supposedly slowed down to 60Hz or less via Vblank timer (and with the CDROM
   9074 reading getting paused when the read-ahead buffer gets full).
   9075 
   9076 Audio Samplerate
   9077 XA-ADPCM audio contains samplerate info (in the FORM2 subheader), the
   9078 samplerate versus amount of audio sectors can be used to compute the CDROM
   9079 rotation speed.
   9080 There are two exceptions: Some movies don't have any audio at all, and some
   9081 movies use SPU-ADPCM instead of XA-ADPCM. In the latter case, the SPU Pitch
   9082 (samplerate) may (or may not) be found somewhere in the audio sector headers.
   9083 
   9084 CDROM Rotation speed
   9085 As said above, the speed can be often detected via audio sample rate.
   9086 Otherwise, the general rule is that most PSX games are used 2x speed (150
   9087 sectors/second). But, there are a few games with 1x speed (see below).
   9088 
   9089 CDROM Single speed (75 sectors/frame)
   9090 Here are probably most of the USA games with videos at 1x speed.
   9091   007 - The World Is Not Enough
   9092   1Xtreme
   9093   Arcade Party Pak
   9094   Atari Anniversary Edition Redux
   9095   Blast Radius
   9096   Blue's Clues - Blue's Big Musical
   9097   Chessmaster II
   9098   Chronicles of the Sword
   9099   Civilization II
   9100   Colin McRae Rally
   9101   Creatures - Raised in Space
   9102   Cyberia
   9103   Demolition Racer
   9104   Dune 2000
   9105   ESPN Extreme Games
   9106   FIFA Soccer 97
   9107   Fade to Black
   9108   Family Connection - A Guide to Lightspan
   9109   Fear Effect
   9110   Fox Hunt
   9111   Interactive CD Sampler Volume 1
   9112   Jade Cocoon - Story of the Tamamayu
   9113   Jeopardy! 2nd Edition
   9114   Juggernaut
   9115   Krazy Ivan
   9116   MTV Sports - Skateboarding featuring Andy Macdonald
   9117   MTV Sports - T.J. Lavin's Ultimate BMX
   9118   Medal of Honor
   9119   Medal of Honor - Underground
   9120   Official U.S. PlayStation Magazine Demo Disc 23
   9121   Planet of the Apes
   9122   PlayStation Underground Number 2
   9123   Shockwave Assault
   9124   Starblade Alpha
   9125   Starwinder - The Ultimate Space Race
   9126   Str.at.e.s. 1 - Match-A-Batch
   9127   Str.at.e.s. 5 - Parallel Lives!
   9128   Str.at.e.s. 7 - Riddle Roundup!
   9129   The X-Files
   9130   Top Gun - Fire at Will!
   9131   Um Jammer Lammy
   9132   Uprising X
   9133   Wheel of Fortune - 2nd Edition
   9134   Williams Arcade's Greatest Hits
   9135 
   9136 CDROM File Video Streaming Audio
   9137 --------------------------------
   9138 
   9139 Audio Stream
   9140 STR movies are usually interleaved with XA-ADPCM sectors (the audio sectors are
   9141 automatically decoded by the CDROM hardware and consist of raw ADPCM data
   9142 without STR headers).
   9143 --> CDROM File Audio Streaming XA-ADPCM
   9144 However, there are also movies without audio. And a few movies with SPU-ADPCM
   9145 audio.
   9146 
   9147 SPU-ADPCM in Chunk-based formats
   9148 --> CDROM File Video Streaming Chunk-based formats
   9149 
   9150 SPU-ADPCM in Chrono Cross/Legend of Mana Audio Sector
   9151 Chrono Cross Disc 1 (HiddenDirectory\1793h..17A6h)
   9152 Chrono Cross Disc 2 (HiddenDirectory\1793h..179Dh)
   9153 Legend of Mana (MOVIE\*.STR, except some movies without audio)
   9154   000h 2    STR ID   (0160h)
   9155   002h 2    STR Type (0000h, 0001h, 0100h, or 0101h)
   9156               0000h=Legend of Mana, Audio normal sectors
   9157               0001h=Legend of Mana, Audio sectors near end of movie
   9158               0000h=Chrono Cross Disc 1, Audio.left?
   9159               0001h=Chrono Cross Disc 1, Audio.right?
   9160               0100h=Chrono Cross Disc 2, Audio.left?
   9161               0101h=Chrono Cross Disc 2, Audio.right?
   9162   004h 2    Sector number in Frame (0=Audio.left?, 1=Audio.right?)
   9163   006h 2    Number of Audio sectors in this frame (always 2)
   9164   008h 4    Frame number (1=First)
   9165   00Ch 4    Unused (Chrono: FFh-filled or Mana: 00000FC0h=2x7E0h=Framesize?)
   9166   010h 10h  Unused (Chrono: FFh-filled or Mana: 00h-filled)
   9167   020h 60h  Unused (FFh-filled)
   9168   080h 4    ID "AKAO"
   9169   084h 4    Frame number (0=First)
   9170   088h 8    Unused (zerofilled)
   9171   090h 4    Remaining Time (step 690h) (can get stuck at 0340h or 0B20h at end)
   9172   094h 4    Zero
   9173   098h 4    Unknown (11h)
   9174   09Ch 4    Pitch (1000h=44100Hz)
   9175   0A0h 4    Number of bytes of audio data (always 690h)
   9176   0A4h 2Ch  Unused (zerofilled)
   9177   0D0h 690h Audio  (10h-byte SPU-ADPCM blocks) (1680 bytes)
   9178   760h A0h  Unused (10h-byte SPU-ADPCM blocks with flag=03h and other bytes=0)
   9179 Note: The Chrono/Mana STR files start with Audio frames in first sector
   9180 (except, some Legend of Mana movies don't have any Audio, and do start with
   9181 Video frames).
   9182 
   9183 SPU-ADPCM in Final Fantasy VIII (FF8)
   9184   000h 4    ID "SMN",01h=Audio/left, "SMR",01h=Audio/right
   9185   004h 1    Sector number in Frame (0=Audio.left, 1=Audio.right)
   9186   005h 1    Total number of Audio+Video sectors in this frame, minus 1 (1 or 9)
   9187   006h 2    Frame number (0=First)
   9188   008h E8h  Unknown (camera data?) (232 bytes)
   9189   0F0h 6    Audio ID (usually "MORIYA", sometimes "SHUN.M")
   9190   0F6h 0Ah  Unknown (10 bytes) (reportedly 10 bytes at offset 250 = FAh ?????)
   9191   100h 4    ID "AKAO"
   9192   104h 4    Frame number (0=First)
   9193   108h 14h  Unknown (20 bytes)
   9194   11Ch 4    Pitch (1000h=44100Hz)
   9195   120h 4    Number of bytes of audio data (always 690h)
   9196   124h 2Ch  Unknown (44 bytes)
   9197   150h 20h  Unknown (32 bytes)
   9198   170h 690h SPU-ADPCM Audio data (690h bytes)
   9199 There is one special case on disc 1: a movie with no video. Each 'frame'
   9200 consists of two sectors: the first is the left audio channel, the second is the
   9201 right audio channel.
   9202 
   9203 SPU-ADPCM in Final Fantasy IX (FF9) (*.STR and *.MBG)
   9204 The FF9 audio sectors are normal MODE2/FORM1 sectors (unlike the FF9 video
   9205 sectors, which are MODE2/FORM2).
   9206   000h 2    STR ID   (0160h)
   9207   002h 2    STR Type (0008h=FF9/Audio)
   9208   004h 2    Sector number in Frame (0=Audio.left, 1=Audio.right)
   9209   006h 2    Total number of Audio+Video sectors in this frame (always 0Ah)
   9210   008h 4    Frame number (1=First)
   9211   00Ch 4    Zero
   9212   010h 1    Audio flag? (00h=No Audio, 01h=Audio)
   9213   011h 4Fh  Zerofilled --- XXX or whatever (when above is 00h)
   9214   060h 4    Number of Frames in this STR file
   9215   064h 1Ch  EEh-filled
   9216  Below 780h bytes are all zerofilled when [10h]=00h (no audio)
   9217  Below 780h bytes are reportedly all ABh-filled "in the last frame of a movie
   9218  on Disc 4" (unknown which movie, and if that occurs in other movies, too)
   9219   080h 4    ID "AKAO"
   9220   084h 4    Frame number (0=First)
   9221   088h 14h  Unknown (20 bytes)
   9222   09Ch 4    Pitch (116Ah=48000Hz) (or 1000h=44100Hz in final movie)
   9223   0A0h 4    Number of bytes of audio data (0, 720h, 730h, or 690h=final movie)
   9224   0A4h 2Ch  Unknown (44 bytes)
   9225   0D0h 730h SPU-ADPCM audio (plus leftover/padding when less than 730h bytes)
   9226 
   9227 Dance series SPU-ADPCM streaming (bigben interactive, DATA.PAK\stream\*.str)
   9228 This format is used for raw SPU-ADPCM streaming (without video).
   9229 SLES-04121 Dance: UK
   9230 SLES-04161 Dance: UK eXtra TraX
   9231 SLES-04129 Dance Europe
   9232 SLES-04162 All Music Dance! (Italy)
   9233   000h 2    STR ID   (0160h)
   9234   002h 2    STR Type (8001h, same as MDEC)
   9235   004h 2    Sector number within current Frame (0000h..num-1)
   9236   006h 2    Number of Sectors in this Frame (always 9)
   9237   008h 4    Frame number (0=First)
   9238   00Ch 4    Frame Size in bytes (always 4000h)
   9239   010h 4    Whatever (always 00A000A0h, would be width/height if it were video)
   9240   014h 8    Zerofilled
   9241   01Ch 4    Special ID (always DDCCBBAAh for Dance audio)
   9242   020h 7E0h Data (in SPU-ADPCM format, mono, 22200Hz aka Pitch=07F5h)
   9243 Note: Sector 0..8 contain 9*7E0h=46E0h bytes data per frame, but only 4000h
   9244 bytes are used (the last 6E0h bytes in sector 8 are same as in sector 7).
   9245 
   9246 Raw SPU-ADPCM Streaming
   9247 Some games are using raw SPU-ADPCM for streaming. That is, the file is
   9248 basically a normal .VB file, but it can be dozens of megabytes tall (ie. too
   9249 large to be loaded into RAM all at once).
   9250   Disney's The Emperor's New Groove (MagDemo39: ENG\STREAM\*.CVS)
   9251   Disney's Aladdin in Nasira's Revenge (MagDemo46: ALADDIN\STREAM\*.CVS)
   9252 
   9253 CDROM File Video Streaming Chunk-based formats
   9254 ----------------------------------------------
   9255 
   9256 Newer Electronic Arts videos (EA)
   9257 EA videos are chunk based (instead of using 20h-byte .STR headers). The next
   9258 chunk starts right at the end of the previous chunk (without padding to sector
   9259 boundaries).
   9260  STR Sector Header:
   9261   No STR Sector header (first sector starts directly with "VLC0" chunk)
   9262  VLC0 Chunk (at begin of movie file):
   9263   000h 4     Chunk ID "VLC0"
   9264   004h 4     Chunk Size (always 1C8h)     (big-endian)
   9265   008h 1C0h  16bit MDEC values for E0h huffman AC codes (little-endian)
   9266  MDEC Chunks (video frames):
   9267   000h 4     Chunk ID "MDEC"                           ;\
   9268   004h 4     Chunk Size (...)             (big-endian) ; custom chunk header,
   9269   008h 2     Bitmap Width in pixels       (big-endian) ; instead of STR header
   9270   00Ah 2     Bitmap Height in pixels      (big-endian) ;
   9271   00Ch 4     Frame Number (starting at 0) (big-endian) ;/
   9272   010h ..    Data (in BS v2 format, but using custom Huffman codes from VLC0)
   9273   ...  ..    Zeropadding to 4-byte boundary
   9274  Audio Chunks (au00/au01):
   9275   000h 4     Chunk ID ("au00"=normal, "au01"=last audio chunk)
   9276   004h 4     Chunk Size (...)                                   (big-endian)
   9277   008h 4     Total number of 2x4bit samples in previous chunks  (big-endian)
   9278   00Ch 2     Unknown (always 800h) (maybe Pitch: 800h=22050Hz)  (big-endian)
   9279   00Eh 2     Unknown (always 200h)                              (big-endian)
   9280   ...  ..    SPU-ADPCM audio data, left  (0Fh bytes per sample block)
   9281   ...  ..    SPU-ADPCM audio data, right (0Fh bytes per sample block)
   9282   ...  ..    Garbagepadding to 4-byte boundary
   9283   Note: SPU-ADPCM does normally have 10h-byte blocks, but in this case,
   9284   the 2nd byte (with loop flags) is omitted, hence only 0Fh-byte blocks.
   9285  Zero Chunk (zeropadding at end of file, exists only in some EA videos):
   9286   000h ..    Zeropadding
   9287 
   9288 Older Electronic Arts videos
   9289 Crusader: No Remorse (1996 Origin Systems) (MOVIES\*.STR)
   9290 Soviet Strike (1996 Electronic Arts)
   9291 Battle Stations (1997 Electronic Arts)
   9292 Andretti Racing (1996 Electronic Arts)
   9293  STR Sector Header:
   9294   000h 4    ID (DDCCBBAAh) (aka AABBCCDDh big-endian)
   9295   004h 4    Sector number within STR file (0=First, up to Filesize/800h-1)
   9296   008h 7F8h Data (video and audio chunks, see below) (first chunk is "ad20")
   9297  Video Chunks (MDEC):
   9298   000h 4    Chunk ID "MDEC"                           ;\
   9299   004h 4    Chunk Size (...)             (big-endian) ;
   9300   008h 2    Bitmap Width in pixels       (big-endian) ; custom chunk header
   9301   00Ah 2    Bitmap Height in pixels      (big-endian) ;
   9302   00Ch 4    Frame Number (starting at 0) (big-endian) ;/
   9303   010h ..   Data (in BS v2 format)                    ;-standard BS v2 data
   9304  Audio Chunks (ad20/ad21) (22050Hz stereo):
   9305   000h 4    Chunk ID ("ad20"=normal, "ad21"=last audio chunk)
   9306   004h 4    Chunk Size (1A50h or 1A70h)                        (big-endian)
   9307   008h 4    Total number of 2x4bit samples in previous chunks  (big-endian)
   9308   00Ch 2    Unknown (always 800h) (maybe Pitch: 800h=22050Hz)  (big-endian)
   9309   00Eh 2    Unknown (always 200h)                              (big-endian)
   9310   010h ..   SPU-ADPCM audio data, left  (10h bytes per sample block)
   9311   ...  ..   SPU-ADPCM audio data, right (10h bytes per sample block)
   9312  Last STR Sector:
   9313   000h 18h  FFh-filled (aka 8-byte STR header and 10h-byte Chunk header)
   9314   018h -    Nothing (total STR filesize is N*800h+18h bytes)
   9315 
   9316 Oldest Electronic Arts videos
   9317 Wing Commander III: Heart of the Tiger (MOVIES1.LIB\*.wve) (1995, EA/Origin)
   9318  STR Sector Header:
   9319   No STR Sector header (first sector starts directly with "Ad10" chunk)
   9320  Video Chunks (MDEC):
   9321   000h 4    Chunk ID "MDEC"                           ;\
   9322   004h 4    Chunk Size (2xx0h)           (big-endian) ;
   9323   008h 2    Bitmap Width in pixels       (big-endian) ; custom chunk header
   9324   00Ah 2    Bitmap Height in pixels      (big-endian) ;
   9325   00Ch 2    Unknown (7FFFh)              (big-endian) ;
   9326   00Eh 2    Unknown (AD14h or AD24h)     (big-endian) ;/
   9327   010h ..   Data (in BS v2 format)                    ;-standard BS v2 data
   9328   ...  ..   Padding, up to circa 20h bytes, FFh-filled
   9329  Audio Chunks (Ad10/Ad11) (22050Hz stereo):
   9330   000h 4    Chunk ID ("ad20"=normal, "ad21"=last audio chunk)
   9331   004h 4    Chunk Size (D38h or D28h) (or less in last chunk)  (big-endian)
   9332   010h ..   SPU-ADPCM audio data, left  ? (10h bytes per sample block)
   9333   ...  ..   SPU-ADPCM audio data, right ? (10h bytes per sample block)
   9334 Audio seems to be 22050Hz stereo, however, chunks with size=D38h have odd
   9335 amounts of sampleblocks, so it isn't as simple as having left/right in
   9336 first/second half.
   9337 
   9338 Policenauts (Japan, 1996 Konami) (NAUTS\MOVIE\*.MOV)
   9339  STR Sector Header:
   9340   No STR Sector header (first sector starts directly with "VMNK" chunk)
   9341  First chunk (800h bytes):
   9342   000h 4     ID "VMNK" (aka KNMV backwards, maybe for Konami Video/Movie)
   9343   004h 4     Unknown (01h)
   9344   008h 4     Unknown (01h)
   9345   00Ch 4     Unknown (F0h)
   9346   010h 4     Size of KLBS chunks?          (40000h)
   9347   014h 4     Bitmap X1 (aka left border)?  (16pix, 10h)
   9348   018h 4     Bitmap Y1 (aka upper border)? (16pix, 10h)
   9349   01Ch 4     Bitmap Width                  (288pix, 120h)
   9350   020h 4     Bitmap Height                 (144pix, 90h)
   9351   024h 7E4h  Zerofilled
   9352  Further chunks (40000h bytes, each):
   9353   000h 8     Zerofilled
   9354   008h 4     Chunk ID "KLBS" (aka SBLK backwards, maybe for Stream Block)
   9355   00Ch 4     Chunk Size (usually 40000h)
   9356   010h 4     Number of Name List entries
   9357   014h 4     Number of Name List entries (same as above)
   9358   018h 8     Zerofilled
   9359   020h N*30h Name List
   9360   ...  ..    Data (referenced from Name List)
   9361   ...  ..    Zeropadding (to end of 40000h-byte chunk)
   9362 The Name List does resemble a file archive, however, the "filenames" are just
   9363 Type IDs (eg. all picture frames do have the same name).
   9364  Name List entries:
   9365   000h 8     Zerofilled
   9366   008h 8     Data Type Name (eg. "SCIPPDTS")
   9367   010h 4     Time when to play/display the frame (0 and up)
   9368   014h 4     Time duration for that frame (usually 14h for Picture frames)
   9369   018h 4     Data Offset in bytes (from begin of chunk)
   9370   01Ch 4     Data Size in bytes
   9371   020h 10h   Zerofilled
   9372 Data Formats for the different Data Types...
   9373  Type "SDNSHDTS" aka SNDS,STDH - SoundStdHeader (Size=800h, Duration=0)
   9374   000h 4     Maybe Pitch? (800h)                            (big-endian)
   9375   004h 4     Maybe Pitch? (800h)                            (big-endian)
   9376   008h 4     Total SPU-ADPCM size in bytes (for whole .MOV) (big-endian)
   9377   00Ch 4     Unknown (FFFFFFFFh)                            (whatever)
   9378   010h 4     Unknown (00007FFFh)                            (big-endian)
   9379   014h 7ECh  Zerofilled
   9380  Type "SDNSSDTS" aka SNDS,STDS - SoundStdStream (Size=10h..4000h, Duration=9Ch)
   9381   000h 4000h SPU-ADPCM data in 10h-byte blocks (last chunk is less than 4000h)
   9382  Type "SCIPPDTS" aka PICS,STDP - PictureStdPicture (Size=3xxxh, Duration=14h)
   9383   000h 3xxxh Picture Frame (in BS v1 format)
   9384  Type "SCTELLEC" aka ETCS,CELL - ExtraCells? (Size=0Ch, Duration=1)
   9385   000h ..    Maybe subtitle related...?
   9386  Type "SCTEGOLD" aka ETCS,DLOG - ExtraD-log? (Size=19h..31h, Duration=27h..44h)
   9387   000h ..    Maybe subtitle related...?
   9388 Note: Total number of 10h-byte SPU-ADPCM blocks can be odd (so the audio seems
   9389 to be mono).
   9390 Apart from the .MOV files, there's also one standard .STR file for the Knnami
   9391 Intro (with normal STR headers and BS v2 data).
   9392 
   9393 Best Sports Games Ever (DD\*.VLC and MOVIES\*.VLC) (Powerline Demo Disc menu)
   9394 This format is used for still images with only frame, and for looping short
   9395 animation sequences in the Demo Disc Menu. There's no audio.
   9396  Header Chunk:
   9397   000h 4    Fixed ID (74h,55h,89h,08h aka 08895574h)
   9398   004h 2    Bitmap Width           (140h)
   9399   006h 2    Bitmap Height          (100h)
   9400   008h 2    Video Frame Size/4     (17A0h or 13B0h)
   9401   00Ah 2    Number of Video Frames (01h or 32h)
   9402   00Ch 4    Frame End ID (eg. 62DCCACEh) (random?, but stays same within movie)
   9403  Video Frame Chunk(s):
   9404   ...  ..   Data (in BS v1/v2/v3 format)         ;\size = hdr[008h]*4
   9405   ...  ..   FFh-filled (padding to Frame Size)   ;/
   9406   ...  4    Frame End ID (eg. 62DCCACEh)         ;-same value as in hdr[00Ch]
   9407 For random access, best is seeking "fpos=N*(Framesize+4)+10h", alternately one
   9408 could search "fpos=LocationAfterFrameEndID".
   9409 
   9410 Sentient (FILMS\*.FXA)
   9411 This is having neither per-sector STR headers nor Chunk headers, instead it's
   9412 having raw data with fixed size of 10 sectors per frame.
   9413 File Header (sector 0, 800h bytes):
   9414   000h 4    File ID (01h,"XSP") (aka PSX backwards)
   9415   004h 2    Unknown (0001h)
   9416   006h 2    Unknown (0040h) (this is used for something...)
   9417   008h 2    Bitmap Width  (0140h)
   9418   00Ah 2    Bitmap Height (00F0h)
   9419   00Ch 4    Total number of video frames
   9420   010h 4    Number of video sectors per frame (always 8)
   9421   014h 4    Total number of video sectors, excluding audio/dummy (=NumFrames*8)
   9422   018h 1    Zero
   9423   019h 1    Sector List size (28h) (ie. each 4 frames)  ;\or zerofilled when
   9424   01Ah 28h  Sector Types (2=Video, 1=Audio, 0=Dummy)    ;/not present
   9425   042h ..   Zerofilled
   9426   7xxh ..   Unknown, maybe just garbage ...?
   9427   ...  ..   Zerofilled
   9428 The frame rate is 15fps with 10 sectors per frame (8xVideo and either 2xAudio
   9429 or 1xAudio+1xDummy). The Video/Audio/Dummy sector arrangement does repeat each
   9430 40 sectors (aka each 4 frames):
   9431   vVvvvvv--vvVvvv--vvvvVv--vvvvvv-Vvvvvvv-  Video
   9432   -------A-------A-------A-------A-------A  Audio
   9433   --------D-------D-------D---------------  Dummy
   9434   V = 1st sector of video frame
   9435   v = 2nd..8th sector of video frame (or fileheader in case of sector 0)
   9436   A = Audio (each 8th sector, ie. sector 07h,0Fh,17h,1Fh,etc.)
   9437   D = Dummy (occurs after some (not all) audio sectors)
   9438  Some files have that sector arrangement stored in header[019h..041h], but
   9439  other files have that header entries zerofilled (despite of using the same
   9440  arrangement).
   9441 Video frames are 8 sectors (4000h-byte), first and last 8 bytes are swapped:
   9442   0000h 8     Last 8 bytes of BS v1 bitstream   ;\or garbage padding
   9443   0008h 3FF0h First 3FF0h of BS v1 bitstream    ;/
   9444   3FF8h 8     Footer (64bit, with squeezed BS header and other info)
   9445  The footer bits are:
   9446   0-4    5bit   Quant (00h..1Fh) (only 5bit, not 6bit)
   9447   5-15   11bit  MDEC Size in 20h-word units (80h-byte units)
   9448   16-23  8bit   Unknown (lowbits are often same as bit48 and up?)
   9449   24-31  8bit   BS ID/100h (3800h/100h)
   9450   32-47  16bit  Frame Number (0=First)
   9451   48-63  16bit  Next Sector Number (start of next video frame)
   9452  To decrypt/convert the frame to standard BS v1 format:
   9453   x=[3FF8h]                      ;get footer
   9454   [3FF8h..3FFFh]=[0000h..0007h]  ;last 8 bytes of bitstream
   9455   [0000h]=(x AND FF00FFE0h)      ;size and ID=3800h
   9456   [0004h]=(x AND 1Fh)+10000h     ;quant and version=v1
   9457  The next_sector number is usually current_sector+1 (or +2 if that would be
   9458  audio), in last frame it does point to end of file.
   9459  Bitstreams smaller than 3FF8h are garbage padded (initially some 32bit garbage
   9460  values, and in later frames leftovers from previous bitstream sectors).
   9461 Dummy sectors contain 800h bytes:
   9462   000h 4     Always FFFFFFFFh (unfortunately, this isn't a unique ID)
   9463   004h 7FCh  Garbage (zeroes, random, or even leaked ASM source code)
   9464  Dummy sectors have the same Subheader as video sectors, the leading FFFFFFFFh
   9465  could also occur in BS bitstreams or frames with garbage padding, so one must
   9466  use the sector arrangement pattern to identify dummy sectors.
   9467 Audio sectors are XA-ADPCM and can be filtered via Subheader, or via sector
   9468 arrangement pattern.
   9469 
   9470 CDROM File Video Streaming Mis-mastered files
   9471 ---------------------------------------------
   9472 
   9473 Mis-mastered streaming files
   9474 There are several discs that have streaming data stored as partial CDROM images
   9475 (instead of as real CDROM sectors).
   9476   Format        Content    Where
   9477   raw 920h-byte STR        K9.5 1 - Live in Airedale (ZZBUFFER.STR)  ;\
   9478   raw 920h-byte STR        Need for Speed 3 (MOVIES\ZZZZZZZ*.PAD)    ;
   9479   raw 920h-byte STR        3D Baseball (ZZZZZZZZ.ZZZ)                ; intended
   9480   raw 920h-byte STR        Wing Commander III (DUMMY.DAT)            ; padding
   9481   raw 920h-byte STR        R-Types (DMY\DUMMY.BIN)                   ;
   9482   raw 920h+junk STR+junk   Grand Slam (DUMMY.BIN)                    ;
   9483   raw 920h-byte XA-ADPCM   Spec Ops Airborne Commando (PADDING.NUL)  ;
   9484   raw 920h-byte SW-STR     Cyberia (ENDFILL\*.STR) (software render) ;
   9485   RIFFs/CDXAfmt STRs       Sonic Wings Special (SW00.DMY = two RIFFs);/
   9486   raw 920h-byte XA-ADPCM   Rugrats (MagDemo19: STREAMS\DB02.ISF)     ;\nonsense
   9487   raw 920h-byte Data BABEh Rugrats (MagDemo19: STREAMS\OPEN.BIN)     ; dupes
   9488   raw ???-byte  CDDA       Championship Surfer (MagDemo43: HWX\MUSIC);/
   9489   raw ???-byte  CDDA       Twisted Metal 2 (MagDemo50: TM2\FRWYSUB.DA) ;-?
   9490   raw 920h-byte STR        Sonic Wings Special (MOV\MQ*.STR)         ;-unused?
   9491   raw 920h-byte STR        Apocalypse (MagDemo16: APOC\*.STR)
   9492   raw 920h-byte XA-ADPCM   Apocalypse (MagDemo16: APOC\*.XA)
   9493   raw 920h-byte XA-ADPCM   NFL Xtreme (MagDemo13: NFLX\GAME\SOUND\2PLAYRNO.XA)
   9494   raw 920h-byte XA-ADPCM   Ace Combat 2 (MagDemo01: ACE2.STP)
   9495   raw 920h-byte XA-ADPCM   Colony Wars (MagDemo02: CWARS\DEMO.PAK)
   9496   raw 920h-byte XA-ADPCM   Best Sports demo (AH2\GAMEDATA\COM\MUSIC\MUSIC.IXA)
   9497   raw 920h-byte XA-ADPCM   Tomb Raider: Last Revelation (MagDemo29: TR4\XA1.XA)
   9498   raw 800h-byte XA-ADPCM   Croc 1 demo (MagDemo02: CROC\MAGMUS.STR) (FORM1)
   9499   RIFF/CDXAfmt  XA-ADPCM   Best Sports demo (LOMUDEMO\SFX\COMMENT.STR)
   9500   RIFF/CDXAfmt  ?+XA-ADPCM Ace Combat 3 Electrosphere (MagDemo30: AC3\*.SPB)
   9501   RIFF/CDXAfmt  XA-ADPCM   Colony Wars Venegance (MagDemo14: CWV\SONYDEMO.PAK)
   9502   RIFF/WAVEfmt  CDDA       T'ai Fu (MagDemo16: TAIFU\3_10.WAV, 2x16bit 44100Hz)
   9503 The 920h-byte sectors exclude the leading Sync mark and MM:SS:FF:Mode2 value.
   9504  Data/movie sectors look as so:
   9505   000h 4    Sub-Header (File, Channel, Submode OR 20h, Codinginfo)
   9506   004h 4    Copy of Sub-Header
   9507   008h 800h Data (2048 bytes)           ;<-- contains STR movie sectors
   9508   808h 4    EDC (zerofilled)
   9509   80Ch 114h ECC (zerofilled)
   9510  And XA-ADPCM sectors look as so:
   9511   000h 4    Sub-Header (File, Channel, Submode OR 64h, Codinginfo)
   9512   004h 4    Copy of Sub-Header
   9513   008h 900h Data (18*128 bytes)         ;\contains XA-ADPCM audio sectors
   9514   908h 14h  Data (zerofilled)           ;/
   9515   91Ch 4    EDC (zerofilled)
   9516 The RIFF/CDXAfmt has a standard RIFF header, followed by 930h-byte sectors
   9517 (same format as when opening CDROM streaming files in Windows). The
   9518 RIFF/WAVEfmt is just a standard .WAV file.
   9519 In case of the ZZ*.* files on retail discs, the developers did intentionally
   9520 append some non-functional dummy STR files (instead of appending zerofilled
   9521 30Mbyte at end of disc).
   9522 --> CDROM File XYZ and Dummy/Null Files
   9523 In case of the Demo Discs, the developers did probably have high hopes to
   9524 release a demo version with working streaming data, just to find out that Sony
   9525 had screwed up the data format (or maybe they had only accidentally included
   9526 streaming data, without actually using it in demo version). Confusingly, the
   9527 corrupted files were released on several discs (magazine demos, and other demo
   9528 releases).
   9529 The Rugrats demo has intact files in RUGRATS\CINEMAT and RUGRATS\XA folders,
   9530 plus nonsense copies of that files in 920h-byte format in STREAMS folder.
   9531 
   9532 Partially mis-mastered files
   9533 Legend of Dragoon (MagDemo34: LOD\XA\LODXA00.XA has FIRST SECTOR mis-mastered
   9534 (it has TWO sub-headers (01,00,48,00,01,00,48,00,01,01,64,04,01,01,64,04), the
   9535 remaining sectors are looking okay).
   9536 
   9537 Porsche Challenge (USA) (SRC\MENU\STREAM\*.STR)
   9538 The subheader and data of the 1st sector are accidently overwritten by some
   9539 ASCII string:
   9540   000h 4    Subheader       01 44 2D 52            ".D-R"    ;\distorted
   9541   004h 4    Subheader copy  01 4D 20 47            ".M G"    ;/"CD-ROM G"
   9542   008h 299h Data ASCII      65 6E 65 72 61 ...     "enerator for Windows"...
   9543   2A1h 567h Data BS bitstream (but lacks BS header and start of bitstream)
   9544 The 2nd sector and up are containing intact STR headers (for the 2nd-Nth sector
   9545 of 1st frame, but the whole 1st frame is unusable due to missing 1st sector;
   9546 however, the following frames are intact).
   9547 
   9548 CDROM File Video BS Compression Versions
   9549 ----------------------------------------
   9550 
   9551 STR/BS Version Summary, with popularity in percents (roughly)
   9552   Version         .STR movies   .BS pictures
   9553   BS v2            60%           6%            Most games
   9554   BS v3            20%           4%            Some newer games
   9555   BS v1            15%           0.1%          Old games
   9556   BS ea            2%            - (?)         Electronic Arts titles
   9557   BS iki           0.5%          0.1%          Several games
   9558   BS fraquant      0.2%          0.1%          Rare (X-Files, Eagle One)
   9559   BS v0            0.1%          -             Rare (Serial Experiments Lain)
   9560   BS v2/v3.crypt   0.2%          -             Rare (Star Wars games)
   9561   BS iki.encrypted 0.1%          -             Rare (Panekit)
   9562   Wacwac MDEC      0.1%          -             Rare (Aconcagua)
   9563   Polygon Streams  0.x% (?)      -             Some titles
   9564   Raw MDEC         -             -             Was never used in files?
   9565   MPEG1            -             -             VCD Video CDs
   9566   None             ?%   (?)      90%           No videos or BS pictures
   9567 Most games can decrypt v1/v2/v3 videos (no matter which of the three versions
   9568 they are actually using), newer games do occassionally use v3 for picture
   9569 compression, but often stick with v2 for video streaming (perhaps because v3
   9570 does require slightly more CPU load; unknown if the higher CPU load has been an
   9571 actual issue, and if it has been solved in the later (more optimized)
   9572 decompressor versions) (unknown if there are other benefits like v2 having
   9573 better DC quality or better compression in some cases?).
   9574 
   9575 BS v0 (used by only one known game)
   9576   v0 used by Serial Experiments Lain
   9577 This game is apparently using a very old and very unoptimized decoder (although
   9578 it was released in 1997, when most or all other games did already have decoders
   9579 with v1/v2/v3 support).
   9580 The v0 decoder has different header, lacks End of Frame codes, and uses Huffman
   9581 codes with different AC values than v1/v2/v3/iki.
   9582 
   9583 BS v1 (used by older games, some of them also having v2 videos)
   9584   v1 used by Wipeout 2097 (MAKE.AV, XTRO*.AV)
   9585   v1 used by Viewpoint (MOVIES\*.STR) (oddly with [08h]=FirstFrame=0 and
   9586         [1Ch]=Unspecified=Nonzero) (the game also has ".str" files in
   9587         VIEW.DIR\streams, but that isn't MDEC/STR stuff)
   9588   v1 used by Ridge Racer Revolution (MOVIE\*.STR)
   9589   v1 used by Policenauts
   9590   v1 used by Final Fantasy VII (FF7)
   9591   v1? used by Tekken 2
   9592   v1/v2 used by Final Fantasy Tactics (OPEN*.STR)
   9593   v1/v2 used by Project Horned Owl (*.STR)
   9594   v1/v2 used by Gex (*.FMV)
   9595   (and probably more)
   9596 v1 and v2 can be decoded with the same decompressor. The only difference is
   9597 that v1 was generated with an older compressor (which did accidently store
   9598 nonsense 22bit escape codes with run=N, level=0 in the bitstream; whereas one
   9599 could as well use run+N+1 in the next code, or omit it completely if next code
   9600 is EOB).
   9601 
   9602 BS v2 (most games)
   9603   v2 used by Gex - Enter the Gecko (*.STR)
   9604   v2 used by Tomb Raider (FMV\*.FMV)
   9605   v2 used by Alone (STR*\*.STR)
   9606   v2 used by Kain (*.STR)
   9607   v2 used by Fear Effect (BOOT.SID, LOGO.SID, ABGA\ABGA.FLX)
   9608   v2 used by Parasite Eve 2 (INTERx.STR, and in .CDF's eg. stage1\folder501)
   9609   v2 used by Witch of Salzburg (MOVIE\*.STR)
   9610   v2 used by Breath of Fire III (LOGO\*.STR)
   9611   v2 used by Hear it Now (MOVIE\*.STR)
   9612   v2 used by Legend of Mana (MOVIE\*.STR)
   9613   v2 used by Misadventures of Tron Bonne (STR\*.STR)
   9614   v2 used by Rayman (VIDEO\*.STR)
   9615   v2 used by Resident Evil 1 (PSX\MOVIE\*.STR)                ;\although v3 is
   9616   v2 used by Resident Evil 2 (PL0\ZMOVIE\*.STR, ZMOVIE\*.STR) ;/used in *.BSS
   9617   v2 used by Tokimeki Memorial 2 (VX*.STR)
   9618   v2 used by Spider-Man (CINEMAS\*.STR)
   9619   v2 used by Perfect Assassin (CDV\*.STR)
   9620   v2 used by Pandemonium 2 (*.STR)
   9621   v2 used by Die Hard Trilogy 2 (MOVIE\*.STR)
   9622   v2 used by Need for Speed 3 (MOVIES\*.STR) (oddly with [14h,18h]<>[20h,24h])
   9623   v2 used by Wild Arms (STR\*.STR)
   9624   v2 used by Wild Arms 2 (STR\*.STR)
   9625   v2 used by Frogger (*.STR)
   9626   v2 used by Gundam Battle Assault (XA\*.STR)
   9627   v2 used by Alundra (MOVIE\*.MOV)
   9628   v2 used by Spec Ops (file 95h,96h within BIGFILE.CAT)
   9629   v2 used by Crash Team Racing (file 1E1h..1F8h,1FAh within BIGFILE.BIG)
   9630   (and many more)
   9631 Same as v1, but without the compressor bug.
   9632 
   9633 BS v3 (used by some newer games, some of them also having v2 videos)
   9634   v2/v3 used by Lemmings Oh No More Lemmings (ANIMS\*.STR)
   9635   v2/v3 used by Castlevania (*.STR)
   9636   v3 used by Heart of Darkness (CINE\*.STR, SETUP\*.STR)
   9637   v3 used by R-Types (MV\*.STR)
   9638   v3 used by Black Matrix (MOVIE\*.STR)
   9639   v3 used by Nightmare Creatures II (INTRO\*.STR, LEVEL*\*.STR)
   9640   (and many more)
   9641 Same as v2, but using Huffman compressed DC values.
   9642 
   9643 BS ea (Electronic Arts)
   9644 Used by many EA Sports titles and several other titles from Electronic Arts:
   9645   Castrol Honda Superbike Racing
   9646   EA Sports Supercross 2000, 2001
   9647   Future Cop - L.A.P.D. (retail and MagDemo14: FCOPLAPD\*.WVE and *.FSV)
   9648   Hot Wheels - Turbo Racing
   9649   Jampack Vol. 2
   9650   Knockout Kings 99, 2000, 2001
   9651   Madden NFL 99, 2000, 2001, 2002, 2003, 2004, 2005 (eg. MADN00\FMVIDEO.DAT\*)
   9652   NASCAR 98, 99, 2000, 2001 (and 98 Collector's Edition, and 99 Legacy)
   9653   NASCAR Thunder 2002, 2003, 2004 and NASCAR Rumble
   9654   Nuclear Strike
   9655   Official U.S. PlayStation Magazine Demo Disc 39 (...XXX which game?)
   9656   PlayStation Underground Jampack - Winter 2000
   9657   Road Rash Jailbreak, and Road Rash 3D
   9658   Tiger Woods PGA Tour Golf, and Tiger Woods USA Tour 2001
   9659 Uses VLC0 and MDEC chunks (instead of STR headers), the MDEC chunks contain
   9660 standard BS v2 data, but using custom MDEC values from VLC0 chunk.
   9661 
   9662 BS fraquant
   9663   X-Files (Fox Interactive/Hyperbole Studios, 1999)
   9664   Eagle One: Harrier Attack (Infogrames/Glass Ghost, 2000)
   9665   Blue's Clues: Blue's Big Musical (Mattel/Viacom/TerraGlyph, 2000)
   9666 This replaces the 6bit quant value by a 16bit fixed-point quant value (done by
   9667 manipulating the Quant Table instead of using QuantDC, apart from that extra
   9668 feature it's internally using normal BS v1/v2/v3 decoding).
   9669 
   9670 BS iki
   9671   iki: Gran Turismo 1 (STREAM.DAT)   ;\with uncommon STR header
   9672   iki: Gran Turismo 2 (STREAM.DAT)   ;/
   9673   iki: Hot Shots Golf 2 / Everybody's Golf 2 (MagDemo31: HSG2\MINGOL2X.BIN)
   9674   iki: Legend of Legaia (MagDemo20: LEGAIA\MOV\MV2.STR)
   9675   iki: Legend of Dragoon (STR\*.IKI)
   9676   iki: Omega Boost (MOVIE\*.IKI)
   9677   iki: Um Jammer Lammy (MagDemo24: UJL\*.IKI) (retail: *\*.IKI and CM\*.IK2)
   9678   iki: plus a dozen of japanese-only titles
   9679 This might have been used between v2 and v3, iki is using uncommon BS headers
   9680 and LZ compressed Quant/DC values (whilst v3 is using Huffman compressed DC
   9681 values).
   9682 
   9683 Encrypted iki
   9684   Panekit - Infinitive Crafting Toy Case (first 13Mbyte in PANEKIT.STR)
   9685 Same as normal iki, with some SWAP/ADD/XOR-encrytion in first 20h-bytes.
   9686 
   9687 Encrypted v2/v3
   9688   v3.xor used by Star Wars Masters of Teras Kasi (MagDemo03: MASTERS\*.STR)
   9689   v2.xor supported (but not actually used) by Star Wars Masters (MagDemo03)
   9690   v3.swap used by Star Wars Rebel Assault II (*.STR, *.SED, Stills)
   9691   v2.swap used by Star Wars Rebel Assault II (*.STR)
   9692   v3.swap used by BallBlazer Champions (*.STR)
   9693 Same as normal v2/v3 with simple XOR-encryption or SWAP-encryption.
   9694 
   9695 Wacwac MDEC
   9696   Aconcagua (JP) (2000 Sony/WACWAC!) (STR_01_00.STR and STR_09_01.STR)
   9697 Similar to v3, but uses completely different Huffman codes than BS video.
   9698 
   9699 Polygon Streaming (instead of MDEC picture streaming)
   9700   Ape Escape (DEMO\*.STR, STR\*.STR, and KKIIDDZZ.HED\STR\0006h and up)
   9701   Aconcagua (most STRs are Polygon Streams, except two are Wacwac MDEC streams)
   9702   Panekit - Infinitive Crafting Toy Case (last 150Mbyte in PANEKIT.STR)
   9703 Polygon streams contain vertices (for textures that are stored elsewhere).
   9704 Usually needing only one sector per frame. This can be useful for animations
   9705 that were recorded from real actors. Drawbacks are more edgy graphics and lower
   9706 color depth (although that may fit in with the game engine).
   9707 --> CDROM File Video Polygon Streaming
   9708 
   9709 MPEG1 (on VCD Video CDs)
   9710 MPEG1 uses I/P/B-Frames, the I-Frames may reach similar compression as BS
   9711 files. However, P-Frames and B-Frames do compress much better than BS files.
   9712 --> CDROM Video CDs (VCD)
   9713 MPEG1 isn't used in any PSX games, but VCDs can be viewed on SCPH-5903 consoles
   9714 (or via software decoder in nocash PSX kernel clone).
   9715 
   9716 Titles without movies
   9717 Most PSX titles do include movies, exceptions are some early launch titles and
   9718 educational titles:
   9719   Ridge Racer 1 (1994)
   9720   Lightspan Online Connection CD
   9721 
   9722 CDROM File Video BS Compression Headers
   9723 ---------------------------------------
   9724 
   9725 There are several different BS headers. The File ID/Version entries can be used
   9726 to detect the correct type. The MDEC Size entry contains the size after Huffman
   9727 decompression (ie. the half-decompressed size before passing the data to the
   9728 MDEC decompression hardware) (usually divided by 4 and rounded up to 80h/4
   9729 bytes).
   9730 
   9731 BS v1/v2/v3 header
   9732   000h 2    MDEC Size/4 (after huffman decompression) (rounded to 80h/4 bytes)
   9733   002h 2    File ID (3800h)
   9734   004h 2    Quantization step/factor (0000h..003Fh, for MDEC "DCT.bit10-15")
   9735   006h 2    Version (1, 2, or 3) (2 is most common)
   9736   008h ...  Huffman compressed data blocks (Cr,Cb,Y1,Y2,Y3,Y4, Cr,Cb,Y1,Y2..)
   9737 
   9738 Encrypted v2/v3
   9739 Encryption is used in Star Wars games, there are two encryption schemes (XOR
   9740 and SWAP).
   9741 XOR-encrypt: Star Wars Masters of Teras Kasi (MagDemo03: MASTERS\*.STR):
   9742   000h 2   MDEC Size/4 (rounded to 80h/4 bytes) (unencrypted) ;\same as normal
   9743   002h 2   File ID (3800h)                      (unencrypted) ; BS v1/v2/v3
   9744   004h 2   Quant (0..3Fh)                       (unencrypted) ;/
   9745   006h 2   Version (in bit15, plus random in LSBs):
   9746              00xxh..7FFFh for v2 (unknown if this could include values 0..3)
   9747              8000h..FFFFh for v3 (bit14-0=random, varies in each frame)
   9748   008h ..  Encrypted bitstream
   9749              (each halfword XORed by BE67h for v2, or XORed by E67Bh for v3)
   9750   ...  (2) Zeropadding to 4-byte boundary (unencrypted)
   9751   ...  ..  Zeropadding to end of sector   (unencrypted)
   9752  The XOR values BE67h/E67Bh are hardcoded in the Star Wars Masters of Teras
   9753  Kasi .EXE (same XOR values for both retail and demo version), unknown if any
   9754  other games are also using that kind of encryption (and if yes, if they are
   9755  using the same XOR values).
   9756 SWAP-encrypt: BallBlazer Champions, Star Wars Rebel Assault II (*.STR, *.SED):
   9757   000h 2   MDEC Size/4 (rounded to 80h/4 bytes) ;\same as normal
   9758   002h 2   File ID (3800h)                      ; BS v1/v2/v3
   9759   004h 2   Quant (0..3Fh)                       ;/
   9760   006h 2   Version (random 16bit, 00xxh..FFFFh) ;-no meaningful version info
   9761   008h 2   Bitstream 2nd halfword               ;\to "decrypt" the file,
   9762   00Ah 2   Bitstream 1st halfword               ;/these must be swapped
   9763   00Ch ..  Bitstream 3rd halfword and up        ;-in normal order
   9764 Whilst XORing or SWAPping the halfwords is simple, the more difficult part is
   9765 distinguishing between SWAP-v2/v3 and XOR-v2/v3 encryption. This can be done as
   9766 so:
   9767   if header[06h]<=0003h then assume unencrypted v0/v1/v2/v3
   9768   if header[06h]>=0004h then strip any trailing 0 bits, and check EndOfFrame..
   9769   if last 10bit = 0111111111 then assume SWAP.v2
   9770   if last 10bit = 1111111111 then assume SWAP.v3
   9771   otherwise assume XOR.v2/v3 (and use header[06h].bit15 to distinguish v2/v3)
   9772 
   9773 BS iki Header
   9774 IKI videos have a custom .BS header, including some GT-ZIP compressed data:
   9775   000h 2   MDEC Size/4 (rounded to 80h/4 bytes)         ;\same as normal
   9776   002h 2   File ID (3800h)                              ;/BS v1/v2/v3
   9777   004h 2   Bitmap Width in pixels     ;instead of Quant
   9778   006h 2   Bitmap Height in pixels    ;instead of Version
   9779   008h 2   Size of GT-ZIP compressed data (plus 2-byte alignment padding)
   9780   00Ah ..  GT-ZIP compressed DC/Quant values (plus 2-byte alignment padding)
   9781   ...  ..  Huffman compressed AC data blocks (Cr,Cb,Y1,Y2,Y3,Y4, Cr,Cb,Y1,Y2..)
   9782 The number of blocks is NumBlocks=(Width+15)/16*(height+15)/16*6. The size of
   9783 the decompressed GT-ZIP data is NumBlocks*2.
   9784 
   9785 Encrypted iki
   9786 The first 20h byte of the iki header & data are encrypted. Among others, the ID
   9787 3800h is inverted (=C7FFh). To decrypt them:
   9788   [buf+00h]=[buf+00h] XOR FFFFFFFFh
   9789   [buf+04h] <--> [buf+08h]          ;exchange 2x32bit
   9790   [buf+0Ch] <--> [buf+0Eh]          ;exchange 2x16bit
   9791   [buf+10h]=[buf+10h]+FFFF6F7Bh
   9792   [buf+14h]=[buf+14h]+69140000h
   9793   [buf+18h]=[buf+18h]+FFFF7761h
   9794   [buf+1Ch]=[buf+1Ch]+6B040000h
   9795 Note: The .STR header's StHeadM/StHeadV fields contain a copy of the decrypted
   9796 values. The PANEKIT.STR file is 170Mbyte tall, but only the first 13Mbyte
   9797 contain movie data... the rest is unknown stuff... often with zeroes followed
   9798 by 7B,44,F0,29,E0,28 unknown what for...?
   9799 
   9800 BS fraquant
   9801   X-Files, GRAPHICS\*.STR,*.BIN, LOGOS\*.STR,*.BS
   9802   Eagle One: Harrier Attack (\*.STR, DATA*\*.STR) (leading zerofilled sectors)
   9803   Blue's Clues: Blue's Big Musical (*.STR) (has one leading zerofilled sector)
   9804 This has a normal BS v1/v2/v3 header, with special quant entry:
   9805   004h 2    Quant (0001h..0003h, or fixed-point 8000h..9xxxh)
   9806 The decoder is using the default_quant_table (02h,10h,10h,13h,..,53h)
   9807 multiplied with a fixed point number:
   9808   quant=BsHeader[04h]   ;get fractional quant value
   9809   BsHeader[04h]=0001h   ;force quant=1 (for use in BS v1/v2/v3 decoder)
   9810   if quant<8000h then quant=quant*200h else quant=quant AND 7FFFh
   9811   quant[0]=default_quant_table[0]
   9812   for i=1 to 3Fh,
   9813     x=(default_quant_table[i]*quant)/200h
   9814     if x=00000000h then quant[i]=01h else quant[i]=(x AND FFh)
   9815   next i
   9816   use MDEC(2) command to apply quant[0..3Fh] to both Luma and Chroma tables
   9817   use normal BS v1/v2/v3 decoder to decompress the bitmap
   9818 BsHeader[04h] should be 0001h..0003h, or 8000h..862Bh (values outside that
   9819 range would overflow the 8bit quant table entries). Values 0001h..0003h should
   9820 should give same results as for normal BS decoding, so only values 8000h and up
   9821 do need special decoding.
   9822 Caution: Despite of the overflows, quant>862Bh is used (eg. X-Files
   9823 GRAPHICS\GRAPHICS.BIN has quant=88C4h, Blue's Big Musical has quant=93E9h;
   9824 those images do look okay, so the compressor seems to have recursed the
   9825 overflows; or the overflow affects only a few pixels), however, very large with
   9826 LSBs all zero (eg. 9000h) can cause 8bit table entries to become 00h (due to
   9827 ANDing the result with FFh).
   9828 Note: X-Files LOGOS\POP*.STR have quant=8001h (=near zero), that files are only
   9829 60Kbyte and seem to be all black.
   9830 Note: The movie engine uses COP2 GPF opcodes to calculate quant values.
   9831 
   9832 v0 Header (in STR files)
   9833   000h 1   Quant for Y1,Y2,Y3,Y4  (00h..3Fh)
   9834   001h 1   Quant for Cr,Cb        (00h..3Fh)
   9835   002h 2   File ID (3800h) (or Frame Number in ENDROLL1.STR on Disc 2)
   9836   004h 2   MDEC Size/2 (!), and without padding (!) (unlike v1/v2/v3/iki)
   9837   006h 2   BS Version (0) (actually MSBs of above Size, but it's always 0)
   9838   008h ..  Huffman Bitstream, first bit in bit7 of first byte
   9839 
   9840 v0 Header (in LAPKS.BIN chunks)
   9841 LAPKS.BIN contains several chunks, each chunk contains an animation sequence
   9842 with picture frame(s), each frame starts with following header:
   9843   000h 2   Bitmap Width in pixels     ;\cropped to non-black screen area,
   9844   002h 2   Bitmap Height in pixels    ;/size can vary within the sequence
   9845   004h 2   Quant for Y1,Y2,Y3,Y4  (0000h..003Fh)
   9846   006h 2   Quant for Cr,Cb        (0000h..003Fh)
   9847   008h 4   Size of compressed BS Bitstream plus 4 ;Transparency at [008h]+0Ch
   9848   00Ch 2   Size/2 of MDEC data (after huffman decompression, without padding)
   9849   00Eh 2   BS Version (0) (actually MSBs of above Size, but it's always 0)
   9850   010h ..  BS Bitstream with DC and AC values (Huffman compressed MDEC data)
   9851   ...  4   Transparency Mask Decompressed Size (Width*Height*2/8) (=2bpp)
   9852   ...  ..  Transparency Mask LZSS-compressed data
   9853 For decompressing the transparency mask:
   9854 --> CDROM File Compression LZSS (Serial Experiments Lain)
   9855 The Transparency Mask is stored as scanlines (not as macroblocks), the
   9856 upper/left pixel is in bit7-6 of first byte, the 2bit alpha values are ranging
   9857 from 0=Transparent to 3=Solid.
   9858 
   9859 BS ea Headers (Electronic Arts)
   9860 EA videos are chunk based (instead of using 20h-byte .STR headers).
   9861 --> CDROM File Video Streaming Chunk-based formats
   9862 VLC0 Chunk: Custom MDEC values (to be assigned to normal BS v2 Huffman codes).
   9863 MDEC Chunks: Width/Height and BS v2 data (using MDEC values from VLC0 chunk).
   9864 
   9865 Raw MDEC
   9866 There aren't any known pictures or movies in raw MDEC format. However, the
   9867 Huffman decompression functions do usually output raw data in this format:
   9868   000h 2   MDEC Size/4 (after huffman decompression) (rounded to 80h/4 bytes)
   9869   002h 2   File ID (3800h)
   9870   004h ..  MDEC data (16bit DC/AC/EOB codes)
   9871   ...  ..  Padding (FE00h-filled to 80h-byte DMA transfer block size boundary)
   9872 The first 4 bytes are the MDEC(1) command, the "ID" is always 3800h (equivalent
   9873 to selecting 16bpp output; for 24bpp this must be changed to 3000h before
   9874 passing the command to the MDEC hardware). The remaining bytes are MDEC data
   9875 (padded to 80h-byte boundary).
   9876 --> Macroblock Decoder (MDEC)
   9877 
   9878 CDROM File Video BS Compression DC Values
   9879 -----------------------------------------
   9880 
   9881 DC v0
   9882   nnnnnnnnnn        DC Value (signed 10bit, -200h..+1FFh)
   9883 This is similar as v1/v2, except there is no End code for End of Frame, and the
   9884 .BS header contains two separate quant values (for Cr/Cb and Y1-Y4).
   9885   If output_size=NumberOfMdecCodes*2 then EndOfFrame
   9886   If BlockIsCrCb then QuantDC=DC+QuantC*400h else QuantDC=DC+QuantY*400h
   9887 
   9888 DC v1/v2/ea
   9889   nnnnnnnnnn        DC Value (signed 10bit, -200h..+1FEh)
   9890   0111111111        End of Frame (+1FFh, that, in place of Cr)
   9891 This is similar as v0, except there is only one Quant value for all blocks, and
   9892 the header lacks info about the exact decompressed size, instead, compression
   9893 end is indicated by a newly added end code:
   9894   If DC=+1FFh then EndOfFrame
   9895   QuantDC=DC+Quant*400h
   9896 
   9897 DC v3
   9898 Similar as v1/v2, but DC values (and End code) are now Huffman compressed
   9899 offsets relative to old DC, with different Huffman codes for Cr/Cb and Y1-Y4:
   9900   For Cr/Cb         For Y1..Y4      Offset (added to old DC of Y/Cr/Cb block)
   9901   00                100             +(00h)                      ;\
   9902   01s               00s             -(01h)*4     ,+(01h)*4      ;
   9903   10sn              01sn            -(03h..02h)*4,+(02h..03h)*4 ; required
   9904   110snn            101snn          -(07h..04h)*4,+(04h..07h)*4 ; codes
   9905   1110snnn          110snnn         -(0Fh..08h)*4,+(08h..0Fh)*4 ; for 10bit
   9906   11110snnnn        1110snnnn       -(1Fh..10h)*4,+(10h..1Fh)*4 ; range
   9907   111110snnnnn      11110snnnnn     -(3Fh..20h)*4,+(20h..3Fh)*4 ;
   9908   1111110snnnnnn    111110snnnnnn   -(7Fh..40h)*4,+(40h..7Fh)*4 ;/
   9909   11111110snnnnnnn  1111110snnnnnnn -(FFh..80h)*4,+(80h..FFh)*4 ;-11bit (!)
   9910   -                 11111110        Unused                      ;\
   9911   111111110         111111110       Unused                      ; unused
   9912   1111111110        1111111110      Unused                      ;/
   9913   1111111111        1111111111      End of Frame                ;-end code
   9914   Note: the "snnn" bits are indexing the values in right column,
   9915   with s=0 for negative values, and s=1 for positive values.
   9916 The decoding works as so (with oldDcXxx=0 for first macroblock):
   9917   If bits=1111111111 then EndOfFrame
   9918   If BlockIsCr then DC=DecodeHuffman(HuffmanCodesCbCr)+oldDcCr, oldDcCr=DC
   9919   If BlockIsCb then DC=DecodeHuffman(HuffmanCodesCbCr)+oldDcCb, oldDcCb=DC
   9920   If BlockIsY1234 then DC=DecodeHuffman(HuffmanCodesY1234)+oldDcY, oldDcY=DC
   9921   If older_version AND DC>=0 then QuantDC=Quant*400h or (DC)       ;\requires
   9922   If older_version AND DC<0  then QuantDC=Quant*400h or (DC+400h)  ;/11bit
   9923   If newer_version           then QuantDC=Quant*400h+(DC AND 3FFh) ;-wrap 10bit
   9924 Note: The offsets do cover signed 11bit range -3FCh..+3FCh. Older v3 decoders
   9925 did require 11bit offsets (eg. add +3FCh to change DC from -200h to +1FCh).
   9926 Newer v3 decoders can wrap within 10bit (eg. add -4 to wrap DC from -200h to
   9927 +1FCh).
   9928 
   9929 DC iki
   9930 The DC values (including Quant values for each block) are separately stored as
   9931 GT-ZIP compressed data in the IKI .BS header.
   9932 --> CDROM File Compression GT-ZIP (Gran Turismo 1 and 2)
   9933 Calculate NumBlocks=(Width+15)/16*(height+15)/16*6, decompress the DC values
   9934 (until DecompressedSize=NumBlocks*2). During Huffman decompression, read the DC
   9935 values from the decompressed DC buffer (instead of from the Huffman bitstream):
   9936   If BlockNo>=NumBlocks then EndOfFrame
   9937   QuantDC = DCbuf[BlockNo]*100h + DCbuf[BlockNo+NumBlocks]
   9938 As shown above, the Hi- and Lo-bytes are stored in separate halves of the DC
   9939 buffer (which may gain better compression).
   9940 
   9941 CDROM File Video BS Compression AC Values
   9942 -----------------------------------------
   9943 
   9944 Below shows the huffman codes and corresponding 16bit MDEC values; the "xx"
   9945 bits contain an index in the list of 16bit MDEC values, the "s" bit means to
   9946 negate the AC level (in lower 10bit of the 16bit MDEC value) when s=1.
   9947 
   9948 Huffman codes for AC values BS v1/v2/v3/iki
   9949   10                     FE00h          ;End of Block, EOB
   9950   11s                    0001h
   9951   011s                   0401h
   9952   010xs                  0002h,0801h
   9953   0011xs                 1001h,0C01h
   9954   00101s                 0003h
   9955   00100xxxs              3401h,0006h,3001h,2C01h,0C02h,0403h,0005h,2801h
   9956   0001xxs                1C01h,1801h,0402h,1401h
   9957   00001xxs               0802h,2401h,0004h,2001h
   9958   000001xxxxxxxxxxxxxxxx 0000h..FFFFh   ;Escape code for raw 16bit values
   9959   000001xxxxxx0000000000 0000h..FC00h   ;Escape nonsense level=0 (used in v1)
   9960   0000001xxxs            4001h,1402h,0007h,0803h,0404h,3C01h,3801h,1002h
   9961   00000001xxxxs          000Bh,2002h,1003h,000Ah,0804h,1C02h,5401h,5001h,
   9962                          0009h,4C01h,4801h,0405h,0C03h,0008h,1802h,4401h
   9963   000000001xxxxs         2802h,2402h,1403h,0C04h,0805h,0407h,0406h,000Fh,
   9964                          000Eh,000Dh,000Ch,6801h,6401h,6001h,5C01h,5801h
   9965   0000000001xxxxs        001Fh,001Eh,001Dh,001Ch,001Bh,001Ah,0019h,0018h,
   9966                          0017h,0016h,0015h,0014h,0013h,0012h,0011h,0010h
   9967   00000000001xxxxs       0028h,0027h,0026h,0025h,0024h,0023h,0022h,0021h,
   9968                          0020h,040Eh,040Dh,040Ch,040Bh,040Ah,0409h,0408h
   9969   000000000001xxxxs      0412h,0411h,0410h,040Fh,1803h,4002h,3C02h,3802h,
   9970                          3402h,3002h,2C02h,7C01h,7801h,7401h,7001h,6C01h
   9971   000000000000           Unused
   9972 
   9973 Huffman codes for AC values BS v0 (Serial Experiments Lain)
   9974   10                           FE00h          ;End of Block, EOB
   9975   11s                          0001h
   9976   011s                         0002h
   9977   010xs                        0401h,0003h
   9978   0011xs                       0801h,0005h
   9979   00101s                       0004h
   9980   00100xxxs                    000Ah,000Bh,0403h,1801h,000Ch,000Dh,1C01h,000Eh
   9981   0001xxs                      0006h,0C01h,0402h,0007h
   9982   00001xxs                     0008h,1001h,0009h,1401h
   9983   000001xxxxxx0xxxxxxx         0000h..FC00h+(+001h..+07Fh AND 3FFh) ;\
   9984   000001xxxxxx000000001xxxxxxx 0000h..FC00h+(+080h..+0FFh AND 3FFh) ; Escape
   9985   000001xxxxxx000000000xxxxxxx Unused                               ; codes
   9986   000001xxxxxx1xxxxxxx         0000h..FC00h+(-080h..-001h AND 3FFh) ;
   9987   000001xxxxxx100000000xxxxxxx 0000h..FC00h+(-100h..-081h AND 3FFh) ;
   9988   000001xxxxxx100000001xxxxxxx Unused                               ;/
   9989   0000001xxxs                  000Fh,0802h,2001h,0404h,0010h,0011h,2401h,0012h
   9990   00000001xxxxs                0013h,0405h,0014h,2801h,0015h,0C02h,3001h,0017h,
   9991                                0016h,2C01h,0018h,001Ch,0019h,0406h,0803h,001Bh
   9992   000000001xxxxs               001Ah,3401h,001Dh,0407h,1002h,001Fh,001Eh,3801h,
   9993                                0020h,0021h,0408h,0023h,0022h,1402h,0024h,0025h
   9994   0000000001xxxxs              0804h,0409h,0418h,0026h,3C01h,0027h,0C03h,1C03h,
   9995                                0028h,0029h,002Ah,002Bh,040Ah,002Ch,1802h,002Dh
   9996   00000000001xxxxs             002Fh,002Eh,4001h,0805h,0030h,040Bh,0031h,0033h,
   9997                                0032h,1C02h,0034h,1003h,0035h,4401h,040Ch,0037h
   9998   000000000001xxxxs            0036h,0038h,0039h,5401h,003Ah,0C04h,040Dh,5C01h,
   9999                                2002h,003Bh,0806h,4C01h,003Ch,2402h,6001h,4801h
  10000   000000000000                 Unused
  10001 Uses different 16bit MDEC values, and the Escape code is different: 8bit levels
  10002 are 2bit shorter than v1/v2/v3, but 9bit levels are much longer, and 10bit
  10003 levels are not supported at all (those v0 Escape codes are described in Sony's
  10004 File Format documented; albeit accidentally because the doc was actually trying
  10005 to describe v2/v3).
  10006 
  10007 Huffman codes for AC values BS ea (Electronic Arts)
  10008 This is using custom MDEC values from VLC0 chunk, and assigns them to the
  10009 standard Huffman codes. There are two special MDEC values:
  10010   FE00h End of Block (EOB)
  10011   7C1Fh Escape code (huffman code will be followed by v2-style 16bit value)
  10012 VLC0 chunk entries 00h..DFh are mapped to the following Huffman codes:
  10013   10                   00
  10014   11x                  01,02
  10015   011x                 03,04
  10016   010xx                05,06,07,08
  10017   0011xx               0D,0E,0B,0C
  10018   00101x               09,0A
  10019   00100xxxx            2E,2F,22,23,2C,2D,2A,2B,26,27,24,25,20,21,28,29
  10020   0001xxx              15,16,13,14,0F,10,11,12
  10021   00001xxx             1A,1B,1E,1F,18,19,1C,1D
  10022   000001               17h
  10023   0000001xxxx          3E,3F,38,39,30,31,34,35,32,33,3C,3D,3A,3B,36,37
  10024   00000001xxxxx        46,47,54,55,4E,4F,44,45,4A,4B,52,53,5E,5F,5C,5D,
  10025                        42,43,5A,5B,58,59,48,49,4C,4D,40,41,50,51,56,57
  10026   000000001xxxxx       74,75,72,73,70,71,6E,6F,6C,6D,6A,6B,68,69,66,67,
  10027                        64,65,62,63,60,61,7E,7F,7C,7D,7A,7B,78,79,76,77
  10028   0000000001xxxxx      9E,9F,9C,9D,9A,9B,98,99,96,97,94,95,92,93,90,91,
  10029                        8E,8F,8C,8D,8A,8B,88,89,86,87,84,85,82,83,80,81
  10030   00000000001xxxxx     B0,B1,AE,AF,AC,AD,AA,AB,A8,A9,A6,A7,A4,A5,A2,A3,
  10031                        A0,A1,BE,BF,BC,BD,BA,BB,B8,B9,B6,B7,B4,B5,B2,B3
  10032   000000000001xxxxx    C6,C7,C4,C5,C2,C3,C0,C1,C8,C9,D4,D5,D2,D3,D0,D1,
  10033                        CE,CF,CC,CD,CA,CB,DE,DF,DC,DD,DA,DB,D8,D9,D6,D7
  10034   000000000000         Unused
  10035 All codes can be freely assigned (Escape and EOB don't need to be at 10 and
  10036 000001, and the last huffman bit doesn't have to serve as sign bit).
  10037 
  10038 Notes
  10039 All BS versions are using the same Huffman codes (the different BS versions do
  10040 just assign different 16bit MDEC codes to them).
  10041 The huffman codes can be neatly decoded by "counting leading zeroes" (without
  10042 needing bitwise node-by-node processing; this is done in IKI video decoders via
  10043 GTE registers LZCS and LZCR). Sony's normal v2/v3 decoders are using a yet
  10044 faster method: A large table to interprete the next 13bit of the bitstream, the
  10045 table lookup can decode up to 3 huffman codes at once (if the 13bit contain
  10046 several small huffman codes).
  10047 
  10048 CDROM File Video BS Picture Files
  10049 ---------------------------------
  10050 
  10051 BS Picture Files
  10052 A couple of games are storing single pictures in .BS files:
  10053   Alice in Cyberland (ALICE.PAC\*.BS)
  10054   BallBlazer Champions (BBX_EXTR.DAT\Pics\*) (SWAP-encrypted)
  10055   Bugriders: The Race of Kings (*\*.BS and STILLS\MENUS.BS\*)
  10056   Die Hard Trilogy 2 (DATA\*.DHB, DATA\DH*\L*\*.DHB, MOVIE\*.DHB)
  10057   Dino Crisis 2 (PSX\DATA\ST*.DBS\*)
  10058   Duke Nukem (MagDemo12: DN_TTK\*)
  10059   Final Fantasy VII (FF7) (MOVIE\FSHIP2*.BIN\*) (BS v1)
  10060   Gran Turismo 1 (retail TITLE.DAT\* and MagDemo10/15) (in BS iki format)
  10061   Jet Moto 2 (MagDemo03: JETMOTO2\*)
  10062   Mary-Kate and Ashley Crush Course (MagDemo52: CRUSH\SCRN\*.BS)
  10063   Mat Hoffman's Pro BMX (MagDemo48: MHPB\STILLS.BIN\*) (with width/height info)
  10064   NFL Gameday '99 (MagDemo17: GAMEDAY\FE\GD98DATA.DAT)
  10065   Official U.S. PlayStation Magazine Demo Disc 01-02 (MENU\DATA\*.BSS)
  10066   Official U.S. PlayStation Magazine Demo Disc 03-54 (MENU.FF\*)
  10067   Parasite Eve 2 (INIT.BS, and within .HED/.CDF archives)
  10068   Resident Evil 1 (PSX\STAGE*\*.BSS, headerless archive, 8000h-byte align)
  10069   Resident Evil 2 (COMMON\BSS\*.BSS, headerless archive, 10000h-byte align)
  10070   Rugrats (MagDemo19: RUGRATS\*)
  10071   Rugrats Studio Tour (MagDemo32: RUGRATS\DATA\RAW\*.BS)
  10072   Starwars Demolition (MagDemo39+MagDemo41: STARWARS\SHELL\.BS+.TBL\*)
  10073   Star Wars Rebel Assault 2 (RESOURCE.000\Stills\*) (SWAP-encrypted)
  10074   Ultimate Fighting Championship (MagDemo38: UFC\CU00.RBB\390h..3E2h)
  10075   Vigilante 8 (MagDemo09: EXAMPLE\*)
  10076   Witch of Salzburg (PICT\PIC*\*.BS and DOT1 archives *.BSS, *.DAT, *.BIN)
  10077   X-Files (LOGOS\*.BS and GRAPHICS\GRAPHICS.BIN and GRAPHICS\PACKEDBS.BIN\*)
  10078   You Don't Know Jack 2 (MagDemo41: YDKJV2\RES\UI\*.BS)
  10079 Note: Those .BS files are usually hidden in custom file archives.
  10080 
  10081 BS Picture Resolution
  10082 Movies have Width/Height entries (in the .STR header). Raw .BS picture files
  10083 don't have any such information. However, there are ways to guess the correct
  10084 resolution:
  10085   For BS iki format, use resolution from iki header (eg. Gran Turismo 1)
  10086   For MHPB\STILLS.BIN, there's width/height in chunk headers
  10087   Count the number of blocks (EOB codes) during Huffman decompression
  10088   Divide that number by 6 to get the number of Macroblocks
  10089   Search matches for Height=NumBlocks/Width with Width>=Height and Remainder=0
  10090   If Height=300..400, assume double H-resolution, repeat with Width/2>=Height
  10091   And/or use a list of known common resoltions (see below examples)
  10092   Search arrangements with many similar colors on adjacent macroblocks
  10093 Common resolutions are:
  10094   Blocks Pixels   Example
  10095   F0h    256x240  any?
  10096   12Ch   320x240  Resident Evil 2 (COMMON\BSS\*.BSS)
  10097   1E0h   512x240  Demo Disc 03-54 (MENU.FF\*), Duke Nukem (MagDemo12)
  10098   1E0h   640x192  Less common than above (but used by Witch of Salzburg)
  10099   4B0h   640x480  Vigilante 8 (MagDemo09), Jet Moto 2 (MagDemo03)
  10100   var    random   Witch of Salzburg has various random resolutions
  10101   iki    ikihdr   Gran Turismo 1 has A0hxA0h and odd size (!) E8hx28h
  10102   ?      ?        Final Fantasy VII (FF7)
  10103   ?      ?        Ultimate Fighting Championship (UFC\CU00.RBB\3B7h..3E2h)
  10104   118h   320x224  Alice in Cyberland (most files; or two such as panorama)
  10105   230h   ?        Alice in Cyberland (AD_115.BS and AD_123A.BS)
  10106 Some other possible, but rather unlikely results would be:
  10107   C8h    320x160  Unlikely for pictures (but used for STR videos, eg. Alone)
  10108   F0h    320x192  Unlikely for pictures (but used for STR videos, eg. Wipeout)
  10109   1E0h   384x320  Very unlikely to see that vertical resolution on PSX
  10110 Witch of Salzburg has many small .BS files with various uncommon resolutions
  10111 (most of them are bundled with 16-byte .TXT files with resolution info).
  10112 
  10113 Extended BS with Width/Height
  10114 Starwars Demolition (MagDemo39: STARWARS\SHELL\DEMOLOGO.BS+RESOURCE.TBL\*)
  10115 Starwars Demolition (MagDemo41: STARWARS\SHELL\DEMOLOGO.BS+RESOURCE.TBL\*)
  10116   000h 2    Width  (280h)       ;\extra header
  10117   002h 2    Height (1E0h)       ;/
  10118   004h 2    MDEC Size/4 (after huffman decompression) (rounded to 80h/4 bytes)
  10119   006h 2    File ID (3800h)
  10120   008h 2    Quantization step/factor (0000h..003Fh, for MDEC "DCT.bit10-15")
  10121   00Ah 2    Version (1, 2, or 3) (2 is most common)
  10122   00Ch ...  Huffman compressed data blocks (Cr,Cb,Y1,Y2,Y3,Y4, Cr,Cb,Y1,Y2..)
  10123 
  10124 CDROM File Video Wacwac MDEC Streams
  10125 ------------------------------------
  10126 
  10127 Wacwac uses different Huffman codes than BS videos, the decoder has some
  10128 promising ideas that might yield slightly better compression than BS v3.
  10129 However, it is used by only one known game:
  10130   Aconcagua (JP) (2000 Sony/WACWAC!)
  10131 And even that game is only using it in two movies, and the movies are barely
  10132 making any use of it: The 20Mbyte intro scene is a picture slide show (where
  10133 the camera is zooming across twelve black and white images), the 50Mbyte ending
  10134 scene is providing a more cinematic experience (the camera is scrolling through
  10135 a text file with developer staff names).
  10136 
  10137 Wacwac MDEC Stream Sectors
  10138   000h 2    STR ID   (0160h)
  10139   002h 2    STR Type WACWAC Tables (0002h=IntroTableSet, 0003h=EndingTableSet)
  10140   004h 2    Sector number within current Frame (0000h..num-1)
  10141   006h 2    Number of Sectors in this Frame
  10142   008h 4    Frame number (6 or 11 and up, because 1st some frames are Polygons)
  10143   00Ch 4    Frame Size in bytes
  10144   010h 2    Bitmap Width  (always 140h)  ;\always 320x208 (in fact, the
  10145   012h 2    Bitmap Height (always 0D0h)  ;/decoder is hardcoded as so)
  10146   014h 4    Quant (0..3Fh) (same for all sectors within the frame)
  10147   018h 8    Zerofilled
  10148   020h 7E0h Raw Bitstream data (without Quant or BS header) (garbage padded)
  10149 Aconcagua has dozens of STR files with Polygon Streams. MDEC Streams are found
  10150 only in two STR files for Intro and Ending scenes:
  10151   Intro=Disc1:\ST01_01\STR_01_00.STR     Ending=Disc2:\ST09_01\STR_09_01.STR
  10152   Leading zeroes (150 sectors)           Leading zeroes (150 sectors)
  10153   Frame 0001h..0005h Polygon Frames      Frame 0001h..000Ah Polygon Frames
  10154   Frame 0006h..0545h MDEC Frames 20MB    Frame 000Bh..0D79h MDEC Frames 50MB
  10155   Frame 0546h..1874h Polygon Frames 48MB
  10156 Audio is normal XA-ADPCM, with the first audio sector occuring before 1st frame
  10157 (after the leading zeropadded 150 sectors).
  10158 
  10159 Wacwac Huffman Bitstreams
  10160 Wacwac uses little-endian bitstreams (starting with low bit in bit0 of first
  10161 byte). To decode the separate blocks in the bitstream:
  10162   Read Huffman code for DC, and output Quant*400h+(DC AND 3FFh)
  10163   Read Huffman code for Size, aka num1,num2,num3 values for below reads
  10164   Repeat num1 times: Read Huffman code for AC1, and output AC
  10165   Repeat num2 times: Read Huffman code for AC2, and output AC
  10166   Repeat num3 times: Read Huffman code for AC3, and output AC
  10167   Output EOB (end of block)
  10168 The header/data lacks info about MDEC size after Huffman decompression, the
  10169 worst case size for 320x208pix would be:
  10170   14h*0Dh*6*41h*2+Align(80h)+Header(4) = 31880h+4 bytes
  10171 Note: The bitstream consists of separate 16x208pix slices (set DC for Cr,Cb,Y
  10172 to zero at begin of each slice, and skip padding to 32bit-boundary at end of
  10173 each slice).
  10174 
  10175 Wacwac Huffman Table Sets
  10176 Aconcagua has two table sets, stored in PROGRAM.BIN (in compressed form,
  10177 appearing as so: FF,90,16,2E,06,20,03,D6,etc). While watching the intro movie,
  10178 the uncompressed sets can be found at these RAM locations:
  10179   80112AF8h (1690h bytes)  ;Table Set for Intro Scene
  10180   80114188h (1B68h bytes)  ;Table Set for Ending Scene
  10181 Each Table Set has a 38h-byte header, followed by five tables:
  10182   000h 4    Table Set size (1690h or 1B68h)
  10183   004h 4    Table Set exploded size (when allocating 16bit/DC, 32bit/Size/AC)
  10184   008h 2    Size Table max Huffman size in bits  (0Ah or 09h)           ;\Size
  10185   00Ah 2    Size Table number of entries         (40h)                  ;/
  10186   00Ch 2    DC Table max Huffman size in bits    (0Bh)                  ;\
  10187   00Eh 2    DC Table number of entries           (100h)                 ; DC
  10188   010h 2    DC Huffman code Escape 10bit (non-relative 10bit DC value)  ;
  10189   012h 2    DC Huffman size Escape 10bit (3 or 6, escape prefix size)   ;/
  10190   014h 2    AC1 Table max Huffman size in bits   (0Eh or 0Bh)           ;\
  10191   016h 2    AC1 Table number of entries          (0DAh or 100h)         ;
  10192   018h 2    AC1 Huffman code Escape 7bit  (run=0bit, level=signed7bit)  ; AC1
  10193   01Ah 2    AC1 Huffman code Escape 16bit (run=6bit, level=10bit)       ;
  10194   01Ch 2    AC1 Huffman size Escape 7bit  (9 or 7, escape prefix size)  ;
  10195   01Eh 2    AC1 Huffman size Escape 16bit (9 or 7, escape prefix size)  ;/
  10196   020h 2    AC2 Table max Huffman size in bits   (0Eh)                  ;\
  10197   022h 2    AC2 Table number of entries          (AAh or F4h)           ;
  10198   024h 2    AC2 Huffman code Escape 8bit  (run=3bit, level=signed5bit)  ; AC2
  10199   026h 2    AC2 Huffman code Escape 16bit (run=6bit, level=10bit)       ;
  10200   028h 2    AC2 Huffman size Escape 8bit  (10 or 9, escape prefix size) ;
  10201   02Ah 2    AC2 Huffman size Escape 16bit (10 or 9, escape prefix size) ;/
  10202   02Ch 2    AC3 Table max Huffman size in bits   (0Eh)                  ;\
  10203   02Eh 2    AC3 Table number of entries          (87h or B2h)           ;
  10204   030h 2    AC3 Huffman code Escape 8bit  (run=4bit, level=signed4bit)  ; AC3
  10205   032h 2    AC3 Huffman code Escape 16bit (run=6bit, level=10bit)       ;
  10206   034h 2    AC3 Huffman size Escape 8bit  (10 or 9, escape prefix size) ;
  10207   036h 2    AC3 Huffman size Escape 16bit (10 or 9, escape prefix size) ;/
  10208   038h ..   Size Table (64bit per entry)    ;\
  10209   ...  ..   DC Table   (32bit per entry)    ;
  10210   ...  ..   AC1 Table  (64bit per entry)    ; Tables
  10211   ...  ..   AC2 Table  (64bit per entry)    ;
  10212   ...  ..   AC3 Table  (64bit per entry)    ;/
  10213 Size Table entries (64bit):
  10214   0-1    Zero
  10215   2-31   Huffman code (10bit max)
  10216   32-39  Number of AC1 codes in this block  ;\implies End of Block (EOB)
  10217   40-47  Number of AC2 codes in this block  ; after those AC codes
  10218   48-55  Number of AC3 codes in this block  ;/
  10219   56-63  Huffman size (1..10 bits)
  10220 DC Table entries (32bit):
  10221   0-9    Relative DC Value (relative to old DC from memorized Cr,Cb,Y)
  10222   10-15  Huffman size (1..11 bits)
  10223   16-31  Huffman code (11bit max)
  10224  Notes: For the relative DC's, the decoder does memorize DC for Cr,Cb,Y upon
  10225   decoding Cr,Cb,Y1,Y3 (but does NOT memorize DC when decoding Y2,Y4).
  10226   Initial DC for Cr,Cb,Y is zero at begin of each 16x208pix slice.
  10227  Obscurities: The decoder does accidentally use bit10 to sign-expand the
  10228   DC value in bit0-9 (but does mask-off those bugged sign bits thereafter),
  10229   and the decoder does uselessly memorize Y1 and Y3 separately (but uses only
  10230   the most recently memorized value).
  10231 AC1/AC2/AC3 Table entries (64bit):
  10232   0-1    Zero
  10233   2-31   Huffman code (14bit max)
  10234   32-47  MDEC code (6bit run, and 10bit AC level)
  10235   48-63  Huffman size (1..14 bits)
  10236 The Escape codes are stored in the 38h-byte Table Set header (instead of in the
  10237 tables), the init function uses that info for patching escape-related opcodes
  10238 in the decoder function (that would allow to omit table lookups upon escape
  10239 codes; the decoder doesn't actually omit such lookups though).
  10240 To simplify things, one could store the escape codes in the tables (eg. using
  10241 special MDEC values like FC00h+35h for run=3bit, level=signed5bit).
  10242 
  10243 CDROM File Video Polygon Streaming
  10244 ----------------------------------
  10245 
  10246 Ape Escape - Polygon Streaming
  10247 Used by Ape Escape (Sony 1999) (DEMO\*.STR and some STR\*.STR files and
  10248 KKIIDDZZ.HED\STR\0006h and up).
  10249 The files start with zerofilled sectors (without STR headers), followed by
  10250 sectors with STR headers with [00h]=0160h, [02h]=8001h (same values as for
  10251 MDEC), but with [10h..1Fh]=zero (without resolution/header info). And the data
  10252 at [20h] starts with something like 14h,00h,03h,FFh,2Ah,02h,00h,00h.
  10253 That data seems to consist of polygon coordinates/attributes that are rendered
  10254 as movie frames. The texture seems to be stored elsewhere (maybe in the .ALL
  10255 files that are bundled with some .STR files).
  10256 
  10257 Panekit - Polygon Streaming
  10258 Panekit STR seems to use Polygon Streaming (except 1st some Megabytes are
  10259 MDEC).
  10260 
  10261 Aconcagua - Polygon Streaming
  10262 Aconcagua STR does use Polygon Streaming (except first+last movie are MDEC).
  10263 
  10264 Cyberia (1996) (TF\STR\*.STR)
  10265 Cyberia is using Software-rendering for both movies and in-game graphics. That
  10266 is, PSX hardware features like MDEC, GTE, and GPU-Polygons are left all unused,
  10267 and the GPU is barely used for transferring data from CPU to VRAM.
  10268 The STR header for software-rendered movie frames looks as so:
  10269   000h 2    STR ID   (0160h)
  10270   002h 2    STR Type (0002h=Custom, Software rendering)
  10271   004h 2    Sector number within current Frame (0..num-1)
  10272   006h 2    Number of Sectors in this Frame    (varies)
  10273   008h 4    Frame Number (1=First)
  10274   00Ch 4    Frame Size in Bytes/4 (note: first frame in MAP*.STR is quite big)
  10275   010h 2    Rendering Width  (0140h)
  10276   012h 2    Rendering Height (00C0h)
  10277   014h 0Ch  Unknown (zerofilled or random garbage)
  10278   020h 7E0h Custom data for software rendering
  10279 Note: First sector of First frame does usually have byte[22h]=88h (except
  10280 FINMUS.STR). The Custom data part is often have garbage padding (such like
  10281 ASCII strings with "c2str" command line tool usage instructions).
  10282 
  10283 Croc 1 (CUTS\*.AN2)
  10284 Probably cut-scenes with polygon animations. The files seem to contain
  10285 2300h-byte data frames (plus XA-ADPCM sectors inserted here and there).
  10286   000h 4     Number of remaining frames
  10287   ...  22FCh Unknown data (zeropadded if smaller)
  10288 
  10289  _______________ Unknown Streaming Data (Polygons or whatever) ________________
  10290 
  10291 Custom STR - 3D Baseball (BIGFILE.FOO)
  10292 This is used for several files in 3D Baseball (BIGFILE.FOO):
  10293   BIGFILE.FOO\0151h\0005h,0009h,000Fh,0017h,001Bh, 02E5h,02E9h,..,0344h,0348h
  10294   BIGFILE.FOO\0152h\0186h,018Ch,0192h,0198h)
  10295   BIGFILE.FOO\0153h\029Ah,02A0h,02A6h,02ACh)
  10296 The files contain some kind of custom streaming data, with custom STR header,
  10297 and data containing increasing/decreasing bytes... maybe non-audio waveforms?
  10298   000h 2    STR ID   (0160h)
  10299   002h 2    STR Type (0001h=Custom)
  10300   004h 2    Sector number within current Frame (always 0)
  10301   006h 2    Number of Sectors in this Frame    (always 1)
  10302   008h 4    Frame Number (1=First)
  10303   00Ch 4    Frame Size (6FAh or 77Ah, sometimes 17Ah or 1FAh or 20Ah)
  10304   010h 2    Unknown (280h, or sometimes 300h or 340h)
  10305   012h 2    Frame Time (0=First, increases with step [19h], usually +5 or +7)
  10306   014h 2    Unknown (280h, or sometimes 300h or 3C0h, or 0)
  10307   016h 1    Frame Time (same as [012h] AND FFh)
  10308   017h 1    Unknown (0 or 1)
  10309   018h 1    Unknown (40h, or 80h, or C0h)
  10310   019h 1    Duration? (5 or 7, or sometimes less, step for Frame Time)
  10311   01Ah 1    Unknown (3, or less in last some frames)
  10312   01Bh 5    Zerofilled
  10313   020h 7E0h Data (increasing/decreasing bytes... maybe non-audio waveforms?)
  10314 
  10315 Army Men Air Attack 2 (MagDemo40: AMAA2\*.PMB)
  10316   000h 2     STR ID   (0160h)
  10317   002h 2     STR Type (0000h=Custom)
  10318   004h 2     Sector number within current Frame (0..2)
  10319   006h 2     Number of Sectors in this Frame    (always 4) (3xSTR + 1xADPCM)
  10320   008h 4     Frame Number (1=First)
  10321   00Ch 4     Frame Size? (800h, despite of having 3 sectors with 7E0h each?)
  10322   010h 2     Unknown (00h or 01h)
  10323   012h 2     Unknown (A3h or ABh ... 6Ch or 7Bh ... or 43h or 49h)
  10324   014h 2     Sector number within current Frame (0..2) (same as [004h])
  10325   016h 0Ah   Zerofilled
  10326   020h 7E0h  Data (polygon streaming or so?)
  10327 Note: The .PMB file is bundled with a .PMH file, which might contain header
  10328 info?
  10329 
  10330 Bits Laboratory games (Charumera, and True Love Story series)
  10331   Charumera                  ENDING.XA     (with dummy/zero data)
  10332   True Love Story            TLS\MULTI.XA  (with nonzero data)
  10333   True Love Story 2          TLS2\ENDING.STR and TLS2\MULTI.XA
  10334   True Love Story Fan Disc            ;\probably use that format, too
  10335   True Love Story: Remember My Heart  ;/(not verified)
  10336 The STR headers have STR ID=0160h and STR Type=0001h, STR header[10h..1Fh]
  10337 contains nonsense BS video info (with BS ID=3800h, although there isn't any BS
  10338 data in the actual data part at offset 20h and up).
  10339 The files do mainly contain XA-ADPCM sectors, plus some STR sectors in non-MDEC
  10340 format. Unknown if that STR sectors are separate channels, or if they are used
  10341 in parallel with the XA-ADPCM channel(s).
  10342 Unknown what the STR sectors are used for (perhaps Polygon Streaming, audio
  10343 subtitles, or simple garbage padding for unused audio sectors). In some files,
  10344 the STR sectors appear to be just dummy padding (STR header plus zerofilled
  10345 data area).
  10346 
  10347 Nightmare Project: Yakata
  10348 This game has normal MDEC Streams, and Special Streams in non-MDEC format (eg.
  10349 Disc1, File 0E9h-16Eh and 985h-B58h), perhaps containing Polygon Streams or
  10350 whatever.
  10351 There are two channels (file=1/channel=00h-01h), each channel contains data
  10352 that consists of 5 sectors per frame (1xHeader plus 4xData). The sectors have
  10353 STR ID=0160h, and STR Type as follows:
  10354   0000h=Whatever special, channel 0 header (sector 0)
  10355   0400h=Whatever special, channel 1 header (sector 1)
  10356   0001h=Whatever special, channel 0 data   (sector 2,4,6,8)
  10357   0401h=Whatever special, channel 1 data   (sector 3,5,7,9)
  10358 
  10359 Eagle One: Harrier Attack STR files
  10360   \*.STR            MDEC movies  ;\BS fraquant (except, demo version
  10361   \DATA*\*.STR      MDEC movies  ;/            on MagDemo31 uses mormal BS v2)
  10362   \DATA*\M*\L*.STR  Multi-language TXT files with STR header on each sector
  10363   \DATA*\M*\I*.STR  unknown binary data (whatever and SPU-ADPCM)
  10364   \LANGN.STR        unknown binary data (whatever)
  10365 All of the above have STR Type=8001h (but only the MDEC movies have BS ID
  10366 3800h; the MDEC movies start with 13 zerofilled sectors that are all zeroes
  10367 without any STR/BS headers).
  10368 
  10369 CDROM File Audio Single Samples VAG (Sony)
  10370 ------------------------------------------
  10371 
  10372 VAG audio samples
  10373 PSX Lightspan Online Connection CD, cdrom:\CD.TOC:\UI*\*.VAG
  10374 PSX Wipeout 2097, cdrom:\WIPEOUT2\SOUND\SAMPLES.WAD:\*.vag (version=02h)
  10375 PSX Perfect Assassin, DATA.JFS:\AUDIO\*.VAG and DATA.JFS:\SND\*.VAG
  10376   000h 4    File ID (usually "VAGp")
  10377   004h 4    Version (usually 02h, or 20h)                       (big-endian)
  10378   008h 4    Reserved (0) (except when ID="VAGi")                (big-endian)
  10379   00Ch 4    Channel Size (data size... per channel?)            (big-endian)
  10380   010h 4    Sample Rate (in Hertz) (eg. 5622h=22050Hz)          (big-endian)
  10381   014h 0Ch  Reserved (0) (except when version=2)
  10382   020h 10h  Name (ASCII, zeropadded)
  10383   ... (..)  Optional ID string (eg. "STEREO" in upper/lowercase)
  10384   ... (..)  Optional Padding to Data start
  10385   ...  ..   ADPCM Data for channel(s) (usually at offset 030h)
  10386 VAG files are used on PSX, PSP, PS2, PS3, PS4. The overall 1-channel mono
  10387 format is same for consoles. But there are numerous different variants for
  10388 interleaved 2-channel stereo data.
  10389 
  10390 VAG Filename Extensions
  10391   .vag      default (eg. many PSX games)
  10392   .vig      2-channel with interleave=10h (eg. PS2 MX vs ATV Untamed)
  10393   .vas      2-channel with interleave=10h (eg. PS2 Kingdom Hearts II)
  10394   .swag     2-channel with interleave=filesize/2 (eg. PSP Frantix)
  10395   .l and .r 2-channel in l/r files (eg. PS2 Gradius V, PS2 Crash Nitro Kart)
  10396   .str      whatever (eg. P?? Ben10 Galactic Racing)
  10397   .abc      whatever (eg. PSP F1 2009 (v6), according to wiki.xentax.com)
  10398 
  10399 VAG File IDs (header[000h])
  10400   "VAGp"  default (eg. many PSX games)
  10401   "VAG1"  1-channel (eg. PS2 Metal Gear Solid 3)
  10402   "VAG2"  2-channel (eg. PS2 Metal Gear Solid 3)
  10403   "VAGi"  2-channel interleaved (eg. ?)
  10404   "pGAV"  little endian with extended header (eg. PS2 Jak 3, PS2 Jak X)
  10405   "AAAp"  extra header, followed by "VAGp" header (eg. PS2 The Red Star)
  10406 
  10407 VAG Versions (header[004h])
  10408   00000000h   v1.8 PC
  10409   00000002h   v1.3 Mac (eg. PSX Wipeout 2097, in SAMPLES.WAD)
  10410   00000003h   v1.6+ Mac
  10411   00000020h   v2.0 PC (most common, eg. PSX Perfect Assassin)
  10412   00000004h   ? (later games, uh when/which?)
  10413   00000006h   ? (vagconf, uh when/which?)
  10414   00020001h   v2.1 (vagconf2)   ;\with HEVAG coding instead SPU-ADPCM
  10415   00030000h   v3.0 (vagconf2)   ;/(eg. PS4/Vita)
  10416   40000000h   ? (eg. PS2 Killzone) (1-channel, little endian header)
  10417 
  10418 Reserved Header entries for ID="VAGi"
  10419   008h 4  Interleave (little endian) (the other header entries are big endian)
  10420 
  10421 Reserved Header entries for Version=00000002h (eg. PSX Wipeout 2097)
  10422 This does reportedly contain some default "base" settings for the PSX SPU:
  10423   014h 2  Volume left                    4Eh,82h  ;-Port 1F801C00h
  10424   016h 2  Volume right                   4Eh,82h  ;-Port 1F801C02h
  10425   018h 2  Pitch (includes fs modulation) A8h,88h  ;-Port 1F801C04h +extra bit?
  10426   01Ah 2  ADSR1                          00h,00h  ;-Port 1F801C08h
  10427   01Ch 2  ADSR2                          00h,E1h  ;-Port 1F801C0Ah
  10428   01Eh 2  ?                              A0h,23h  ;-Port 1F801C0xh maybe?
  10429 
  10430 Reserved Header entries for Version=00000003h (according to wiki.xentax.com)
  10431   01Eh 1  Number of channels (0 or 1=Mono, 2=Stereo)
  10432 
  10433 Reserved Header entries for Version=00020001h and Version=00030000h
  10434   01Ch 2  Zero                                      ;if non-zero: force Mono
  10435   01Eh 1  Number of channels (0 or 1=Mono, 2=Stereo ;if 10h..FFh: force Mono
  10436   01Fh 1  Zero                                      ;if non-zero: force Mono
  10437 Unknown if the above "force Mono" stuff is really needed (maybe it was intended
  10438 to avoid problems with Version=00000002h, and maybe never happens in
  10439 Version=00000003h and up)?
  10440 
  10441 VAG ADPCM Data
  10442 The ADPCM data uses PSX SPU-ADPCM encoding (even on PS2 and up, except PS4 with
  10443 Version=0002001h or Version=00030000h, which do use HEVAG encoding).
  10444 --> SPU ADPCM Samples
  10445 The data does usually start at offset 0030h (except, some files have extra
  10446 header data or padding at that location).
  10447 The first 10h-byte ADPCM block is usually all zero (used to initialize the
  10448 SPU).
  10449 2-channel (stereo) files are usually interleaved in some way.
  10450 
  10451 VAG Endiannes
  10452 The file header entries are almost always big-endian (even so when used on
  10453 little endian consoles). There are a few exceptions:
  10454 ID="VAG1" has little endian [008h]=Interleave (remaining header is big-endian).
  10455 ID="pVAG" has (some?) header entries in little endian.
  10456 Version=40000000h has most or all header entries in little endian (perhaps
  10457 including the version being meant to be 00000040h).
  10458 
  10459 VAG Channels
  10460 VAGs can be 1-channel (mono) or 2-channel (stereo). There is no standarized way
  10461 to detect the number of channels (it can be implied in the Filename Extension,
  10462 Header ID, in Reserved Header entries, in the Name string at [020h..02Fh], in
  10463 optional stuff at [030h], or in a separate VAG Header in the middle of the
  10464 file).
  10465 
  10466 VAG Interleave
  10467   None       default (for 1-channel mono) (and separate .l .r stereo files)
  10468   800h       when ID="VAG2"
  10469   [008h]     when ID="VAGi" (little-endian 32bit header[008h])
  10470   1000h      when ID="pGAV" and [020h]="Ster" and this or that
  10471   2000h      when ID="pGAV" and [020h]="Ster" and that or this
  10472   10h        when filename extension=".vig"
  10473   10h        when Version=0002001h or Version=00030000h (and channels=2)
  10474   filesize/2 when filename extension=".swag"
  10475   6000h      when [6000h]="VAGp" (eg. PSX The Simpsons Wrestling)
  10476   1000h      when [1000h]="VAGp" (eg. PS2 Sikigami no Shiro)
  10477   ...
  10478 
  10479 AAAp Header
  10480   000h 4     ID "AAAp"
  10481   004h 2     Interleave
  10482   006h 2     Number of Channels (can be 1 or 2?)
  10483   008h 30h*N VAGp header(s) for each channel, with Version=00000020h
  10484   ...  ..    ADPCM Data (interleaved when multiple channels)
  10485 
  10486 See also
  10487 http://github.com/vgmstream/vgmstream/blob/master/src/meta/vag.c ;very detailed
  10488 http://wiki.xentax.com/index.php/VAG_Audio ;rather incomplete and perhaps wrong
  10489 
  10490 CDROM File Audio Sample Sets VAB and VH/VB (Sony)
  10491 -------------------------------------------------
  10492 
  10493 VAB vs VH/VB
  10494   .VAB  contains VAB header, and ADPCM binaries   ;-all in one file
  10495   .VH   contains only the VAB header              ;\in two separate files
  10496   .VB   contains only the ADPCM binaries          ;/
  10497 PSX Perfect Assassin has some v7 .VH/.VB's (in \DATA.JFS:\SND\*.*)
  10498 PSX Resident Evil 2, COMMON\DATA\*.DIE (contains .TIM+.VAB badged together)
  10499 PSX Spider-Man, CD.HED\l2a1.vab is VAB v5 (other VABs in that game are v7)
  10500 PSX Tenchu 2 (MagDemo35: TENCHU2\VOLUME.DAT\5\* has VAB v20h, maybe a typo)
  10501 
  10502 VAB Header (VH)
  10503   0000h 4       File ID ("pBAV")
  10504   0004h 4       Version (usually 7) (reportedly 6 exists, too) (5, 20h exists)
  10505   0008h 4       VAB ID (usually 0)
  10506   000Ch 4       Total .VAB filesize in bytes (or sum of .VH and .VB filesizes)
  10507   0010h 2       Reserved (EEEEh)
  10508   0012h 2       Number of Programs, minus 1 (0000h..007Fh = 1..128 programs)
  10509   0014h 2       Number of Tones, minus? (max 0800h?) (aka max 10h per program)
  10510   0016h 2       Number of VAGs, minus? (max 00FEh)
  10511   0018h 1       Master Volume (usually 7Fh)
  10512   0019h 1       Master Pan    (usually 40h)
  10513   001Ah 1       Bank Attribute 1 (user defined) (usually 00h)
  10514   001Bh 1       Bank Attribute 2 (user defined) (usually 00h)
  10515   001Ch 4       Reserved (FFFFFFFFh)
  10516   0020h 800h    Program Attributes 10h-byte per Program 00h..7Fh   (fixed size)
  10517   0820h P*200h  Tone Attributes 200h-byte per Program 00h..P-1  (variable size)
  10518   xx20h 200h    16bit VAG Sizes (div8) for VAG 00h..FFh            (fixed size)
  10519   xx20h (...)   ADPCM data (only in .VAB files, otherwise in separate .VB file)
  10520 Program Attributes (10h-byte per Program, max 80h programs)
  10521   000h 1      tones        Number of Tones in the Program (Yaroze: 4) (uh?)
  10522   001h 1      mvol         Master Volume   (Yaroze: 0..127)
  10523   002h 1      prior                        (Yaroze: N/A)
  10524   003h 1      mode                         (Yaroze: N/A)
  10525   004h 1      mpan         Master Panning  (Yaroze: 0..127)
  10526   005h 1      reserved0
  10527   006h 2      attr                         (Yaroze: N/A)
  10528   008h 4      reserved1
  10529   00Ch 4      reserved2
  10530 Tone Attributes (20h-byte per Tone, max 10h tones per Program)
  10531   000h 1      prior        Tone Priority   (Yaroze: 0..127, 127=highest)
  10532   001h 1      mode         Mode            (Yaroze: 0=Normal, 4=Reverberation)
  10533   002h 1      vol          Tone Volume     (Yaroze: 0..127)
  10534   003h 1      pan          Tone Panning    (Yaroze: 0..127)
  10535   004h 1      center       Centre note (in semitone units) (Yaroze: 0..127)
  10536   005h 1      shift        Centre note fine tuning         (Yaroze: 0..127)
  10537   006h 1      min          Note limit minimum value     (Yaroze: 0..127)
  10538   007h 1      max          Note limit maximum value     (Yaroze: 0..127)
  10539   008h 1      vibW                                      (Yaroze: N/A)
  10540   009h 1      vibT                                      (Yaroze: N/A)
  10541   00Ah 1      porW                                      (Yaroze: N/A)
  10542   00Bh 1      porT                                      (Yaroze: N/A)
  10543   00Ch 1      pbmin        Max? value for downwards pitchbend  (Yaroze: 0..127)
  10544   00Dh 1      pbmax        Max value for upwards pitchbend     (Yaroze: 0..127)
  10545   00Eh 1      reserved1
  10546   00Fh 1      reserved2
  10547   010h 2      ADSR1        Attack,Decay    (Yaroze: 0..127,0..15)
  10548   012h 2      ADSR2        Release,Sustain (Yaroze: 0..127,0..31)
  10549   014h 2      prog         Program number that tone belongs to (Yaroze: 0..127)
  10550   016h 2      vag          VAG number                          (Yaroze: 0..254)
  10551   018h 8      reserved
  10552 
  10553 VAB Binary (VB) (ADPCM data) (to be loaded to SPU RAM)
  10554 This can contain max 254 "VAG files" (maybe because having two (?) reserved
  10555 8bit numbers?).
  10556 Sony wants the total size of the ADPCM data to be max 7E000h bytes (which would
  10557 occupy most of the 512Kbyte SPU RAM, leaving little space for the echo buffer
  10558 or additional effects).
  10559 Note: The "VAG files" inside of VAB/VB are actually raw SPU-ADPCM data, without
  10560 any VAG file header. The first 10h-byte ADPCM block is usually zerofilled.
  10561 
  10562 CDROM File Audio Sequences SEQ/SEP (Sony)
  10563 -----------------------------------------
  10564 
  10565 SEQ - Single Sequence
  10566 .SEQ contains MIDI-style sequences, the samples for the instruments can be
  10567 stored in a separate .VAB file (or .VH and .VB files).
  10568 Used by Perfect Assassin, DATA.JFS:\SND\*.SEQ (bundled with *.VH and *.VB)
  10569 Used by Croc (MagDemo02: CROC\CROCFILE.DIR\AMBI*.BIN, MAP*.BIN, JRHYTHM.BIN)
  10570 Used by many other games.
  10571   000h 4   File ID "pQES"
  10572   004h 4   Version (1)                    (big endian?)
  10573   008h 2   Resolution per quarter note      (01h,80h)
  10574   00Ah 3   Tempo 24bit (8bit:16bit maybe?)  (07h,27h,0Eh)
  10575   00Dh 2   Rhythm (NN/NN)                   (04h,02h)
  10576   00Fh ... Score data, uh?    (with many MIDI KeyOn's: xx,9x,xx,xx)
  10577   ...  3   End of SEQ (2Fh=End of Track)    (FFh,2Fh,00h)
  10578 The "Score data" seems to be more or less same as in Standard Midi Format (.smf
  10579 files), ie. containing timing values and MIDI commands/parameters.
  10580 
  10581 SEP - Multi-Track Sequences
  10582 This is a simple "archive" with several SEQ-like sequences.
  10583   000h 4   File ID "pQES"  ;same ID as in .SEQ files (!)
  10584   004h 2   Version (0)     ;value 0, and only 16bit, unlike .SEQ files
  10585   006h ..  1st Sequence
  10586   ...  ..  2nd Sequence
  10587   ...  ..  etc.
  10588 Sequences:
  10589   000h 2   Sequence ID (0000h and up)     (big endian)        ;-ID number
  10590   002h 2   Resolution per quarter note      (01h,80h)         ;\
  10591   004h 3   Tempo 24bit                      (07h,27h,0Eh)     ; as in SEQ files
  10592   007h 2   Rhythm (NN/NN)                   (04h,02h)         ;/
  10593   009h 4   Data size (big endian, from 00Dh up to including End of SEQ(
  10594   00Dh ... Score data, uh?                  (...)             ;\as in SEQ files
  10595   ...  3   End of SEQ (2Fh=End of Track)    (FFh,2Fh,00h)     ;/
  10596 Used by Hear It Now (Playstation Developer's Demo) (RCUBE\RCUBE.SEP)
  10597 Used by Rayman (SND\BIGFIX.ALL\0002)
  10598 Used by Monster Rancher (MagDemo06, MR_DEMO\DATA\MF_DATA.OBJ\025B)
  10599 Used by Rugrats (MagDemo19: RUGRATS\DB02\*.SEP and MENU\SOUND\SEPS\*.SEP)
  10600 Used by Rugrats Studio Tour (MagDemo32: RUGRATS\DATA\SEPS\*.SEP)
  10601 Used by Monkey Hero (MagDemo17: MONKEY\BIGFILE.PSX}*.SEP)
  10602 Used by Pitfall 3D
  10603 Used by Blue's Clues: Blue's Big Musical (SEPD chunks in *.TXD)
  10604 
  10605 CDROM File Audio Streaming XA-ADPCM
  10606 -----------------------------------
  10607 
  10608 Audio Streaming (XA-ADPCM)
  10609 Audio streaming is usually done by interleaving the .STR or .BS file's Data
  10610 sectors with XA-ADPCM audio sectors (the .STR/.BS headers don't contain any
  10611 audio info; because XA-ADPCM sectors are automatically decoded by the CDROM
  10612 controller).
  10613 Raw XA-ADPCM files (without video) are usually have .XA file extension.
  10614 
  10615 CDROM File Audio CD-DA Tracks
  10616 -----------------------------
  10617 
  10618 The eleven .SWP files in Wipeout 2097 seem to be CD-DA audio tracks.
  10619 The one TRACK01.WAV in Alone in the Dark, too?
  10620 Other than that, tracks can be accessed via TOC instead of filenames.
  10621 
  10622 CDROM File Archives with Filename
  10623 ---------------------------------
  10624 
  10625  _______________________________ Entrysize=08h ________________________________
  10626 
  10627 WWF Smackdown (MagDemo33: TAI\*.PAC)
  10628   000h 4     ID ("DPAC")                                        ;\
  10629   004h 4     Unknown (100h)                                     ;
  10630   008h 4     Number of files (N)                                ;
  10631   00Ch 4     Directory Size (N*8)                               ; Header
  10632   010h 4     File Data area size (SIZE = Totalsize-Headersize)  ;
  10633   014h 4     Unknown (1)                                        ;
  10634   018h 7E8h  Zerofilled (padding to 800h-byte boundary)         ;
  10635   800h N*8   File List                                          ;
  10636   ...  ..    Zerofilled (padding to 800h-byte boundary)         ;/
  10637   ...  SIZE  File Data area                                     ;-Data area
  10638  File List entries:
  10639   000h 8     Filename ("NAME")
  10640   004h 2     File Offset/800h (increasing)
  10641   006h 2     File Size/800h
  10642 The DPAC archives can contain generic files (eg .TIM) and child archives (in a
  10643 separate archive format, with ID "PAC ").
  10644 
  10645  _______________________________ Entrysize=10h ________________________________
  10646 
  10647 Championship Motocross (MagDemo25: SMX\RESHEAD.BIN and RESBODY.BIN)
  10648 RESHEAD.BIN:
  10649   000h N*10h  File List (220h bytes)
  10650  File List entries:
  10651   000h 8      Filename ("FILENAME", if shorter: terminated by 00h plus garbage)
  10652   008h 4      Filesize in bytes
  10653   00Ch 4      Offset/800h in RESBODY.BIN (increasing) (or FFFFFFFFh if Size=0)
  10654 RESBODY.BIN:
  10655   000h ..     File Data (referenced from RESHEAD.BIN)
  10656 
  10657 One (DIRFILE.BIN\w*\sect*.bin)
  10658   000h N*10h File List
  10659   ...  ..    File Data area
  10660  File List entries:
  10661   000h 0Ch   Filename (eg. "FILENAME 001")     ;for last entry: "END      000"
  10662   00Ch 4     Offset (increasing, N*10h and up) ;for last entry: zero
  10663 
  10664 True Love Story 1 and 2 (TLS*\MCD.DIR and MCD.IMG)
  10665 MCD.DIR:
  10666   000h N*10h  File List
  10667   ...  10h    End marker (FFh-filled)
  10668  File List entries:
  10669   000h 8      Filename (zeropadded if less than 8 chars)
  10670   008h 2      Zero (0000h)
  10671   00Ah 2      Size/800h
  10672   00Ch 4      Offset/800h in MCD.IMG
  10673  Note: Filenames are truncated to 8 chars (eg. "FOREST.T" instead "FOREST.TIM")
  10674 MCD.IMG:
  10675   000h ..     File Data area (encrypted in True Love Story 2)
  10676 In True Love Story 2, the MCD.IMG data is encrypted as follows:
  10677  init_key_by_filename(name):    ;for MCD.IMG (using filenames from MCD.DIR)
  10678   i=0, key0=0001h, key1=0001h, key2=0001h
  10679   while i<8 and name[i]<>00h
  10680     key0=(key0 XOR name[i])
  10681     key1=(key1 * name[i]) AND FFFFh
  10682     key2=(key2 + name[i]) AND FFFFh
  10683   ret
  10684  init_key_by_numeric_32bit_seed(seed):  ;maybe for LINEAR.IMG and PICT.IMG ?
  10685   key0=(seed) AND FFFFh
  10686   key1=(seed - (seed*77975B9h/400000000h)*89h) AND FFFFh
  10687   key2=(seed - (seed*9A1F7E9h/20000000000h)*3527h) AND FFFFh
  10688   ret
  10689  decrypt_data(addr,len):
  10690   for i=1 to len/2
  10691     key2=key2/2 + (key0 AND 1)*8000h
  10692     key0=key0/2 + (key1 AND 1)*8000h
  10693     key1=key1/2 + ((key1/2 OR key0) AND 1)*8000h
  10694     key0=((((key1+47h) AND FFFFh)/4) XOR key0)+key2+(((key1+47h)/2) AND 1)
  10695     halfword[addr]=halfword[addr] XOR key0, addr=addr+2
  10696   ret
  10697 The MCD.* files don't contain any encryption flag. Below are some values that
  10698 could be used to distinguish between encrypted and unencrypted MCD archives
  10699 (though that may fail in case of any other games/versions with other values):
  10700   Item                    Unencrypted   Encrypted
  10701   Parent Folder name      "TLS"         "TLS2"
  10702   First name in MCD.DIR   "BACKTILE"    "TEST.RPS"
  10703   First word in MCD.IMG   00000010h     074D4C8Ah
  10704 
  10705 Star Wars Rebel Assault 2 (RESOURCE.*, and nested therein)
  10706 BallBlazer Champions (*.DAT, and nested therein)
  10707 The Rebel RESOURCE.* files start with name "bigEx" or "fOFS", BallBlazer *.DAT
  10708 start with "SFXbase" or "tpage", nested files start with whatever other names.
  10709   000h N*10h File List
  10710   ...  (4)   CRC32 on above header (Top-level only, not in Nested archives)
  10711   ...  ..    File Data area
  10712   ...  (..)  Huge optional padding to xx000h-byte boundary (in BallBlazer .DAT)
  10713  File List entries in Top-level archives (with [0Ch].bit31=1):
  10714   000h 8     Filename (zeropadded if less than 8 chars)
  10715   008h 4     Decompressed Size (or 0=File isn't compressed)
  10716   00Ch 4     Offset, self-relative from current List entry (plus bit31=1)
  10717  File List entries in Nested archives (with [0Ch].bit31=0):
  10718   000h 0Ch   Filename (zeropadded if less than 12 chars)
  10719   00Ch 4     Offset, self-relative from current List entry (plus bit31=0)
  10720  Last File List entry has [00h..0Bh]=zerofilled, and Offset to end of file.
  10721 Uncompressed Data Format (when List entry [08h]=0 or [0Ch].bit31=0):
  10722   000h ..    Uncompressed Data
  10723   ...  ..    CRC32 on above Data (Top-level only, not in Nested archives)
  10724 Compressed Data Format (when List entry [08h]>0 and [0Ch].bit31=1)::
  10725   000h 1     Compression Method (01h=LZ/16bit, 02h=LZ/24bit)
  10726   001h 3     Decompressed Size (big-endian)
  10727   004h ..    Compressed Data
  10728   ...  ..    Zeropadding to 4-byte boundary
  10729   ...  ..    CRC32 on above bytes (method, size, compressed data, padding)
  10730 --> CDROM File Compression RESOURCE (Star Wars Rebel Assault 2)
  10731 
  10732  _______________________________ Entrysize=14h ________________________________
  10733 
  10734 Fighting Force (MagDemo01: FGHTFRCE\*.WAD)
  10735   000h 4     Number of files                                  (big endian)
  10736   004h N*14h File List
  10737   ...  ..    File Data
  10738 File List entries:
  10739   000h 0Ch   Filename ("FILENAME.EXT", zeropadded if shorter than 12 chars)
  10740   00Ch 4     Filesize in bytes (can be odd)                   (big endian)
  10741   010h 4     Fileoffset in bytes (increasing, 4-byte aligned) (big endian)
  10742 
  10743 Parappa (MagDemo01: PARAPPA\*.INT)
  10744 Um Jammer Lammy (MagDemo24: UJL\*.INT)
  10745   0000h 2000h Folder 1
  10746   2000h ..    File Data for Folder 1
  10747   ...   2000h Folder 2
  10748   ...   ..    File Data for Folder 2
  10749   ...   2000h Folder End marker (FFFFFFFFh, plus zeropadding)
  10750 Folder entries:
  10751   0000h 4      Folder ID (increasing, 1,2,3, or FFFFFFFFh=End)
  10752   0004h 4      Number of files (max 198h) (N)
  10753   0008h 4      File Data Area size/800h   (S)
  10754   000Ch 4      Zero (0)
  10755   0010h N*14h  File List
  10756   ...   ..     Zeropadding to 2000h
  10757   2000h S*800h File Data Area for this folder
  10758 File List entries:
  10759   000h 4     Filesize in bytes
  10760   004h 10h   Filename (FILENAME.EXT, zeropadded)
  10761 File Offsets are always 4-byte aligned (required for Um Jammer Lammy, which
  10762 contains Filesizes that aren's multiples of 4).
  10763 Note: There can be more than one folder with same ID (ie. when having more than
  10764 198h TIM files, which won't fit into a single 2000h-byte folder).
  10765 
  10766 Gran Turismo 1 (MagDemo10: GT\BG.DAT\*, GT\COURSE.DAT\*)
  10767 Gran Turismo 1 (MagDemo15: GT\BG.DAT\*, GT\COURSE.DAT\*)
  10768 JumpStart Wildlife Safari Field Trip (MagDemo52: DEMO\DATA.DAT\*.DAT)
  10769 These are child archives found inside of the main GT-ARC and DATA.DAT archives.
  10770   000h 4     Number of Files (eg. 26h) (usually at least 02h or higher)
  10771   004h N*14h File List
  10772   ...  ..    File Data area
  10773  File List entries:
  10774   000h 10h   Filename ("FILENAME.EXT", zeropadded if shorter)
  10775   010h 4     Offset in bytes (increasing, 4-byte-aligned?)
  10776 
  10777 Croc 2 (MagDemo22: CROC2\CROCII.DAT and CROCII.DIR)
  10778 Disney's The Emperor's New Groove (MagDemo39: ENG\KINGDOM.DIR+DAT)
  10779 Disney's Aladdin in Nasira's Revenge (MagDemo46: ALADDIN\ALADDIN.DIR+DAT)
  10780  DIR:
  10781   000h 4     Number of Entries (0Eh)
  10782   004h N*14h File List
  10783  DAT:
  10784   000h ..    File Data (referenced from CROCII.DIR)
  10785 File List entries:
  10786   000h 0Ch   Filename ("FILENAME.EXT", zeropadded if shorter)
  10787   00Ch 4     File Size in bytes
  10788   010h 4     File Offset in .DAT file (800h-byte aligned, increasing)
  10789 
  10790 Alice in Cyberland (ALICE.PAC, and nested .PAC, .FA, .FA2 archives)
  10791   000h N*14h File List
  10792   ...  14h   Zerofilled (File List end marker)
  10793   ...  ..    File Data area
  10794  File List entries:
  10795   000h 0Ch   Filename ("FILENAME.EXT", zeropadded if shorter)
  10796   00Ch 4     Offset (increasing, 4-byte aligned)
  10797   010h 4     Filesize in bytes (can be odd, eg. for .FA2 files)
  10798 PAC and FA are uncompressed, FA2 is compressed via some LZ5-variant:
  10799 --> CDROM File Compression LZ5 and LZ5-variants
  10800 
  10801 Interplay Sports Baseball 2000 (MagDemo22:BB2000\DATA\HOG.TOC\UNIFORMS\*.UNI)
  10802   000h N*14h  File List (3Ch*14b bytes, unused entries are zeropadded)
  10803   4B0h ..     Data area (TIM files for player uniforms)
  10804  File List entries:
  10805   000h 10h    Filename ("FILENAME.EXT", zeropadded)
  10806   010h 4      Offset (zerobased, from begin of Data area, increasing)
  10807 
  10808  _______________________________ Entrysize=18h ________________________________
  10809 
  10810 Invasion from Beyond (MagDemo15: IFB\*.CC)
  10811   000h 0Ch   Fixed ID (always "KotJCo01Dir ") (always that same string)
  10812   00Ch 4     Number of Files
  10813   010h N*18h File List
  10814   ...  ..    File Data area
  10815 File List entries:
  10816   000h 10h   Filename ("FILENAME.EXT", zeropadded)
  10817   010h 4     Offset in bytes (increasing, 1-byte or 4-byte aligned)
  10818   014h 4     Filesize in bytes (can be odd)
  10819 Note: Alignment is optional: Files in IFB\HANGAR\*.CC and IFB\MAPS\*.CC use
  10820 4-byte aligned offsets (but may have odd filesizes). Files in IFB\INCBINS\*.CC
  10821 don't use any alignment/padding.
  10822 
  10823 Ghost in the Shell (MagDemo03: GITSDEMO\S01\*.FAC)
  10824   000h N*18h File List (18h-bytes each)
  10825   ...  18h   File List end marker (zerofilled)
  10826   ...  ..    File Data
  10827 File List entries:
  10828   000h 1     Filename Checksum (sum of bytes at [001h..00Dh])
  10829   001h 1     Filename Length (excluding ending zeroes) (eg. 8, 9, 10, 12)
  10830   002h 0Ch   Filename ("FILENAME.EXT", zeropadded if less than 12 chars)
  10831   00Eh 2     Unknown (2000h) (maybe attr and/or ending zero for filename)
  10832   010h 4     Filesize in bytes (can be odd)
  10833   014h 4     Offset (increasing, 4-byte aligned)
  10834 
  10835 Oddworld: Abe's Exodus (MagDemo17: ABE2\*.LVL)
  10836 Oddworld: Abe's Exodus (MagDemo21: ABE2\*.LVL and nested .IDX files)
  10837   000h 4     Header Size in bytes  (2800h) (can be MUCH bigger than needed)
  10838   004h 4     Zero
  10839   008h 4     ID "Indx"
  10840   00Ch 4     Zero
  10841   010h 4     Number of Files (N)   (CEh) (can be zero=empty in .IDX files)
  10842   014h 4     Header Size/800h      (05h)
  10843   018h 4     Zero
  10844   01Ch 4     Zero
  10845   020h N*18h File List
  10846   ...  ..    Zeropadding to end of Headersize
  10847   ...  ..    File Data area
  10848 File List entries (in .LVL files):
  10849   000h 0Ch   Filename ("FILENAME.EXT", zeropadded if shorter)
  10850   00Ch 4     Offset/800h
  10851   010h 4     File Size/800h
  10852   014h 4     File Size in bytes
  10853 File List entries (in .IDX files):
  10854   IDX files use the same File List entry format as LVL, but the offsets
  10855   seem to refer to an external file with corresponding name, for example:
  10856     cdrom:\ABE2\CR.LVL\CR.IDX     ;directory info
  10857     cdrom:\ABE2\CR.MOV            ;external data (the .MOV being a .STR video)
  10858   XXX: That's not tested/verified, and not implemented in no$psx file viewer.
  10859 
  10860 Monkey Hero (MagDemo17: MONKEY\BIGFILE.PSX and nested .PSX files)
  10861   000h 4     Unknown              (6)
  10862   004h 4     Total Filesize       (1403800h)
  10863   008h 2     Unknown, Alignment?  (800h)
  10864   00Ah 2     Number of Files, excluding zerofilled File List entries (ACh)
  10865   00Ch 4     Header Size          (1800h)
  10866   010h 4     Unknown, Entrysize?  (18h)
  10867   014h 4     Unknown, Entrysize?  (18h)
  10868   018h N*18h File List (can contain unused zerofilled entries here and there!)
  10869   ...  ..    File Data area
  10870 File List entries:
  10871   000h 10h   Filename ("FILENAME.EXT", zeropadded)
  10872   010h 4     File Offset in bytes (800h-byte aligned, unusorted/not increasing)
  10873   014h 4     File Size in bytes
  10874 
  10875 NHL Faceoff '99 (MagDemo17: FO99\*.KGB and nested *.PRM *.TMP *.ZAM)
  10876 NHL Faceoff 2000 (MagDemo28: FO2000\*.KGB, Z.CAT, and nested *.PRM and *.TMP)
  10877   000h 4     ID "KGB",00h
  10878   004h 4     Number of Files         (N)
  10879   008h (4)   Number of Files negated (-N)   ;<-- optional, not in LITESHOW.KGB
  10880   ...  N*18h File List
  10881   ...  (..)  CBh-padding to alignment boundary (only if align=800h)
  10882   ...  ..    File Data area
  10883 File List entries:
  10884   000h 10h   Filename ("FILENAME.EXT", terminated by 00h, padded with CDh)
  10885   010h 4     File Size in bytes
  10886   014h 4     File Offset (800h-byte or 1/4-byte? aligned)
  10887 
  10888 Syphon Filter 1 (MagDemo18: SYPHON\SUBWAY.FOG) (4Mbyte, namelen=10h)
  10889   000h 4     Unknown (80000001h)
  10890   004h 4     Offset/800h to Final Padding area
  10891   008h 8     Zerofilled
  10892   010h N*18h File List
  10893   ...  (..)  CDh-padding to 800h-byte alignment boundary
  10894   ...  ..    File Data area
  10895   ...  800h  Some text string talking about "last-sector bug"
  10896   ...  40BEh Final Padding area (CDh-filled)
  10897 File List entries:
  10898   000h 10h   Filename ("FILENAME.EXT", terminated by 00h, padded with CDh)
  10899   010h 4     File Offset/800h (increasing)
  10900   014h 4     File Size/800h
  10901 This is almost same as the newer v2 format in Syphon Filter 2 (see there for
  10902 details).
  10903 
  10904 Centipede (MagDemo23: ARTFILES\*.ART)
  10905   000h 0Fh   ID ("Art", zeropadded)             ;\
  10906   00Fh 1     Type or so ("?")                   ; sorts of File List entry
  10907   010h 4     Number of entries plus 1 (N+1)     ; for root folder
  10908   014h 4     Total Size in bytes (can be odd)   ;/
  10909   018h N*18h File List
  10910   ...  ...   File Data area
  10911  File List entries:
  10912   000h 0Fh   Filename ("FILENAME", zeropadded)
  10913   00Fh 1     Type/extension or so ("X" or "D")
  10914   010h 4     File Offset (unaligned, increasing)
  10915   014h 4     File Size in bytes (can be odd)
  10916 Note: C0L7.ART includes zerofilled 18h-bytes as last File List entry, BONU.ART
  10917 doesn't have any such zerofilled entry.
  10918 Unknown if this can have child folders (maybe in similar form as the root
  10919 folder entry).
  10920 
  10921 Sheep Raider (MagDemo52: SDWDEMO\*.SDW)
  10922 Sheep Raider (MagDemo54: SDWDEMO\*.SDW)
  10923   000h 4     Unknown (301h)
  10924   004h 4     Zero (0)
  10925   008h 4     Number of files (N)
  10926   00Ch N*18h File List
  10927   ...  ..    Zeropadding to 800h-byte boundary
  10928   ...  ..    File Data area
  10929  File List entries:
  10930   000h 4     Offset (800h-byte aligned, increasing)
  10931   004h 4     Filesize in bytes
  10932   008h 1     Unknown (01h)
  10933   009h 0Fh   Filename ("FILENAME.EXT",00h, plus garbage padding)
  10934 The SDW archive contains malformed 200h*1A4h pixel TIMs.
  10935   Texsize is 6900Eh, but should be 6900Ch = 200h*1A4h*2+0Ch
  10936   Filesize is 6A000h, but should be 69014h = 200h*1A4h*2+14h
  10937 
  10938 Wing Commander III (*.LIB)
  10939   000h 2     Number of Files (C9h)
  10940   002h N*18h File List
  10941   ...  (..)  Padding to 800h-byte boundary (if any, eg. in MOVIES.LIB)
  10942   ...  ..    File data area (800h-byte aligned, or unaligned)
  10943  File List entries:
  10944   000h 4     Filesize in bytes
  10945   004h 4     Offset (increasing, 800h-byte aligned, or unaligned)
  10946   008h 10h   Filename ("filename.ext", zeropadded)
  10947 
  10948 Largo Winch - Commando SAR (LEVELS\*.DCF)
  10949   000h 4     ID "DCAT"
  10950   004h 4     Number of Entries
  10951   008h N*18h File List
  10952   ...  ..    Zerofilled (padding to 800h-byte boundary)
  10953   ...  ..    File Data area
  10954  File List entries:
  10955   000h 10h   Filename ("FILENAME.EXT", terminated by 00h, plus garbage padding)
  10956   010h 4     Filesize in bytes
  10957   014h 4     Offset (increasing, 800h-byte aligned)
  10958 
  10959 Policenauts (NAUTS\*.DPK)
  10960   000h 4     ID "FRID"
  10961   004h 4     Always E0000000h
  10962   008h 4     Always 800h (...maybe alignment)
  10963   00Ch 4     Number of Entries (N)
  10964   010h 4     Header Size (N*18h+20h, plus padding to 800h-byte boundary)
  10965   014h 4     Always 18h (...maybe entry size)
  10966   018h 8     Zerofilled
  10967   020h N*18h File List
  10968   ...  ..    Zerofilled (padding to 800h-byte boundary)
  10969   ...  ..    File Data area
  10970  File List entries:
  10971   000h 0Ch   Filename ("FILENAME.EXT", zeropadded if shorter)
  10972   00Ch 4     Offset (increasing, 800h-byte aligned)
  10973   010h 4     Filesize in bytes
  10974   014h 4     Unknown (checksum? random?)
  10975 
  10976 Actua Ice Hockey 2 (Best Sports Games Ever (demo), AH2\GAMEDATA\*.MAD)
  10977   000h N*18h File List
  10978   ...  ..    File Data area (directly after File List, without end-code)
  10979  Note: There is no file-list end-marker (instead, the Offset in 1st File
  10980        entry does imply the end of File List).
  10981  File List entries:
  10982   000h 10h  Filename ("FILENAME.EXT", zeropadded)
  10983   010h 4    Offset (increasing, 4-byte aligned, or unaligned for TXT files)
  10984   014h 4    Filesize in bytes (or weird nonsense in SFX.MAD)
  10985 There are several oddities in demo version (unknown if that's in retail, too):
  10986  SFX.MAD has nonsense Filesize entries (eg. 164h for a 15150h-byte file).
  10987  FACES.MAD contains only one TIM file... but as 3Mbyte junk appended?
  10988  RINKS.MAD and TEAMS.MAD start with 0Dh,0Ah,1Ah followed by 4Mbyte junk.
  10989  MISCFILE.MAD contains several nested .mad files.
  10990  MISCFILE.MAD\panfont.mad\*.txt --> starts with FF,FE --> that's 16bit Unicode?
  10991 
  10992 Muppet Monster Adventure (MagDemo37: MMA\GAMEDATA+WORLDS*\*.INF+WAD)
  10993  INF:
  10994   000h N*18h File List
  10995  WAD:
  10996   000h ..    File Data area
  10997 File List entries:
  10998   000h 4     File Offset/800h in .WAD file
  10999   004h 4     File Size in bytes
  11000   008h 10h   Filename ("FILENAME.EXT", zeropadded)
  11001 
  11002 Army Men Air Attack 2 (MagDemo40: AMAA2\*.PCK)
  11003   000h 4     Number of entries (N)
  11004   004h N*18h File List
  11005   ...  ..    Zeropadding to 800h-byte boundary
  11006   ...  ..    File Data area
  11007  File List entries:
  11008   000h 10h   Filename ("FILENAME.EXT", zeropadded)
  11009   010h 4     Fileoffset (800h-byte aligned, increasing)
  11010   014h 4     Filesize in bytes
  11011 
  11012 Mort the Chicken (MagDemo41: MORT\*.PPF and .TPF)
  11013   000h 2     Type (31h=TPF with TIMs, 32=PPF with PMDs)
  11014   002h 2     Number of entries (N) (can be 0=None, eg. STAGE*\MORT.PPF)
  11015   004h 4     File List Size (N*18h)
  11016   008h 4     Header Size (always 14h)
  11017   00Ch 4     Data area Size (Filesize-14h-N*18h)
  11018   010h 4     Data area Offset (14h+N*18h)
  11019   014h N*18h File List
  11020   ...  ..    File Data area
  11021  File List entries:
  11022   000h 10h   Filename ("FILENAME.EXT", zeropadded)
  11023   010h 4     Filesize in bytes
  11024   014h 4     Fileoffset (from begin of Data area, increasing)
  11025 
  11026 Hot Wheels Extreme Racing (MagDemo52: US_01293\VEHICLES\*.CAB)
  11027   000h 4     ID "BACR" (aka RCAB backwards)
  11028   004h 4     Number of entries (N)
  11029   008h N*18h File List
  11030   ...  ..    File Data area
  11031  File List entries:
  11032   000h 10h   Filename ("FILENAME.EXT", zeropadded)
  11033   020h 4     Offset (from begin of Data area, increasing, 4-byte aligned)
  11034   024h 4     Filesize in bytes (can be odd)
  11035 
  11036  _______________________________ Entrysize=19h ________________________________
  11037 
  11038 WAD Format (Wipeout 2097)
  11039 PSX Wipeout 2097, cdrom:\WIPEOUT2\SOUND\SAMPLES.WAD:\*.vag
  11040 PSX Wipeout 2097, cdrom:\WIPEOUT2\TRACK*\TRACK.WAD:\*.*
  11041 PSX Wipeout 3 (MagDemo25: WIPEOUT3\*)
  11042   000h 2     Number of files
  11043   002h N*19h Directory Entries for all files
  11044   ...  ..    Data for all files (without any alignment, in same order as above)
  11045 Directory Entries
  11046   000h 10h Filename (ASCII, can be lowercase), terminated by 00h, plus garbage
  11047   010h 4   Filesize in bytes  ;\maybe compressed/uncompressed, or rounded,
  11048   014h 4   Filesize in bytes  ;/always both same
  11049   018h 1   Unknown (always 00h)
  11050 The filesize entry implies offset to next file.
  11051 
  11052  _______________________________ Entrysize=1Ch ________________________________
  11053 
  11054 Command & Conquer, Red Alert (MagDemo05: RA\*) FAT/MIX/XA
  11055   000h 4     Number of entries with location 0=MIX (M=65h)
  11056   000h 4     Number of entries with location 1=XA  (X=1)
  11057   008h M*1Ch File List for location 0=MIX
  11058   ...  X*1Ch File List for location 1=XA
  11059 File List entries:
  11060   000h 10h   Filename (terminated by 00h, padded with garbage)
  11061   010h 4     Offset/800h in DATA.MIX or Offset/930h DATA.XA file (increasing)
  11062   014h 4     Filesize in bytes
  11063   018h 4     File Location (0=DATA.MIX, 1=DATA.XA)
  11064 
  11065 Syphon Filter 2 (MagDemo30: SYPHON\TRAIN.FOG) (2.8Mbyte, namelen=14h)
  11066   000h 4     Unknown (80000001h)
  11067   004h 4     Offset/800h to Final Padding area
  11068   008h 8     Zerofilled
  11069   010h N*1Ch File List
  11070   ...  (..)  CDh-padding to 800h-byte alignment boundary
  11071   ...  ..    File Data area
  11072   ...  3394h Final Padding area (CDh-filled)
  11073 File List entries:
  11074   000h 14h   Filename ("FILENAME.EXT", terminated by 00h, padded with CDh)
  11075   014h 4     File Offset/800h (increasing)
  11076   018h 4     File Size/800h
  11077 This is almost same as the older v1 format in Syphon Filter 1:
  11078   v1 (Syphon Filter 1) has filename_len=10h (and filelist_entrysize=18h)
  11079   v2 (Syphon Filter 2) has filename_len=14h (and filelist_entrysize=1Ch)
  11080 To detect the version: Count the length of the "ASCII chars + 00h byte + CDh
  11081 padding bytes" at offset 10h.
  11082 Note: The FOG archive in Syphon Filter 2 demo version does contain some empty
  11083 dummy files (with intact filename, but with offset=0 and size=0).
  11084 
  11085  _______________________________ Entrysize=20h ________________________________
  11086 
  11087 Colony Wars (MagDemo02: CWARS\GAME.RSC)
  11088 Colony Wars Venegance (MagDemo14: CWV\GAME.RSC, 8Mbyte)
  11089   000h 4     Number of Files
  11090   004h N*20h File List
  11091   ...  10h   File List End: Name    (zerofilled)
  11092   ...  4     File List End: Offset  (total filesize, aka end of last file)
  11093   ...  0Ch   File List End: Padding (zerofilled)
  11094   ...  ..    File Data area
  11095 File List entries:
  11096   000h 10h   Filename ("FILENAME.EXT", terminated by 00h, padded with garbage)
  11097   010h 4     File Offset in bytes (increasing, 4-byte aligned)
  11098   014h 0Ch   Padding (garbage) (usually 800F68A0h,800F68A0h,800F68A0h)
  11099 Note: Colony Wars Red Sun does also have a GAME.RSC file (but in different
  11100 format, with folder structure).
  11101 
  11102 WarGames (MagDemo14: WARGAMES\*.DAT)
  11103   000h 4     Number of Files (1C3h)
  11104   004h N*20h File List
  11105   ...  ..    Zeropadding to 800h-byte boundary
  11106   ...  ..    File Data area
  11107 File List entries:
  11108   000h 10h   Filename ("FILENAME.EXT", zeropadded, sorted alphabetically)
  11109   010h 4     File Offset/800h (unsorted, not increasing)
  11110   014h 4     File Size in bytes
  11111   018h 4     File Size/800h
  11112   01Ch 4     Zero
  11113 
  11114 Running Wild (MagDemo15: RUNWILD\*.BIN)
  11115   000h N*20h File List
  11116   ...  4     File List End Offset/800h (end of last file)
  11117   ...  4     File List End Size (zero)
  11118   ...  18h   File List End Name (zerofilled)
  11119   ...  ..    Padding to 800h-byte boundary (each 20h-byte: 01h, and 1Fh zeroes)
  11120   ...  ..    File Data
  11121 File List entries:
  11122   000h 4     Offset/800h (increasing)
  11123   004h 4     Filesize in bytes
  11124   008h 18h   Filename ("FILENAME.EXT" or ":NAME" or ":NAME:NAME", zeropadded)
  11125 Files with extension .z or .Z are compressed:
  11126 --> CDROM File Compression Z (Running Wild)
  11127 
  11128 Test Drive Off-Road 3 (MagDemo27: TDOR3\TDOR3.DAT)
  11129 About same as the other Test Drive games, but with shorter filenames.
  11130   000h N*20h  File List (1920h bytes used; with padding: 5800h bytes in total)
  11131   ...  ..     Zeropadding to Headersize (5800h)
  11132   ...  ..     File Data area
  11133  File List entries:
  11134   000h 18h    Filename ("FILENAME.EXT" or "PATH\FILENAME.EXT", zeropadded)
  11135   018h 4      Filesize in bytes
  11136   01Ch 4      File (Offset-Headersize)/800h
  11137 TDOR3.DAT contains DOT1 child archives and many RNC compressed files: --> CDROM
  11138 File Compression RNC (Rob Northen Compression)
  11139 
  11140 Tiny Tank (MagDemo23: TINYTANK\*.DSK)
  11141   000h 4     ID ("TDSK")                                      ;\
  11142   004h 4     Number of Files (1Bh)                            ; Directory
  11143   008h N*20h File List                                        ;/
  11144   ...  4     1st File Size (same as Size entry in File List)  ;\File Data area
  11145   ...  ..    1st File Data                                    ; (each file os
  11146   ...  4     2nd File Size (same as Size entry in File List)  ; preceeded by
  11147   ...  ..    2nd File Data                                    ; a size entry)
  11148   ...  ..    etc.                                             ;/
  11149  File List entries:
  11150   000h 10h   Filename ("FILENAME.EXT", zeropadded)
  11151   010h 4     File Size in bytes
  11152   014h 4     Unknown (35xxxxxxh..372xxxxxh)
  11153   018h 4     Unknown (3724xxxxh) (Timestamp maybe?)
  11154   01Ch 4     File Offset in bytes (increasing, 4-byte aligned)
  11155 Note: The File Offset points to a 32bit value containing a copy of the
  11156 Filesize, and the actual file starts at Offset+4.
  11157 
  11158 MAG 3 (MagDemo26: MAG3\MAG3.DAT, 7Mbyte)
  11159   000h N*20h  File List (B60h bytes)
  11160   ...  ..     Zeropadding to 800h-byte boundary
  11161   ...  ..     File Data area (files are AAh-padded to 800h-byte boundary)
  11162  File List entries:
  11163   000h 4      Filesize in bytes
  11164   004h 2      File Offset/800h (16bit) (increasing)
  11165   006h 1Ah    Filename ("FILENAME.EXT" or "PATH\FILENAME.EXT", zeropadded)
  11166 
  11167 Play with the Teletubbies (MagDemo35: TTUBBIES\*.RES)
  11168   000h 2     Zero (0000h)
  11169   002h 2     Number of Files (N)
  11170   004h 4     Data Base (N*20h+10h)
  11171   008h 4     Unknown (20h)  ;-maybe File List entry size?
  11172   00Ch 2     Unknown (10h)  ;\maybe filename length and/or header size?
  11173   00Eh 2     Unknown (10h)  ;/
  11174   010h N*20h File List
  11175   ...  ..    File Data area
  11176 File List entries:
  11177   000h 4     Zero
  11178   004h 4     File Offset (increasing, 4-byte aligned, relative to Data Base)
  11179   008h 4     File Size in bytes (can be odd)
  11180   00Ch 4     Zero
  11181   010h 10h   Filename ("FILENAME.EXT", zeropadded)
  11182 
  11183 Mat Hoffman's Pro BMX (old demo) (MagDemo39: BMX\FE.WAD+STR) (uncompressed)
  11184 Mat Hoffman's Pro BMX (new demo) (MagDemo48: MHPB\FE.WAD+STR) (compressed)
  11185  WAD:
  11186   000h N*20h File List
  11187  STR:
  11188   000h ..    File Data (MagDemo39: 4.5Mbyte, MagDemo48: compressed/2.8Mbyte)
  11189  File List entries:
  11190   000h 14h   Filename ("FILENAME.EXT", zeropadded)
  11191   014h 4     Offset in bytes, 4-byte aligned, in STR file
  11192   018h 4     Filesize, compressed (always rounded to multiple of 4 bytes)
  11193   01Ch 4     Filesize, decompressed (zero when not compressed)
  11194 The decompressor is using an Inflate variant with slightly customized block
  11195 headers:
  11196   - end flag is processed immediately (instead of after the block)
  11197   - blocktype is only 1bit wide (instead of 2bit)
  11198   - stored blocks have plain 16bit len (without additional 16bit inverse len)
  11199 Everything else is same as described here:
  11200 --> CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  11201 Instead of "tinf_uncompress", use the function below:
  11202  bmx_tinf_style_uncompress(dst,src)
  11203   tinf_init()                   ;init constants (needed to be done only once)
  11204  @@lop:
  11205   if tinf_getbit()=0 then goto @@done   ;end flag, 1bit
  11206   if tinf_getbit()=0 then               ;blocktype, 1bit
  11207     tinf_align_src_to_byte_boundary()
  11208     len=LittleEndian16bit[src], src=src+2   ;get len (without inverse len)
  11209     for i=0 to len-1, [dst]=[src], dst=dst+1, src=src+1, next i   ;uncompressed
  11210   else
  11211     tinf_decode_dynamic_trees(), tinf_inflate_compressed_block()  ;compressed
  11212   gpto @@lop
  11213  @@done:
  11214   ret
  11215 Note: Apart from the MHPB\FE.WAD archive, many MHPB\*.BIN files seem to be also
  11216 compressed (unknown if that's the same compression method; and, if so, they
  11217 would lack decompressed size info).
  11218 
  11219  _______________________________ Entrysize=28h ________________________________
  11220 
  11221 Demo Menu, PlayStation Magazine Demo Disc 03-54, MENU.FF
  11222 Used on most PlayStation Magazine Demo Discs (Disc 03-54, except Disc 01-02)
  11223 Used on PlayStation Underground 3.1 (and maybe other issues)
  11224 Used on Interactive CD Sampler Disc Volume 10 (maybe others, but not Vol 4,5)
  11225   000h 4     Number of entries (eg. 20h or 28h)
  11226   004h N*28h File List
  11227   ...  ..    Garbage padding to 800h-byte boundary
  11228   ...  ..    File Data
  11229   ...  ..    Huge zeropadding to 200000h or 2EE000h (2048Kbyte or 3000Kbyte)
  11230 File List entries:
  11231   000h 20h   Filename (terminated by 00h, padded with... looks like garbage)
  11232   020h 4     Size/800h
  11233   024h 4     Offset/800h (increasing)
  11234 Contains .BS, .TIM, .TXT, .VH, .VB files. The size seems to be always(?)
  11235 2048Kbytes, 2992Kbytes, 2000Kbytes, or 3000Kbytes (often using only the first
  11236 quarter, and having the remaining bytes zeropadded).
  11237 
  11238 Test Drive 4 (MagDemo03: TD4.DAT) (headersize=2000h, used=0...h)
  11239 Test Drive 5 (MagDemo13: TD5.DAT) (headersize=3000h, used=1EF8h)
  11240 Demolition Racer (MagDemo27: DR\DD.DAT) (headersize=5000h, used=2328h)
  11241 This is used by several games, with different Headersizes (2000h or 3000h or
  11242 5000h), with Offsets relative to the Headersize. To detect the Headersize, skip
  11243 used entries, skip following zeropadding, then round-down to 800h-byte boundary
  11244 (in case the 1st file contains some leading zeroes).
  11245   000h N*28h File List (less than 0C00h bytes used in TD4 demo)
  11246   ...   ..   Zeropadding to Headersize (2000h or 3000h or 5000h)
  11247   ...   ..   File Data
  11248 File List entries:
  11249   000h 20h   Filename ("PATH\FILENAME.EXT", zeropadded)
  11250   020h 4     Size in bytes
  11251   024h 4     (Offset-Headersize)/800h (increasing)
  11252 TD5.DAT and DD.DAT contain DOT1 child archives and many RNC compressed files:
  11253 --> CDROM File Compression RNC (Rob Northen Compression)
  11254 
  11255 Gekido (MagDemo31: GEKIDO\GLOBAL.CD)
  11256   0000h N*28h File List
  11257   21C0h ...   Unknown random gibberish? (23h,E8h,0Ch,1Dh,79h,C5h,24h,...)
  11258   4000h ...   File Data area
  11259 File List entries:
  11260   000h 1Ch   Filename ("\PATH\FILENAME.EXT;0", zeropadded)
  11261   01Ch 4     Filesize in bytes
  11262   020h 4     Fileoffset in bytes (4000h and up, increasing)
  11263   024h 4     Filechecksum (32bit sum of all bytes in the file)
  11264 There is no "number of files" entry, and no "file list end marker" (though the
  11265 "random gibberish" might serve as end marker, as long it doesn't start with "\"
  11266 backslash).
  11267 
  11268 Team Buddies (MagDemo37: BUDDIES\BUDDIES.DAT\* and nested *.BND files)
  11269   000h 4     ID "BIND"
  11270   004h 4     Number of files (N)
  11271   008h N*28h File List
  11272   ...  ..    File Data area
  11273 File List entries:
  11274   000h 20h   Filename ("\FILENAME.EXT", zeropadded)
  11275   020h 4     File Offset (increasing, 4-byte aligned)     ;\see note
  11276   024h 4     File Size in bytes (always a multiple of 4)  ;/
  11277 Note: There is a 4-byte gap between most files, that appears to be caused by
  11278 weird/bugged alignment handling done as so:
  11279   size=((filesize+3) AND not 3)       ;size entry for curr file (plus 3)
  11280   offs=((filesize+4) AND not 3)+offs  ;offs entry for next file (plus 4 !!!)
  11281 Namely, odd filesizes (eg. for TXT files in BUDDIES.DAT\00D2h..00D7h) are
  11282 forcefully rounded-up to 4 bytes boundary. If that rounding has occurred then
  11283 there is no additional 4-byte gap (but the 4-byte gap will appear if the
  11284 original filesize was already 4-byte aligned).
  11285 
  11286 JumpStart Wildlife Safari Field Trip (MagDemo52: DEMO\DATA.DAT)
  11287   000h 4     Number of entries (N)
  11288   004h 4     Number of entries (same as above)
  11289   008h 4     Number of entries (same as above)
  11290   00Ch 4     Number of entries (same as above)
  11291   010h N*28  File List
  11292   ...  ..    Zeropadding to 800h-byte boundary
  11293   ...  ..    File Data area
  11294  File List entries:
  11295   000h 20h   Filename ("\PATH\FILENAME.EXT", zeropadded)
  11296   020h 4     Offset/800h, from begin of Data area (increasing)
  11297   024h 4     Filesize in bytes
  11298 
  11299  _______________________________ Entrysize=34h ________________________________
  11300 
  11301 Army Men: Air Attack (MagDemo28: AMAA\PAK\*.PAK)
  11302   000h 4      Number of Files
  11303   004h N*34h  File List
  11304   ...  ..     Zeropadding to 4000h
  11305   4000h ..    File Data area
  11306  File List entries:
  11307   000h 10h    Filename ("FILENAME.EXT", zeropadded)
  11308   010h 4      Filesize in bytes  ;\always both same, always
  11309   014h 4      Filesize in bytes  ;/both multiple of 800h
  11310   018h 4      Zero
  11311   01Ch 4      Type    (07h..1Ah)
  11312   020h 4      Subtype (00h..01h)
  11313   024h 10h    Zero
  11314 The used Type.Subtype values are:
  11315   07h.0   .TIM (*.TIM)
  11316   07h.01h .TIM (HUD_*.TIM)
  11317   08h.0   .TIM (PSTART.TIM)
  11318   09h.0   .TIM (FONT.TIM)
  11319   0Ah.0   .SFX
  11320   0Eh.0   .MBL
  11321   10h.0   .ATR
  11322   11h.0   .RLC
  11323   13h.0   .AST
  11324   15h.0   .SCD
  11325   16h.0   .TXT (PAUSED.TXT)
  11326   17h.0   .TXT (OBJECT*.TXT)
  11327   18h.0   .BIN
  11328   1Ah.0   Misc (.3DO=TIM, .V=TXT, and TERRAIN.CLP .HI .LIT .MAP .PAT .POB .TER)
  11329 
  11330  _______________________________ Entrysize=40h ________________________________
  11331 
  11332 Ninja (MagDemo13: NINJA\CUTSEQ\*.WAD and NINJA\WADS\*.WAD)
  11333   000h 4     Number of Files (N)
  11334   004h 4     Size of File Data area (SIZ) (total filesize-8-N*40h)
  11335   008h N*40h File List
  11336   ...  SIZ   File Data area
  11337  File List entries:
  11338   000h 4     Filesize in bytes
  11339   004h 4     Fileoffset in bytes (zerobased, from begin of File Data area)
  11340   008h 38h   Filename, zeropadded
  11341 You Don't Know Jack (MagDemo23: YDKJ\RES\*.GLU)
  11342 You Don't Know Jack 2 (MagDemo41: YDKJV2\*\*.GLU)
  11343   000h 4     ID ("GLUE")
  11344   004h 4     Unknown (always 400h)
  11345   008h 4     Number of Files (N)
  11346   00Ch 4     Header Size (40h+N*40h)
  11347   010h 30h   Zerofilled
  11348   040h N*40h File List
  11349   ...  ..    Garbage padding to alignment boundary
  11350   ...  ..    File Data area
  11351  File List entries:
  11352   000h 20h   Filename ("FILENAME.EXT", zeropadded)
  11353   020h 4     File Offset in bytes (increasing, 800h-byte aligned)
  11354   024h 4     File Size in bytes
  11355   028h 2     File ID Number 1 (eg. 1-71 for C01.GLU-C71.GLU)
  11356   02Ah 2     Unknown (random, checksum, ?)
  11357   02Ch 4     File ID Number 2 (eg. increasing: 1, 2, 3)
  11358   030h 10h   Zerofilled
  11359 Most .GLU files are 800h-byte aligned (except SHORTY\*.GLU and THREEWAY\*GLU
  11360 which use 4-byte alignment).
  11361 The files do start on alignment boundaries, but there is no alignment padding
  11362 after end of last file.
  11363 
  11364  _______________________________ Entrysize=60h ________________________________
  11365 
  11366 Army Men Air Attack 2 (MagDemo40: AMAA2\*.PCK\*.PAK)
  11367   000h 4     Number of entries (N)
  11368   010h N*60h File List
  11369   ...  ..    Zeropadding to 2000h
  11370   2000h ..   File Data area
  11371  File List entries:
  11372   000h 4     Timestamp? (BFxxxxh..C0xxxxh) (or zero, in first file)
  11373   004h 4     Unknown (always 421C91h)
  11374   008h 4     Unknown (200h or 60200h)
  11375   00Ch 4     Filesize (uncompressed)
  11376   010h 4     Filesize (compressed, or 0 when not compressed)
  11377   014h 4     File Checksum (sum of all bytes in uncompressed file data)
  11378   018h 4     Unknown (random 32bit value?)
  11379   01Ch 10h   Filename ("FILENAME.EXT", zeropadded)
  11380   02Ch 4     Zerofilled
  11381   030h 4     Unknown (0 or 1 or 8)
  11382   034h 4     File Type (see below)
  11383   038h 8     Zerofilled
  11384   040h 4     Offset MSBs (Fileoffset-2000h)/800h  ;\increasing, 4-byte aligned
  11385   044h 4     Offset LSBs (Fileoffset AND 7FFh)    ;/(or zero when filesize=0)
  11386   048h 18h   Zerofilled
  11387 File Type values are 07h=TIM, 0Ah=SFX, 0Eh=MBL, 10h=ATR, 13h=AST, 15h=SCD,
  11388 19h=VTB, 1Bh=DCS, 1Dh=DSS, 1Eh=STR, 1Fh=DSM, 20h=FNT, 21h=TER, 25h=PMH,
  11389 26h=Misc.
  11390 Most of the files are SCRATCH compressed:
  11391 --> CDROM File Compression LZ5 and LZ5-variants
  11392 There are also several uncompressed files (eg. VERSION.V, *.SFX, and many of
  11393 the TERRAIN.* files).
  11394 
  11395  _______________________________ Entrysize=90h ________________________________
  11396 
  11397 Grind Session (MagDemo33: GRIND\SLIP.GRV)
  11398 Grind Session (MagDemo36: GRIND\SLIP.GRV)
  11399 Grind Session (MagDemo42: GRIND\SLIP.GRV)
  11400 Grind Session (MagDemo45: GRIND\SLIP.GRV)
  11401   000h 4     ID (A69AA69Ah)
  11402   004h 4     Number of files (N)
  11403   008h N*90h File List
  11404   ...  ..    File Data area
  11405  File List entries:
  11406   000h 80h   Filename ("DATA\FILENAME.EXT",00h, plus CDh-padding)
  11407   080h 4     File Offset in bytes (increasing, 4-byte aligned)
  11408   084h 4     File Size in bytes
  11409   088h 8     Unknown (random/checksum?)
  11410 
  11411  _____________________________ Variable Entrysize _____________________________
  11412 
  11413 HED/WAD
  11414   Used by Spider-Man (MagDemo31,40: SPIDEY\CD.HED and CD.WAD)
  11415   Used by Spider-Man 2 (MagDemo52: SPIDEY\CD.HED and CD.WAD)
  11416   Used by Tony Hawk's Pro Skater (MagDemo22: PROSKATE\CD.HED and CD.WAD)
  11417   Used by Apocalypse (MagDemo16: APOC\CD.HED and CD.WAD)       ;with PADBUG
  11418   Used by MDK (Jampack Vol. 1: MDK\CD.HED and CD.WAD)          ;without ENDCODE
  11419   Used by Mat Hoffman's Pro BMX (old demo) (MagDemo39: BMX\BMXCD.HED+WAD)
  11420 Format of the CD.HED file:
  11421   000h ..  File Entries (see below)
  11422   ...  (1) End code (FFh) (if any, not present in MDK)
  11423 File Entry format:
  11424   000h ..  Filename (ASCII, terminated by 00h, zeropadded to 4-byte boundary)
  11425   ...  4   Offset in CD.WAD (in bytes, usually 800h-byte aligned)
  11426   ...  4   Filesize (in bytes)
  11427 PADBUG: Apocalypse does append 1..800h bytes alignment padding (instead of
  11428 1..7FFh or 0 bytes).
  11429 
  11430 Dance UK (DATA.PAK)
  11431   000h 4      Number of Files (N) (1ADh)
  11432   004h 4      Unknown (7) (maybe HeaderSize/800h, same as first Offset/800h ?)
  11433   008h 4      Unknown (1430h = 14h+N*0Ch, same as first Name pointer)
  11434   00Ch 4      Unknown (1430h = 14h+N*0Ch, same as first Name pointer)
  11435   010h 4      Unknown (1430h = 14h+N*0Ch, same as first Name pointer)
  11436   014h N*4    Name List (pointers to name strings, 1430h and up)  6B4h bytes
  11437   ...  N*4    Size List (filesize in bytes)                       6B4h bytes
  11438   ...  N*4    Offset List (Offset/800h)                           6B4h bytes
  11439   ...  N*var  Name Strings (ASCII strings, "folder\filename.ext",00h)
  11440   ...  ..     Zerofilled (padding to 800h-byte boundary)
  11441   ...  ..     File Data area
  11442 
  11443 Kula Quest / Kula World / Roll Away (*.PAK)
  11444   000h 4     Number of Files (N)
  11445   004h N*8   File List (2x32bit entries: Offset, Size) (unaligned, can be odd)
  11446   ...  N*4   File Name Offsets
  11447   ...  N*var File Name Strings ("FILE NN",0Ah,00h)
  11448   ...  ..    Garbage-padding to 4-byte boundary
  11449   ...  (4)   Optional extra garbage? ("MON " in ATLANTFI.PAK, MARSFI.PAK, etc.)
  11450   ...  ..    File Data area (ZLIB compressed, starting with big-endian 789Ch)
  11451 --> CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  11452 
  11453 Largo Winch - Commando SAR (NTEXTURE\*.GRP and LEVELS\*.DCF\*.CAT and *.GRP)
  11454   000h 4     ID (12h,34h,56h,78h) (aka 12345678h in big endian)
  11455   004h 4     Header Size (offset to File Data area)
  11456   008h 4     Number of Entries (can be 0=None, eg. LEVELS\LARGO07.DCF\Z16.CAT)
  11457   00Ch N*var Name List (Filenames in form "FILENAME.EXT",00h)
  11458   ...  ..    Zeropadding to 4-byte boundary
  11459   ...  N*4   Size List (Filesizes in bytes)
  11460   ...  ..    File Data area
  11461 
  11462 Jackie Chan Stuntmaster (RTARGET\GAME.GCF and LEV*.LCF)
  11463   000h 4     Number of files (N) (3..EBh)                 (big-endian)
  11464   004h N*Var File List (list size is implied in first file offset)
  11465   ...  ..    Zeropadding to 800h-byte boundary
  11466   ...  ..    File Data area
  11467  File List entries:
  11468   000h 4     File Type (ascii, .LLN .TXI .TPG .RCI .RCP .WDB .PCI .PCP .BLK)
  11469   004h 4     File Size (can be odd)                       (big-endian)
  11470   008h 4     File Offset (increasing, 800h-byte aligned)  (big-endian)
  11471   00Ch 4     Extra Size (0 or 4 or 8)                     (big-endian)
  11472   010h ..    Extra Data (if any) (32bit number, or "TEXTURES")
  11473 
  11474 Syphon Filter 1 (MagDemo18: SYPHON\*.HOG, SYPHON\SUBWAY.FOG\*.HOG,SLF.RFF)
  11475 Syphon Filter 2 (MagDemo30: SYPHON\*.HOG, SYPHON\TRAIN.FOG\*.HOG,SLF.RFF)
  11476   000h 4     Timestamp? (36xxxxxxh=v1?, 38xxxxxxh=v2?, other=SLF.RFF)
  11477   004h 4     Number of Files          (N)
  11478   008h 4     Base for Offset List  (always 14h)
  11479   00Ch 4     Base for String Table (v1=N*4+14h, or v2=N*4+18h)
  11480   010h 4     Base for File Data (end of String Table plus align 4/800h/920h)
  11481   014h N*4   Offsets to File(s) (increasing, first=0, relative to above [010h])
  11482   ... (4)    v2 only: End Offset for Last File (HOG filesize minus [010h])
  11483   ...  ..    String Table (filename list in form of "FILENAME.EXT",00h)
  11484   ...  ..    Zeropadding to 4-byte or 800h-byte boundary
  11485   ...  ..    File Data area
  11486 There are two versions: Syphon Filter 1 (v1) and Syphon Filter 2 (v2):
  11487   v1 has [0Ch]=N*4+14h (without end-of-last-file entry; use end=total_size)
  11488   v2 has [0Ch]=N*4+18h (and does have end-of-last-file entry)
  11489   v1 has STR files in ISO filesystem (not in HOG archives)
  11490   v2 has STR files in MOVIES.HOG (with [10h]=920h and [14h and up]=sectors)
  11491 Normally, the following is common for v1/v2:
  11492   v1/v2 has [10h]=data base, aligned to 4 or 800h
  11493   v1/v2 has [14h and up] in BYTE-offsets, relative to base=[10h]
  11494   v1/v2 uses HOG format in .HOG files also in SLF.RFF
  11495   v1/v2 has further .RFF files (but that aren't in HOG format)
  11496 There are several inconsistent special cases for some v2 files:
  11497   v2 MOVIE.HOG has [10h]=920h (which is meant to mean base="after 1st sector")
  11498   v2 MOVIE.HOG has [14h and up] in SECTOR-units, with base="after 1st sector"
  11499   v2 SLF.RFF does contain two HOG archives badged together (plus final padding)
  11500   v2 has some empty 0-byte .HOG files (at least so in demo version)
  11501 Danger: The special value 920h means that headersize is one 800h-byte sector
  11502 (whereas 920h is dangerously close to REAL headersize, eg. v1 PCHAN.HOG has
  11503 headersize=908h which means one 800h-byte sector plus 108h bytes) (the 920h
  11504 thing should occur only in v2 though, since v1 has STR files stored in ISO
  11505 filesystem instead of in HOG archives).
  11506 
  11507 Electronic Arts 32bit BIGF archives
  11508   000h 4   ID "BIGF" (normal case, all big-endian, 4-byte aligned)     ;\
  11509            ID "BIGH" (with [04h]=little-endian instead big-endian)     ;
  11510            ID "BIG4" (with 40h-byte alignment padding instead 4-byte)  ;
  11511   004h 4   Sum of Header+Filesizes (excluding Padding's!) (big-endian) ; Header
  11512   008h 4   Number of entries (N)                  ;11h    (big-endian) ;
  11513   00Ch 4   Size of Header (including File List)   ;11Fh   (big-endian) ;
  11514   010h ..  File List                                                   ;/
  11515   ...  ..  Padding to 1/4/8-byte boundary (optional, before each file) ;\Data  
  11516 ...  ..  File Data                                                   ;/
  11517 File List entries (with variable length names, entries aren't 4-byte aligned):
  11518   000h 4   Offset in bytes (increasing, often 4/8-byte aligned)    (big-endian)
  11519   004h 4   Size in bytes (can be odd, but often rounded to 4-byte) (big-endian)
  11520   008h ..  Filename (ASCII, terminated by 00h) ;variable length
  11521   Note: Filenames can be empty ("",00h) (eg. in WCWDEMO\ZSOUND.BIG)
  11522 Used by PGA Tour 96, 97, 98 (*.VIV)
  11523 Used by FIFA - Road to World Cup 98 (MOP*.BK*, Z4TBLS.BIG\*.t, ZMO*.BIG\*.viv)
  11524 Used by Fifa 2000 (Best Sports demo: FIFADEMO\*.BIG, *.SBK, and nested .viv)
  11525 Used by Need for Speed 3 Hot Pursuit (*.VIV)
  11526 Used by WCW Mayhem (MagDemo28: WCWDEMO\*.BIG) (odd filesizes & nameless files)
  11527 This is reportedly also used for various other Electronic Arts games for PC,
  11528 PSX, and PS2 (often with extension *.BIG, *.VIV).
  11529 Reportedly also "BIGH" and "BIG4" exist:
  11530   http://wiki.xentax.com/index.php/EA_BIG_BIGF_Archive
  11531 Other Electronic Arts file formats (used inside or alongside big archives):
  11532   https://wiki.multimedia.cx/index.php/Electronic_Arts_Formats_(2) - BNK etc
  11533 
  11534 Electronic Arts 24bit C0FB archives
  11535   000h 2   ID C0FBh                (C0h,FBh)  (big-endian)      ;\
  11536   002h 2   Size of Header-4        (00h,15h)  (big-endian)      ; Header
  11537   004h 2   Number of Files         (00h,01h)  (big-endian)      ;
  11538   006h ..  File List                                            ;/
  11539   019h ..  Padding to 4-byte boundary?                          ;-Padding
  11540   01Ch ..  File Data                                            ;-Data
  11541   ...  4   "CRCF"                                               ;\
  11542   ...  4   Unknown (0C,00,00,00) (chunk-size little-endian?)    ; Footer
  11543   ...  4   Unknown (3B,2E,00,00) (checksum maybe?)              ;/
  11544 File List entries (with variable length names, and unaligned 24bit values):
  11545   000h 3   Offset in bytes (increasing)        ;(big-endian, 24bit)
  11546   004h 3   Size in bytes                       ;(big-endian, 24bit)
  11547   008h ..  Filename (ASCII, terminated by 00h) ;variable length
  11548 Used by FIFA - Road to World Cup 98 (*.BIG)
  11549 Used by Sled Storm (MagDemo24: ART\ZZRIDER.UNI, with 8 files insides)
  11550 
  11551 Destruction Derby Raw (MagDemo35: DDRAW\*.PTH+.DAT, and nested therein)
  11552  PTH File:
  11553   000h N*var File List
  11554  DAT File:
  11555   000h ..    File Data area
  11556 File List entries:
  11557   000h ..    Filename ("FILENAME.EXT",00h) (variable length)
  11558   ...  4     File Size in bytes (can be odd)
  11559   ...  4     File Offset in bytes in DAT file (increasing, unaligned)
  11560 Caution: Filenames in PTH archives aren't sorted alphabetically (so DAT isn't
  11561 always guaranteed to be the previous entry from PTH, namely, that issue occurs
  11562 in MagDemo35: DDRAW\INGAME\NCKCARS.PTH\*.PTH+DAT).
  11563 Caution: The whole .DAT file can be compressed: If the sum of the filesizes in
  11564 PTH file does exceed the size of the DAT file then assume compression to be
  11565 used (normally, the top-level DATs are uncompressed, and nested DATs are
  11566 compressed).
  11567 --> CDROM File Compression PCK (Destruction Derby Raw)
  11568 
  11569 SnoCross Championship Racing (MagDemo37: SNOCROSS\SNOW.TOC+.IMG)
  11570  TOC:
  11571   000h N*var File List
  11572  IMG:
  11573   000h ..    File Data area
  11574 File List entries:
  11575   000h ..    Filename ("DATA\FILENAME.EXT",00h) (variable length)
  11576   ...  4     File Offset (increasing, 800h-byte aligned, in .IMG file)
  11577   ...  4     File Size in bytes
  11578 Resembles DDRAW\*.PTH+.DAT (but Offset/Size are swapped, and uses 800h-align).
  11579 Note: The archive contains somewhat corrupted TGA's:
  11580   TGA[10h..11h] = 08h,08h  ;bpp=8 (okay) and attr=8 (nonsense)
  11581   TGA[10h..11h] = 10h,01h  ;bpp=16 (okay) and attr=1 (okay) but it's yflipped
  11582 
  11583 CDROM File Archives with Offset and Size
  11584 ----------------------------------------
  11585 
  11586 Crash Team Racing (retail: BIGFILE.BIG, and MagDemo30/42: KART\SAMPLER.BIG)
  11587   000h 4     Zero
  11588   004h 4     Number of Files (260h)
  11589   010h N*8   File entries
  11590   ...  ..    Zeropadding to 800h byte boundary
  11591   ...  ..    File Data
  11592 File Entries:
  11593   000h 4   Fileoffset/800h (increasing)
  11594   004h 4   Filesize in bytes
  11595 Filetypes in the archive include...
  11596   MDEC v2 STR's  (file 1E1h..1F8h,1FAh)
  11597   TIM textures  (file 01FBh..0200h and others)
  11598   empty files   (file 01F9h and others)
  11599   small archives with named entries (file B5h,124h,125h,126h and others)
  11600   stuff with date string and names (file 253h,256h)
  11601   there seem to be no nested BIG files inside of the main BIG file
  11602 
  11603 Black Matrix (*.DAT)
  11604   000h 4    Number of files (N) (eg. 196h)
  11605   004h 4    Unknown (always 0Bh) (maybe sector size shift?)
  11606   008h N*4  File List
  11607   ...  ..   Zeropadding to 800h-byte boudary
  11608   ...  ..   File Data
  11609 File List entries:
  11610   000h 2    Offset/800h (increasing)
  11611   002h 2    Size/800h (can be zero)
  11612 The "files" might actually contain small child folders? Or the whole stuff is
  11613 just some kind of data structure, not an actual file system archive.
  11614 
  11615 Charumera (*.CVF)
  11616   000h N*4  File List
  11617   ...  ..   Zeropadding to 800h-byte boundary
  11618   ...  ..   File Data area
  11619  File List entries:
  11620   000h 1    Size/800h   (8bit)
  11621   001h 3    Offset/800h (24bit, increasing)
  11622 
  11623 Vs (MagDemo03: THQ\*) has .CDB archives
  11624   000h  N*8   File List
  11625   ...   ..    Zeropadding to 800h-byte boundary
  11626   ...   ..    File Data
  11627   ...   ..    Garbage padding (can be several megabytes tall)
  11628 File List entries:
  11629   000h 2     Offset/800h (increasing)
  11630   002h 2     Size/800h (same as below, rounded up to sector units)
  11631   004h 4     Size in bytes
  11632 Note: The files may consist of multiple smaller files badged together (eg.
  11633 DISPLAY.CDB contains several TIMs per file).
  11634 Some CDB archives have garbage padding at end of file: BIN.CDB (2Kbyte),
  11635 CSEL.CDB (80K), DISPLAY.CDB (70K), MOT.CDB (10648Kbyte). Maybe that's related
  11636 to deleted files in the Vs demo version and/or to updating the CDB archives
  11637 with newer/smaller content, but without truncating the CDB filesize
  11638 accordingly.
  11639 
  11640 Monster Rancher (MagDemo06: MR_DEMO\*.OBJ)
  11641 Deception III Dark Delusion (MagDemo33: DECEPT3\K3_DAT.BIN)
  11642 Star Trek Invasion (MagDemo34: STARTREK\STARTREK.RES)
  11643 Similar as .CDB archives (but with 32bit offset, and without duplicated size).
  11644   000h  N*8   File List
  11645   ...   4     File List end marker (00000000h)
  11646   ...   ..    Garbage padding to 800h-byte boundary
  11647   ...   ..    File Data
  11648 File List entries:
  11649   000h 4     Offset/800h (increasing)
  11650   004h 4     Size in bytes (often zero; for unused file numbers)
  11651 Note: Files are usually padded with 0..7FFh bytes to 800h-byte boundary, but
  11652 STARTREK.RES does append additional 800h-byte padding after each file (ie.
  11653 800h..FFFh padding bytes in total).
  11654 
  11655 Einhander (MagDemo08: BININDEX.BIN/BINPACK0.BIN/BINPACK1.BIN)
  11656   000h X*4  File List for BINPACK0.BIN                   ;\
  11657   ...  ..   Zeropadding                                  ; BINPACK0
  11658   410h ..   Unknown (some/all of it looks like garbage)  ;/
  11659   800h Y*4  File List for BINPACK1.BIN                   ;\
  11660   ...  ..   Zeropadding                                  ; BINPACK1
  11661   C10h ..   Unknown (some/all of it looks like garbage)  ;/
  11662 File List entries:
  11663   000h 2    Offset/800h in BINPACK0.BIN or BINPACK1.BIN
  11664   002h 2    Size/800h
  11665 
  11666 SO98 Archives (NBA Shootout '98, MagDemo10: SO98\..*.MDL *.TEX *.ANI *.DAT)
  11667 Resembles .BZE (in terms of duplicated size entry).
  11668   000h 4     Number of Files
  11669   004h 4     Size of File Data area (total filesize-N*0Ch-8)
  11670   008h N*0Ch File List
  11671   ...  ..    File Data area
  11672 File List entries:
  11673   000h 4   Offset (zerobased, from begin of File Data area)
  11674   004h 4   Size in bytes
  11675   008h 4   Size rounded to mutiple of 4-bytes
  11676 .DAT contains .TIM .SEQ .VB .VH and nested SO98 archives
  11677 .MDL contains whatever (and empty 0-byte files)
  11678 .TEX contains .TIM
  11679 .ANI contains whatever
  11680 
  11681 Gran Turismo 1 (MagDemo10: GT\*.DAT) GT-ARC
  11682 Gran Turismo 1 (MagDemo15: GT\*.DAT) GT-ARC
  11683 Gran Turismo 2 (GT2.VOL\arcade\arc_fontinfo) GT-ARC
  11684   000h 0Ch   ID "@(#)GT-ARC",00h,00h
  11685   00Ch 2     Content Type (8001h=Compressed, 0001h=Uncompressed)
  11686   00Eh 2     Number of Files (eg. 0Fh)
  11687   010h N*0Ch File List
  11688   ...  ..    File Data area
  11689  File List entries:
  11690   000h 4     Offset in bytes (increasing, unaligned)
  11691   004h 4     Compressed File Size (can be odd)  ;\both same when uncompressed
  11692   008h 4     Decompressed File Size             ;/(ie. when [00Ch]=0001h)
  11693 MESSAGES.DAT, SOUND.DAT, TITLE.DAT which are completely uncompressed GT-ARC's.
  11694 Most other GT-ARC's contain LZ compressed files. In case of CARINF.DAT it's
  11695 vice-versa, the files are uncompressed, but the GT-ARC itself is LZ compressed
  11696 (the fileheader contains 00h,"@(#)GT-A",00h,"RC",00h,00h; it can be detected
  11697 via those bytes, but lacks info about decompressed size).
  11698 --> CDROM File Compression GT-ZIP (Gran Turismo 1 and 2)
  11699 
  11700 O.D.T. (MagDemo17: ODT\*.LNK and ODT\RSC\NTSC\ALLSOUND.SND and nested LNK's)
  11701 Barbie Explorer (MagDemo50: BARBIEX\*.STR and nested therein)
  11702   000h 4     Number of Files (N)
  11703   004h N*8   File List
  11704   ...  ..    File Data area
  11705 File List entries:
  11706   000h 4     Offset in bytes (increasing, 1/4-byte? aligned)
  11707   004h 4     File Size in bytes (usually N*4, TXT's in ODT are padded as so)
  11708 Quirk: Instead of rounding only Offsets to N*4 byte boundary, all Sizes are
  11709 rounded to N*4 bytes (eg. TXT files in ODT\RSC\NTSC\GFILES.LNK\01 with odd
  11710 number of characters are are zeropadded to N*4 bytes).
  11711 Note: The PADBUG archives in Final Fantasy VIII (FF8) are very similar (but
  11712 have a different alignment quirk).
  11713 
  11714 Bust A Groove (MagDemo18: BUSTGR_A\*.DFS and BUSTGR_B\*.DFS) (DFS)
  11715 Bust-A-Groove 2 (MagDemo37: BUSTAGR2\BUST2.BIN\*) (main=DF2 and child=DFS)
  11716 Same as in O.D.T. with extra "DFS_" ID at start of file.
  11717   000h 4     ID "DFS_" (with align 4) or "DF2_" (with align 800h)
  11718   004h 4     Number of Files (N)
  11719   008h N*8   File List
  11720   ...  ..    File Data area
  11721  File List entries:
  11722   000h 4     Fileoffset in bytes (4-byte or 800h-byte aligned, increasing)
  11723   004h 4     Filesize in bytes (can be odd, eg. in BUSTGR_A\SELECT.BPE\*)
  11724 The game does use uncompressed DFS archives (in .DFS files) and compressed DFS
  11725 archives (in .BPE files):
  11726 --> CDROM File Compression BPE (Byte Pair Encoding)
  11727 The game does also use .DBI files (which contain filenames and other strings,
  11728 whatever what for).
  11729 
  11730 Monaco Grand Prix Racing Simulation 2 (MagDemo24: EXE\*\*.SUN)
  11731 Same as DFS, but with Total Filesize instead of "DFS_".
  11732   000h 4     Total used filesize (excluding zeropadding to 2EE000h)
  11733   004h 4     Number of Files (N)
  11734   008h N*8   File List
  11735   ...  ..    File Data area
  11736   ...  (..)  In some files: Zeropadding to 2EE000h (3072Kbytes)
  11737 File Entries:
  11738   000h 4     Offset (increasing, 4-byte aligned, see note)
  11739   004h 4     Filesize in bytes (can be odd in Monaco)
  11740 Note: The alignment in Monaco is a bit glitchy:
  11741   If (Size AND 3)=0 then NextOffset=Offset+Size             ;Align4
  11742   If (Size AND 3)>0 then NextOffset=Offset+Size+Align800h   ;Align800h
  11743   Namely, Monaco has files with Size=3BC5h.
  11744 The first file starts with unknown 32bit value, followed by "pBAV".
  11745 
  11746 Rollcage (MagDemo19: ROLLCAGE\SPEED.IMG) (2Mbyte)
  11747 Rollcage Stage II (MagDemo31: ROLLCAGE\SPEED.IDX+SPEED.IMG) (3Kbyte+9Mbyte)
  11748 Sydney 2000 (MagDemo37: OLY2000\DEMO.IDX+DEMO.IMG) (1Kbyte+2Mbyte)
  11749  Rollcage 1 uses a single IMG file that contains both directory and data:
  11750   000h 4     Header offset (0)          ;\
  11751   004h 4     Header size (10h+N*10h)    ; this seems to be a File List entry
  11752   008h 4     Header size (10h+N*10h)    ; for the header itself
  11753   00Ch 4     Zero                       ;/
  11754   010h N*10h File List                  ;-File List for actual files
  11755   ...  ..    Zeropadding to 800h-byte boundary
  11756   ...  ..    File Data area
  11757   Number of files is "IMG[04h]/10h" (minus 1 for excluding the header itself)
  11758  The other titles have seaparate IDX and IMG files for directory and data:
  11759   SPEED.IDX = Directory (N*10h bytes File List with offsets into SPEED.IMG)
  11760   SPEED.IMG = File data
  11761   Number of files is "Filesize(SPEED.IDX)/10h"
  11762 File List entries:
  11763   000h 4     Fileoffset in bytes (800h-byte aligned, increasing)
  11764   004h 4     Filesize in bytes
  11765   008h 4     When compressed:   GT20 Header [004h] (decompressed size)
  11766              When uncompressed: Same as filesize
  11767   00Ch 4     When compressed:   GT20 Header [008h] (overlap, usuallly 3, or 7)
  11768              When uncompressed: Zero
  11769 The compression related entries allow to pre-allocated the decompression buffer
  11770 (without needing to load the actual GT20 file header), and then load the
  11771 comprssed file to the top of the decompression buffer.
  11772 --> CDROM File Compression GT20 and PreGT20
  11773 
  11774 Ultimate 8 Ball (MagDemo23: POOL.DAT) (5.5Mbyte)
  11775   000h 4      Number of Entries
  11776   004h N*0Ch  File List
  11777   ...  ..     Zeropadding to 800h-byte boundary
  11778   ...  ..     File Data area
  11779  File List entries:
  11780   000h 4      Unknown (random/checksum?)
  11781   004h 4      File Offset (800h-byte aligned, increasing)
  11782   008h 4      File Size in bytes
  11783 Notes: The LAST file isn't zeropadded to 800h-byte boundary. The File List
  11784 includes some unused entries (all 0Ch-bytes zerofilled).
  11785 
  11786 BIGFOOL - 3D Baseball (BIGFILE.FOO)
  11787   000h N*0Ch  File List                                   (154h entries)
  11788   ...  N*4    Filename Checksums (?)                      (154h entries)
  11789   ...  ..     Zerofilled (padding to 800h-byte boundary)
  11790   ...  ..     File Data area
  11791 The 1st list entry describes the current directory itself, as so:
  11792   000h 4      Number of entries (including the 1st entry itself)
  11793   004h 4      Offset/800h (always 0, relative from begin of directory)
  11794   008h 4      Type        (always 3=Directory)
  11795 Further list entries are Files or Subdirectories, as so:
  11796   000h 4      For Files: Size in bytes, for Directories: Number of entries
  11797   004h 4      Offset/800h (from begin of current directory, increasing)
  11798   008h 4      Type        (0=File, 3=Directory)
  11799 
  11800 Spec Ops - Airborne Commando (BIGFILE.CAT and nested CAT files therein)
  11801   000h 4     File ID                                 (always 01h,02h,04h,08h)
  11802   004h 4     Maybe Version?                          (always 01h,00h,01h,00h)
  11803   008h 4     Header Size (18h+N*8+ArchiveNameLength)    ;eg. 4ECh
  11804   00Ch 4     Sector Alignment (can be 4 or 800h)
  11805   010h 4     Number of Files (N)                        ;eg. 99h
  11806   014h 4     Length of Archive Name (including ending 00h)
  11807   018h N*8   File entries (see below)
  11808   ...  ..    Archive Name, ASCII, terminated by 00h     ;eg. "bigfile.dir",00h
  11809   ...  ..    Zeropadding to Sector Alignment boundary
  11810   ...  ..    File Data
  11811 File Entries:
  11812   000h 4   Fileoffset (with above Sector Alignment) (increasing)
  11813   004h 4   Filesize in bytes
  11814 Filetypes in the archive include...
  11815   nested CAT archives (file 07h,0Ch,11h,16h,1Bh,20h,25h,etc)
  11816   empty files         (file 3Eh,5Ah-5Fh,62h-67h,etc)
  11817   MDEC v2 STR's       (file 95h-96h)
  11818   XA-ADPCM's          (inside of nested CAT, in file94h\file*)
  11819 There are "strings" in some files, are those filenames, eg. Icon_xxx etc?
  11820 
  11821 Hot Shots Golf 2 (retail: DATA\F0000.BIN, MagDemo31/42: HSG2\MINGOL2.BIN)
  11822 The DATA directory is 13800h bytes tall. But, the PSX kernel supports max 800h
  11823 bytes per ISO directory (so the kernel can only see the first 33 files in that
  11824 directory). The game isn't actually trying to parse the ISO directory entries,
  11825 instead, it's using the 2800h-byte offset/size list in F0000.BIN to access the
  11826 directory content:
  11827   0000h+N*4 1     Sector MM in BCD      ;\based at 00:06:00 for file 0
  11828   0001h+N*4 1     Sector SS in BCD      ; (unused files are set to 00:00:00)
  11829   0002h+N*4 1     Sector FF in BCD      ;/
  11830   0003h+N*4 1     Size MSB in hex (Size/800h/100h)
  11831   2000h+N   1     Size LSB in hex (Size/800h AND FFh)
  11832   2800h     (..)  Data area for file 001h..590h (demo version only)
  11833 Retail Version disc layout:
  11834   Sector 000ADh  SCUS_944.76       ;exefile     ;\
  11835   Sector 00130h  SYSTEM.CNF                     ; iso root folder
  11836   Sector 00131h  DATA (sub-folder, 27h sectors) ;/
  11837   Sector 00158h  (padding)                      ;-padding to 00:06:00
  11838   Sector 001C2h  DATA\F0000.BIN    ;file 000h   ;\
  11839   Sector 001C7h  DATA\F0001.BIN    ;file 001h   ;
  11840   ...                                           ; iso data folder
  11841   Sector 00B54h  DATA\F0032.BIN    ;file 020h   ;
  11842   Sector 00B9Bh  DATA\F0033.BIN    ;file 021h   ;  ;\files exceeding the 800h
  11843   ...            ...                            ;  ; directory size limit, not
  11844   Sector 1A0C9h  DATA\F1907.BIN    ;file 773h   ;/ ;/accessible via PSX kernel
  11845   Sector 1AAF1h  DUMMY.BIN                      ;-iso root folder (padding)
  11846 Demo version in Playstation Magazine is a bit different: It has only two large
  11847 .BIN files (instead of hundreds of smaller .BIN files). The directory is stored
  11848 in first 2800h bytes of MINGOL2.BIN. The MM:SS:FF offsets are numbered as if
  11849 they were located on sector 00:06:00 and up (to get the actual location:
  11850 subtract 00:06:00 and then add the starting sector number of MINGOL2.BIN).
  11851   Sector 07148h  HSG2\MINGOL2.BIN  ;file 000h..590h  ;demo binary files
  11852   Sector 0AC1Dh  HSG2\MINGOL2X.BIN ;file 76Ch        ;demo streaming file(s)
  11853   Sector 0B032h  HSG2\SCUS_944.95  ;exefile          ;demo exe file
  11854 Note: File 000h is a dummy entry referring to the 2800h-byte list itself
  11855 (retail file 000h has offset=00:06:00 but size=0, demo file 000h has offset and
  11856 size set to zero). File 001h is the first actual file (at offset=00:06:05, ie.
  11857 after the 2800h-byte list)
  11858 
  11859 Threads of Fate (MagDemo33: TOF\DEWPRISM.HED+.EXE+.IMG)
  11860 The demo version uses "Virtual Sectors" in HED+EXE+IMG files. Apart from that,
  11861 the format is same as for the "Hidden Sectors" in retail version:
  11862 --> CDROM File Archives in Hidden Sectors
  11863 
  11864 WWF Smackdown (MagDemo33: TAI\*.PAC\*, and nested therein)
  11865 These "PAC " files are found in the main archives (which use a separate archive
  11866 format, with ID "DPAC").
  11867   000h 4     ID ("PAC ")                                        ;\
  11868   004h 4     Number of files (N)                                ; Header
  11869   008h N*8   File List                                          ;/
  11870   ...  ..    File Data area                                     ;-Data area
  11871 File List entries:
  11872   000h 2     File ID (inreasing, but may skip numbers, ie. non-linear)
  11873   002h 3     File Offset (increasing, relative to begin of Data area)
  11874   005h 3     File Size
  11875 Bug: TAI\C.PAC\EFFC\0001h has TWO entries with File ID=0002h.
  11876 
  11877 Tyco R/C Racing (MagDemo36: TYCO\MAINRSRC.BFF)
  11878   000h 4     Unknown (1)
  11879   004h 4     Filelist Offset          (800h)
  11880   008h 4     Filelist Size (N*8+4)    (7ACh)
  11881   ...  ..    Padding to 800h-byte boundary (see note)
  11882   800h 4     Number of files (N)      (F5h)
  11883   804h N*8   File List
  11884   ...  ..    Padding to 800h-byte boundary (see note)
  11885   ...  ..    File Data area
  11886 File List entries:
  11887   000h 4     File Offset in bytes (increasing, 800h-byte aligned)
  11888   004h 4     File Size in bytes
  11889 Padding Note: Padding after headers & files is weirdly done in two steps:
  11890   Step 1: Zeropadding to 200h-byte boundary    (first 0..1FFh bytes)
  11891   Step 2: Garbagepadding to 800h-byte boundary (last 0..600h bytes)
  11892 
  11893 Team Buddies (MagDemo37: BUDDIES\BUDDIES.DAT)
  11894   000h 2     ID ("BD")
  11895   002h 2     Number of files (N)
  11896   004h N*8   File List
  11897   ...  ..    Zeropadding to 3000h
  11898   3000h ..   File Data area
  11899 File List entries:
  11900   000h 4     File Offset/800h (increasing)
  11901   004h 4     File Size in bytes
  11902 
  11903 Gundam Battle Assault 2 (DATA\*.PAC, and nested therein)
  11904   000h 4     ID ("add",00h)
  11905   004h 4     Fixed (4)
  11906   008h 4     Offset to File List (usually/always 20h)
  11907   00Ch 4     Number of Files (N)
  11908   010h 4     Fixed (10h)
  11909   014h 0Ch   Zerofilled
  11910   020h N*10h File List
  11911   ...  ..    File Data area
  11912 File List entries:
  11913   000h 4     Offset (increasing, 4-byte aligned)  ;\or both zero
  11914   004h 4     Size (can be odd)                    ;/
  11915   008h 4     Unknown (0) (or 00h,10h,11h,20h,30h,40h when Offset/Size=0)
  11916   00Ch 4     Zero (0)
  11917 
  11918 Incredible Crisis (MagDemo38: IC\*.CDB)
  11919   000h 4     Number of files (N)
  11920   004h N*4   File List
  11921   ...  ..    Zeropadding to 800h-byte boundary
  11922 File List entries:
  11923   000h 2     File Offset/800h (increasing)
  11924   002h 2     File Size/800h
  11925 
  11926 Ultimate Fighting Championship (MagDemo38: UFC\CU00.RBB)
  11927   0000h 4    ID "siff"                                  ;\Header
  11928   0004h 4    Total Filesize (DADB1Ch)                   ;/
  11929   0008h 4    ID "RSRC"                                  ;\
  11930   000Ch 4    String Size (70h)                          ; ASCII string
  11931   0010h 70h  String "RC ver1.0 Copyright",...,00h       ;/
  11932   0080h 4    ID "RIDX"                                  ;\
  11933   0084h 4    File List Size     (1F78h) (3EFh*8)        ; Directory
  11934   0088h N*8  File List (Offset, Size1)                  ;/
  11935   2000h 4    ID "EXIX"                                  ;\
  11936   2004h 4    Extended List Size (FBCh)  (3EFh*4)        ; Extended
  11937   2008h N*4  Extended List (Size2)                      ;/
  11938   2FC4h 4    ID "GAP0"                                  ;\Alignment Padding
  11939   2FC8h 4    Padding Size (2Ch)                         ; (so that next chunk
  11940   2FCCh 2Ch  Padding (1Ah-filled)                       ;/starts at boundary-8)
  11941   2FF8h 4    ID "RBB0"                                  ;\
  11942   2FFCh 4    File Data area Size (DAAB1Ch)              ; Data area
  11943   3000h ..   File Data area                             ;/
  11944 File List entries (RIDX):
  11945   000h 4     File Offset (increasing, 4-byte aligned, from ID "RBB0" plus 8)
  11946   004h 4     File Size in bytes (can be odd)
  11947 Extended List entries (EXIX):
  11948   000h 4     File Size in bytes (always the same size as in RIDX chunk)
  11949 
  11950 Ultimate Fighting Championship (MagDemo38: UFC\CU00.RBB\183h,37Bh..3EBh)
  11951   000h 4     ID "OIFF"                                  ;\Header
  11952   004h 4     Total Filesize                             ;/
  11953   008h 4     ID "TIMT" or "ANMT"                        ;\
  11954   00Ch 4     Size (N*4)                                 ; Directory Table
  11955   010h N*4   File List (offsets from begin of Data ID+8);/
  11956   ...  4     ID "TIMD" or "ANMD"                        ;\
  11957   ...  4     Data Area size (SIZ) (Filesize-18h-N*4)    ; Data area
  11958   ...  SIZ   Data Area                                  ;/
  11959 
  11960 E.T. Interplanetary Mission (MagDemo54: MEGA\MEGA.CSH+.BIN)
  11961  MEGA.CSH:
  11962   000h N*0Ch File List
  11963  MEGA.BIN:
  11964   000h ..    File Data area
  11965 File List entries:
  11966   000h 4     Offset (in MEGA.BIN file, 800h-byte aligned, increasing)
  11967   004h 4     Unknown (32bit id/random/checksum/whatever)
  11968   008h 4     Filesize in bytes
  11969 
  11970 Driver 2 The Wheelman is Back (MagDemo40: DRIVER2\SOUND\*\*)
  11971   000h 4     Number of entries (1 or more)
  11972   004h N*10h File List
  11973   ...  ..    File Data area (.VB aka SPU-ADPCM)
  11974  File List entries:
  11975   000h 4     Offset from begin of Data area, increasing
  11976   004h 4     Filesize in bytes
  11977   008h 4     Unknown (0 or 1)
  11978   00Ch 4     Unknown (AC44h, 0FA0h, 2EE0h, 2710h, 2B11h, 3E80h, 1F40h, etc.)
  11979  Note: Above AC44h might 44100Hz, or just file number 44100 decimal?
  11980 
  11981 Thrasher: Skate and Destroy (MagDemo27: SKATE\ASSETS\*.ZAL) (Z-Axis)
  11982 Dave Mirra Freestyle BMX (MagDemo36: BMX\ASSETS\*.ZAL) (Z-Axis)
  11983 Dave Mirra Freestyle BMX (MagDemo46: BMX\ASSETS\*.ZAL) (Z-Axis)
  11984   000h 4     ID (always 2A81511Ch)
  11985   004h 0Ch   Zerofilled
  11986   010h 1     Unknown (1)
  11987   011h 1     Compression Flag for all files (00h=Uncompressed, 80h=Compressed)
  11988   012h 2     Number of files (bit0-13?=N, bit14=Unknown, can be set)
  11989   014h N*0Ch File List, 12 bytes/entry      ;<-- when [11h]=00h=uncompressed
  11990   014h N*10h File List, 16 bytes/entry      ;<-- when [11h]=80h=compressed
  11991   ...  ..    File Data area
  11992 File List entries (0Ch or 10h bytes per entry, depending on compression):
  11993   000h 4     File ID (usually 0=first, increasing) (or 0001h,7531h,7532h,...)
  11994   004h 4     Offset-10h in bytes (increasing, 4h-byte aligned)
  11995   008h 4     Filesize, uncompressed (can be odd)
  11996   00Ch (4)   Filesize, compressed (can be odd)   ;<-- exists only if compressed
  11997 For decompression, see:
  11998 --> CDROM File Compression ZAL (Z-Axis)
  11999 
  12000 Speed Punks (MagDemo32: SPUNKS\*.GDF)
  12001   000h 4     ID "0FDG XSP" (aka PSX GDF0 backwards)
  12002   008h 4     Header Size (N*10h+10h)
  12003   00Ch 4     Number of files (N)
  12004   010h N*10h File List
  12005   ...  ..    Zeropadding to 800h-byte boundary
  12006   ...  ..    File Data area
  12007  File List entries:
  12008   000h 4     ID/Type ("MARV", "MARS", "MARD", "PMET", "COLR", "MROF")
  12009   004h 4     ID/Num  (usually 1 SHL N, or all zero)
  12010   008h 4     Offset (800h-byte aligned, increasing)
  12011   00Ch 4     Size in bytes
  12012 
  12013 Legend of Dragoon (MagDemo34: LOD\SECT\*.BIN, and nested therein)
  12014   000h 4     ID "MRG",1Ah
  12015   004h 4     Number of Files (eg. 0, 1, 2, 193h, 2E7h, or 1DBBh)
  12016   008h N*8   File List
  12017   ...  ..    Padding to 800h-byte boundary (8Ch-filled) (not in nested MRG's)
  12018   ...  ..    File Data area
  12019  File List entries:
  12020   000h 4     Offset/800h, or 4-byte aligned Offset/1 (increasing)
  12021   004h 4     Size (can be odd, and can be zero)
  12022  Size oddities:
  12023   Empty files in demo version have Size=0 and Offset=0.
  12024   Empty files in retail version have Size=0 and Offset=OffsetOfNextFile.
  12025   MRG archives can start or end with Empty files.
  12026   All files can be empty (eg. retail DRAGN0.BIN\1190h).
  12027   NumFiles can be zero (eg. retail DRAGN0.BIN\1111h, demo DRAGN0.BIN\10E2h).
  12028  Offset oddities:
  12029   SECT\*.BIN have Offset/800h
  12030   Nested MRGs have 4-byte aligned Offset/1
  12031   The two variants can be detected as:
  12032    if FirstOffset=(NumFiles*8+8) then NestedVariant
  12033    if FirstOffset=(NumFiles*8+8+7FFh) AND NOT 7FFh then RootVariant
  12034   Whereas, FirstOffset is the first NONZERO offset in file list (important
  12035   for demo version, which has archives that start with ZERO offsets).
  12036 
  12037 RC Revenge (MagDemo37: RV2\BB\3.BBK and Retail: BB\*\*.BBK)
  12038 This does basically contain four large files (and four info blocks with info on
  12039 the content of those files).
  12040   000h 4     Random/Checksum?
  12041   004h 4     Faded ID (FADED007h)
  12042   008h 4     Part 1 Offset (Sound)     (always E5Ch)
  12043   00Ch 4     Part 2 Offset (Texture)   (when Type=01h: Offset-E5Ch)
  12044   010h 4     Part 3 Offset (?)         (when Type=01h: Offset-E5Ch)
  12045   014h 4     Part 4 Offset (?)         (when Type=01h: Offset-E5Ch)
  12046   018h 4     Type (10h or 20h=Normal)  (or 01h=Special in BB\8\*.BBK)
  12047   01Ch B0Ch  Part 1 Info (Sound)       (when Type=01h: garbage-filled)
  12048   B28h 314h  Part 2 Info (Texture)
  12049   E3Ch 14h   Part 3 Info (?)
  12050   E50h 0Ch   Part 4 Info (?)
  12051   E5Ch ..    Part 1 Data (Sound, SPU-ADPCM data, if any)
  12052   ...  ..    Part 2 Data (Texture data) (starts with BDEF1222h or BDEF1111h)
  12053   ...  ..    Part 3 Data (?)   ;\maybe map, models, and/or whatever
  12054   ...  ..    Part 4 Data (?)   ;/
  12055 Part 1 Info (Sound info) (if any):
  12056   01Ch 4     Random/Checksum?
  12057   020h 4     Faded ID (FADED007h)
  12058   024h 4     Part 1 Size              (eg.7C7F0h)
  12059   028h 4     SPU Start Addr           (1010h) (for data from file offset E5Ch)
  12060   02Ch 4     SPU Middle Addr          (eg. 58F70h)
  12061   030h 4     SPU End Addr             (eg. 7D800h) (start+size)
  12062   034h 2     Middle entry number      (often 3Ch)
  12063   036h 2     Number of used entries-1 (eg. 50h means that 51h entries are used)
  12064   038h AF0h  Sample List (100 entries, unused ones are zerofilled)
  12065   914h 214h  Zerofilled (unused 1Ch-byte entries) (total is 1Ch*64h)
  12066  Sample List entries:
  12067   000h 4     SPU Offset (1010h and up) (SpuOffset=1010h is FileOffset=E5Ch)
  12068   004h 4     Sample Size in bytes
  12069   008h 4     Unknown (0)
  12070   00Ch 4     Unknown (0)
  12071   010h 4     Pitch   (400h=11025Hz, 800h=22050Hz, 2E7h=8000Hz, 8B5h=24000Hz)
  12072   014h 4     Unknown (0 or 1)
  12073   018h 4     File ID (00001F08h and up)
  12074 Part 2 Info (Texture info):
  12075   B28h 4     Random/Checksum?
  12076   B2Ch 4     Faded ID (FADED007h)
  12077   B30h 4     Part 2 Size      (N*16000h)  ;Width=2C0h halfwords, Height=N*64
  12078   B34h 4     Zero             (0h)
  12079   B38h 4     Some RAM Address (8010xxxxh)
  12080   B3Ch 4     Unknown          (eg. 195h or E3h) ;same as at [DA4h]
  12081   B40h 4+4   VRAM Address X,Y (140h,0)          ;maybe load target
  12082   B48h 4+4   VRAM Address X,Y (140h,0)          ;maybe palette base?
  12083   B50h 4+4   VRAM Address X,Y (xx0h,Height-40h) ;often at/near end of used area
  12084   B58h 4     Unknown          (eg. 1D0h or 1E0h)
  12085   B5Ch 4     Unknown          (eg. 1Ah or 0Dh)
  12086   B60h 200h  Some halfwords?  (most are FFFFh, some are 0000h)
  12087   D60h 40h   Zerofilled       (0)
  12088   DA0h 4     Unknown          (eg. 185h or E2h)
  12089   DA4h 4     Unknown          (eg. 195h or E3h) ;same as at [B3Ch]
  12090   DA8h 9x10h Special Texpages (VramX,Y, SizeX,Y, StepX,Y, Flag/Type/Num or so?)
  12091   E38h 4     Some RAM Address (800Axxxxh)
  12092 Part 3 Info:
  12093   E3Ch 4     Random/Checksum?
  12094   E40h 4     Faded ID (FADED007h)
  12095   E44h 4     Part 3 Size                  (eg. A9728h or 51264h)
  12096   E48h 4     RAM End Address (start+size) (eg. 801Fxxxxh) (near memtop)
  12097   E4Ch 4     RAM Start Address (end-size) (eg. 801xxxxxh)
  12098 Part 4 Info:
  12099   E50h 4     Random/Checksum?
  12100   E54h 4     Faded ID (FADED007h)
  12101   E58h 4     Part 4 Size (usually 10CCCh) (or 105E0h in demo version)
  12102 Note: File CAT\RDS.CAT does also start with ID=FADED007h (but contains whatever
  12103 different stuff).
  12104 
  12105 CDROM File Archives with Offset
  12106 -------------------------------
  12107 
  12108 Below are archives that start with a simple Offset list. The DOT1 and DOTLESS
  12109 types are "standard" archives used by many PSX games (although the "standard"
  12110 was probably independently created by different developers).
  12111 
  12112 DOT1 Archives (named after the ".1" extension in R-Types)
  12113 Used by various titles:
  12114   R-Types (CG.1, PR\PR.1, and nested inside CG.1)
  12115   Final Fantasy IX (nested inside FF9.IMG, FF9.IMG\DB, FF9.IMG\DB\DOT1)
  12116   Legend of Mana (*.EFF,*.SET,*.BTP(?) in folders SND*,SOUND,WM(?))
  12117   Witch of Salzburg (*.ANM/BIN/BSS/DAT/MDL/SCE)
  12118   Rayman (RAY\*.XXX, RAY\SND\*.ALL, and nested inside *.XXX)
  12119   Pandemonium II (JESTERS.PKG\0101\0008 and JESTERS.PKG\0101\000D)
  12120   Incredible Crisis (MagDemo38: IC\TAN_DAT.CDB\<DOTLESS>\<DOT1>\<SHIFTJIS>)
  12121   Various games on PlayStation Magazine Demo Discs (Disc 03-54)
  12122 DOT1 (in lack of a better name) is a simple archive format that contains Number
  12123 of Entries and List with Increasing Offsets to File data.
  12124   000h 4    Number of Files (N)                 (eg. 2..18)
  12125   004h N*4  File List (offsets to each file, increasing, aligned)
  12126   ...  (4)  Optional: Total filesize (aka end-offset for last list entry)
  12127   ...  ..   Optional: Zeropadding to alignment boundary (when alignment>4)
  12128   ...  ..   File Data
  12129 There are four variants with different alignment (and in some cases, with an
  12130 extra entry with end-offset for last file):
  12131   Align800h, no extra entry    R-Types (CG.1 and PR\PR.1)
  12132   Align4,    no extra entry    R-Types (nested in CG.1), FF9 (in IMG, IMG\DB)
  12133   Align2,    no extra entry    Incredible Crisis (IC\TAN_DAT.CDB\*\*)
  12134   Align800h, with extra entry  MLB 2000 (DATA.WAD)
  12135   Align10h,  with extra entry  Witch of Salzburg (*.ANM/BIN/BSS/DAT/MDL/SCE)
  12136   Align4,    with extra entry  Rayman (*.XXX, *.ALL)
  12137 The files can be detected by checking [004h]=4+(N*4), 4+(N*4)+Align800h,
  12138 4+(N*4)+4, or 4+(N*4)+4+Align10h, and checking that the offsets are increasing
  12139 with correct alignment (Rayman has some empty files with same offset), and
  12140 don't exceed the total filesize. And that the alignment space is zeropadded (in
  12141 case of R-Types, only the header is 00h-padded, but files are FFh-padded).
  12142 The detection could go wrong, especially if the archive contains very few
  12143 files, some of the nested DOT1's contain only one file (header "00000001h,
  12144 00000008h", without any further increasing offsets or padding). As workaround,
  12145 accept such files only if they have a ".1" filename extension, or if they were
  12146 found inside of a bigger DOT1, IMG, or DB archive.
  12147 Final Fantasy IX contains some DOT1's with fewer than few entries (the file
  12148 being only 4-bytes tall, containing value NumEntries=00000000h).
  12149 
  12150 NFL Gameday '98 (MagDemo04: GAMEDAY\*.FIL) (32bit) (with nested FIL's)
  12151 NFL Gameday '99 (MagDemo17: GAMEDAY\*.FIL) (32bit)
  12152 NFL Gameday 2000 (MagDemo27: GAMEDAY\*.FIL) (16bit and 32bit)
  12153 NCAA Gamebreaker '98 (MagDemo05: GBREAKER\*.FIL,*.BIN) (16bit and 32bit)
  12154 NCAA Gamebreaker 2000 (MagDemo27: GBREAKER\*.FIL) (16bit and 32bit)
  12155 FIL/32bit (with [02h]=FFFFh):
  12156   000h 2    Number of Files (N)
  12157   002h 2    ID for 32bit version (FFFFh=32bit entries)
  12158   004h N*4  File List (offsets to each file, increasing, 4-byte aligned)
  12159   ...  ..   File Data
  12160 FIL/16bit (with [02h]<>FFFFh, eg. FLAG*.FIL and VARS\STARTUP2.FIL\0\*):
  12161   000h 2    Number of Files (N)
  12162   002h N*2  File List (offsets to each file, increasing, 4-byte aligned)
  12163   ...  ..   Zeropadding to 4-byte boundary
  12164   ...  ..   File Data
  12165 
  12166 PreSizeDOT1 (Ace Combat 2) (retail and MagDemo01: ACE2.DAT\*)
  12167 Like DOT1, but with Total Filesize being oddly stored at begin of file.
  12168   000h 4    Total Filesize (aka end-offset for last list entry)
  12169   004h 4    Number of Files (N)
  12170   008h N*4  File List (offsets to each file, increasing, 4-byte aligned)
  12171   ...  ..   File Data
  12172 Note: Ace Combat 2 contains PreSizeDOT1 (ACE2.DAT\02h..1Dh,36h..B2h) and normal
  12173 DOT1 archives (nested in PreSizeDOT1's and in ACE2.DAT\B3h..E1h).
  12174 
  12175 DOT-T (somewhat same as DOT1, but with 16bit entries)
  12176 Armored Core (MagDemo02, AC10DEMP\*.T)
  12177   000h 2    Number of Files
  12178   002h N*2  File List (Offset/800h to file data, increasing)
  12179   ...  2    Total Size/800h (end-offset for last file)
  12180   ...  ..   Zeropadding to 800h-byte boundary
  12181   ...  ..   File Data
  12182 This can contain many empty 0-byte files (aka unused file numbers; though maybe
  12183 those files exist in the retail version, but not in the demo version).
  12184 
  12185 DOTLESS Archive
  12186 Hot Shots Golf (MagDemo07: HSG\*.DAT)
  12187 Hot Shots Golf 2 (retail: DATA\F0000.BIN\*, MagDemo31/42: HSG2\MINGOL2.BIN\*)
  12188 Starblade Alpha (FLT\*.DAT, TEX\*.DAT)
  12189 Incredible Crisis (MagDemo38: IC\TAN_DAT.CDB\<DOTLESS>)
  12190   000h N*4  Offsets to File data (increasing, usually 4-byte aligned)
  12191   ...  (4)  Filesize (end-offset for last file) (only in Ape Escape)
  12192   ...  ...  File Data
  12193 Like DOT1, but without Number of Files entry (instead, the first offset does
  12194 imply the end of file list). There's no extra entry for end of last file
  12195 (instead, that's implied in the total filesize). Most files have at least 5
  12196 entries, but HSG\TITLE0.DAT seems to contain only one entry (ie. the whole
  12197 header contains only one value, 00000004h, followed by something that looks
  12198 like raw bitmap data).
  12199 Also used by Ape Escape (MINIGAME\* included nested ones), the Ape Escape files
  12200 do have an end-marker with last-offset (that will appear as an empty 0-byte
  12201 file at end of list when not specifically handling it).
  12202 MINIGAME\MINI2\BXTIM.BIN does also have several 0-byte files inside of the file
  12203 list.
  12204 
  12205 Twisted Metal: Small Brawl (MagDemo54: TMSB\SHL\*.TMS)
  12206   000h 4     Size of Data Area (total filesize minus 0D0h)
  12207   004h 4     Number of files
  12208   008h N*4   File List (zerobased offsets from begin of Data Area)
  12209   ...  ..    Zeropadding to 0D0h
  12210   0D0h ..    File Data Area
  12211 This resembles DOT1, with an extra size entry and padding to 0D0h.
  12212 
  12213 Ridge Racer Type 4 (MagDemo19: R4DEMO\R4.BIN, 39Mbyte)
  12214 Ridge Racer Type 4 (MagDemo21: R4DEMO\R4.BIN, 39Mbyte)
  12215 Basically, this is alike DOT1, but SECTOR numbers, and with extra entries...
  12216   000h 4     Number of Files (N) (3C9h)
  12217   004h N*4   File List (Offset/800h)
  12218   ...  4     Total Size/800h                  ;<-- last offset
  12219   ...  4     Unknown (00,E8,82,2E)            ;<-- ??? maybe chksum*800h or so?
  12220   ...  ..    Zeropadding to 800h-byte boundary
  12221   ...  ..    File Data area
  12222 
  12223 Legend of Legaia (MagDemo20: LEGAIA\PROT.DAT)
  12224   000h 4     Zero
  12225   004h 4     Number of Entries (4D3h)
  12226   008h N*4   File List (Offset/800h)
  12227   ...  4     Total Size/800h (aka end Offset/800h of last file)
  12228   ...  ..    Zeropadding to 800h-byte boundary
  12229   ...  ..    File Data area
  12230 The PROT.DAT does not contain filenames, however, it's bundled with CDNAME.TXT,
  12231 which appears to contain symbolic names for (some) indices:
  12232   #define init_data 0           ;for file 0000h
  12233   #define gameover_data 1       ;for file 0001h
  12234   #define town01 3              ;for file 0003h
  12235   #define town0b 12             ;for file 000Ch
  12236   ...                           ;...
  12237   #define other6 1222           ;for file 04C6h
  12238   #define other7 1228           ;for file 04CCh
  12239 The DAT file contains many zerofilled "dummy" files with 800h-byte size.
  12240 
  12241 Bloody Roar 1 (MagDemo06: BL\*.DAT)
  12242 Bloody Roar 2 (MagDemo22: ASC,CMN,EFT,LON,SND,ST5,STU\*.DAT)
  12243   000h 4     Number of Entries (N)
  12244   004h N*4   File List (Offset-(4+N*4), increasing) (or FFFFFFFFh=Unused entry)
  12245   ...  ..    File Data area
  12246 Most or all files in DAT archives are PreGT20 compressed.
  12247 --> CDROM File Compression GT20 and PreGT20
  12248 Note: Unused entries can occur anywhere, eg. Bloody Roar 2 CMN\SEL01.DAT does
  12249 have both first and LAST entry marked as unused (FFFFFFFFh). Also, there may be
  12250 a lot of unused entries, eg. Bloady Roar 1 CMN\TITLE00.DAT uses only 5 of 41h
  12251 entries).
  12252 
  12253 Klonoa (MagDemo08: KLONOA\FILE.IDX\*)
  12254   000h 4     ID "OA05"
  12255   004h N*4   Offset List (usually/always 5 used entries, plus zeropadding)
  12256   030h ..    File Data area (usually/always starting at offset 30h)
  12257 
  12258 C - The Contra Adventure (DATA\SND\*.SGG)
  12259   000h 4    ID "SEGG"
  12260   004h 4    Offset to .VH file
  12261   008h 4    Offset to .VB file
  12262   00Ch 4    Number of .SEQ files (N) (usually 6Eh, or 08h in MENU.SGG)
  12263   010h N*4  Offsets to .SEQ files (increasing, unaligned)
  12264   ...  ..   SEQ files
  12265   ...  ..   Padding to 4-byte boundary
  12266   ...  ..   VH file
  12267   ...  ..   VB file
  12268 
  12269 Ninja (MagDemo13: NINJA\VRW\*.VRW)
  12270   000h 8     ID "VRAM-WAD" (here as archive ID, although same as compress ID)
  12271   004h N*4   File List (offsets to Data)  ;NumFiles=(FirstOffset-8)/4
  12272   ...  ..    Data (compressed .PAK files, which do ALSO have ID="VRAM-WAD")
  12273 The compressed .PAK files are using a LZ5-variant:
  12274 --> CDROM File Compression LZ5 and LZ5-variants
  12275 
  12276 The Next Tetris (MagDemo22: TETRIS\*) has PSX.BSE (and nested therein)
  12277   000h 4     Unknown (3)
  12278   004h 4     Total Size
  12279   008h 4     Number of Files (N) (max 40h, for max 40h*4 bytes in file list)
  12280   00Ch N*4   File List (increasing offsets, 800h-byte aligned)
  12281   ...  ..    Unknown (looks like garbage padding for unused File List entries)
  12282   10Ch 6F4h  42h-filled padding to 800h-byte boundary
  12283   800h ..    File Data area
  12284 
  12285 Tactics Ogre (UBF*.BIN)
  12286   000h 8     Fixed (88h,0,0,0,0,0,0,0)
  12287   008h 4     Number of Files (eg. 1Dh or 585h, including last/end file)
  12288   00Ch N*4   File List (increasing offsets, 800h-byte aligned)
  12289   ...  ..    Zeropadding to 800h-byte boundary
  12290   ...  ..    File Data area
  12291 Note: The last file is a TXT file containing "LINK-FILE END....",0Dh,0Ah,1Ah,
  12292 plus zeropadding to 800h-byte boundary.
  12293 
  12294 Spyro the Dragon (MagDemo12: SPYRO\PETE.WAD)
  12295   000h 4     Total Filesize (3E800h in Spyro)
  12296   004h N*8   File List      (1B0h bytes in Spyro)
  12297   ...  ..    Zeropadding to 800h-byte boundary
  12298   ...  ..    File Data (4-byte aligned, despite of above 800h-byte hdr padding)
  12299 File List entries:
  12300   000h 4     Fileoffset (increasing, 4-byte aligned)
  12301   004h 4     File ID? (unsorted, not increasing, used range is 000h..1FAh)
  12302 
  12303 CDROM File Archives with Size
  12304 -----------------------------
  12305 
  12306 Disney-Pixar's Monsters, Inc. (MagDemo54: MINC\*.BZE)
  12307   000h 4     Zero (0)
  12308   004h 4     Type/ID (27100h=160000, 2BF20h=180000, 30D40h=200000 decimal)
  12309   008h 4     Number of files
  12310   00Ch N*0Ch File List
  12311   ...  ..    Zeropadding to 7FCh
  12312   7FCh 4     Checksum (32bit sum of SIGN-EXPANDED bytes at [000h..7FBh])
  12313   ...  ..    File Data
  12314 File List entries:
  12315   000h 4     File Type/ID or so (roughly increasing, eg. 1,3,6,5,7,8,9,A,B)
  12316   004h 4     Filesize in bytes
  12317   008h 4     Filesize rounded up to multiple of 800h bytes
  12318 
  12319 Bugs Bunny: Lost in Time (MagDemo25: BBLIT\*.BZZ) (without extra entry)
  12320 The Grinch (MagDemo40: GRINCH\*.BZZ) (with extra entry)
  12321 Resembles .BZE, but without the Type entry in Header.
  12322   000h 4     Fixed 1 (maybe version, or compression flag)
  12323   004h (4)   Unknown (000xxxx0h)   ;<-- Extra in The Grinch only (not Bunny)
  12324   ...  4     Number of files
  12325   ...  N*0Ch File List
  12326   ...  ..    Zeropadding to 7FCh
  12327   7FCh 4     Checksum (32bit sum of SIGN-EXPANDED bytes at [000h..7FBh])
  12328   ...  ..    File Data
  12329 File List entries:
  12330   000h 4     File Type/ID or so (roughly increasing, eg. 1,2,3,6,5,7,8,9,A)
  12331   004h 4     Filesize in bytes (rounded to N*4 even if compressed data is less)
  12332   008h 4     Filesize rounded up to multiple of 800h bytes
  12333 Files are compressed, starting with 0Bh, same as in Jersey Devil...
  12334 --> CDROM File Compression BZZ
  12335 Note: The TIM files in Bugs Bunny and The Grinch BZZ archives consists of two
  12336 TIMs badged together: A 4x4 pix dummy TIM, followed by the actual 512x125 pix
  12337 TIM (in some cases followed some extra bytes at end of file?).
  12338 
  12339 Jersey Devil .BZZ (MagDemo10: JD\*.BZZ)
  12340 Resembles .BZE, but without the Type entries in Header and File List, and
  12341 without Header checksum.
  12342   000h 4     Fixed 1 (maybe version, or compression flag)
  12343   004h 4     Number of files (4)
  12344   008h N*8   File List
  12345   ...  ..    Zeropadding to 800h-byte boundary (without checksum, unlike .BZE)
  12346   ...  ..    File Data
  12347 File List entries:
  12348   000h 4     Size in bytes
  12349   004h 4     Size rounded to multiple of 800h
  12350 Files are compressed, starting with 0Bh, same as in Bugs Bunny...
  12351 --> CDROM File Compression BZZ
  12352 
  12353 Jackie Chan Stuntmaster (RCHARS\*.RR)
  12354 NBA Basketball 2000 (MagDemo28: FOXBB\*.RR)
  12355   000h 2     ID ("PX")
  12356   002h 2     Unknown (1 or 3)
  12357   004h 4     Header Size (eg. 80h, 7C0h, or 1730h) (N*8+8)
  12358   008h N*8   File List
  12359   ...  ..    Zeropadding to 800h-byte boundary
  12360   ...  ..    File Data area
  12361  File List entries:
  12362   000h 4     Offset (increasing, 800h-byte aligned)
  12363   004h 1     Zero
  12364   005h 3     Filesize in bytes (24bit) (can be odd)
  12365 Jackie Chan Stuntmaster does always have headersize=1730h (with many unused
  12366 entries with size=0, both in the middle & at the end of File List).
  12367 
  12368 Bomberman World (MagDemo15: BOMBER\*.RC)
  12369                 XXX detect this WITH extension=".RC" check before OBJ
  12370                     (else type=1 could be mistaken as offs=1) (eg RC1\BP0*.RC)
  12371 Resembles .OBJ but contains Filetype? instead of Offset.
  12372   000h N*8   File List
  12373   ...  8     File List end (zerofilled)
  12374   ...  ..    Garbage padding to 800h-byte boundary
  12375 File List entries:
  12376   000h 4     Filetype (see below)
  12377   004h 4     Filesize in bytes
  12378 There can be several files with same type in one .RC archive. Type values are:
  12379   00h = End of File List (at least so when Type and Size are both zero)
  12380   01h = .TIM
  12381   02h = Unknown
  12382   03h = Unknown
  12383   05h = .VH
  12384   06h = .VB
  12385   09h = Unknown
  12386   0Ah = .TIM (left half of a larger image) (right half has type 01h)
  12387   0Bh = Unknown
  12388   0Ch = Unknown
  12389 
  12390 Mat Hoffman's Pro BMX (new demo) (MagDemo48: MHPB\BMXCD.HED+WAD)
  12391 This format is used by the NEW demo version on MagDemp48 (the OLD demo version
  12392 on MagDemo39 did use Spider-Man-style HED/WAD format with filenames).
  12393  HED:
  12394   000h 2     Number of entries (N)
  12395   002h N*6   File List
  12396  WAD:
  12397   000h ...   File data (at 800h-byte aligned locations)
  12398 File List entries:
  12399   000h 3     File ID (24bit)
  12400   003h 3     File Size in bytes (21bit, max 2Mbyte) (upper 3bit=unused?)
  12401 Note: HED is processed at 80052AC0h in MagDemo48.
  12402 
  12403 Madden NFL 2000 (MagDemo27: MADN00\*.DAT and nested therein)
  12404 Madden NFL 2001 (MagDemo39: MADN01\*.DAT and nested therein)
  12405   000h 4     Header Size (N*SectorSize) (xxh, 800h, 1000h, 4800h, or 920h)
  12406   004h 4     Sector Size (4=ChildArchive, 800h=MainArchive, 920h=FMV/MADN00)
  12407   008h 4     File List entrysize (0=32bit, 1=16bit/MADN00, 4=16bit/MADN01)
  12408   00Ch N*2/4 File List (16bit or 32bit filesizes in bytes)
  12409   ...  ..    Zeropadding to SectorSize boundary
  12410   ...  ..    Files (with above sizes, each zeropadded to SectorSize boundary)
  12411 Dummy files have filesize=1 (but they do nethertheless occupy a whole data
  12412 sector).
  12413 Unknown why the FMV file in MADN00 is using SectorSize=920h (it appears to be
  12414 FORM2 related, although the file seems to be stored in FORM1 sectors, but the
  12415 STR movie appears to work okay despite of the odd size).
  12416 
  12417 Croc 2 (MagDemo22: CROC2\CROCII.DIR\FESOUND.WAD)
  12418 Disney's The Emperor's New Groove (MagDemo39:ENG\KINGDOM.DIR\FESOUND.WAD)
  12419 Disney's Aladdin in Nasira's Rev. (MagDemo46:ALADDIN\ALADDIN.DIR\FESOUND.WAD)
  12420   000h 4     Total Filesize-4
  12421   004h N*14h File List (2 entries in Croc2, 3 entries in Aladdin/Emperor)
  12422   ...  ..    File Data area (SPU-ADPCM( (.VB files with leading zeroes)
  12423  File List entries:               (Aladdin/Emperor) (Croc2)
  12424   000h 4     Sample Rate in Hertz (AC44h=44100Hz)   (5622h=22050Hz)
  12425   004h 2     Sample Rate Pitch    (1000h=44100Hz)   (0800h=22050Hz)
  12426   006h 2     Unknown              (7Fh)             (32h)
  12427   008h 4     Unknown              (1)               (8)
  12428   00Ch 4     Unknown              (1FC0001Fh)       (40008Fh)
  12429   010h 4     Filesize             (xxx0h)           (xxx0h)
  12430 The number of files is implied in sum of filesizes versus total size.
  12431 
  12432 Dino Crisis 1 and 2 (PSX\DATA\*.DAT and *.DBS and *.TEX) ("dummy header")
  12433   000h 800h  File List (with 10h or 20h bytes per entry)
  12434   800h ..    File Data (each file is zeropadded to 800h-byte boundary)
  12435 File List entrysize can be 10h or 20h bytes:
  12436   Dino Crisis 1 --> always size 10h
  12437   Dino Crisis 2 --> usually size 20h
  12438   Dino Crisis 2 --> sometimes size 10h (eg. SC24.DAT, SC48.DAT, WEP_*.DAT)
  12439 File List entries:
  12440  File List entries, type 0 and 7:
  12441   000h 4     Type (0=Data (or .BS pictures), 7=CompressedData)
  12442   004h 4     Size
  12443   008h 4     RAM Addresss (80000000h..801FFFFFh)
  12444   00Ch 4     Zero
  12445   010h (10h) Zerofilled
  12446  File List entries, type 1 and 2 and 8:
  12447   000h 4     Type (1=Bitmap, 2=Palette, 8=CompressedBitmap)
  12448   004h 4     Size (see below Size Notes)
  12449   008h 2     VRAM Address X     (0..3FFh)
  12450   00Ah 2     VRAM Address Y     (0..1FFh) (or 280h in Dino 2 ST703.DAT)
  12451   00Ch 2     Width in halfwords (1..400h)
  12452   00Eh 2     Height             (1..200h)
  12453   010h (10h) Zerofilled
  12454  File List entries, type 3 and 4:
  12455   000h 4     Type (3=VoiceHeader("Gian"), 4=VoiceData(SPU-ADPCM))
  12456   004h 4     Size
  12457   008h 4     SPU Address (0..7FFF0h)
  12458   00Ch 2     Unknown (0..7)  ;\usually both same (or val1=0, val2>0)
  12459   00Eh 2     Unknown (0..7)  ;/
  12460   010h (10h) Zerofilled
  12461  File List entries, type 5 (eg. ME*.DAT):
  12462   000h 4     Type (5=Unknown... maybe Midi-style or so)
  12463   004h 4     Size
  12464   008h 4     Load Address (0, or on next 4-byte boundary after previous file)
  12465   00Ch 2     Unknown (0..2)  ;\always both same
  12466   00Eh 2     Unknown (0..2)  ;/
  12467   010h (10h) Zerofilled
  12468  File List entries, type 6 and 9:
  12469   The EXE code does also accept type 6 and 9 (type 6 is handled same as
  12470   type 0, and type 9 is ignored), but the actual archives don't seem to
  12471   contain any files with those types.
  12472  File List entries, padding for unused entries:
  12473   000h 10h   Type ("dummy header    ")
  12474   010h (10h) Zerofilled
  12475 Size Notes:
  12476  Bitmaps and Palettes can have following sizes:
  12477   Width*Height*2                       ;normal case
  12478   Width*Height*2 + Align(1000h)        ;eg. Dino Crisis 1 DOOR*.DAT
  12479   Width*Height*2 + Align(800h)         ;eg. Dino Crisis 2 DOOR27.DAT
  12480  CompressedBitmaps can have following sizes in compressed form:
  12481   Less than Width*Height*2             ;normal case
  12482   Less than Width*Height*2 + 1000h     ;eg. Dino Crisis 2 M_RESULT,ST002.DAT
  12483  CompressedBitmaps can have following sizes after decompression:
  12484   Width*Height*2 + 8                   ;normal case
  12485   Width*Height*2 + Align(1000h?) + 8   ;eg. Dino Crisis 2 M_RESULT,ST002.DAT
  12486 Note: Dino Crisis DEMO version (MagDemo28: DINO\TRIAL.DAT) does also contain
  12487 "dummy header" DAT archives (but, unlike as in retail version, they are hidden
  12488 somewhere inside of the headerless 14Mbyte TRIAL.DAT archive).
  12489 Type 7 and 8 are using LZSS compression:
  12490 --> CDROM File Compression LZSS (Dino Crisis 1 and 2)
  12491 Apart from LZSS, Type 4 is using SPU-ADPCM compression, and some Type 0 files
  12492 contain .BS compressed pictures (eg. Dino Crisis 2 PSX\DATA\ST*.DBS\*).
  12493 
  12494 CDROM File Archives with Chunks
  12495 -------------------------------
  12496 
  12497 Chunk-based archives have chunk headers for each file, but don't have a central
  12498 directory. That's mainly useful when loading the whole archive to memory.
  12499 
  12500 Interchange File Format (IFF)
  12501 IFF has been invented by Electronic Arts in 1985 on Amiga (hence using 2-byte
  12502 alignment and big-endian size values).
  12503 IFF does mainly define a standarized file structure for use with custom
  12504 group/chunk types (it does also define some Amiga-specific standard audio/video
  12505 types, but those are barely useful on PSX).
  12506 The files are starting with a Group Header, followed by Chunks:
  12507  Group Header:
  12508   000h 4     Group ID ("FORM") (or "LIST" or "CAT " or "PROP")
  12509   004h 4     Group Size-08h (SIZ) (filesize-8) (big-endian)
  12510   008h 4     Group Type (4-character ASCII) (should be an unique identifier)
  12511   00Ch SIZ-4 Chunk(s), and/or nested Group(s)
  12512  Chunk Format:
  12513   000h 4     Chunk Type (4-character ASCII) (meaning depends on Group Type)
  12514   004h 4     Chunk Size (SIZ) (big-endian)
  12515   00Ch SIZ   Data (eg. .TIM, .VB, .VH or custom data)
  12516   ...  ..    Zeropadding to 2-byte boundary
  12517 Used by Forsaken (MagDemo09: FORSAKEN\*\*.BND,MP,PCO)
  12518 Used by Star Wars Demolition (MagDemo39,41: STARWARS\*.EXP)
  12519 Used by Turbo Prop Racing (MagDemo11: RRACER\*.IFF, except COURSE.IFF)
  12520 Used by Viewpoint (VIEW.DIR\*.VCF,*.VCS,*.ST*) - some have wrong Size entry?
  12521 Used by Vigilante 8 (MagDemo09: EXAMPLE\*.EXP)
  12522 Used by Wing Commander III (*.LIB\*.IFF)
  12523 Bugs in Viewpoint: fonts\*.vcf have correct Groupsize=Filesize-8, but
  12524 screens\*.vcf have incorrect Groupsize=Filesize-4, and streams\*.vcf have
  12525 weirdest random Groupsize=Filesize+(-04h,+08h,+14h,+5A0h).
  12526 
  12527 Z-Axis little-endian IFF variant
  12528 Unlike real IFF, these are using little-endian, and don't have a Group Type
  12529 entry. There seem to be no nested FORMs. Alignment is kept as 2-byte.
  12530  Group Header:
  12531   000h 4     Group ID ("FORM" or "BODY")
  12532   004h 4     Group Size-08h (SIZ) (little-endian)
  12533   008h SIZ   Chunk(s)
  12534  Chunk Format:
  12535   000h 4     Chunk Type (4-character ASCII)
  12536   004h 4     Chunk Size (SIZ) (little-endian)
  12537   00Ch SIZ   Data
  12538   ...  ..    Zeropadding to 2-byte boundary
  12539 ID "FORM" used by Thrasher: Skate and Destroy (MagDemo27: SKATE\ASSETS\*.ZAL\*)
  12540 ID "FORM" used by Dave Mirra Freestyle BMX (MagDemo36,46: BMX\ASSETS\*.ZAL\*)
  12541 ID "BODY" used by Colony Wars (MagDemo02: CWARS\GAME.RSC\*.BND)
  12542 ID "BODY" used by Colony Wars Venegance (MagDemo14: CWV\GAME.RSC\*.BND)
  12543 
  12544 Alice in Cyberland little-endian IFF variant (.TPK)
  12545 Same as Z-Axis IFF variant, except Group IDs are different, and the Header
  12546 sizes are included in the Group/Chunk sizes.
  12547  Group Header:
  12548   000h 4     Group ID ("hTIX","hFNT","hMBD","hHBS")
  12549   004h 4     Group Size (total filesize) (little-endian)
  12550   ...  (8)   Unknown extra (0,0,0,0,0Ch,0,0,0)   ;<-- only in "hHBS" files
  12551   ...  ..    Chunk(s)
  12552  Chunk Format:
  12553   000h 4     Chunk Type ("cCLT","cBIT","cSTR","cMAP","cIDX","cVAB","cSEQ")
  12554   004h 4     Chunk Size (SIZ) (little-endian)
  12555   00Ch SIZ-8 Data
  12556   ...  ..    Maybe Zeropadding to boundary? (Chunk Size is always N*4 anyways)
  12557 ID "hTIX" used by Alice in Cyberland (ALICE.PAC\alice.tpk, csel.tpk, etc.)
  12558 ID "hFNT" used by Alice in Cyberland (ALICE.PAC\alice.tpk, juri.tpk, etc.)
  12559 ID "hMBD" used by Alice in Cyberland (ALICE.PAC\*.FA2\*.MBD)
  12560 ID "hHBS" used by Alice in Cyberland (ALICE.PAC\0x_xx.HBS)
  12561 
  12562 Touring Car Championship (MagDemo09: TCAR\GAME\*\*.BFX)
  12563 Jarret & LaBonte Stock Car Racing (MagDemo38: WTC\*\*.BFX)
  12564 Contains several simple chunks:
  12565   000h 4     Chunksize in bytes (SIZ) (usually a multiple of 4)
  12566   004h SIZ   Chunkdata (eg. .TIM file or other stuff)
  12567 There is no end-marker in last chunk (it simply ends at total filesize).
  12568 
  12569 Colony Wars Venegance (MagDemo14: CWV\GAME.RSC\VAG.WAD)
  12570 Colony Wars Red Sun (MagDemo31: CWREDSUN\GAME.RSC\0002\VAG_WAD)
  12571 Contains several simple chunks with filenames:
  12572   000h 0Ch   Chunk Filename ("filename.ext", zeropadded if shorter)
  12573   00Ch 4     Chunk Data Size in bytes (SIZ)
  12574   010h SIZ   Chunk Data (usually VAGp files, in VAG.WAD)
  12575 There is no end-marker in last chunk (it simply ends at total filesize).
  12576 Red Sun VAG_WAD is a bit odd: The "extension" is _WAD instead .WAD, the chunk
  12577 names include prefix "RedSun\", which leaves only 5 chars for the actual name,
  12578 causig duplicated names like "RedSun\laser" (which were supposedly meant to be
  12579 named laser1, laser2, laser3 or the like), and many of the Red Dun VAG files
  12580 contain damaged 30h-byte VAG header entries, eg. zero instead of ID "VAGp").
  12581 
  12582 Mat Hoffman's Pro BMX (new demo) (MagDemo48: MHPB\STILLS.BIN)
  12583 Contains .BS files in several chunks:
  12584   000h ..    Chunk(s) (.BS files with extra header info)
  12585   ...  4     End Marker (00000000h)
  12586  Chunk format:
  12587   000h 4     Chunk size (including whole chunk header)
  12588   004h 2     Bitmap Width  (eg. F0h)
  12589   006h 2     Bitmap Height (eg. 80h)
  12590   008h 2     Data Size/4 (same as (Chunksize-0Ch-filenamelen)/4)
  12591   00Ah 2     MDEC Size/4 (same as at Data[0])
  12592   00Ch ..    Filename (eg. "lsFact",00h or "bsRooftop1",00h)  ;\filename field
  12593   ...  ..    Filename Zeropadding to 4-byte boundary          ;/
  12594   ...  ..    Data (in BS v2 format) (MDEC Size/4, BS ID 3800h, etc.)
  12595 Note: STILLS.BIN exists in newer BMX demo in MagDemo48 only (not in MagDemo39).
  12596 
  12597 Ridge Racer (TEX*.TMS)
  12598 Ridge Racer Revolution (BIG*.TMS)
  12599 Ridge Racer Type 4 (MagDemo19+21: R4DEMO\R4.BIN\*\*)
  12600   000h 4     ID (100h)
  12601   004h ..    Chunk(s)
  12602   ...  4     Zero (Chunk Size=0=End)
  12603   ...  ..    Optional zeropadding to 800h-byte boundary (in R4.BIN\*)
  12604 Chunk Format:
  12605   000h 4     Chunk Size (SIZ)
  12606   004h SIZ   Chunk Data (TIM file) (note: includes 0x0pix TIMs with palette)
  12607 
  12608 Jet Moto 2 (MagDemo03: JETMOTO2\*.TMS)
  12609 Twisted Metal 2 (MagDemo50: TM2\*.TMS)
  12610 Contains a fileheader and .TIM files in several chunks:
  12611   000h 8     ID "TXSPC",0,0,0 (aka CPSXT backwards)
  12612   008h 4     Timestamp? (32A5C8xxh)
  12613   00Ch 4     Number of Chunks (N) (can be 0=None, eg. TM2\SCREEN\ARROWS.TMS)
  12614   010h N*4   Unknown
  12615   ...  N*var Chunks
  12616  Chunk format:
  12617   000h 4     Chunk Size-4 (SIZ)
  12618   004h SIZ   Chunk Data (TIM file)
  12619 
  12620 Princess Maker - Yumemiru Yousei (BDY\*.BD and PM.*)
  12621 The BDY\*.BD files do simply contain several chunks:
  12622   000h ..   Chunk(s)
  12623 The PM.* files do contain several "folders" with fixed size:
  12624   000h ..   Chunk(s) for 1st folder              ;\Foldersizes are:
  12625   ...  ..   Zeropadding to Foldersize-boundary   ;  20000h (PM.DT0 and PM.PCC)
  12626   ...  ..   Chunk(s) for 2nd folder              ;  28000h (PM.MAP)
  12627   ...  ..   Zeropadding to Foldersize-boundary   ;  42000h (PM.SD0)
  12628   ...  ..   etc.                                 ;/
  12629 Chunk Format:
  12630   000h 4    Chunk ID   (800000xxh)
  12631   004h 4    Chunk Size (size of Data part, excluding ID+Size)
  12632   008h ..   Data
  12633 The Data for different Chunk IDs does usually have a small header (often with
  12634 w,h,x,y entries, aka width/height, vram.x/y) followed by the actual data body:
  12635   80000004h  x(2),y(2),width(2),height(2)    Bitmap 8bpp          ;PM.PCC,MAP
  12636   80000005h  w(2),h(2),zero(4)               Array32bit(w,h)      ;PM.MAP
  12637   80000006h  x(2),width(2)                   Bitmap Palette       ;PM.*
  12638   80000007h  x(2),y(2),w(1),h(1),zero(2)     Array8bit(w,h)       ;PM.MAP
  12639   80000010h  width(2),height(2),x(2),y(2)    Bitmap 16bpp         ;*.BD
  12640   80000012h  zero(0)                         ?                    ;*.BD
  12641   80000014h  x(2),y(2),width(2),height(2)    Bitmap 4bpp          ;PM.DT0
  12642   80000016h  x(2),y(2),w(1),h(1),n(1),3Fh(1) BitmapArray4bpp(n*2) ;PM.DT0
  12643   80000018h  ...                             ?                    ;PM.PCC
  12644   8000001Ah  zero(8)                         ?                    ;PM.PCC
  12645   8000001Ch  x(2),y(2),width(2),height(2)    Bitmap 1bpp flags?   ;*.BD
  12646   80000020h  zero(8)                         Sound .SEQ file      ;PM.SD0
  12647   80000021h  zero(8)                         Sound .VH file       ;PM.SD0
  12648   80000022h  zero(8)                         Sound .VB file       ;PM.SD0
  12649   80000024h  x(2),zero(6)                    ?                    ;PM.DT0\4\0
  12650   00000000h  Zeropadding to next folder      Zeropadding          ;PM.*
  12651 
  12652 Project Horned Owl (COMDATA.BIN, DEMODATA.BIN, ROLL.BIN, ST*DATA.BIN)
  12653   000h ..    Chunks
  12654 Chunk Format:
  12655   000h 1     Chunk Type (see below)
  12656   001h 3     Unknown (some flags or file ID, or zero in many files)
  12657   004h 4     Chunk Size (SIZ)
  12658   008h SIZ   Chunk Data (eg. SEQ file)
  12659 Chunk Type values:
  12660   02h  unknown                      ST*.BIN
  12661   05h  .TXT                         ROLL.BIN
  12662   05h  LZ-compressed TIM            DEMODATA.BIN, ST*.BIN (except ST1*.BIN)
  12663   06h  DOT1 with stuff and TSQ??    ST*.BIN
  12664   07h  .TMD                         DEMODATA.BIN, ST*.BIN (except ST1*.BIN)
  12665   08h  unknown                      ST*.BIN
  12666   09h  "PRM:"                       ST*.BIN
  12667   0Ah  unknown                      ST*.BIN
  12668   0Bh  DOT1 with stuff              ST*.BIN (except ST1*.BIN) (odd: ST3*.BIN)
  12669   0Ch  .SEQ                         ROLL.BIN, ST*.BIN
  12670   0Dh  unknown                      COMDATA.BIN
  12671   0Eh  unknown                      ST*.BIN
  12672   0Fh  DOT1 with LZ-compressed TIMs ST*.BIN
  12673   10h  DEFLATE-compressed TIM       COMDATA.BIN, ROLL.BIN, ST*.BIN
  12674   11h  DOT1 with stuff              ST*.BIN
  12675   Note: Type=05h can be uncompressed TXT or compressed TIM.
  12676 For detection, the existing .BIN files start with following values:
  12677   07 00 00 00 xx xx 00 00 41 00 00 00 ..   TMD Model ("A")
  12678   0C 00 00 00 xx xx 00 00 70 51 45 53 ..   SEQ Midi  ("pQES")
  12679   0E xx 00 00 08 00 00 00 xx xx xx xx ..   Whatever in ST7DATA.BIN (see note)
  12680   10 01 00 00 24 28 00 00 EC 9B 7F 70 ..   Deflated TIM in COMDATA.BIN
  12681   10 08 1A 00 30 0C 00 00 ED 58 4F 88 ..   Deflated TIM in ROLL.BIN
  12682   ST7DATA.BIN has 2 chunks with Type=0Eh, followed by SEQ chunk at offset=20h.
  12683 TIMs are compressed via HornedLZ (Type=05h,0Fh) or Deflate (Type=10h).
  12684 --> CDROM File Compression HornedLZ
  12685 --> CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  12686 The game's Inflate function does ignore the 2bit blocktype: All blocks must
  12687 have dynamic trees (fixed trees and uncompressed blocks aren't supported).
  12688 
  12689 See also
  12690 --> CDROM File Archive Darkworks Chunks (Alone in the Dark)
  12691 --> CDROM File Archive Blue Chunks (Blue's Clues)
  12692 --> CDROM File Archive HED/CDF (Parasite Eve 2)
  12693 --> CDROM File Compression LZSS (Serial Experiments Lain)
  12694 --> CDROM File Compression SLZ/01Z (chunk-based compressed archive)
  12695 
  12696 CDROM File Archives with Folders
  12697 --------------------------------
  12698 
  12699 There are several ways to implement folder-like directory trees:
  12700   - Using multiple archive files nested within each other
  12701   - Using filenames with path string (eg. "path\filename.ext")
  12702 Other than that, below are special formats with dedicated folder structures.
  12703 
  12704 Archives with Folders
  12705 --> CDROM File Archive HUG/IDX/BIZ (Power Spike)
  12706 --> CDROM File Archive TOC/DAT/LAY
  12707 --> CDROM File Archive WAD (Doom)
  12708 --> CDROM File Archive WAD (Cardinal Syn/Fear Effect)
  12709 --> CDROM File Archive DIR/DAT (One/Viewpoint)
  12710 --> CDROM File Archive HED/CDF (Parasite Eve 2)
  12711 --> CDROM File Archive IND/WAD (MTV Music Generator)
  12712 --> CDROM File Archive GAME.RSC (Colonly Wars Red Sun)
  12713 --> CDROM File Archive BIGFILE.DAT (Soul Reaver)
  12714 --> CDROM File Archive FF8 IMG (Final Fantasy VIII)
  12715 --> CDROM File Archive FF9 IMG (Final Fantasy IX)
  12716 --> CDROM File Archive GTFS (Gran Turismo 2)
  12717 --> CDROM File Archive Nightmare Project: Yakata
  12718 --> CDROM File Archive FAdj0500 (Klonoa)
  12719 See also: PKG (a WAD.WAD variant with folders)
  12720 
  12721 Perfect Assassin (*.JFS)
  12722  Overall File Structure
  12723   JFS for root                                   ;\
  12724   JFS for 1st folder   ;\these are dupicated,    ; header with complete list
  12725   JFS for 2nd folder   ; also stored in below    ; of all file/folder names
  12726   JFS for 3rd folder   ; data area               ;
  12727   etc.                 ;/                        ;/
  12728   JFS for 1st folder, plus data for files in that folder  ;\
  12729   JFS for 2nd folder, plus data for files in that folder  ; data area
  12730   JFS for 3rd folder, plus data for files in that folder  ;
  12731   etc.                                                    ;/
  12732 JFS Headers (0Ch+N*14h bytes)
  12733   00h 4     ID "JFS",00h
  12734   04h 4     Size in bytes (for root: including nearby child JFS's)
  12735   08h 4     Number of file/folder entries in this folder (N)
  12736   0Ch N*14h File/Folder entries
  12737 File Entries (with [10h].bit31=0):
  12738   00h 12  "FILENAME.EXT" (or zeropadded if shorter)
  12739   0Ch 4   Offset from begin of JFS in data area (without any alignment)
  12740   10h 4   Size in bytes, plus 00000000h=File
  12741 Folder Entries (with [10h].bit31=1):
  12742   00h 12  "DIRNAME.EXT" (or zeropadded if shorter)
  12743   0Ch 4   Offset to child JFS in data area
  12744   10h 4   Offset to child JFS in header area, plus 80000000h=ChildFolder
  12745 The JFS format is almost certainly unrelated to IBM's "Journaled File System".
  12746 
  12747 Alone in the Dark The New Nightmare (FAT.BIN=Directory, and DATA.BIN=Data)
  12748  FAT.BIN:
  12749   00h 2     Number of folders (X) (43h)
  12750   02h 2     Number of files   (Y) (8F0h)
  12751   04h 4     Unknown               (1000h)
  12752   08h X*10h Directory Entry 0000h..X-1 (entry 0000h is named "ROOT")
  12753   ..  Y*10h File Entry 0000h..Y-1
  12754  DATA.BIN:
  12755   00h ..    File Data area
  12756 Directory Entries (10h bytes):
  12757   00h 8    Name (terminated by 00h if less than 8 chars)
  12758   08h 2    First Subdirectory number (0001h and up, 0000h would be root)
  12759   0Ah 2    Number of Subdirectories  (0000h=None, if so above is usually 00FFh)
  12760   0Ch 2    First File number         (0000h and up)
  12761   0Eh 2    Number of files           (0000h=None, if so above is usually 00FFh)
  12762 File Entries (10h bytes):
  12763   00h 8    Name (terminated by 00h if less than 8 chars)
  12764   08h 4    Offset/800h to DATA.BIN
  12765   0Ch 4    Size in bytes (when compressed: decompressed size+02000000h)
  12766 Compressed files (in LEVELS\*\* with Size.bit25=1) can be decompressed as so:
  12767 --> CDROM File Compression Darkworks
  12768 The files include some TIM images, WxH images, binary files, and chunks:
  12769 --> CDROM File Archive Darkworks Chunks (Alone in the Dark)
  12770 
  12771 Interplay Sports Baseball 2000 (MagDemo22: BB2000\* HOG.DAT and HOG.TOC)
  12772  HOG.TOC:
  12773   000h N*14h Folder/File List (starting with root folder)
  12774  HOG.DAT:
  12775   000h ..    File Data (referenced from HOG.TOC)
  12776 Folder entries:
  12777   000h 1     Type      ("D"=Directory)
  12778   001h 8     Name      ("FILENAME", zeropadded if shorter) (or "\" for root)
  12779   009h 3     Extension (usually zero for directories)
  12780   00Ch 4     Folder Offset/14h in .TOC file (aka 1st child file/folder index)
  12781   010h 4     Folder Size/14h                (aka number of child files/folders)
  12782 File entries:
  12783   000h 1     Type      ("F"=File)
  12784   001h 8     Name      ("FILENAME", zeropadded if shorter)
  12785   009h 3     Extension ("EXT", zeropadded if shorter)
  12786   00Ch 4     File Offset/800h in .DAT file (increasing)
  12787   010h 4     File Size in bytes
  12788 
  12789 Tenchu 2 (MagDemo35: TENCHU2\VOLUME.DAT)
  12790   000h 4     Unknown (demo=A0409901h, us/retail=A0617023h)
  12791   004h 4     Unknown (0h)
  12792   008h 4     Number of files   (F) (demo=B7h, us/retail=1294h)
  12793   00Ch 4     Number of folders (D) (demo=0Fh, us/retail=3Eh)
  12794   010h D*8   Folder List
  12795   ...  ..    Zerofilled (padding to 800h-byte boundary)
  12796   800h F*10h File List
  12797   ...  ..    Zerofilled (padding to 800h-byte boundary)
  12798   ...  ..    File Data area
  12799 Folder List entries:
  12800   000h 4     Folder ID (Random, maybe folder name checksum?)
  12801   004h 4     First file number in this folder (0=first, increasing)
  12802 File List entries:
  12803   000h 4     File Offset/800h
  12804   004h 4     File Size in bytes
  12805   008h 4     Folder ID (same as Parent Folder ID in Folder List)
  12806   00Ch 4     File ID (Random, maybe file name checksum?)
  12807 
  12808 Blasto (MagDemo10: BLASTO\BLASTO.DAT and BLASTO\BLASTO.LFS)
  12809  LFS:
  12810   000h N*18h File/Folder List
  12811  DAT:
  12812   000h ..    File data
  12813 File entries (with [10h]=Positive):
  12814   000h 10h   Filename ("FILENAME.EXT", zeropadded)
  12815   010h 4     Offset in bytes, in BLASTO.DAT
  12816   014h 4     Size in bytes
  12817 Folder entries (with [10h]=Negative):
  12818   000h 10h   Foldername ("DIRNAME", zeropadded)
  12819   010h 4     Index to first child (at Offset=(-Index)*18h in BLASTO.LFS)
  12820   014h 4     Zero
  12821 Folder end marker (with [00h]=00h or 80h):
  12822   000h 1     End marker, at end of root & child directories (00h or 80h)
  12823   001h 17h   Unknown
  12824 
  12825 Twisted Metal 4 (MagDemo30: TM4DATA\*.MR and *.IMG)
  12826 These are relative small archives with hundreds of tiny chunks (with registry
  12827 style Symbol=Value assignments), and a few bigger chunks (with .mod .vab .bit
  12828 .clt files).
  12829   000h 4     Fixed ID (CCCC0067h)
  12830   004h ..    Root Folder (with Name="Root",00h,FDh,FDh,FDh)
  12831  Folder Chunk format:
  12832   000h 1     Length of Name (including 4-byte padding)
  12833   001h 1     Number of Child Folders
  12834   002h 2     Number of Child Files
  12835   004h ..    Name ("name",00h, CDh-padded to 4-byte boundary; Root=FDh-padded)
  12836   ...  ..    Child File(s)
  12837   ...  ..    Child Folder(s)
  12838  File Chunk format:
  12839   000h 1     Length of filename (including 4-byte padding)
  12840   001h 1     Filetype           (see below)
  12841   002h 2     Array Size         (or FFFFh for non-array filetypes)
  12842   004h 4     Filesize (SIZ)     (including 4-byte padding)
  12843   008h 4     Decompressed Size  (or 0=Uncompressed)
  12844   00Ch ..    Filename/Symbol    ("name.ext",00h, CDh-padded to 4-byte boundary)
  12845   ...  SIZ   Data/Value         (CDh-padded to 4-byte boundary)
  12846 Some filenames have trailing non-ascii characters, for example:
  12847   "AXEL.MR\display\resolution\r3\Groups\Combined_Polyset",1Ah,01h,04h,00h
  12848   "CALYPSO.MR\display\resolution\r3\Groups\Combined_Polyset",A8h,00h, CDh,CDh
  12849 Filetypes:
  12850   Typ Size  Expl.
  12851   02h var   Text String (terminated by 00h, garbage-or-00h-padded to 4-byte)
  12852   03h 8     Misc (*.IMG\textures\*)                          ;\
  12853   03h 20h   Misc (*.MR\display\resolution\r*\Groups\*)       ; these are all
  12854   03h var   Misc (*.MR\display\resolution\*List)             ; filetype=03h
  12855   03h file  Misc (*.MR\display\*.bit) (same as type=0Ch)     ;/
  12856   04h 4     Numeric 32bit
  12857   05h 8     Numeric 4x16bit point (X,Y,Z,CDCDh)
  12858   06h file  Model (*.mod) (DOTLESS archive with model data)
  12859   0Bh 4     Numeric 32bit repeat,light
  12860   0Ch file  XYWH Bitmap/Palette (*.bit, *.clt) (in GAME.IMG, MENU\menu)
  12861   0Dh 4     Numeric 32bit delay
  12862   0Eh 4     Numeric 32bit color (maybe 24bit RGB plus 00h-padding?)
  12863   0Fh 10h   Whatever 10h-byte "pos"
  12864   10h file  Sony .VAB file (*.vab)
  12865   12h N*1   Array? (with Arraysize=0014h)
  12866   16h N*??  Array Text Strings (with Arraysize=0001h) (in MAIN.MR\worlds)
  12867   1Ah N*10h Array Guns,startpoints (RCCAR.MR\*, NEON.MR\world)
  12868   1Bh 4     Numeric 2x16bit (X,Y) (in MENU.MR)
  12869   1Ch N*4   Array lloc (in MENU.MR\menu\screens) (with Arraysize=04h or 1Fh)
  12870   25h 8     Whatever 8-byte (in GAME.MR\dualShock)
  12871   26h N*8   Array CollideArray (in GAME.MR\dualShock) (with Arraysize=4 or 6)
  12872 Compressed Data (when [008h]<>0):
  12873   000h ..    ZLIB compressed data (usually starting with big-endian 789Ch)
  12874   (compression is used for almost all files, except VERY small ones)
  12875 --> CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  12876 
  12877 CDROM File Archive HUG/IDX/BIZ (Power Spike)
  12878 --------------------------------------------
  12879 
  12880 Power Spike (MagDemo43: POWER\GAME.IDX and .HUG)
  12881 POWER\GAME.HUG
  12882   000h ..    File Data
  12883 POWER\GAME.IDX
  12884   000h 4     ID "HUGE"
  12885   004h 4     Checksum (sum of all bytes at [010h and up])
  12886   008h 4     Number of Folders (D) (87h)
  12887   00Ch 4     Number of Files   (F) (F9h)
  12888   010h D*1Ch Folder List (Folder 0..D-1)
  12889   ...  F*18h File List   (File 0..F-1)
  12890 Folder List entries:
  12891   000h 0Ch   Folder Name ("DIRNAME", zeropadded)
  12892   00Ch 4     First Child File      (or FFFFFFFFh=None)
  12893   010h 4     Number of Child Files (or 00000000h=None)
  12894   014h 4     First Child Folder    (or FFFFFFFFh=None)
  12895   018h 4     Next Sibling Folder   (or FFFFFFFFh=None)
  12896 File List entries:
  12897   000h 0Ch   File Name ("FILENAME.EXT", zeropadded if shorter than 12)
  12898   00Ch 4     File Checksum (sum of all bytes in file added together)
  12899   010h 4     File Offset/800h in GAME.HUG
  12900   014h 4     File Size in bytes
  12901 The root entries are Folder 0 (and its siblings). That is, the root can contain
  12902 only folders (not files).
  12903 The IDX/HUG archive contains many BIZ archives (and some TXT files).
  12904 
  12905 Power Spike (MagDemo43: POWER\GAME.IDX\*.BIZ) (BIZ nested in IDX/HUG)
  12906   000h 4     ID "BIG!"
  12907   004h 4     Number of entries (N)
  12908   008h N*1Ch File List
  12909   ...  ..    BIZ compressed File Data
  12910 File List entries
  12911   000h 10h   Filename (zeropadded)
  12912   010h 4     File Offset (increasing, unaligned, can be odd)
  12913   014h 4     File Size decompressed
  12914   018h 4     File Size compressed
  12915 All files in the BIZ archive are BIZ compressed (unknown if it does also
  12916 support uncompressed files).
  12917 --> CDROM File Compression LZ5 and LZ5-variants
  12918 The BIZ archive seems to be solely containing PSI bitmaps (even files in
  12919 GAME.IDX\SOUND\MUSIC\*.BIZ do merely contain PSI bitmaps, not audio files).
  12920 
  12921 CDROM File Archive TOC/DAT/LAY
  12922 ------------------------------
  12923 
  12924 Used in PSX Lightspan Online Connection CD (CD.TOC, CD.DAT, CD.LAY).
  12925   CD.TOC contains File/Folder entries
  12926   CD.DAT contains the actual File bodies
  12927   CD.LAY devkit leftover (list of filenames to be imported from PC to TOC/DAT)
  12928 The .TOC file doesn't have any file header, it does just start with the first
  12929 File/Folder folder entry in root directory. The directory chains with
  12930 file/folder entries are sorted alphabetically, each chain is terminated by a
  12931 final entry which does point to parent directory.
  12932 
  12933 File Entries
  12934   00h 4   Offset to next Sibling File/Folder/Final entry
  12935   04h 4   Filesize in bytes
  12936   08h 4   Filedata Offset/800h in CD.DAT
  12937   0Ch ..  Filename (ASCII, terminated by 00h)
  12938   ... ..  Padding to 4-byte boundary (garbage)
  12939 
  12940 Folder Entries (with Filesize=FFFFFFFFh)
  12941   00h 4   Offset to next Sibling File/Folder/Final entry
  12942   04h 4   Filesize (always FFFFFFFFh in Folder entries)
  12943   08h 4   Offset to first File/Folder in Child directory
  12944   0Ch ..  Name of Child directory (ASCII, terminated by 00h)
  12945   ... ..  Padding to 4-byte boundary (garbage)
  12946 
  12947 Final Entries (with Name="",00h and Filesize=FFFFFFFxh)
  12948   00h 4   Offset to next Sibling entry (00000000h=None)
  12949   04h 4   Filesize (FFFFFFFFh in child folders, FFFFFFFEh in root folder)
  12950   08h 4   Offset to first File/Folder in Parent directory (or to self for root)
  12951   0Ch 1   Empty Name ("",00h)
  12952   0Dh 3   Padding to 4-byte boundary (garbage)
  12953 
  12954 CDROM File Archive WAD (Doom)
  12955 -----------------------------
  12956 
  12957 Doom, PSXDOOM\ABIN\*.WAD and PSXDOOM\MAPDIR*\*.WAD)
  12958 The .WAD format is used by Doom (for DOS, Jaguar, PSX, etc), various homebrew
  12959 Doom hacks, and some other developers have adopted the format and used .WAD in
  12960 other game engines.
  12961   000h 4     ID "IWAD" (or "PWAD" for homebrew patches, or "PACK" in A.D. Cop)
  12962   004h 4     Number of File List entries (N) (including final ENDOFWAD entry)
  12963   008h 4     Offset to Directory Area (filesize-N*10h)
  12964   00Ch ..    File Data area
  12965   ...  N*10h File List
  12966 File List entries:
  12967   000h 4   Offset to file data (increasing by compressed size, 4-byte aligned)
  12968   004h 4   Filesize in bytes   (uncompressed size) (zero in ENDOFWAD file)
  12969   008h 8   Filename (uppercase ASCII, zeropadded if less than 8 chars)
  12970 
  12971 Folders
  12972 The directory can contain names like F_START, F_END, P1_START, P1_END with
  12973 filesize=0 to mark begin/end of something; that stuff can be considered as
  12974 subdirectories with 1- or 2-character names.
  12975 Notes: There are also regular files with underscores which are unrelated to
  12976 folders (eg. F_SKY01). There are also 0-byte dummy files (eg. MAP17 in first
  12977 entry MAP17.WAD). And there's a 0-byte dummy file with name ENDOFWAD in last
  12978 file list entry (at least, it's present versions with compression support).
  12979 
  12980 LZSS Decompression
  12981 Compression is indicated by Filename[0].bit7=1. The compressed size is
  12982 NextFileOffset-FileOffset (that requires increasing offsets in File List,
  12983 including valid offsets for 0-byte files like F_START, F_END, ENDOFWAD).
  12984   @@collect_more:
  12985    flagbits=[src]+100h, src=src+1    ;8bit flags
  12986   @@decompress_lop:
  12987    flagbits=flagbits SHR 1
  12988    if zero then goto @@collect_more
  12989    if carry=0 then
  12990      [dst]=[src], dst=dst+1, src=src+1
  12991    else
  12992      disp=([src]*10h)+([src+1]/10h)+1, len=([src+1] AND 0Fh)+1, src=src+2
  12993      if len=1 then goto @@decompress_done
  12994      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  12995    endif
  12996    goto @@decompress_lop
  12997   @@decompress_done:
  12998    ret
  12999 The game engine may insist on some files to be compressed or uncompressed (so
  13000 compression may be required even if the uncompressed data would be smaller).
  13001 
  13002 More info: http://doomwiki.org/wiki/WAD
  13003 
  13004 CDROM File Archive WAD (Cardinal Syn/Fear Effect)
  13005 -------------------------------------------------
  13006 
  13007 .WAD files (Cardinal Syn/Fear Effect)
  13008 This format exists in two version:
  13009   Old format: Without leading Header Size entry (Cardinal Syn MagDemo03: SYN\*)
  13010   New format: With leading Header Size entry    (eg. Fear Effect)
  13011 Version detection could be done somewhat as so:
  13012   if [04h]*1Ch+8 >= [00h] then OLD version
  13013 For loading the Old Header, one must guess the max header size (4000h should
  13014 work, in fact, most or all Old Headers seem to be max 800h), or load more data
  13015 on the fly as needed.
  13016   000h (4) Header Size (including folder/type/file directories) (new version)
  13017   ...  4   Number of Folders
  13018   ...  ..  Folder List (root)
  13019   ...  ..  Type Lists  (for each folder)
  13020   ...  ..  File Lists  (for each folder\type)
  13021   ...  ..  File Data   (for each folder\type\file)
  13022  Folder List Entries:
  13023   000h 14h Folder name (ASCII, zeropadded)
  13024   014h 4   Offset to Type List
  13025   018h 4   Number of different Types in this folder
  13026  Type List Entries:
  13027   000h 4   Offset to file entries (of same type, eg. .TIM files)
  13028   004h 4   Number of file entries (of same type, eg. .TIM files)
  13029   008h 4   Sum of all Filesizes with that type
  13030   00Ch 4   Group Type (0000000xh)
  13031  File List entries (Files within Type list):
  13032   000h 14h Name (ASCII, terminated by 00h, plus garbage padding)
  13033   014h 4   Offset to File Data  (seems 4-byte aligned... always?)
  13034   018h 4   File Type (000x00xxh)
  13035   01Ch 4   Filesize in bytes  ;\maybe compressed/uncompressed, or rounded,
  13036   020h 4   Filesize in bytes  ;/always both same
  13037 Note: The Type List for one folder can contain several entries with same Group
  13038 Type, eg. Fear Effect GSHELLE.WAD\CREDIT has 5 type list entries (with
  13039 2xGroup0, 2xGroup1, 1xGroup2).
  13040 
  13041 The Type List, Group Type and File Type stuff seems to have no function, apart
  13042 from faster look up (the types are also implied in the filename extension).
  13043 Except, Fear Effect .RMD .VB .VH have some unknown stuff encoded in File Type
  13044 bit16-19.
  13045 Group Type is usually 0 (except for .TIM .VB .VH .MSG .SPU .OFF).
  13046 The .TIM .VB .VH .SEQ files are using standard Sony file formats. The .PMD file
  13047 seems to be also Sony standard (except that it contains a 00000000h prefix,
  13048 then followed by the 00000042h PMD format ID).
  13049 
  13050 Cardinal Syn Types
  13051   .BGD FileType=00000001h
  13052   .ANM FileType=00000003h
  13053   .TIM FileType=00000004h (GroupType=1)
  13054   .SP2 FileType=00000005h
  13055   .PMD FileType=00000007h
  13056   .MOV FileType=00000008h
  13057   .SPR FileType=0000000Ch
  13058   .PVT FileType=0000000Dh
  13059   .DB  FileType=0000000Eh
  13060   .VH  FileType=00000010h (GroupType=1) ;only in OLDER demo version MagDemo03
  13061   .VB  FileType=00000011h (GroupType=1)
  13062   .MSG FileType=00000012h (GroupType=1) (actually, this is .TIM, too)
  13063   .KMD FileType=00000013h
  13064   .OC  FileType=00000018h
  13065   .EMD FileType=00000019h
  13066   .COL FileType=0000001Bh
  13067   .CF  FileType=0000001Ch
  13068   .CFB FileType=0000001Dh
  13069   .CL  FileType=0000001Eh
  13070   .SPU FileType=0000001Fh (GroupType=1) ;added in newer demo version MagDemo09
  13071   .OFF FileType=00000020h (GroupType=1) ;added in newer demo version MagDemo09
  13072   .RCT FileType=00000021h               ;added in newer demo version MagDemo09
  13073 
  13074 Fear Effect Types
  13075   .TIM FileType=00000000h (GroupType=1)
  13076   .RMD FileType=000x0001h
  13077   .DB  FileType=00000002h
  13078   .ANM FileType=00000003h
  13079   .SYM FileType=00000004h
  13080   .VB  FileType=000x0008h (GroupType=1)
  13081   .SEQ FileType=00000010h
  13082   .BIN FileType=00000012h
  13083   .SFX FileType=00000013h
  13084   .VH  FileType=000x0014h (GroupType=2)
  13085   .TM  FileType=00000015h
  13086   .NRM FileType=00000017h
  13087   .WPD FileType=00000018h
  13088 
  13089 CDROM File Archive DIR/DAT (One/Viewpoint)
  13090 ------------------------------------------
  13091 
  13092 DIR/DAT (One/Viewpoint)
  13093   Used by One (DATAFILE.BIN and DIRFILE.BIN)
  13094   Used by Viewpoint (VIEW.DAT and VIEW.DIR)
  13095 Format of the DIR file:
  13096   000h 60h Extension List (20h x 3-char ASCII, zeropadded if shorter than 3)
  13097   060h ..  Root Directory    (can contain folders and files)
  13098   ...  ..  Child Directories (can contain files) (maybe also sub-folders?)
  13099 Extension List contains several uppercase 3-character ASCII extensions, in a
  13100 hex editor this will appear as a continous string of gibberish (dots=00h):
  13101   In Viewpoint: "...VCSVCFBINTXTVH.VB.STRST1ST2ST3......//..."
  13102   In One:       "...VCTVCKSNDBINCPEINI..................//..."
  13103 Directory Entries contain bitstreams with ASCII characters squeezed into 6bit
  13104 values:
  13105   000h 1   Length of Filename and Extension index
  13106              bit7-3  File Extension Index (0..1Fh = Offset I*3 in DIR file)
  13107              bit2-0  Filename Length-1    (0..7 = 1..8 chars)
  13108   001h ..  Filename in 6bit chars (N*6+7/8 bytes = 1..6 bytes for 1..8 chars)
  13109              bit7-2  1st character, whole 6bit            ;\1st byte
  13110              bit1-0  2nd character, upper 2bit (if any)   ;/
  13111              bit7-4  2nd character, lower 4bit (if any)   ;\2nd byte (if any)
  13112              bit3-0  3rd character, upper 4bit (if any)   ;/
  13113              bit7-6  3rd character, lower 2bit (if any)   ;\3rd byte (if any)
  13114              bit5-0  4th character, whole 6bit (if any)   ;/
  13115              bit7-2  5th character, whole 6bit (if any)   ;\4th byte (if any)
  13116              bit1-0  6th character, upper 2bit (if any)   ;/
  13117              bit7-4  6th character, lower 4bit (if any)   ;\5th byte (if any)
  13118              bit3-0  7th character, upper 4bit (if any)   ;/
  13119              bit7-6  7th character, lower 2bit (if any)   ;\6th byte (if any)
  13120              bit5-0  8th character, whole 6bit (if any)   ;/
  13121              bitN-0  Zeropadding in LSBs of last byte     ;-zeropadding
  13122            The 6bit characters codes are:
  13123              00h..09h="0..9", 0Ah..23h="a..z", 24h="_", 25h..3Fh=Unused
  13124   ...  4   Filesize and End Flag
  13125              bit31   End of Directory Flag   (0=Not last entry, 1=Last entry)
  13126              bit30-0 Filesize 31bit          (or 0=Child Folder)
  13127   ...  4   Offset and fixed bit
  13128              bit31   Unknown (always 1)
  13129              bit30-0 File Offset in DAT file (or Folder offset in DIR file)
  13130 
  13131 CDROM File Archive Darkworks Chunks (Alone in the Dark)
  13132 -------------------------------------------------------
  13133 
  13134 Alone in the Dark The New Nightmare (FAT.BIN\*)
  13135 The files in FAT.BIN are using a messy chunk format: There's no clear ID+Size
  13136 structure. There are 7 different chunk types (DRAM, DSND, MIDB, G3DB, VRAM,
  13137 WEAP, HAND), each type requires different efforts to compute the chunk size.
  13138 
  13139 VRAM Chunks (Texture/Palette) (in various files)
  13140   000h 4     ID "VRAM"
  13141   004h 4     With Tags (0=No, 1=Yes) (or "DRAM" when empty 4-byte chunk)
  13142   008h (4)   Number of Tagged items (N) (0=None)  ;\only when [4]=1
  13143   00Ch N*10h Tagged Item(s)                       ;/(not so in LEVELS\*\VIEW*)
  13144   ...  ..    Scanline Rows(s)
  13145   ...  4     End code (00000000h) (aka final Scanline Row with width=0)
  13146  Tagged Item(s) (IMG, LINE, GLOW, FLARE, BALLE, BLINK, COURIER7, BMP_xxx):
  13147   000h 8     Tag (ASCII, if less than 8 chars: terminate by 00h, pad by FDh)
  13148   008h 8     Data
  13149  Scanline Row(s) (bitmap scanlines and palette data):
  13150   000h 4     Header (bit0-8=Width, bit10-18=Y, bit20-29=X, bit9,19,30,31=?)
  13151   004h W*2   Data (Width*2 bytes, to be stored at VRAM(X,Y))
  13152 Empty VRAM chunks can be either 4 or 10h bytes tall. The 4-byte variant is
  13153 directly followed by another chunk name (eg. "VRAMDRAM"), the 10h-byte variant
  13154 contains four words ("VRAM",WithTags=1,NumTags=0,EndCode=0).
  13155 Note: Some files contain two VRAM chunks (eg. LEVELS\*\VIEW*).
  13156 
  13157 G3DB Chunks (Models) (in various files)
  13158   000h 4   ID "G3DB"
  13159   004h 4   Unknown (0, 1, or 2)
  13160   008h 4   Size of Data part (SIZ)
  13161   00Ch 4   Number of List entries (eg. 6 or 0Ah or 117Ch) (N)
  13162   010h SIZ Data (supposedly LibGDX models in G3DB format)
  13163   ...  N*4 List
  13164 
  13165 DRAM Chunks (Text and Binary data) (in various files)
  13166   000h 4   ID "DRAM"
  13167   004h 4   Size of Data part (SIZ) (can be odd)
  13168   008h 4   Number of List entries (N)
  13169   00Ch SIZ Data (raw data, and/or tags TEXT, SPC, COURIER7)
  13170   ...  N*4 List
  13171 
  13172 WEAP Chunks (Weapons) (in WEAPON\*\*)
  13173   000h 4   ID "WEAP"
  13174   004h 4   Size-10h?
  13175   008h ..  Data
  13176 Followed by VRAM and DSND chunks.
  13177 
  13178 HAND Chunks (Hands) (in LEFTHAND\*\HAND*)
  13179   000h 4   ID "HAND"
  13180   004h 4   Size-0Ch?  (18h)
  13181   008h 8   Zerofilled
  13182   010h 4x4 Unknown (FFh,FF00h,xF0000h,FF3232h,FF6464h,FFDCDCh,FFFFFFh,..)
  13183   020h 4   Unknown (0, 1, 101h, or 201h)
  13184 Followed by VRAM and G3DB chunks.
  13185 
  13186 MIDB Chunks (Music) (in MIDI\*\*)
  13187   000h 4      ID "MIDB"
  13188   004h 1      Unknown (0 or 1)
  13189   005h 1      Number of SEQ blocks              (1..4) (S)
  13190   006h 1      Number of Unknown 80h-byte blocks (1..2) (U)
  13191   007h U*80h  Unknown Blocks (mostly FFh-filled)
  13192   ...  S*Var  SEQ Block(s)
  13193   ...  ..     VAB Block
  13194  SEQ Blocks:
  13195   Probably some MIDI sequence data, similar to Sony's .SEQ format.
  13196   000h 4      Size-0Ch (can be odd)
  13197   004h 8      Name (zeropadded if less than 8 chars)
  13198   00Ch 4      ID "DSEQ"    ;\Size
  13199   010h ..     Data         ;/
  13200  VAB Blocks:
  13201   Apparently inspired on Sony's .VAB format (but the ID is spelled other way
  13202   around, Lists have variable size, and entries have different format).
  13203   000h 4      ID "VABp"
  13204   004h 4      Unknown (0)
  13205   008h 4      Unknown (0)
  13206   00Ch 4      Size of all SPU-ADPCM samples (SIZ)
  13207   010h 2      Number of List 1 entries (N1)
  13208   012h 2      Number of List 2 entries (N2)
  13209   014h 2      Number of Samples        (N3)
  13210   016h 6      Unused? (CCh-filled)
  13211   01Ch N1*10h List 1
  13212   ...  N2*10h List 2
  13213   ...  N3*2   Sample Size List (size of each SPU-ADPCM sample)
  13214   ...  SIZ    SPU-APDCM Sample(s)
  13215 
  13216 DSND Chunks (Sounds) (in various files)
  13217   000h 4   ID "DSND"
  13218   004h 4   Unknown (0 or 2)
  13219   008h ..  VAB Block (same as in MIDB chunks, see there)
  13220 
  13221 Note
  13222 DRAM and MIDB chunks can have odd size; there isn't any alignment padding, so
  13223 all following chunks can start at unaligned locations.
  13224 
  13225 CDROM File Archive Blue Chunks (Blue's Clues)
  13226 ---------------------------------------------
  13227 
  13228 Blue's Clues: Blue's Big Musical (*.TXD)
  13229   000h 4    Size of AUDD+SEPD+VABB chunks ;\for quick look-up only
  13230   004h 4    Size of all VRAM chunks       ; (can be ignored by chunk crawlers)
  13231   008h 4    Size of STGE+ANIM+FRAM chunks ;/(note: sum is total filesize-0Ch)
  13232   ...  ..   AUDD Chunk    (contains .VH)                  ;\
  13233   ...  ..   SEPD Chunk(s) (contains .SEP)                 ; sound
  13234   ...  ..   VABB Chunk    (contains .VB)                  ;/
  13235   ...  (..) VRAM Chunk(s) (not in IN\FE2.TXD)             ;-textures/palettes
  13236   ...  (..) STGE Chunk    (if any, not in IN\FE*.TXD)     ;-stage data?
  13237   ...  (..) ANIM Chunk    (if any, not in IN\FE*.TXD)     ;\animation
  13238   ...  (..) FRAM Chunk(s) (if any, not in IN\FE*.TXD)     ;/
  13239   ...  (..) Further groups with ANIM+FRAM Chunks (if any) ;-more animation(s)
  13240  AUDD Chunks:
  13241   000h 4    Chunk ID ("AUDD")
  13242   004h 4    Chunk Size (of whole chunk from Chunk ID and up)
  13243   008h 4    Compression Flag (0=Uncompressed)
  13244   00Ch 4    Zero
  13245   010h ..   VH File (Sony Voice Header, starting with ID "pBAV")
  13246  SEPD Chunks:
  13247   000h 4    Chunk ID ("SEPD")
  13248   004h 4    Chunk Size (of whole chunk from Chunk ID and up)
  13249   008h 4    Compression Flag (0=Uncompressed)
  13250   00Ch 2    Zero
  13251   00Eh 2    Number of sequences (in the SEP sequence archive)
  13252   010h 4    Zero
  13253   014h ..   SEP File (Sony Sequence archive, starting with ID "pQES")
  13254   ...  ..   Zeropadding to 4-byte boundary
  13255  VABB Chunks:
  13256   000h 4    Chunk ID ("VABB")
  13257   004h 4    Chunk Size (of whole chunk from Chunk ID and up)
  13258   008h 4    Compression Flag (0=Uncompressed)
  13259   00Ch ..   VB File (Sony Voice Binary, with raw SPU-ADPCM samples)
  13260  VRAM Chunks:
  13261   000h 4    Chunk ID ("VRAM")
  13262   004h 4    Chunk Size (of whole chunk from Chunk ID and up)
  13263   008h 4    Compression Flag (1=Compressed)
  13264   00Ch 2    VRAM.X
  13265   00Eh 2    VRAM.Y
  13266   010h 2    Width in halfwords
  13267   012h 2    Height
  13268   014h 4    Decompressed Size (Width*Height*2)  ;\Texture Bitmaps 8bpp
  13269   018h ..   Compressed Data                     ; (or Palettes, in last VRAM
  13270   ...  ..   Zeropadding to 4-byte boundary      ;/chunk)
  13271  STGE Chunks:
  13272   000h 4    Chunk ID ("STGE")
  13273   004h 4    Chunk Size (of whole chunk from Chunk ID and up)
  13274   008h 4    Compression Flag (0=Uncompressed)
  13275   00Ch ..   Unknown (stage data?)
  13276  ANIM Chunks:
  13277   000h 4    Chunk ID ("ANIM")
  13278   004h 4    Chunk Size (of whole chunk from Chunk ID and up)
  13279   008h 4    Compression Flag (0=Uncompressed)
  13280   00Ch ..   Unknown (animation sequence info?)
  13281  FRAM Chunks:
  13282   000h 4    Chunk ID ("FRAM")
  13283   004h 4    Chunk Size (of whole chunk from Chunk ID and up)
  13284   008h 4    Compression Flag (0=When Chunksize=14h, 1=When Chunksize>14h)
  13285   00Ch 1    Width in bytes
  13286   00Dh 1    Height
  13287   00Eh 6    Unknown, looks like three signed 16bit values (maybe X,Y,Z)?
  13288   014h (4)  Decompressed Size (Width*Height*1)  ;\Animation Frame Bitmap 8bpp
  13289   018h (..) Compressed Data                     ; (only if Chunksize>14h)
  13290   ...  (..) Zeropadding to 4-byte boundary      ;/
  13291 VRAM and FRAM chunks with [08h]=1 (and Chunksize>14h) are compressed:
  13292 --> CDROM File Compression Blues
  13293 
  13294 CDROM File Archive HED/CDF (Parasite Eve 2)
  13295 -------------------------------------------
  13296 
  13297 Crazy Data Format (CDF) is used by Parasite Eve 2, on Disc 1 and 2:
  13298 1: PE_Disk.01 Stage0.hed Stage0.cdf Stage1.cdf Stage2.cdf Stage3.cdf Inter0.str
  13299 2: PE_Disk.02 Stage0.hed Stage0.cdf Stage3.cdf Stage4.cdf Stage5.cdf Inter1.str
  13300 
  13301 STAGE0.HED and STAGE0.CDF
  13302 This uses separate header/data files. The directory is stored in STAGE0.HED:
  13303   0000h 78h   Streaming List (03h entries, 28h-bytes each, all entries used)
  13304   0078h 1B00h File List (360h entries, 8 bytes each, all entries used)
  13305   1B78b 8     File List End Code (FFFFFFFFh,FFFFFFFFh)
  13306 The actual data for the files (and audio stream) is stored in STAGE0.CDF.
  13307 
  13308 STAGE1.CDF .. STAGE5.CDF
  13309   0000h 800h  Root: Folder List (100h entries, 8-byte each, unused=zeropadded)
  13310   0800h ..    1st Folder (File/Streaming List and Data)
  13311   ...   ..    2nd Folder (File/Streaming List and Data)
  13312   ...   ..    etc.
  13313 Folder List entries:
  13314   000h 4  Folder ID (usually N*100+1 decimal, increasing, eg. 101,201,301,etc.)
  13315   004h 4  Folder Size/800h (of whole folder, with File/Stream List and Data)
  13316   The Folder List ends with unused/zeropadded entries with ID/Size=00000000h.
  13317 Folder format:
  13318   0000h 510h  File List      (A2h entries, 8-bytes each, unused=zeropadded)
  13319   0510h 4     Zero           (padding to decimally-minded offset 1300 aka 514h)
  13320   0514h 2D0h  Streaming List (12h entries, 28h-bytes each, unused=zeropadded)
  13321   07E4h 1Ch   Zero           (padding to end of sector)
  13322   0800h ...   Data (for Files, Audio streams, and sometimes also Movie streams)
  13323 
  13324 File List entries (in STAGE0 and STAGE1-5)
  13325   000h 4  File ID (increasing, eg. 0,1,2,3,4,etc.) (or 99) (or N*100+x)
  13326   004h 4  File Offset/800h in in .CDF (from begin of current Folder)
  13327 For STAGE0, file list ends with ID/Offset=FFFFFFFFh at end of HED file. For
  13328 STAGE1-5, file list ends with unused/zeropadded entries with
  13329 ID/Offset=00000000h.
  13330 The filesize can be computed as "NextOffset-CurrOffset" (at 800h-byte
  13331 resolution). Whereas, "NextOffset" can be:
  13332   The offset of next File in File List (same as CurrOffset for 0-byte files)
  13333   The offset of next Audio stream in Streaming List
  13334   The offset of next Movie stream in Streaming List (if it's in .CDF, not .STR)
  13335   The size of the current Folder (for STAGE1-5)
  13336   The size of the whole .CDF file (for STAGE0)
  13337 For STAGE1-5, audio streams are usually stored at the end of folder (after the
  13338 files). However, for STAGE0, audio streams are oddly inserted between file21000
  13339 and file30100.
  13340 
  13341 File Chunks (for files within File List)
  13342 Most CDF files in STAGE0 and STAGE1-5 do contain one or more chunks with
  13343 10h-byte chunk headers (this can be considered as an additional filesystem
  13344 layer, with the chunk data being the actual files).
  13345   000h 1  Chunk Type (see below)
  13346   001h 1  End Flag (01h=More Chunks follow, FFh=Last Chunk)
  13347   002h 2  Unknown (usually 800h, sometimes 500h or 600h)
  13348             (eg. 500h in stage0\file30301\chunkX)
  13349             (eg. 600h in stage1\folder1201\file0\chunkXYZ)
  13350   004h 4  Chunk Size/800h
  13351   008h 4  Unknown (usually zero) (or 80xxxx00h in Chunk Type 0 files?)
  13352   00Ch 4  Zero (0)
  13353   010h .. Data (Chunk Size-10h bytes)
  13354 Chunk Types:
  13355   00h=Room package            .pe2pkg
  13356   01h=Image                   .pe2img
  13357   02h=CLUT                    .pe2clut
  13358   04h=CAP2 Text               .pe2cap2
  13359   05h=Room backgrounds        .bs
  13360   06h=SPK/MPK music program   .spk  ;stereo/mono, sound/music, single/multiple?
  13361   07h=ASCII text              .txt     (eg. stage0\20101..20132)
  13362  ;Reportedy also (but wrong):
  13363  ;60h=Sounds                  .pe2snd  (but nope, that's wrong, see below)
  13364  ;60h is a MDEC movie from Streaming List (unrelated to File List chunks),
  13365  ;60h is 20h-byte .STR header each 800h-bytes (occurs in "stage1\folder501")
  13366 There are some chunkless files:
  13367   stage0\40105...40198 are raw hMPK files without chunks
  13368   stage0\11000, 20213, 20214, 20300, .., 660800 and 900000 are empty 0-byte
  13369 
  13370 Streaming List Movie entries (stream type 1)
  13371   000h 2    Stream Type (0001h=Movie)
  13372   002h 2    Unknown (8000h or 0000h)
  13373   004h 4    Offset/800h in current Folder of .CDF file ;<-- used when [024h]=0
  13374   008h 4    Offset/800h in INTERx.STR file             ;<-- used when [024h]>0
  13375   00Ch 2    Unknown (0000h)
  13376   00Eh 2    Stream ID (increasing, usually starting at 64h aka 100 decimal)
  13377   010h 2    Stream sub.ID (usually 0, increases +1 upon multiple same IDs)
  13378   012h 2    Picture Width  (0140h = 320 decimal)
  13379   014h 2    Picture Height (00F0h = 224 decimal)
  13380   016h 2    Unknown (0000h)
  13381   018h 2    Unknown (0000h or 0018h)   maybe 24bpp or 24fps
  13382   01Ah 2    Unknown (73Ah or 359h or 3DCh)  (Size? but it's slighty too large?)
  13383   01Ch 6    Unknown (zero)
  13384   022h 2    Unknown (0 or 1) (often 1 when [024h]>0, but not always)
  13385   024h 2    Movie number in INTERx.STR, 1 and up? (or 0=Movie is in STAGEx.CDF)
  13386   026h 2    Unknown (0 or 1)
  13387 The size of movie streams in .CDF can be computed in similar fashion as for
  13388 File List entries (see there for details).
  13389 The size of movie streams in .STR cannot be computed easily (the next stream
  13390 isn't neccassarily stored at the next higher offset; even if it's within same
  13391 folder). As workaround, one could create a huge list with all streams from all
  13392 Folders in all STAGEx.CDFs (or scan the MDEC .STR headers in .STR file; and
  13393 check when the increasing frame number wraps to next stream).
  13394 The dual offsets are oddly computed as: [004h]=[008h]+EndOfLastFileInFolder
  13395 (that gives the correct value in the used entry, and a nonsensical value in the
  13396 other entry).
  13397 
  13398 Streaming List Audio entries (stream type 2)
  13399   000h 2    Stream Type (0002h=Audio)
  13400   002h 2    Unknown (806Ah or increasing 0133h,0134h,0135h)
  13401   004h 4    Offset/800h in STAGEx.CDF file (increasing offsets)
  13402   008h 4    Unknown (0 or 13000h or E000h)
  13403   00Ch 2    Stage Number (0..5 = STAGE0-5)
  13404   00Eh 2    Stream ID (1, or increasing 3Ah,3Bh,3Ch)
  13405   010h 4    Stream sub.ID (usually 0Bh, increases +0Ah upon multiple same IDs)
  13406   014h 2    Unknown (0 or 2B0h or 3ADh or 398h) (Size/800h minus something?)
  13407   016h 2    Unknown (usually 20h, sometimes 0Fh)
  13408   018h 4    Unknown (2 or 1)              ... maybe num channels ?
  13409   01Ch 2+2  Unknown (0,0 or 800h,800h)
  13410   020h 8    Unknown (0)
  13411 The size of audio streams can be computed in similar fashion as for File List
  13412 entries (see there for details).
  13413 
  13414 Audio Stream Data (stored alongsides with file data in STAGEx.CDF file)
  13415 This contains a 800h-byte header a list of 32bit indices:
  13416   000h 800h Whatever increasing 32bit index/timing values? FFFFFFFFh=special?
  13417   ;That header exists in stage0\ and stage3\folder101\
  13418   ;That header doesn't exist in all files (eg. not in stage1\folder301\)
  13419 then followed by several chunk-like STM blocks with 10h-byte headers:
  13420   000h 4  Chunk Index (increases each second chunk, from 0 and up)
  13421   004h 4  Number of Chunk Indices
  13422   008h 4  Fixed (02h,"STM")                                  ;2-channel Stream?
  13423   00Ch 1  Chunk Subindex (toggles 00h or 01h per each chunk) ;ch left/right?
  13424   00Dh 1  Chunk Size/800h
  13425   00Eh 4  Unknown (can be 00h, 01h, 11h, 20h, 21h)
  13426   00Fh 4  Unknown (can be A0h or C0h)
  13427   010h .. Data (Chunk Size-10h bytes) (looks like SPU-ADPCM audio)
  13428 After the last STM chunk, there is more unknown stuff:
  13429   000h 0   Number of ADPCM blocks?            (eg. 28h    or 49h)
  13430   004h 4   Size of extra data block in bytes  (eg. 13900h or 24200h)
  13431   008h 38h Zerofilled
  13432   040h 8   Zerofilled (maybe 1st sample of 1st SPU-ADPCM block)
  13433   048h ..  Looks like more SPU-ADPCM block(s), terminated by ADPCM end flag(s)
  13434   ...  ..  Zerofilled (padding to end of last 800h-byte sector)
  13435 
  13436 Movie Stream Data (stored in .CDF, or in separate INTERx.STR file)
  13437 The movies are usually stored in INTERx.STR (except, some have them stored in
  13438 STAGEx.CDF, eg. stage1\folder501, stage1\folder801, stage2\folder2101,
  13439 stage2\folder3001).
  13440 The data consists of standard .STR files (with 20h-byte headers on each
  13441 800h-byte sector), with the MDEC data being in huffman .BS format (with .BS
  13442 header... per frame?).
  13443 And, supposedly interleaved with XA-ADPCM audio sectors...?
  13444 
  13445 PE_DISK.01 and PE_DISK.02
  13446 The presence of these files is probably used to detect which disc is inserted.
  13447 The file content is unknown (looks like 800h-byte random values).
  13448 
  13449 Note
  13450 Reportedly "Files inside archive may be compressed with custom LZSS
  13451 compression" (unknown if/when/where/really/which files).
  13452 
  13453 CDROM File Archive IND/WAD (MTV Music Generator)
  13454 ------------------------------------------------
  13455 
  13456 MTV Music Generator (IND/WAD) (MagDemo30: JESTER\WADS\ECTS.IND and .WAD)
  13457 ECTS.IND contains FOLDER info:
  13458   0000h 20h   Name/ID ("Music 2", zeropadded)
  13459   0020h 4     Unknown (110000h)
  13460   0024h 4     Filesize-1000h (size excluding last 1000h-byte padding)
  13461   0028h 4     Unknown (17E0h)
  13462   002Ch 4     Unknown (5)
  13463   0030h N*10h Folder List, starting with Root in first 10h-byte
  13464   2CF0h 4     Small Padding (34h-filled)
  13465   2CF4h 1000h Final Padding (34h-filled)
  13466  Folder List entries that refer to Child Folders in ECTS.IND:
  13467   000h 8     Folder Name ("EXTRA*~*", zeropadded if less than 8) ("" for root)
  13468   008h 2     Self-relative Index to first Child folder (positive)
  13469   00Ah 2     Number of Child Folders (0..7FFFh)
  13470   00Ch 4     Always 0007FFFFh (19bit Offset=7FFFFh, plus 13bit Size=0000h)
  13471  Folder List entries that refer to File Folders in ECTS.WAD:
  13472   000h 8     Folder Name ("EXTRA*~*", zeropadded if less than 8)
  13473   008h 2     Self-relative Index to Parent folder (negative)
  13474   00Ah 2     Number of Child Folders (always 8000h=None)
  13475   00Ch 4     Offset and Size in ECTS.WAD
  13476  The 32bit "Offset and Size" entry consists of:
  13477   0-18   19bit Offset/800h in ECTS.WAD
  13478   19-31  13bit Size/800h-1 in ECTS.WAD
  13479 ECTS.WAD contains FILE info and actual FILE data:
  13480  There are several File Folders (at the locations specified in ECTS.IND).
  13481  The separate File Folders look as so:
  13482   000h 4     Number of files (N)
  13483   004h N*10h File List
  13484   ...  ..    34h-Padding to 800h-byte boundary
  13485   ...  ..    File Data area
  13486  File List entries:
  13487   000h 8     File Name ("NAMELIST", "ACIDWO~1", etc.) (00h-padded if shorter)
  13488   008h 4     Offset/800h (always from begin of WAD, not from begin of Folder)
  13489   00Ch 4     Filesize in bytes
  13490  The first file in each folder is called "NAMELIST" and contains this:
  13491   000h 20h   Long Name for Parent Folder (eg. "Backgrounds", zeropadded)
  13492   020h 20h   Long Name for this Folder   (eg. "Extra 1", zeropadded)
  13493   040h N*20h Long Names for all files in folder (except for NAMELIST itself)
  13494  For example, Long name for "ACIDWO~1" would be "Acidworld". Short names are
  13495  uppercase, max 8 chars, without spaces (with "~N" suffix if the long name
  13496  contains spaces or more than 8 chars). Many folder names are truncated to
  13497  one char (eg. "D" for Long name "DTex"), in such cases short names CAN be
  13498  lowercase (eg. "z" for  Long name "zTrans").
  13499  The Long Names are scattered around in the NAMELIST files in ECTS.WAD file,
  13500  so they aren't suitable for lookup (unless when loading all NAMELIST's).
  13501 
  13502 CDROM File Archive GAME.RSC (Colonly Wars Red Sun)
  13503 --------------------------------------------------
  13504 
  13505 Colony Wars Red Sun (MagDemo31: CWREDSUN\GAME.RSC, 13Mbyte)
  13506   0000h 4     Offset to Bonkers List (2794h)
  13507   0004h F*8   Folder List                      (80h bytes, 10h entries)
  13508   0084h N*14h File List(s) for each folder     (2710h bytes, 1F4h entries)
  13509   2794h 4     Number of Bonkers     (FE3h)
  13510   2798h B*8   Bonkers List                     (7F18h bytes, FE3h entries)
  13511   A6B0h 8     Unknown (zerofilled)
  13512   A6B8h ..    File Data area
  13513 Folder List entries:
  13514   000h 4     Offset to File List for this folder   ;\both zero when empty
  13515   004h 4     Number of Files in this folder        ;/
  13516 File List entries:
  13517   000h 10h   Filename ("FILENAME_EXT", zeropadded)
  13518   010h 3     Index (in Bonkers list) (000h..Fxxh)
  13519   013h 1     Folder Number where the file is stored (00h..0Fh)
  13520 Bonkers List entries:
  13521   000h 4     File Offset (to Data, inreasing, 4-byte aligned, A6B8h and up)
  13522   004h 4     Folder Number where the file is stored (00h..0Fh)
  13523 Offsets/Indices in Folder/File list are unsorted (not increasing).
  13524 Offsets in Bonkers List are increasing (so filesizes can be computed as
  13525 size=next-curr, except, the LAST file must be computed as size=total-curr).
  13526 There is no "number of folders entry" nor "folder list end marker", as
  13527 workaround, while crawling the folder list, search the smallest file list
  13528 offset, and treat that as folder list end offset.
  13529 In the demo version, all File List entries for Folder 5 are pointing to files
  13530 with filesize=0, however, the Bonkers List has a lot more "hidden" entries that
  13531 are marked to belong to Folder 5 with nonzero filesize.
  13532 Note: Older Colony Wars titles did also have a GAME.RSC file (but in different
  13533 format, without folder structure).
  13534 
  13535 CDROM File Archive BIGFILE.DAT (Soul Reaver)
  13536 --------------------------------------------
  13537 
  13538 Legacy of Kain: Soul Reaver - BIGFILE.DAT
  13539 Legacy of Kain: Soul Reaver (MagDemo26: KAIN2\BIGFILE.DAT)
  13540   000h 2     Number of Folders (175h in retail, 0Ah in demo)
  13541   002h 2     Zero
  13542   004h N*8   Folder List (8-byte per Folder)
  13543   ...  ..    Zeropadding (to 800h-byte boundary)
  13544   ...  ..    1st Folder (with File List, and File Data for that folder)
  13545   ...  ..    2nd Folder (with File List, and File Data for that folder)
  13546   ...  ..    3rd Folder (with File List, and File Data for that folder)
  13547   ...  ..    etc.
  13548 Folder List entries:
  13549   000h 2     Unknown (somehow randomly increases from -8000h to +7E8Fh)
  13550   002h 2     Number of Files in this Folder (eg. 97h)
  13551   004h 4     Offset to Folder (usually 800h-aligned)
  13552 Folder format:
  13553   000h 2     Number of Files (same value as FolderistEntry[002h]) ;\encrypted
  13554   002h 2     Zero                                                 ; by 16bit
  13555   004h N*10h File List (10h-byte per Folder)                      ; XOR value
  13556   ...  ..    Zeropadding (to 800h-byte boundary)                  ;/
  13557   ...  ..    File Data for this folder                            ;-unencrypted
  13558 File List entries:
  13559   000h 4     Unknown (random? filename hash? encrypted name?)
  13560   004h 4     File Size in bytes
  13561   008h 4     File Offset (usually 800h-aligned)
  13562   00Ch 4     Unknown (random? filename hash? encrypted name?)
  13563 Encryption:
  13564 The file header, the first some Folder headers (those in first quarter or so),
  13565 and (all?) File Data is unencrypted (aka XORed with 0000h).
  13566 The Folder headers at higher offsets are encrypted with a 16bit XOR value. That
  13567 XOR value is derived from Subchannel Q via LibCrypt:
  13568 --> CDROM Protection - LibCrypt
  13569 When not having the Subchannel data (or when not knowing which Folders are
  13570 encrypted or unencrypted), one can simply obtain the encryption key from one of
  13571 these entries (which will be key=0000h when unencrypted):
  13572   key = FileListEntry[000h] XOR FolderListEntry[002h]  ;encrypted num entries
  13573   key = FileListEntry[002h]                            ;encrypted Zero
  13574   key = FileListEntry[zeropadding, if any]             ;encrypted Zeropadding
  13575 LibCrypt seems to be used only in PAL games, unknown if the Soul Reaver NTSC
  13576 version does also have some kind of encryption.
  13577 
  13578 CDROM File Archive FF8 IMG (Final Fantasy VIII)
  13579 -----------------------------------------------
  13580 
  13581 FF8 is quite a mess without cear directory structure. Apart from SYSTEM.CNF and
  13582 boot EXE, there is only one huge IMG file. There are at least two central
  13583 directories: The Root directory (usually at the start of the IMG file), and the
  13584 Fields directory (hidden in a compressed file that can be found in the Root
  13585 directory). Moreover, there are files that exist in neither of the directories
  13586 (most notably the Movies at the end of the IMG file).
  13587 
  13588 IMG File
  13589 The IMG file doesn't have a unique file header, it can be best detected by
  13590 checking the filename: FF8DISCn.IMG with n=1-4 for Disc 1-4 (or only
  13591 FF8DISC1.IMG or FF8.EXE+FF8TRY.IMG for demo versions).
  13592 The directories contain ISO sector numbers (originated from begin of the ISO
  13593 area at sector 00:02:00). Accordingly, it's best to extract data from the whole
  13594 disc image (in CUE/BIN format or the like). When having only the raw IMG file,
  13595 one most know/guess the starting sector number (eg. assume that the first Root
  13596 File is located on the sector after the Root Directory, and convert sector
  13597 numbers ISO-to-IMG accordingly).
  13598 Another oddity is that many files contain RAM addresses (80000000h-801FFFFFh),
  13599 unknown how far that's relevant, and if there are cases where one would need to
  13600 convert RAM addresses to IMG offsets.
  13601 
  13602 Root Directory
  13603 The Root Directory is found at:
  13604   Offset 0000h in FF8DISCn.IMG in NTSC retail versions
  13605   Offset 2800h in FF8DISCn.IMG in PAL retail versions
  13606   Offset 0000h in FF8DISC1.IMG in french demo version
  13607   Offset ?????h in FF8.EXE in MagDemo23 (...maybe offset 3357Ch ?)
  13608   Offset 33510h in FF8.EXE in japanese demo version ?
  13609   Offset 33584h in FF8.EXE in other demo versions   ?
  13610 For detection:
  13611   if FF8DISCn.IMG starts with 000003xxh --> assume Root at IMG offset 0
  13612   if FF8DISCn.IMG starts with xxxxxxxxh --> assume Root at IMG offset 2800h
  13613   if FF8TRY.IMG starts with "SmCdReadCore" --> assume Root somewhere in EXE
  13614 File List:
  13615   000h N*8  File List entries
  13616   ...  ..   Zeropadding to end of 800h-byte sector
  13617 File List entries:
  13618   000h 4    ISO Sector Number (origin at 00:02:00) (unsorted, not increasing)
  13619   004h 4    Filesize in bytes
  13620 The file list does usually end with zeropadding (unknown if that applies to all
  13621 versions; namely the Demo version might end with gibberish instead of having
  13622 800h-byte sector padding).
  13623 
  13624 Fields Directory
  13625 The Fields Directory is located in Root file 0002h. First of, decompress that
  13626 file, then search the following byte sequences to find the start/end of the
  13627 directory:
  13628   retail.start  040005241800bf8f1400b18f1000b08f2000bd270800e00300000000
  13629   retail.end    0000010002000300
  13630   demo.start    76DF326F34A8D0B863C8C0EC4BE817F8
  13631   demo.end      0000000000000000000000000000000000100010
  13632 The bytes between those start/end pattern contain the Directory, with entries
  13633 in same format as Root directory:
  13634   000h 4    ISO Sector Number (origin at 00:02:00)
  13635   004h 4    Filesize in bytes
  13636 Notes: Root file 0002h is about 190Kbyte (decompressed), of which, the Fields
  13637 Directory takes up about 8Kbytes, the remaining data contains other stuff.
  13638 The sector numbers in the Fields Directory refer to other locations in the IMG
  13639 file (not to data in Root File 0002h).
  13640 
  13641 Movie List
  13642 There is no known central directory for the movies (unknown if such a thing
  13643 exists, or if the movie sector numbers are scattered around, stored in separate
  13644 files). However, a movie list can be generated by crawling the movie headers,
  13645 starting at end of IMG file:
  13646   sector = NumSectors(IMG file)
  13647  @@lop:
  13648   seek(sector-1), read(buf,08h bytes)
  13649   if first4byte[buf+0]=("SMJ",01h), or ("SMN",01h) then
  13650     num_sectors=(byte[buf+5]+1)*(halfword[buf+6]+1)
  13651     sector=sector-num_sectors
  13652     AddToMovieFileList(sector, num_sectors)
  13653     goto @@lop
  13654   endif
  13655 That should cover all movies, which are all at the end of the IMG file (except,
  13656 there's one more movie-like file elsewhere in the middle of IMG file, that file
  13657 has only SMN/SMR audio sectors, without any SMJ video sectors).
  13658 
  13659 PADBUG archives
  13660 PADBUG archives are used in Root files 001Eh..007Fh, most of them contain two
  13661 AKAO files (except file 004Bh contains one AKAO and one TXT file).
  13662   000h 4     Number of Files (N) (usually 2)
  13663   004h N*8   File List
  13664   ...  ..    File Data area
  13665 File List entries:
  13666   000h 4     Offset in bytes (increasing, 4-byte aligned, see Quirk)
  13667   004h 4     File Size in bytes (can be odd)
  13668 Quirk: All files are zeropadded with 1-4 bytes to 4-byte boundary (ie. files
  13669 that do end on a 4-byte boundary will be nethertheless padded with 4 zeroes).
  13670 Note: The PADBUG archives resemble LNK archives in  O.D.T. (though those LNK
  13671 archives have a different unique 4-byte padding quirk).
  13672 
  13673 Compression
  13674 --> CDROM File Compression LZ5 and LZ5-variants
  13675 FF8 does reportedly also use GZIP (unknown in which files).
  13676 
  13677 Known/unknown sectors for US version FF8DISC1.IMG
  13678   root sectors:       27CBh ;\
  13679   field sectors:      D466h ; total known sectors: 36D13h
  13680   movie sectors:     270E2h ;/
  13681   unknown sectors:   14F49h
  13682   total IMG sectors: 4BC5Ch
  13683 
  13684 See also
  13685 https://github.com/myst6re/deling/blob/master/FF8DiscArchive.cpp
  13686 https://ff7-mods.github.io/ff7-flat-wiki/FF8/PlaystationMedia.html
  13687 
  13688 CDROM File Archive FF9 IMG (Final Fantasy IX)
  13689 ---------------------------------------------
  13690 
  13691 Final Fantasy IX (FF9.IMG, 320Mbyte) Overall format
  13692   000h Root Directory
  13693   800h 1st Child Folder
  13694   ...  2nd Child Folder
  13695   ...  3rd Child Folder
  13696   ...  ...
  13697   8000h ?     Last folder, with Type3, contains 1FFh x increasing 16bit numbers
  13698   ...  Data for files in 1st Child Folder
  13699   ...  Data for files in 2nd Child Folder
  13700   ...  Data for files in 3rd Child Folder
  13701   ...
  13702 
  13703 IMG Root Directory
  13704   000h 4     ID "FF9 "
  13705   004h 4     Unknown (06h on Disc 1 of 4) (maybe version, or disc id?)
  13706   008h 4     Number of Folder List entries (0Fh)
  13707   00Ch 4     Unknown (01h on Disc 1 of 4) (maybe version, or disc id?)
  13708                  (or Offset/800h to first file list?)
  13709   010h N*10h Folder List
  13710   ...  ..    Padding to 800h-byte boundary ("FF9 FF9 FF9 FF9 ")
  13711 Folder List entries:
  13712   000h 4     FolderType (2=Normal, 3=Special, 4=Last entry)
  13713   004h 4     Number of entries in File List (0..1FFh ?)
  13714   008h 4     Offset/800h to Child Folder with File List
  13715   00Ch 4     Offset/800h to File Data (same as 1st offs in File List) (0=Last)
  13716 
  13717 IMG Child Folders (FolderType=2)
  13718   000h N*8   File List entries (N=Number of files, from Root directory)
  13719   N*8  8     File List END entry (ID=FFFFh, Attr=FFFFh, Offs=EndOfLastFile)
  13720   ...  ..    Zeropadding to 800h-byte boundary
  13721 File List entries:
  13722   000h 2     File ID (increasing, often decimal 0,10,100, or FFFFh=Last)
  13723   002h 2     Attr (unknown purpose, eg. 0,2,3,4,8,21h,28h,2Fh,44h,114h,FFFFh)
  13724   004h 4     Offset/800h to File Data (increasing, implies end of prev entry)
  13725 
  13726 IMG Child Folders (FolderType=3)
  13727   000h N*2   File Offsets/800h, from File Data Offset in Root (or FFFFh=None)
  13728   N*2  2     End Offset for last file
  13729 The filesize can be computed as (NextOffs-CurrOffs)*800h, however, one must
  13730 skip unused entries (FFFFh) to find NextOffs.
  13731 
  13732 Nested Child Archives
  13733 Most of the files in FF9.IMG are DB archives, there are also some DOT1
  13734 archives.
  13735 --> CDROM File Archive FF9 DB (Final Fantasy IX)
  13736 There are various combinations of IMG, DB, DOT1 archives nested up to 4 levels
  13737 deep:
  13738   IMG\DOT1         (eg. dir01\file003C)
  13739   IMG\DB           (eg. dir01\file2712)
  13740   IMG\DB\DOT1      (eg. dir01\file2712\00-0411)
  13741   IMG\DB\DOT1\DOT1 (eg. dir01\file2712\00-0443\*)
  13742   IMG\DB\DB        (eg. dir03\file2328\1B-000*)
  13743 
  13744 Folders in Root directory
  13745   dir00 - Status/Menu/Battle/... -Text and random stuff.
  13746   dir01 - Misc Images (Logos, Fonts, World 'mini' Map images, etc).
  13747   dir02 - Dialog Text
  13748   dir03 - Map models (Mini-zidane, airships, save point moogle, tent...)
  13749   dir04 - Field models
  13750   dir05 - Monster Data (Part I, stats, names, etc).
  13751   dir06 - Location Data (Dungeon, Cities, etc).
  13752   dir07 - Monster Data (Part II, 3d models)
  13753   dir08 - Weapon Data (including models)
  13754   dir09 - Samplebanks and Sequencer Data (ie music).
  13755   dir0A - party members Data (including models)
  13756   dir0B - Sound effects
  13757   dir0C - World Map Data
  13758   dir0D - Special effects (magic, summons...)
  13759 
  13760 See also
  13761 https://ninjatoes.blogspot.com/2020/07/
  13762 https://wiki.ffrtt.ru/index.php?title=Main_Page
  13763 
  13764 CDROM File Archive GTFS (Gran Turismo 2)
  13765 ----------------------------------------
  13766 
  13767 Gran Turismo 2 (MagDemo27: GT2\GT2.VOL, GT2.VOL\arcade\arc_carlogo) - GTFS
  13768   000h 4     ID "GTFS"                                             ;\
  13769   004h 4     Zero                                                  ;
  13770   008h 2     Number of 4-byte File Offset List entries (N)         ; File(0)
  13771   00Ah 2     Number of 20h-byte File/Folder Name List entries (F)  ;
  13772   00Ch 4     Zero                                                  ;
  13773   010h N*4   File Offset List (see below)                          ;/
  13774   ...  ..    Zeropadding to 800h-byte boundary
  13775   ...  F*20h File/Folder Name List (see below)                     ;-File(1)
  13776   ...  ..    Zeropadding to 800h-byte boundary
  13777   ...  ..    File Data                                             ;-File(2)
  13778   ...  ..    Zeropadding to 800h-byte boundary
  13779   ...        File Data                                             ;-File(3)
  13780   ...  ..    ...
  13781   ...        File Data                                             ;-File(N-2)
  13782   ...  ..    Zeropadding to 800h-byte boundary
  13783   EOF  0     End of File                                           ;-File(N-1)
  13784 That is, for N files, numbered File(0)..File(N-1):
  13785   File(0) and File(1) = Directory information
  13786   File(2)..File(N-2)  = Regular data files
  13787   File(N-1)           = Offset List entry points to the end of .VOL file
  13788 File Offset List entries, in File(0):
  13789 Contains information for all files, including File(0) and File(1), and
  13790 including an entry for File(N-1), which contains the end offset for the last
  13791 actual file, ie. for File(N-2).
  13792   Bit0-10  = Number of padding bytes in last sector of this file (0..7FFh)
  13793   Bit11-31 = Offset/800h to first sector of this file (increasing)
  13794   To compute the filesize: Size=(Entry[N+1] AND FFFFF800h)-Entry[N]
  13795 File/Folder Name List entries, in File(1):
  13796 Contains information for all files, excpet File(0), File(1), File(N-1), plus
  13797 extra entries for Folders, plus ".." entries for links to Parent folders.
  13798   000h 4     Unknown (379xxxxxh) (maybe timestamp?)
  13799   004h 2     When Flags.bit0=0: Index of File in File Offset List (2 and up)
  13800              When Flags.bit0=1: Index of first child in Name List, or...
  13801              When Flags.bit0=1: Index of 1st? parent in Name List (Name="..")
  13802   006h 1     Flags (bit0:0=File, 1=Directory; bit7:1=Last Child entry)
  13803   007h 19h   Name (ASCII, zeropadded)
  13804 The game does use several archive formats: GTFS (including nested GTFS inside
  13805 of main GTFS) and WAD.WAD and DOT1.
  13806 The game does use some GT-ZIP compressed files, and many GZIP compressed files
  13807 (albeit with corrupted/zeropadded GZIP footers; due to DOT1 filesize 4-byte
  13808 padding and (unneccessarily) GTFS 800h-byte padding).
  13809 --> CDROM File Compression GT-ZIP (Gran Turismo 1 and 2)
  13810 --> CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  13811 To extract the decompressed size from the corrupted GZIP footers, one could
  13812 compute the compressed "size" (excluding the GZIP header, footer, and padding),
  13813 and search for a footer entry that is bigger than "size".
  13814   size=gz_filesize
  13815   size=size-GzipHeader(including ExtraHeader, Filename, Comment, HeaderCrc)
  13816   size=size-GzipFooter(8)   ;initially assuming 8-byte footer (without padding)
  13817   i=gz_filesize-4
  13818  @@search_footer:
  13819   if buf[i]<size then i=i-1, size=size-1 goto @@search_footer
  13820   decompressed_size = buf[i]
  13821 Note: Above doesn't recurse the worst-case compression ratio, where compressed
  13822 files could be slightly bigger than decompressed files.
  13823 
  13824 CDROM File Archive Nightmare Project: Yakata
  13825 --------------------------------------------
  13826 
  13827 Nightmare Project: Yakata
  13828 ISO Files:
  13829   CD.IMG      550Mbyte  Contains file 004h..FFFh
  13830   CDRTBL.DAT  32Kbyte   Alias for file 000h (File List for file 000h..FFFh)
  13831   FDTBL.DAT   2Kbyte    Alias for file 001h (Folder List and Disc ID)
  13832   SLPS_010.4* 500Kbyte  Alias for file 003h (Boot EXE)
  13833   SYSTEM.CNF  72bytes   Alias for file 002h (Boot Info)
  13834   XXXXXXXX.   27Mbyte   Padding (zerofilled)
  13835 FDTBL.DAT (Folder List):
  13836  FDLTBL.DAT seems to be used to divide the file list in CDRTBL.DAT into
  13837  separate folders. The Folder List entries are containing the first file number
  13838  for each folder. Empty folders have same file number as next entry.
  13839  The last folder contains the specified file number plus all remaining files.
  13840   000h 56h*2 Folder List (16bit File Numbers, increasing from 0004h to 0xxxh)
  13841   0ACh 748h  Zerofilled
  13842   7F4h 0Ah   Game ID (ASCII "SLPS1045",00h,00h; always so on Disc 1..3)
  13843   7FEh 2     Disc ID (1..3 = Disc 1..3)
  13844 CDRTBL.DAT (File List):
  13845   000h 8000h File List (1000h x 8-byte entries)
  13846  File List entries:
  13847   000h 4   Sector (MM:SS:FF:00 in BCD, increasing)  ;\all zero for
  13848   004h 2   Size1  (NumFramesCh1 or NumSectors)      ; unused entries
  13849   006h 2   Size0  (NumFramesCh0 or Zero)            ;/
  13850  The meaning of the Size entries depends on the file type:
  13851   Normal binaries:  [004h]=NumSectors     [006h]=0             (1 channel)
  13852   XA-ADPCM streams: [004h]=NumSectors-50h [006h]=0             (16 channels)
  13853   MDEC streams:     [004h]=NumFrames      [006h]=0             (audio+video)
  13854   Special streams:  [004h]=NumFramesCh1   [006h]=NumFramesCh0  (2 channels)
  13855  To determine the actual filesize, one must compute the difference between
  13856   sectors for current and next used file entry (or end of CD.IMG for last file;
  13857   or alternately assume last file to be a Normal Binary with Size=NumSectors).
  13858  Normal Binaries:
  13859   Contains single files (file=0/channel=0). Filetypes include TIM, VB, VH,
  13860   other/custom file formats, and DOT1 archives.
  13861   The DOT1 archives have 4-byte aligned offsets, but, unconventionally, with
  13862   some offsets set to ZERO (usually the last entry, and sometimes also other
  13863   entries):
  13864   SEQ files (Disc1:Dir08h\File173h)       ;with ZERO entries    (=uncommon)
  13865   SEQ files (Disc1:Dir09h\File176h..3D7h) ;with ZERO entries    (=uncommon)
  13866   SEQ files (Disc1:Dir0Ah\File3DAh..3E6h) ;with ZERO entries    (=uncommon)
  13867   TIM files (Disc1:Dir4Fh\File962h..983h) ;with ZERO entries    (=uncommon)
  13868   TIM files (Disc1:Dir0Ch\File414h..426h) ;without ZERO entries (=normal DOT1)
  13869  XA-ADPCM Streams (Disc1:Dir0Bh\File3E7h..413h):
  13870   These contain 16 audio streams (file=1/channel=00h-0Fh). The Size entry is
  13871   set to total size in sectors for all streams, minus 50h (ie. there appears
  13872   to be 50h sectors appended as padding before next file).
  13873  MDEC Streams (Disc1:Dir53h\FileBD1h..BEBh):
  13874   These are standard STR files with MDEC video (file=0/channel=1) and
  13875   XA-ADPCM (file=1/channel=1). There are 10 sectors per frame (8-9 video
  13876   sectors plus 1-2 audio sectors). The total filesize is NumFrames*10+Align(8)
  13877   sectors; the Align(8) might be there to include one final audio sector.
  13878  Special Streams (Disc1:Dir07h\File0E9h-16Eh and Dir50h\File985h..B58h):
  13879   These are custom STR files (non-MDEC format), perhaps containing Polygon
  13880   streams or whatever.
  13881   There are two channels (file=1/channel=00h-01h), each channel contains
  13882   data that consists of 5 sectors per frame (1xHeader plus 4xData).
  13883   The sectors have STR ID=0160h, and STR Type as follows:
  13884     0000h=Whatever special, channel 0 header (sector 0)
  13885     0400h=Whatever special, channel 1 header (sector 1)
  13886     0001h=Whatever special, channel 0 data   (sector 2,4,6,8)
  13887     0401h=Whatever special, channel 1 data   (sector 3,5,7,9)
  13888   The File List size entries contain Number of Frames for each channel (either
  13889   of these entries may be zero, or bigger/smaller/same than the other entry).
  13890   The smaller channel is padded to same size as bigger channel (ie. total
  13891   filesize is "max(NumFramesCh0,NumFramesCh1)*10 sectors"; though that formula
  13892   doesn't always hold true, for example, Disc1:Dir50h\FileA2Dh and FileB1Bh
  13893   are bigger or smaller than expected).
  13894 
  13895 CDROM File Archive FAdj0500 (Klonoa)
  13896 ------------------------------------
  13897 
  13898 Klonoa (MagDemo08: KLONOA\FILE.IDX+FILE.BIN)
  13899  FILE.IDX
  13900   000h 8     ID "FAdj0500"
  13901   008h 38h   RAM addresses       (80xxxxxxh, 0Ch words)
  13902   038h 4     Zero
  13903   03Ch 4     RAM address         (80xxxxxxh)
  13904   040h N*10h File List (including Folder start/end markers)
  13905  FILE.BIN
  13906   000h ..    File Data area (split into filesizes from FILE.IDX)
  13907 File List entries:
  13908  Type 0 (Folder End):
  13909   000h 4     Type (0=Folder End)
  13910   000h 4     Zero
  13911   008h 4     RAM address         (always 801EAF8Ch)
  13912   00Ch 4     Zero
  13913  Type 1.a (Folder Start):
  13914   000h 4     Type (1=Folder Start)
  13915   000h 4     Folder Offset/800h  (offset of FIRST file in this Folder)
  13916   008h 4     RAM address         (always 801EAF8Ch)
  13917   00Ch 4     Folder Size/800h    (size of ALL files in this Folder)
  13918  Type 1.b (Force Offset, can occur between Files within a Folder):
  13919   000h 4     Type (1=Same as Folder Start)
  13920   000h 4     Folder Offset/800h  (offset of NEXT file in this Folder)
  13921   008h 4     RAM address         (always 801EAF8Ch)
  13922   00Ch 4     Folder Size/800h    (zero for Force Offset)
  13923  Type 2 (File entries, within Folder Start/End):
  13924   000h 4     Type (2=File)
  13925   004h 4     Filesize in bytes   (4-byte aligned?)
  13926   008h 4     RAM address 1       (80xxxxxxh, or zero)
  13927   00Ch 4     RAM address 2       (80xxxxxxh)
  13928 File Offsets are usually 4-byte aligned (at offset+filesize from previous
  13929 entry). Except, the first file after Folder Start (and Force Offset) is
  13930 800h-byte aligned.
  13931 The archive contains DOT1 archives, OA05 archives, Ulz compression, and TIM,
  13932 TMD, VAB, SEQ, VB files.
  13933 
  13934 CDROM File Archives in Hidden Sectors
  13935 -------------------------------------
  13936 
  13937 Hidden Sector Overview
  13938 Xenogears, Chrono Cross, and Threads of Fate contain only two files in the ISO
  13939 filesystem (SYSTEM.CNF and the boot executable). The CDROMs contain standard
  13940 ISO data in Sector 10h-16h, followed by Hidden stuff in Sector 17h and up:
  13941   Sector 10h (00:02:16)  Volume Descriptor (CD001)      ;\
  13942   Sector 11h (00:02:17)  Volume Terminator (CD001)      ;
  13943   Sector 12h (00:02:18)  Path Table 1                   ;
  13944   Sector 13h (00:02:19)  Path Table 2                   ; standard ISO
  13945   Sector 14h (00:02:20)  Path Table 3                   ;
  13946   Sector 15h (00:02:21)  Path Table 4                   ;
  13947   Sector 16h (00:02:22)  Root Directory                 ;/
  13948   Sector 17h (00:02:23)  Hidden ID                      ;\
  13949   Sector 18h (00:02:24)  Hidden Directory               ; hidden directory
  13950   Sector ..  (00:02:xx)  Hidden Unknown                 ;/
  13951   Sector ..  (00:02:xx)  Hidden Files... (referenced via Hidden Directory)
  13952 Note: Like normal files, all hidden entries have their last sector flagged as
  13953 SM=89h (that applies to all three Hidden ID, Directory, Unknown entries, and to
  13954 all Hidden Files). For details, see:
  13955 --> CDROM XA Subheader, File, Channel, Interleave
  13956 
  13957 Xenogears (2 discs, 1998)
  13958  Sector 17h (Hidden.ID)
  13959   000h 0Eh  ID ("DS01_XENOGEARS"=Disc 1, or "DS02_XENOGEARS"=Disc 2)
  13960   00Eh 7F2h Zerofilled
  13961  Sector 18h..27h
  13962   000h N*7  File List entries
  13963  Sector 28h (Hidden.Unknown)
  13964   Seems to contain a list of 16bit indices 0000h..1037h,FFFFh in File List
  13965   (that, as raw list indices, regardless of the directory structure)
  13966   000h      Unknown 0016 0018 FFFF FFFF 01A8 FFFF FFFF FFFF  ;\
  13967   010h      Unknown FFFF FFFF FFFF FFFF 0A35 0A3A 0D35 0AD3  ; as so on Disc 2
  13968   020h      Unknown 0A22 0A2E 0A2F FFFF FFFF FFFF FFFF FFFF  ; (values<>FFFFh
  13969   030h      Unknown 0014 0001 0013 FFFF 0075 FFFF FFFF FFFF  ; on Disc 1
  13970   040h      Unknown 0C10 0C14 0C15 0C19 0F52 FFFF FFFF FFFF  ; are 5 less, eg.
  13971   050h      Unknown 0F4C 0B6E 0C4D 1037 0C09 0BAD FFFF FFFF  ;
  13972 0011,0013,FFFF..)
  13973   060h      Unknown 002E 0034 FFFF FFFF FFFF FFFF FFFF FFFF  ;
  13974   070h      Unknown FFFF FFFF FFFF FFFF                      ;/
  13975   078h 2    Disc Number      (0001h=Disc 1, 0002h=Disc 2)
  13976   07Ah 786h Zerofilled
  13977  Sector 29h 1st file
  13978 File List entries:
  13979   000h 3    24bit Offset (increasing sector number, or 0=special)
  13980   003h 4    32bit Size   (filesize in bytes, or negative or 0=special)
  13981 The Offset/Size can have following meanings:
  13982   offset=curr,    size=+N    file at sector=curr, size N bytes
  13983   offset=curr,    size=-N    begin of sub-directory, with N files
  13984   offset=curr,    size=0     empty file, size 0 bytes
  13985   offset=0,       size=0     unused file entry
  13986   offset=FFFFFFh, size=0     end of root-directory
  13987 Notes: The Hidden.Directory size seems to be hardcoded to 10h sectors
  13988 (alternately, one could treat the sector of the 1st file entry as end of
  13989 Hidden.Directory plus Hidden.Unknown).
  13990 Root entry 0004h and 0005h are aliases for ISO files SYSTEM.CNF and boot EXE.
  13991 There seem to be no nested sub-directories (but there are several DOT1 child
  13992 archives, in root- and sub-directories, eg. 00DCh\0000h\*).
  13993 
  13994 Chrono Cross (2 discs, 1999,2000)
  13995 Threads of Fate (aka Dewprism) (1 disc, 1999,2000)
  13996  Sector 17h (Hidden.ID)
  13997   000h 2    Disc Number      (0001h=Disc 1, 0002h=Disc 2)
  13998   002h 2    Number of Discs? (0002h) (always 2, even if only 1 disc)
  13999   004h 2+2  Sector and Size for Hidden.ID        (Sector=0017h, Size=002Ch)
  14000   008h 2+2  Sector and Size for Hidden.Directory (Sector=0018h, Size=60E0h)
  14001   00Ch 2+2  Sector and Size for Hidden.Unknown   (Sector=0025h, Size=0022h)
  14002   010h 10h  Zerofilled
  14003   020h 0Ch  Title ID ("CHRONOCROSS",00h)      ;Chrono Cross (retail)
  14004        09h  Title ID ("DEWPRISM",00h)         ;Threads of Fate (retail)
  14005        10h  Title ID ("DEWPRISM_TAIKEN",00h)  ;Threads of Fate (demo)
  14006   0xxh 7xxh Zerofilled (unused, since Hidden.ID has only Size=2Ch/29h/30h)
  14007  Sector 18h..24h (Hidden.Directory)
  14008   000h N*4  File List entries
  14009   ...  ..   Zeropadding (till Size=60E0h, aka 6200 entries)
  14010   ...  720h Zeropadding (till end of 800h-byte sector)
  14011  Sector 25h (Hidden.Unknown)
  14012   Seems to contain a list of 16bit indices 0000h..1791h,FFFFh in File List
  14013   (though many of the listed indices are unused file list entries)
  14014   000h 2    Disc Number      (0001h=Disc 1, 0002h=Disc 2)
  14015   002h 10h  Unknown 0000 1791 1777 1775 00ED 09DF FFFF 0002    ;\same on
  14016   012h 10h  Unknown 0025 0943 10E3 FFFF FFFF 0C77 0FD9 0FA3    ;/Disc 1+2
  14017   022h ..   Zerofilled (unused, since Hidden.ID has only Size=0022h)
  14018  Sector 26h  1st file (same as boot EXE in ISO)
  14019 File List entries:
  14020   0-22   Sector number
  14021   23     Flag (0=Normal, 1=Unused entry)
  14022   24-31  Number of unused bytes in last sector, div8 (0..FFh = 0..7F8h bytes)
  14023 The directory is just a huge list of root files (without any folder structure;
  14024 many of the root files do contain DOT1 child archives though).
  14025 Root entry 0000h and 0001h are aliases for ISO files boot EXE and SYSTEM.CNF.
  14026 Filesizes can be computed as follows (that works for all entries including last
  14027 used entry; which is followed by some unused entries with bit23=1):
  14028   filesize = ([addr+4]-[addr] AND 7FFFFFh)*800h - ([addr+3] AND FFh)*8
  14029 Unused entries with bit23=1 have Sector pointing to end of previous file
  14030 (needed for filesize calculation). There are some zeropadded entries at end of
  14031 list (with whole 32bit zero). There are hundreds of dummy txt files (24-byte
  14032 "It's CDMAKE Dummy!",0Dh,0Ah,,0Dh,0Ah,20h and File08xxh: 8-byte "dummy",0,0,0)
  14033 although those are real used file entries, each occupying a whole separate
  14034 800h-byte sector.
  14035 
  14036 Threads of Fate (demo version) (MagDemo33: TOF\DEWPRISM.HED+.EXE+.IMG)
  14037 The demo version is using the same directory format as retail version (but with
  14038 Virtual Sector numbers in HED+EXE+IMG files instead of Hidden Sectors).
  14039   TOF\DEWPRISM.HED (6000h bytes)    VirtSector=1Ah,  PhysSector=A0A5h
  14040   TOF\DEWPRISM.EXE (97800h bytes)   VirtSector=26h,  PhysSector=A0B1h
  14041   TOF\DEWPRISM.IMG (19EA800h bytes) VirtSector=155h, PhysSector=A1E0h
  14042 The demo's Virtual Sectors start at 1Ah (instead of 17h), to convert them to
  14043 Physical Sectors: Subtract 1Ah, then add starting Sector Number of HED file.
  14044 The HED file contains Hidden.ID, Hidden.Directory, and Hidden.Unknown.
  14045 
  14046 CDROM File Archive HED/DAT/BNS/STR (Ape Escape)
  14047 -----------------------------------------------
  14048 
  14049 Ape Escape KKIIDDZZ.HED/.DAT/.BNS/.STR
  14050   000h 52Ch List for .DAT file    ;value 0000h..6FFFh = sector 0..6FFFh in DAT
  14051   52Ch D4h  Zerofilled
  14052   600h C4h  List for .BNS file    ;value 7000h..71AFh = sector 0..1AFh in BNS
  14053   6C4h 3Ch  Zerofilled
  14054   700h 50h  List for .STR file(s) ;raw CDROM sector numbers from 00:02:00
  14055   750h B0h  Zerofilled
  14056 List entries, for all three lists (32bit values):
  14057   0-19   File Offset/800h (20bit)
  14058   20-31  File Size/800h   (12bit)
  14059 The sector numbers in DAT and BNS are basically counted from begin of the .DAT
  14060 file (which has 7000h sectors in retail version, and the .BNS file does follow
  14061 right thereafter on the next sector) (the demo version (MagDemo22: KIDZ\*) has
  14062 only 105Ah sectors in .DAT, and the BNS entries at offset 600h start with 105Ah
  14063 accordingly).
  14064 There are 29 STR files in DEMO\*.STR and STR\*.STR, and 20 of them (?) are
  14065 referenced in HED ? There are also several .ALL files in above folders.
  14066 Note: Most of the STR files in Ape Escape contain polygon animation streams
  14067 rather than BS compressed bitmaps. Ape Escape is (c)1999 by Sony.
  14068   .HED is 2048 bytes
  14069   .DAT is 58720256 bytes = 3800000h bytes  ;div800h would be 7000h
  14070   .BNS is 884736 bytes = D8000h bytes      ;div800h would be 1B0h
  14071   .STR's: 7D3Bh+150 = 7DD1h = sector for STR\LAB.STR
  14072 Some files contain RLE compressed TIMs:
  14073 --> CDROM File Compression TIM-RLE4/RLE8
  14074 Some files contain raw headerless SPU-ADPCM (eg. DAT file 00Ah).
  14075 
  14076 CDROM File Archive WAD.WAD, BIG.BIN, JESTERS.PKG (Crash/Herc/Pandemonium)
  14077 -------------------------------------------------------------------------
  14078 
  14079 Below are two slightly different formats. WAD.WAD has unused entries
  14080 00h-filled. The PKG format has them FFh-filled, and does additionally support
  14081 Folders, and does have a trailing ASCII string. There's also a difference on
  14082 whether or not to apply alignment to empty 0-byte files.
  14083 However, the formats can appear almost identical (unused entries, 0-byte files,
  14084 and folders are optional, without them, the only difference would be the
  14085 presence of the ASCII string; which does exist only in 800h-byte aligned PKG's
  14086 though).
  14087 
  14088 WAD.WAD (Crash/Crash)
  14089 Used by Crash Bandicoot 3 (DRAGON\WAD.WAD, plus nested WADs inside of WAD.WAD)
  14090 Used by Crash Team Racing (SPYR02\WAD.WAD, plus nested WADs inside of WAD.WAD)
  14091 Used by Madden NFL'98 (MagDemo02: TIBURON\.DAT except PORTRAIT,SPRITES,XA.DAT)
  14092 Used by N2O (MagDemo09, N2O\PSXMAP.TRM and N2O\PSXSND.SND)
  14093 Used by Speed Racer (MagDemo10: SPDRACER\ALL1.BIN, with 0-byte, unpadded eof)
  14094 Used by Gran Turismo 2 (MagDemo27: GT2\GT2.OVL = 128Kbyte WAD.WAD with GZIP's)
  14095 Used by Jonah Lomu Rugby (LOMUDEMO\SFX\*.VBS, ENGLISH\*.VBS)
  14096 Used by Judge Dredd (*.CAP and *.MAD)
  14097 Used by Spyro 2 Ripto's Rage (SPYRO2\WAD.WAD, and nested WAD's therein)
  14098 Used by Spyro 3 Year of the Dragon (SPYRO3\WAD.WAD, and nested WAD's therein)
  14099 Used by Men: Mutant Academy (MagDemo33: PSXDATA\WAD.WAD\*, childs in PWF)
  14100   000h N*8  File List
  14101   ...  ..   Zeropadding to 4-byte or 800h-byte boundary (or garbage padding)
  14102   ...  ..   File Data...
  14103 The File List can contain Files, and Unused entries:
  14104   000h 4    Offset in bytes (4- or 800h-byte aligned, increasing) ;\both zero
  14105   004h 4    Size in bytes (always multiples of 800h bytes)        ;/when Unused
  14106 The Offset in first entry implies size of the File List (the list has no
  14107 end-marker other than the following zeropadding; which doesn't always exist,
  14108 ie. not in 4-byte aligned files, and not in case of garbage padding).
  14109 The last entry has Offset+Size+Align = Total WAD filesize (except, Speed Racer
  14110 doesn't have alignment padding after the last file).
  14111 The WAD.WAD format doesn't have folder entries, however, it is often used with
  14112 nested WADs inside of the main WAD, which is about same as folders.
  14113 The alignment can be 4-byte or 800h-byte: N2O uses 4-byte for the main WADs.
  14114 Madden NFL '98 uses 800h-byte for main WAD and 4-byte for child WADs (file
  14115 08h,0Ah,0Ch in TIBURON\MODEL01.DAT and file 76h in PIX01.DAT). Crash Bandicoor
  14116 3 and Crash Team Racing use 800h-byte for both main & child WADs (although with
  14117 garbage padding instead of zeropadding in child WAD headers).
  14118 Unused entries have Offset=0, Size=0.
  14119 Empty 0-byte files (should) have Size=0 and Offset=PrevOffs+PrevSize+Align
  14120 (except, Speed Racer has Offset=PrevOffs+PrevSize, ie. without Align for 0-byte
  14121 files).
  14122 
  14123 X-Men: Mutant Academy (MagDemo33,50: PSXDATA\WAD.WAD)
  14124 This does resemble standard WAD.WAD, but with leading 800h-byte extra stuff.
  14125   000h 4     ID ("PWF ")                                ;\
  14126   004h 4     Total Filesize (707800h)                   ;
  14127   008h 4     Unknown (1)                                ; extra stuff
  14128   00Ch 4     Number of files (N)                        ;
  14129   010h 7F0h  Zerofilled                                 ;/
  14130   800h N*8   File List                                  ;\
  14131   ...  ..    Zerofilled (padding to 800h-byte boundary) ; standard WAD.WAD
  14132   ...  ..    File Data area                             ;/
  14133  File List entries:
  14134   000h 4     File Offset in bytes (increasing, 800h-byte aligned)
  14135   004h 4     File Size in bytes
  14136 The archive contains child archives in DOT1 format, and in standard WAD.WAD
  14137 format (without PWF header).
  14138 
  14139 PKG (Herc/Pandemonium/UnholyWar)
  14140 Used by Pandemonium II (JESTERS.PKG, with Files+Folders+Unused entries)
  14141 Used by Herc's Adventure (BIG.BIN, with Files+Unused entries, without Folders)
  14142 Used by Unholy War (MagDemo12:CERBSAMP.PKG, with 0-byte files and nested PKG's)
  14143 Used by 102 Dalmatians (MagDemo40: PTTR\PSXDEMO.PKG)
  14144   000h N*8  File List
  14145   ...  ..   ASCII string (junk, but somewhat needed as nonzero end marker)
  14146   ...  ..   Zeropadding to 800h-byte boundary; not in 4-byte aligned nested PKG
  14147   ...  ..   File Data...
  14148 The File List can contain Files, Folders, and Unused entries. The overall
  14149 format of the list entries is:
  14150   000h 4    Offset in bytes (increasing, or 0=First child)  ;\both FFFFFFFFh
  14151   004h 4    Size in bytes (always nonzero)                  ;/when Unused
  14152 Files and Folders do have exactly the same format, the only difference is that
  14153 Folders will have Offset=00000000h in the NEXT list entry (in other words, the
  14154 folder entry is followed by child entries, which start with Offset=0).
  14155 Offsets for Root entries are 800h-byte aligned, relative to begin of PKG file.
  14156 Offsets for Child entries are 4-byte aligned, relative to Parent Folder Offset.
  14157 The last Child entry has Offset+Size+Align(4) = Parent Folder Size.
  14158 The last Root entry has Offset+Size+Align(800h) = Total PKG filesize.
  14159 The last Root entry is usually followed by the ASCII string (which looks like
  14160 junk, but it is useful because it equals to NextOffset=Nonzero=NoChilds).
  14161   Example
  14162   00003800h,00000666h   ;root00h          (file 666h bytes, padded=800h)
  14163   00004000h,00000300h   ;root01h\..       (folder 300h bytes, padded=800h)
  14164   00000000h,000000FDh   ;root01h\child00h (file FDh bytes, padded=100h)  ;\300h
  14165   FFFFFFFFh,FFFFFFFFh   ;root01h\child01h (unused)                       ; byte
  14166   00000100h,000001FDh   ;root01h\child02h (file 1FDh bytes, padded=200h) ;/
  14167   00004800h,00001234h   ;root02h          (file 1234h bytes, padded=1800h)
  14168   00006000h,00001234h   ;root03h          (file 1234h bytes, padded=1800h)
  14169   FFFFFFFFh,FFFFFFFFh   ;root04h          (unused)
  14170   00007800h,00001234h   ;root05h          (file 1234h bytes, padded=1800h)
  14171   etc.
  14172 Notes: Unused entries can occur in both root and child folders (except, of
  14173 course, not as first or last entry in child folders). Folders seem to occur
  14174 only in root folder (although the format would allow nested folders).
  14175 Alternately, instead of Folders, one can use nested PKG's (the nested ones are
  14176 using 4-byte align, without ASCII string and zeropadding in header).
  14177 
  14178 CDROM File Archive BIGFILE.BIG (Gex)
  14179 ------------------------------------
  14180 
  14181 Gex (GXDATA\BIGFILE.BIG and nested BIG files therein)
  14182   000h 4     Number of Files (eg. F4h)
  14183   004h 0Ch   Zero
  14184   010h N*10h File entries
  14185   ...  4     Archive ID (eg. 00000000h, FF53EC8Bh, or 83FFFFFFh)
  14186   ...  ..    Zeropadding to 800h byte boundary
  14187   ...  ..    File Data
  14188 File Entries:
  14189   000h 4   Archive ID (same value as in above header)
  14190   004h 4   Filename checksum or so (randomly ordered, not increasing)
  14191   008h 4   Filesize in bytes
  14192   00Ch 4   Fileoffset (800h-byte aligned) (increasing)
  14193 Filetypes in the archive include...
  14194   looks like a lot of raw data without meaningful file headers...
  14195   file C3h,ECh are raw SPU-ADPCM
  14196   file 08h,09h are nested BIG archives, but with FileEntry[00h]=FF53EC8Bh
  14197   file D9h,DAh are nested BIG archives, but with FileEntry[00h]=83FFFFFFh
  14198 FileEntry[04h] sometimes has similar continous values (maybe caused by similar
  14199 filenames, and using a simple checksum, not CRC32).
  14200 
  14201 CDROM File Archive BIGFILE.DAT (Gex - Enter the Gecko)
  14202 ------------------------------------------------------
  14203 
  14204 Gex - Enter the Gecko - BIGFILE.DAT
  14205 Used by Gex 2: Enter the Gecko (BIGFILE.DAT)
  14206 Used by Gex 3: Deep Cover Gecko (MagDemo20: G3\BIGFILE.DAT) -- UNSORTED
  14207 Used by Akuji (MagDemo18: AKUJI\BIGFILE.DAT)
  14208 Used by Walt Disney World Racing Tour (MagDemo35: GK\BIGFILE.DAT) -- UNSORTED
  14209   000h 4     Number of Files      (C0h)
  14210   004h N*18h File entries
  14211   ...  ..    Zeropadding to 800h byte boundary
  14212   ...  ..    File Data
  14213 File Entries:
  14214   000h 4     Random
  14215   004h 4     Filesize in bytes (uncompressed size)
  14216   008h 4     Filesize in bytes (compressed size, or 0=uncompressed)
  14217   00Ch 4     Fileoffset (800h-byte aligned) (increasing, unless UNSORTED)
  14218   010h 4     Random
  14219   014h 4     Random (or ascii in 1st file)
  14220 LZ Decompression:
  14221   @@collect_more:
  14222    flagbits=[src]+[src+1]*100h+10000h, src=src+2    ;16bit flags, unaligned
  14223   @@decompress_lop:
  14224    if dst>=dst.end then goto @@decompress_done
  14225    flagbits=flagbits SHR 1
  14226    if zero then goto @@collect_more
  14227    if carry=0 then
  14228      [dst]=[src], dst=dst+1, src=src+1
  14229    else
  14230      len=([src] AND 0Fh)+1), disp=([src] AND 0F0h)*10h+[src+1], src=src+2
  14231      if len=1 or disp=0 then goto invalid   ;weirdly, these are left unused
  14232      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  14233    endif
  14234    goto @@decompress_lop
  14235   @@decompress_done:
  14236    ret
  14237 Filetypes in the archive include...
  14238   standard TIM  (eg. file 01h,02h)
  14239   malformed TIM (eg. file 0Fh,14h) (with [8]=2*cx*cy+4 instead 2*cx*cy+0Ch)
  14240   crippled VAB  (eg. file 0Eh,13h) (with hdr=filesize-4 plus raw ADPCM samples)
  14241   several DNSa  (eg. file 0Dh,12h,17h,BCh) SND sound? (also used by kain)
  14242   PMSa          (eg. Gex 3, World Racing) (SMP spu-adpcm samples)
  14243   there seem to be no nested DAT files inside of the main DAT file
  14244 Note: same malformed TIMs are also in Legacy of Kain (folder0004h\file0013h).
  14245 
  14246 CDROM File Archive FF9 DB (Final Fantasy IX)
  14247 --------------------------------------------
  14248 
  14249 DB Archive
  14250   000h 1   ID (DBh)
  14251   001h 1   Number of Types
  14252   002h 2   Zero (0)
  14253   004h N*4 Type List
  14254   ...  ..  File Lists & File Data for each Type
  14255 Type List entries:
  14256   000h 3   Offset to File List (self-relative, from current entry in Type List)
  14257   003h 1   Data Type (00h..1Fh)
  14258 File List:
  14259   000h 1   Data type (00h..1Fh) (same as in Type List)
  14260   001h 1   Number of Files
  14261   002h 2   Zero (0)
  14262   004h N*2 File ID List (unique ID per type) (different types may have same ID)
  14263   ...  ..  Zeropadding to 4-byte boundary
  14264   ...  N*4 Offset List (self-relative, from current entry in Offset List)
  14265   ...  4   End Offset  (first-relative, from first entry in Offset List)
  14266   ...  ..  File Data (referenced from above Offset List)
  14267 
  14268 Data Types
  14269   00h  Misc (DOT1 Archives, or other files)
  14270   01h  Unused?
  14271   02h  Reportedly 3D Model data (vertices,quads,triangles,texcoords)
  14272   03h  Reportedly 3D Animation sequences
  14273   04h  TIM Texture
  14274   05h  Reportedly Scripts (hdr="EV")              (eg. dir04\file32\1B-0001)
  14275   06h  ?                                          (eg. dir02\file*)
  14276   07h  Sound "Sequencer Data" (hdr="AKAO")        (eg. dir09\file*)
  14277   08h  Sound? tiny files (hdr="AKAO")             (eg. dir04\file32\1B-0001)
  14278   09h  Sound Samples (hdr="AKAO")                 (eg. dir0B\file*)
  14279   0Ah  Reportedly Field Tiles and Field Camera parameters
  14280   0Bh  Reportedly Field Walkmesh                  (eg. dir04\file32\1B-0001)
  14281   0Ch  Reportedly Battle Scene geometry           (eg. dir06\file*)
  14282   0Dh  ?                                          (eg. dir01\file01)
  14283   0Eh  Unused?
  14284   0Fh  Unused?
  14285   10h  ?                                          (eg. dir05\file*)
  14286   11h  ?                                          (eg. dir05\file*)
  14287   12h  Reportedly CLUT and TPage info for models  (eg. dir04\file32\1B-0001)
  14288   13h  Unused?
  14289   14h  ?                                          (eg. dir05\file*)
  14290   15h  Unused?
  14291   16h  ?  (eg. dir04\file32\1B-0001)
  14292   17h  ?  (eg. dir04\file32\1B-0000)
  14293   18h  Sound (hdr="AKAO")  (eg. dir04\file32\1B-0001)
  14294   19h  ?  (eg. dir04\file32\1B-0001)
  14295   1Ah  ?  (eg. dir06\file*)
  14296   1Bh  DB Archives (ie. further DB's nested inside of the parent DB archive)
  14297   1Ch  ?  (eg. dir04\file32\1B-0001)
  14298   1Dh  ?  (eg. dir03\file2328\1B-0001)
  14299   1Eh  ?  (eg. dir04\file32\1B-0001)
  14300   1Fh  ?  (eg. dir04\file32\1B-0001)
  14301   20h..FFh Unused?
  14302 
  14303 CDROM File Archive Ace Combat 2 and 3
  14304 -------------------------------------
  14305 
  14306 Ace Combat 2 (Namco 1997) (ACE2.DAT and ACE2.STH/STP)
  14307 There are two archives, stored in three files:
  14308   ACE2.DAT Directory for Data in ACE2.DAT itself         ;normal binary data
  14309   ACE2.STH Directory for Data in separate ACE2.STP file  ;streaming data
  14310 Directory Format:
  14311   000h 4    Unknown (1)
  14312   004h 4    Number of entries (N)
  14313   008h N*8  File List
  14314 File List entries (64bit):
  14315   0-27   28bit Size/N (DAT=Size/4, STP=Size/800h)
  14316   28-31  4bit  Type or Channel Number (see below)
  14317   32-63  32bit Offset/800h in ACE2.STP or ACE2.DAT file
  14318 The files are interleaved depending on the Type/Channel number:
  14319   File    Bit28-31 Channel Sector types...             Interleave Notes
  14320   DAT     0        ch=0    DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD 1:1   data (normal)
  14321   DAT     2        ch=0    DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD 1:1   data (exe)
  14322   STH     0-6      ch=0-6  S.......S.......S.......S....... 1:8   stereo
  14323   STH     8        ch=1    vvvvvvvSvvvvvvvSvvvvvvvSvvvvvvvS 1:1   video+stereo
  14324   Whereas D=data, S=Stereo/Audio, v=video, .=other channels
  14325 Note: The DAT file does additionally contain PreSizeDOT1 and DOT1 child
  14326 archives.
  14327 Demo: The archives in demo version (MagDemo01: ACE2.*) contain only a handful
  14328 of files; the two EXE files in demo DAT archive are only 800h-byte dummy files,
  14329 and demo STP is corrupted: Recorded as CDROM image with 920h-byte sectors,
  14330 instead of as actual CD-XA sectors).
  14331 
  14332 Ace Combat 3 Electrosphere (Namco 1999) (ACE.BPH/BPB and ACE.SPH/SPB)
  14333 There are two archives, stored in four files:
  14334   ACE.BPH Directory for Data in separate ACE.BPB file  ;normal binary data
  14335   ACE.SPH Directory for Data in separate ACE.SPB file  ;streaming data
  14336 Directory Format:
  14337   000h 4    ID "AC3E" (=Ace Combat 3 Electrosphere)
  14338   004h 4    Type (BPH=3=Data?, SPH=1=Streaming?)
  14339   008h 2    BCD Month/Day?     (Japan=0427h, US=1130h)
  14340   00Ah 2    BCD Year (or zero) (SPH=1999h, BPH=0)
  14341   00Ch 4    Unknown (SPH=0, BPH/US=16CFh or BPH/JP=1484h)
  14342   010h 4    Number of entries (N)
  14343   014h N*8  File List
  14344 File List entries (64bit), when Bit31=1 (normal entries):
  14345   0-18   19bit Size/N           (BPH=Size/4, SPB=Size/800h)
  14346   19-23  5bit  Channel Number   (BPH=0, SPH=0..1Fh)
  14347   24-26  3bit  Channel Interval (BPH=0, SPH=1 SHL N, eg. 3=Interval 1:8)
  14348   27     1bit  Video Flag       (0=No, 1=Has Video sectors)
  14349   28     1bit  Audio Flag       (0=No, 1=Has Audio sectors)
  14350   29     1bit  Always 1 (except special entries with Bit31=0, see below)
  14351   30     1bit  Unknown (US: Always 1, Japan: 0 or 1)
  14352   31     1bit  Always 1 (except special entries with Bit31=0, see below)
  14353   32-63  32bit Offset/800h in ACE.BPB or ACE.SPB file   (or 0 when bit31=0 ?)
  14354 File List entries (64bit), when Bit31=0:
  14355   For unknown purpose, the normal entries with Bit31=1 are occassionally  
  14356 followed by one or more entries with Bit31=0.
  14357   Unknown if those entries do affect the actual storage (like switching to
  14358   different channel numbers, or jumping to non-continous sector numbers).
  14359   That unknown stuff exists in Japanese version only, not in US version.
  14360   0-18   19bit Unknown (maybe some snippet size value in whatever units?)
  14361   19-23  5bit  Always 0     (instead of Channel)
  14362   24-27  4bit  Same as in most recent entry with Bit31=1
  14363   28-31  4bit  Always 5     (instead of Flags)
  14364   32-63  32bit Always 0     (instead of Offset)
  14365 The files are interleaved depending on the Channel Interval setting (and with
  14366 types data/audio/video depending on Flags).
  14367   File    Bit24-31    Sector types...                  Interval  Content
  14368   BPH.US  E0h         DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD 1:1       data
  14369   SPH.US  F8h         SvvvvvvvSvvvvvvvSvvvvvvvSvvvvvvv 1:1       stereo+video
  14370   SPH.US  FBh         S.......v.......S.......v....... 1:8       stereo+video
  14371   SPH.US  F3h         S.......S.......S.......S....... 1:8       stereo
  14372   SPH.US  F4h         S...............S............... 1:16      stereo
  14373   SPH.US  F5h         M............................... 1:32      mono
  14374   BPH.JAP E0h         DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD 1:1       data
  14375   SPH.JAP B8h,F8h     SvvvvvvvSvvvvvvvSvvvvvvvSvvvvvvv 1:1       stereo+video
  14376   SPH.JAP B9h         Svvv....vvvv....Svvv....vvvv.... 1:2       stereo+video
  14377   SPH.JAP BAh,FAh     Mv......vv......vv......vv...... 1:4 (4:8) mono+video
  14378   SPH.JAP BBh,FBh     S.......v.......S.......v....... 1:8 (2:8) stereo+video
  14379   SPH.JAP B3h,F3h     S.......S.......S.......S....... 1:8       stereo
  14380   SPH.JAP B5h,F5h     M............................... 1:32      mono
  14381   Whereas D=data, S=Stereo/Audio, M=Mono/Audio, v=Video, .=Other channels
  14382 As shown above, interval 1:2 and 1:4 are grouped as 4:8 and 2:8 (ie. 4 or 2
  14383 continous sectors per 8 sectors).
  14384 The Subheader's Channel number is specified in the above directory entries,
  14385 Subheader's File number is fixed (0 for BPB, and 1 for SPB).
  14386 --> CDROM XA Subheader, File, Channel, Interleave
  14387 The SPB file is about 520Mbyte in both US and Japan, however, the Japanese
  14388 version does reportedly contain more movies and some storyline that is missing
  14389 in US/EU versions.
  14390 The BPB file contains DOT1 child archives, and Ulz compressed files.
  14391 --> CDROM File Compression Ulz/ULZ (Namco)
  14392 The SPB file contains movies with non-standard STR headers (and also uncommon:
  14393 interleaved videos on different channels, at least so in the japanese version).
  14394 Demo: The archives do also exist on the demo version (MagDemo30: AC3\*), but
  14395 the .SPB file is corrupted: Recorded as a RIFF/CDXAfmt file, instead of as
  14396 actual CD-XA sectors).
  14397 
  14398 CDROM File Archive NSD/NSF (Crash Bandicoot 1-3)
  14399 ------------------------------------------------
  14400 
  14401 NSD/NSF versions
  14402   v0  Crash Bandicoot Prototype (oldest known prototype from 08 Apr 1996)
  14403   v1  Crash Bandicoot 1         (retail: S*\*.NSD and .NSF)
  14404   v2  Crash Bandicoot 2         (MagDemo02: CRASH\S0\*.NSD and .NSF)
  14405   v3  Crash Bandicoot 3 Warped  (MagDemo26,50: (S0\*.NSD and .NSF)
  14406 
  14407  ____________________________________ NSD _____________________________________
  14408 
  14409 Overall NSD Structure (v0 contains only the Lookup entries)
  14410   0000h 100h*4  Lookup Table, using index=((Filename/8000h) AND FFh) ;\
  14411   0400h 4       Number of Chunks in .NSF file                        ; Lookup
  14412   0404h 4       Number of Files in Lookup File List (N)              ;/
  14413   0408h 4       Level Data Filename (eg. 4F26E8DFh="DATh.L")         ;-LevelDat
  14414   040Ch 4       Bitmap Number of Colors (100h) (P) (0=None)          ;\
  14415   0410h 4       Bitmap Width    (200h or 1B0h) (X) (0=None)          ; Bitmap
  14416   0414h 4       Bitmap Height   (0D8h or 090h) (Y) (0=None)          ;/
  14417   0418h 4       Compression: Offset/800h of first uncompressed chunk ;\
  14418   041Ch 4       Compression: Number of compressed chunks (0..40h)    ; Compress
  14419   0420h 40h*4   Compression: Compressed Chunk List (0=unused entry)  ;/
  14420   ...   N*8     Lookup File List                                     ;-Lookup
  14421   ...   ..      Level Data (size/format varies, see below)           ;-LevelDat
  14422   ...   P*2     Bitmap Palette (16bit values, 8000h..FFFFh)          ;\Bitmap
  14423   ...   X*Y     Bitmap Pixels  (0D8h*200h)                           ;/
  14424 There are four .NSD versions, which can be distinguished via filesize:
  14425   v0  NSD Filesize=408h + N*8                           ;-Lookup only
  14426   v1  NSD Filesize=520h + N*8 + P*2+X*Y + 210h          ;\
  14427   v2  NSD Filesize=520h + N*8 + P*2+X*Y + 1DCh+S*18h    ; with extra stuff
  14428   v3  NSD Filesize=520h + N*8 + P*2+X*Y + 2DCh+S*18h    ;/
  14429 Note: v0 is mainly used by the Crash Bandicoot prototype, but the Crash
  14430 Bandicoot 1 retail version does also have a few v0 files.
  14431 
  14432 NSD Lookup
  14433 The lookup table allows to find files (by filenames) in the NSF files. It does
  14434 merely contain the NSF chunk number, so one must load/decompress that chunk to
  14435 find the file's exact size/location in that chunk.
  14436 One can create a complete file list by scanning the whole NSF file without
  14437 using the NDS lookup table.
  14438  Lookup File List entries (indexed via Lookup Table):
  14439   00h 4   Chunk Number in .NSF file
  14440   04h 4   Filename (five 6bit characters)
  14441 Filenames:
  14442   0     Type (always 1=Filename) (as opposed to 0=Memory Pointer)
  14443   1-6   5th character ;-Extension  ;\character set is:
  14444   7-12  4th character ;\           ; 00h..09h="0..9"
  14445   13-18 3rd character ; Name       ; 0Ah..23h="a..z"
  14446   19-24 2nd character ;            ; 24h..3Dh="A..Z"
  14447   25-30 1st character ;/           ;/3Eh..3Fh="_" and "!"
  14448   31    Always zero?
  14449 Special name: 6396347Fh="NONE.!"
  14450 
  14451 NSD Level Data
  14452 Level Data exists in NSD v1-v3 (v0 does also have Level Data, but it's stored
  14453 in NSF file "DAT*.L" instead of in the NSD file). There are two major versions:
  14454  Level Data in NSD v1 (or NSF v0 file DAT*.L):
  14455   000h  4       01h                                                  ;\
  14456   004h  4       Level Number (xxh) (same as xx in S00000xx.NSD/NSF)  ;
  14457   008h  4       3807C8FBh = "s0_h.Z" ?                               ; LevelDat
  14458   00Ch  4       Zero                                                 ; v1
  14459   010h  4       Zero                                                 ;
  14460   014h  L*4     Namelist (40h*4)                                     ;
  14461   ...   4       5Ah                                                  ;
  14462   ...   F8h     Zerofilled                                           ;/
  14463  Level Data in NSD v2-v3:
  14464   000h  4       Number of Spawn Points (S)                           ;\
  14465   004h  4       Zero                                                 ;
  14466   008h  4       Level Number (xxh) (same as xx in S00000xx.NSD/NSF)  ; LevelDat
  14467   00Ch  4       Number of Objects? (can be bigger than below list)   ; v2/v3
  14468                   (eg. 1BDh or A5h or E4h)                           ;
  14469   010h  L*4     Namelist for Objects?  (v2=40h*4, or v3=80h*4)       ;
  14470   ...   4       Unknown, always 5Ah (maybe just list end marker?)    ;
  14471   ...   C8h     Zerofilled                                           ;
  14472   ...   S*18h   Spawn Points                                         ;/
  14473 
  14474 NSD Bitmap
  14475 This bitmap is displayed while loading the level.
  14476 
  14477 NSD Compression Info
  14478 Compression is only used in v1 (v2-v3 do also have the compression entries at
  14479 [418h..51Fh], but they are always zerofilled).
  14480  Compressed Chunk List entries at [420h..51Fh]:
  14481   0-5   Compressed Chunk Size/800h (1..1Fh=800h..F800h bytes, 20h..3Fh=Bad?)
  14482   6-31  Compressed Chunk Offset/800h
  14483 Note: Crash Bandicoot 1 retail does also have a few uncompressed files (either
  14484 v0 files without compression info, or v1 files with zerofilled compression
  14485 info).
  14486 
  14487  ____________________________________ NSF _____________________________________
  14488 
  14489 NSF files consist of 64Kbyte chunks (compressed chunks are smaller, but will be
  14490 64Kbyte after decompression). Each chunk can contain one or more file(s). That
  14491 implies that all files must be smaller than 64Kbyte (larger textures or ADPCM
  14492 samples must be broken into multiple smaller files).
  14493 All files (except Textures) are NSF Child Archives which contain one or more
  14494 smaller files/items.
  14495 
  14496 NSF Chunk Types
  14497  N*8Kbyte-Compressed-chunks:
  14498   000h 2    ID, always 1235h (instead of 1234h)
  14499   002h 2    Zero
  14500   004h 4    Decompressed Size (max 10000h) (usually 9xxxh..Fxxxh, often Fxxxh)
  14501   008h 4    Skip Size (max 40h or so, when last LZSS_len was 40h)
  14502   00Ch ..   Compressed data
  14503   ...  SK   Unused (Skip size)
  14504   ...  ..   Final uncompressed bytes (10000h-compressed_size-skip_size)
  14505  64Kbyte-Texture-chunks:
  14506   000h 2    ID, always 1234h
  14507   002h 2    Chunk Family (1=Texture)
  14508   004h 4    Filename (five 6bit characters)
  14509   008h 4    File Type (5=Texture)
  14510   00Ch 4    Checksum (sum of bytes ar [0..FFFFh], with initial [0Ch]=00000000h)
  14511   010h ...  Zerofilled
  14512   020h ...  Texture data (raw VRAM data, FFE0h bytes?)
  14513  64Kbyte-NonTexture-chunks:
  14514   000h 2    ID, always 1234h
  14515   002h 2    Chunk Family (0=Misc or 2..5=Sound)
  14516   004h 4    Chunk Number*2+1
  14517   008h 4    Number of Files (N) (can be 0, eg. prototype S0000003 chunk21h)
  14518   00Ch 4    Checksum (sum of bytes ar [0..FFFFh], with initial [0Ch]=00000000h)
  14519   010h N*4  File List (Offsets from ID=1234h to entries) (4-byte aligned)
  14520   ...  ..   Offset for end of last File
  14521   ...  ..   File Data (NSF Child Archives) (includes Type/Filename)
  14522   ...  ..   Padding to 10000h-byte boundary
  14523 
  14524 NSF Child Archives
  14525   000h 4    ID, always 0100FFFFh
  14526   004h 4    Filename (five 6bit characters)
  14527   008h 4    File Type (01h..04h, or 06h..15h)
  14528   00Ch 4    Item Count (I)
  14529   010h I*4  Item List (Offsets from ID=0100FFFFh to items) (...unaligned?)
  14530   ...  ..   Offset for end last item
  14531   ...  ..   Data (Items)
  14532 
  14533 NSF Chunk Loading and Decompression
  14534 The compression is a mixup of LZSS and RLE. Compressed chunks are max F800h
  14535 bytes tall (10000h bytes after decompression).
  14536   dst=chunk_buffer_64kbyte
  14537   if chunksize is known (from NSD file)
  14538     src=dest=dst+10000h-chunksize
  14539     diskread(fpos,src,chunksize)
  14540   else (when parsing raw NSF file without NSD file)
  14541     src=temp_buffer_64kbyte
  14542     diskread(fpos,src,10000h)
  14543   dst_start=dst, src_start=src
  14544   if halfword[src+00h]<>1234h then   ;check ID (1234h=raw, or 1235h=compressed)
  14545     dst_end=dst+word[src+04h]
  14546     skip_size=word[src+08h]
  14547     src=src+0Ch
  14548     while dst<dst_end
  14549       x=[src], src=src+1
  14550       if x<80h then
  14551         for i=0 to x-1, [dst]=[src], dst=dst+1, src=src+1, next i ;uncompressed
  14552       else
  14553         x=(x AND 7Fh)*100h+[src], src=src+1
  14554         disp=x/8, len=(x AND 7)+3, if len=0Ah then len=40h
  14555         for i=0 to len-1, [dst]=[dst-disp], dst=dst+1, next i     ;compressed
  14556     src=src+src_skip
  14557   if src<>dst then
  14558     while dst<dst_start+10000h, [dst]=[src], dst=dst+1, src=src+1 ;uncompressed
  14559   chunksize=src-src_start  ;<-- compute (when chunksize was unknown)
  14560   fpos=fpos+chunksize      ;<-- fileposition of next chunk
  14561 As shown above, the chunk is intended to be loaded to the end of the
  14562 decompression buffer, so trailing uncompressed bytes would be already in place
  14563 without needing further relocation (despite of that intention, the actual game
  14564 code is uselessly relocating src to dst, even when src=dst).
  14565 Note: All compressed files seem to have an uncompressed copy with same filename
  14566 in another chunk (the NSD Lookup table does probably(?) point to the compressed
  14567 variant, which should reduce CDROM loading time).
  14568 
  14569  _________________________________ Filetypes __________________________________
  14570 
  14571 Filetype Summary
  14572 Below shows File Type, Chunk Family, Extension (5th character of filename), the
  14573 version where the type is used, 4-letter type names (as found in the EXE
  14574 files), and a more verbose description.
  14575   Typ Family Ext Ver  Name Description
  14576   00h -      !   -    NONE Nothing
  14577   01h 0      V   all  SVTX Misc.Vertices
  14578   02h 0      G   all  TGEO Misc.Model         ;\changed format in v2-v3 ?
  14579   03h 0      W   all  WGEO Misc.WorldScenery  ;/
  14580   04h 0      S   all  SLST Misc.UnknownSLST
  14581   05h 01h    T   all  TPAG Texture.VRAM
  14582   06h 0      L   v0   LDAT Misc.LevelData     ;-stored in NSD in v1-v3
  14583   07h 0      Z   all  ZDAT Misc.Entity        ;-changed format in v2-v3 ?
  14584   08h -      -   -    CPAT Internal?
  14585   09h -      -   -    BINF Internal?
  14586   0Ah -      -   -    OPAT Internal?
  14587   0Bh 0      C   all  GOOL Misc.GoolBytecode
  14588   0Ch 02h    A   v0   ADIO OldSound.Adpcm     ;\type 0Ch
  14589   0Ch 03h    A   all  ADIO Sound.Adpcm        ;/
  14590   0Dh 0      M   all  MIDI Misc.MidiMusic     ;-changed format in v1-v3 ?
  14591   0Eh 04h    N   all  INST Sound.Instruments
  14592   0Fh 0      D   v0-1 IMAG Misc.UnknownIMAG   ;\type 0Fh
  14593   0Fh 0      X   v2-3 VCOL Misc.UnknownVCOL   ;/
  14594   10h -      -   -    LINK Internal?
  14595   11h 0      P   v0-1 MDAT Misc.UnknownMDAT   ;\type 11h
  14596   11h 0      R   v3   RAWD Misc.UnknownRAWD   ;/
  14597   12h 0      U   v0-1 IPAL Misc.Unknown      ;-Crash 1 only? (eg. S0000019.NSF)
  14598   13h 0      B   v1-3 PBAK Misc.DemoPlayback ;-eg. in MagDemo02
  14599   14h 0      V   v0-1 CVTX Misc.UnknownCVTX   ;\type 14h
  14600   14h 05h    O   v2-3 SDIO Speech.Adpcm       ;/
  14601   15h 0      D   v2-3 VIDO Misc.UnknownVIDO
  14602 As shown above, Type 0Ch is used with family 02h/03h, and Type 0Fh,11h,14h have
  14603 two variants each (with different extensions). The Extensions do usually
  14604 correspong with the Types (although extension V,D are used for two different
  14605 types each).
  14606 
  14607 See also:
  14608 https://gist.github.com/ughman/3170834
  14609 https://dl.dropbox.com/s/fu29g6xn97sa4pl/crash2fileformat.html
  14610 
  14611 Weird Note
  14612 "Sound entries don't need to be aligned as strictly for most (all?) emulators."
  14613 What does that mean???
  14614 Is there a yet unknown 16-byte DMA alignment requirement on real hardware?
  14615 
  14616 CDROM File Archive STAGE.DIR and *.DAT (Metal Gear Solid)
  14617 ---------------------------------------------------------
  14618 
  14619 Metal Gear Solid (MagDemo13: MGS\*)
  14620 Metal Gear Solid (MagDemo25: MGS\*)
  14621 Metal Gear Solid (MagDemo44: MGS\*) (looks same as in MagDemo13)
  14622 Metal Gear Solid (Retail: MGS\*)
  14623 
  14624 Summary of ISO files in MGS folder (with filesizes for different releases)
  14625   File        MagDemo13/44 MagDemo25  Retail/PAL
  14626   .EXE        9C000h       9C800h     9D800h      ;-executable
  14627   STAGE.DIR   590800h      11A7800h   42AE000h    ;-main archive
  14628   FACE.DAT    2CA000h      3Dh (txt)  358800h     ;-face animation archive
  14629   ZMOVIE.STR  -            -          2D4E800h    ;-movie archive
  14630   DEMO.DAT    149B000h     3Dh (txt)  EC20000h    ;\DAT/SYM combos (the .SYM
  14631   DEMO.SYM    88h          -          -           ; files were leaked in
  14632   VOX.DAT     14F2000h     9F800h     B054800h    ; MagDemo13/MagDemo44 only)
  14633   VOX.SYM     988h         -          -           ;/
  14634   BRF.DAT     -            66800h     575800h     ;\whatever, unknown format(s)
  14635   RADIO.DAT   16CB8h       3Dh (txt)  1AA956h     ;/
  14636 
  14637 STAGE.DIR:
  14638   000h 4     Size of File List (N*0Ch)
  14639   004h N*0Ch Folder List
  14640   ...  ..    Zeropadding to 800h-byte boundary
  14641   ...  ..    Folder Data
  14642  Folder List entries:
  14643   000h 8     Foldername (zeropadded if less than 8 chars)  ;nickname=stg
  14644   008h 4     Offset/800h to File List
  14645  Folder Data (per folder):
  14646   000h 2     Unknown (always 1) (maybe File List size/800h?)
  14647   002h 2     Folder Size/800h (of whole folder, with file list plus file data)
  14648   004h N*8   File List
  14649   ...        Zeropadding to 800h-byte
  14650   800h       Data (for files in current folder)
  14651  File List entries:
  14652   000h 2     File ID (checksum on name)
  14653   002h 1     File Family (one of following chars: "cnrs")
  14654   003h 1     File Type   (one of following chars: "abcdeghiklmoprswz",FFh)
  14655   004h 4     File Size (or File Offset, when File Family="c")
  14656 Combinations of Family/Type characters are:
  14657   .?a    ???? if any ???? (does NOT exist on PAL disc 1)    ;nickname=azm
  14658   .sb    MIPS binary code  (leading)                        ;nickname=bin
  14659   .cc    Whatever          (eg. vr10\*, s01a\*)             ;nickname=con
  14660   .nd    Texture Archive   (leading) (contains PCX files)   ;nickname=dar
  14661   .rd    Misc Archive      (leading) (eg. init\*)           ;nickname=dar
  14662   .se    Sound Effects?    (trailing)                       ;nickname=efx
  14663   .cg    Whatever, reportedly bytecode functions            ;nickname=gcx
  14664   .ch    Whatever                                           ;nickname=hzm
  14665   .ci    Whatever          (eg. ending\*, s01a\*)           ;nickname=img
  14666   .ck    Whatever, model? aka "pat_xxx" files               ;nickname=kmd
  14667   .cl    Lights, first word = size/10h                      ;nickname=lit
  14668   .sm    Sound Music? Nested DOT1+DOTLESS Archives          ;nickname=mt3
  14669   .co    Whatever "OARa"   (eg. d16e\*, s00a\*, s02c\*)     ;nickname=oar
  14670   .cp    PCX bitmap        (eg. init\*)                     ;nickname=pcc
  14671   .cr    Whatever "sNRJ1F" (eg. roll\*)                     ;nickname=rar
  14672   .cs    Whatever          (eg. d16e\*, s01a\*)             ;nickname=sgt
  14673   .sw    Wave Archive      (trailing)                       ;nickname=wvx
  14674   .cz    Whatever "KMDa"   (eg. s11a, a11c, s14e, s15a)     ;nickname=zmd
  14675   .c,FFh End of Family="c" area                             ;nickname=dar?
  14676 Files are starting on 800h-byte boundaries. Files with Family="c" are special,
  14677 they contain an Offset entries instead of a Size entries, that Offsets are
  14678 4-byte aligned (relative to the 800h-byte aligned offset of the first
  14679 Family="c" entry), the list of Family="c" entries is terminated by an entry
  14680 with Family="c" and Type=FFh (which contains the end-offset of the last
  14681 c-Family entry, aka the size of all c-Family entries).
  14682 Note: The above 3-letter nicknames are used on some webpages (unknown why,
  14683 maybe they are derived from MGS filename extensions in the PC version).
  14684 
  14685 FACE.DAT (face animations for video calls):
  14686 This contains several large blocks (supposedly one per stage, each block having
  14687 its own file list). There is no directory to find the begin of the separate
  14688 blocks, but one can slowly crawl through the file:
  14689   NextBlock = CurrBlock + 4 + Offset(lastfile)+Size(lastfile) + Align800h
  14690 The content of each block is:
  14691   000h 4     Number of Files in this block (eg. 19h or 1Ch)
  14692   004h N*0Ch File List for this block
  14693   ...  ..    File Data for this block
  14694   ...  ..    Zeropadding to 800h-byte boundary (followed by next block, if any)
  14695  File List entries:
  14696   000h 2     File Type (0=Main/Eye/Mouth frames, 1=All frames are full size)
  14697   002h 2     File ID (name checksum?)
  14698   004h 4     Filesize in bytes
  14699   008h 4     Offset in bytes, minus 4
  14700 Type 0 Files in FACE.DAT:
  14701  This type use a single palette for all frames, and only the first frame is
  14702  full 52x89pix, the other frames contain only the update sections (eg. eyes).
  14703   000h 4     Offset to 200h-byte palette       (usually 20h)    ;\Main
  14704   004h 4     Offset to Main Bitmap (52x89pix) (usually 220h)    ;/
  14705   008h 4     Offset to 4th Bitmap  (usually xxxxh or 0=None)    ;\Eyes
  14706   00Ch 4     Offset to 5th Bitmap  (usually xxxxh or 0=None)    ;/
  14707   010h 4     Zero
  14708   014h 4     Offset to 2nd Bitmap  (usually 143Ch or 0=None)    ;\Mouth
  14709   018h 4     Offset to 3rd Bitmap  (usually xxxxh or 0=None)    ;/
  14710   01Ch 4     Zero
  14711   020h 200h  Palette (256 colors) ;\Main
  14712   220h 1218h Main Bitmap          ;/
  14713   1438h 4    Zero
  14714   143Ch ..   2nd Bitmap (if any)  ;\Mouth
  14715   ...   ..   3rd Bitmap (if any)  ;/
  14716   ...   ..   4th Bitmap (if any)  ;\Eyes
  14717   ...   ..   5th Bitmap (if any)  ;/
  14718 Type 1 Files in FACE.DAT:
  14719  This type use separate palettes for each frame, all frames are full 52x89pix.
  14720   000h 4     Number of frames
  14721   004h N*0Ch Frame List
  14722   ...  200h  1st Frame Palette
  14723   ...  1218h 1st Frame Bitmap (52x89pix)
  14724   ...  4     ?
  14725   ...  200h  2nd Frame Palette
  14726   ...  1218h 2nd Frame Bitmap (52x89pix)
  14727   ...  4     ?
  14728   ...  ..    3rd Frame ...
  14729  Frame List entries:
  14730   000h 4     Offset to Palette
  14731   004h 4     Offset to Bitmap (usually at Palette+200h)
  14732   008h 4     Unknown (often 000x000xh)
  14733 Bitmap Format (for both Type 0 and Type 1):
  14734   000h 1     Offset X (always 00h in Main Bitmap)
  14735   001h 1     Offset Y (always 00h in Main Bitmap)
  14736   002h 1     Width    (always 34h in Main Bitmap, or less in 2nd-5th bitmap)
  14737   003h 1     Height   (always 59h in Main Bitmap, or less in 2nd-5th bitmap)
  14738   004h ..    Bitmap Pixels at 8bpp (Width*Height bytes)
  14739 
  14740 DEMO.DAT, DEMO.SYM
  14741 VOX.DAT, VOX.SYM
  14742 The .DAT files contain several huge blocks, found on 800h-boundaries starting
  14743 with:
  14744   10 08 00 00 0x 00 00 00 ..
  14745 The .SYM files (if present) contain Names and .DAT Offsets/800h for those huge
  14746 blocks in text format:
  14747   "0xNNNNNNNN name",0Ah
  14748 VOX.DAT does (among others) contain SPU-ADPCM chunks with 2004h bytes or less,
  14749 that is, a 1+3 byte chunk header (01h=SPU-ADPCM, 002004h=Size), plus 2000h byte
  14750 or less SPU-ADPCM data.
  14751 
  14752 RADIO.DAT:
  14753 Whatever, contains chunks with text messages, chunks are about as so:
  14754   000h 4   Unknown    (eg. 36h,BFh,5Eh,00h)
  14755   004h 4   Unknown    (eg. 03h,13h,00h,00h)
  14756   008h 1   Unknown    (eg. 80h)
  14757   009h 2   Chunk Size (eg. 0xh,xxh)          ;big-endian
  14758   ..   ..  Chunk Data (Chunk Size-2 bytes) (binary stuff, and text strings)
  14759 
  14760 BRF.DAT:
  14761 Contains several "folders" in this format:
  14762   000h 4   Number of files in this folder
  14763   004h ..  File(s)
  14764   ...  ..  01h-padding to 800h-byte boundary
  14765  Files have this format:
  14766   000h ..  Filename ("name.pll",00h)
  14767   ...  ..  Zeropadding to 4-byte boundary (aligned to begin of BRF.DAT)
  14768   ...  4   File data size (usually a multiple of 4)
  14769   ...  ..  File data
  14770   ...  1   Zero (00h)
  14771 The above "folders" are then followed by several PCX files:
  14772   000h ..  PCX file (starting with 0A,05,01,01 or 0A,05,01,08)
  14773   ...  ..  01h-padding to 800h-byte boundary
  14774 The first part with .pll files does contain some kind of chunk sizes that could
  14775 be used to find the next entry (but that would be very slow).
  14776 The second part with .PCX files doesn't have any chunk sizes at all (though one
  14777 could decompress the .PCX file to find the end of each file) (also one could
  14778 guess/find them by looking for 0A,05,01,01/08 on 800h-byte boundaries).
  14779 
  14780 ZMOVIE.STR (movie archive with several STR files with subtitles)
  14781 --> CDROM File Video Streaming STR Variants
  14782 
  14783 STAGE.DIR\*\*.sb - stage binary/header
  14784 This is the first file in most folders (except "init*" folders).
  14785 The file contains MIPS binary program code. And, there are ascii strings near
  14786 end of .sb files, which include filenames, alike:
  14787   "name.c",00h + garbage-padding to 4-byte boundary  ;<-- maybe source code?
  14788   "pat_lamp",00h + zero- padding to 4-byte boundary  ;<-- name for File ID !
  14789 Those filenames do cover some (not all) of the name checksums in the STAGE.DIR
  14790 folder.
  14791 
  14792 STAGE.DIR\*\*.cp, STAGE.DIR\*\*.nd\.p, BRF.DAT\* - PCX bitmap files
  14793 MGS is using customized/corrupted PCX files as standard texture format (in
  14794 STAGE.DIR\*\*.cp, STAGE.DIR\*\*.nd\*.p, and BRF.DAT\*).
  14795 For details on PCX format (and MGS-specific customizations), see:
  14796 --> CDROM File Video Texture/Bitmap (PCX)
  14797 Apart from PCX, there's also custom texture format for animated bitmaps (in
  14798 FACE.DAT), and a few TIM images (in STAGE.DIR\init*\*.rd\*.r)
  14799 
  14800 STAGE.DIR\*\*.nd - texture archive (with .PCX files)
  14801 STAGE.DIR\init*\*.rd - misc archive (with misc files)
  14802 These archives contain several chunks in following format:
  14803   000h 2     File ID (checksum on name?)
  14804   002h 1     File Type (one of following chars: "p" for .nd, or "kors" for .rd)
  14805   003h 1     Zero (00h)
  14806   004h 4     Chunk Size (rounded to 4-byte boundary)
  14807   008h ..    Chunk Data
  14808 The File Type can be:
  14809   .p    PCX bitmap                      ;-in *\*.nd archives
  14810   .k    Whatever                        ;\
  14811   .o    Whatever "OARa"                 ; in init*\*.rd archives
  14812   .a    Whatever                        ;
  14813   .r    Misc (TIM and other stuff)      ;/
  14814 There can be 1-2 texture archives per STAGE.DIR folder (both having File
  14815 ID=0000h) (probably due to a memory size limit: the game does probably load one
  14816 archive with max 300Kbytes, relocate its contents to VRAM, then load the next
  14817 archive, if any).
  14818 
  14819 STAGE.DIR\*\*.sw - wave archive
  14820 There can be one or more .sw files per stage folder (eg. two sw's in
  14821 "vr*\*.sw").
  14822   000h 4     Unknown (800h or C00h)       ;big-endian
  14823   004h 4     Size of File List (N*10h)    ;big-endian
  14824   008h 8     Zerofilled
  14825   010h N*10h File List (xx,xx,xx,00,00,00,00,7F,00,00,00,0F,00,19,0A,00)
  14826   ...  4     Unknown (40000h or 60000h)   ;big-endian
  14827   ...  4     Size of SPU-ADPCM Data area  ;big-endian
  14828   ...  8     Zerofilled
  14829   ...  ..    SPU-ADPCM Data area (indexed from File List)
  14830  File List entries:
  14831   000h 4     Offset+Flags                 ;little-endian!
  14832                bit0-16  Offset (from begin of SPU-ADPCM Data area)
  14833                bit17    Unknown (0 or 1)
  14834                bit18    Unknown (1)
  14835                bit19-31 Unknown (0)
  14836   004h 12    Whatever (always 00,00,00,7F,00,00,00,0F,00,19,0A,00)
  14837 The unknown fields might contain volume, ADSR, pitch or the like?
  14838 
  14839 STAGE.DIR\*\*.se - sound effects? maybe short midi-like sequences or so?
  14840   000h 80h*10h List (unused entries are 1x00000000h,3xFFFFFFFFh)
  14841   800h ..      Data (whatever, usually 14h or more bytes per list entry)
  14842  List entries:
  14843   000h 1       Unknown (eg. 01h,10h,20h,A0h,80h,FFh)    ;\
  14844   001h 1       Number of Voices? (1..3)                 ; all zero for
  14845   002h 1       Unknown (1 or 0)                         ; unused list entries
  14846   003h 1       Unknown (2 or 0 or 1)                    ;/
  14847   004h 4       Offset-800h for 1st Voice?               ;-FFFFFFFFh=Unused
  14848   008h 4       Offset-800h for 2nd Voice? (if any)      ;-FFFFFFFFh=Unused
  14849   00Ch 4       Offset-800h for 3rd Voice? (if any)      ;-FFFFFFFFh=Unused
  14850  Data:
  14851   Seems to contain 4-byte entries (last entry being 00,00,FE,FF).
  14852 
  14853 STAGE.DIR\*\*.sm - whatever nested archives - sound music? mide-like?
  14854 This does resemble a DOT1 Parent archive with 1-4 DOTLESS Child archives.
  14855 Except, the offsets in Child archives are counted from begin of Parent archive.
  14856  Data:
  14857   Seems to contain 4-byte entries (last entry being 00,00,FE,FF).
  14858 
  14859 File IDs
  14860 File IDs in STAGE.DIR (and maybe elsewhere, too) are computed as so:
  14861   sum=0,
  14862   for i=0 to len(filename)-1
  14863     sum=sum*20h+filename[i]          ;\or so, 16bit overflows might be
  14864     sum=(sum+sum/10000h) AND FFFFh   ;/cropped slightly differently
  14865 Examples: "abst"=1706h, "selectvr"=8167h.
  14866 Some filenames are empty (name="", ID=0000h).
  14867 Some filenames do match up with the STAGE.DIR foldername.
  14868 Some filenames do match up with strings in .sb file of current folder.
  14869 Other filenames are unknown.
  14870 
  14871 CDROM File Archive DRACULA.DAT (Dracula)
  14872 ----------------------------------------
  14873 
  14874 Dracula - The Resurrection - DRACULA.DAT (180Mbyte)
  14875   000h 4     Zero
  14876   004h 4     Number of Entries (503h)
  14877   008h 4     Zero
  14878   00Ch 4     Random
  14879   010h 10h   Zero
  14880   020h N*10h File List
  14881   ...  ..    Zeropadding to 800h-byte boundary
  14882   ...  ..    Fild Data area
  14883 File List entries:
  14884   000h 4     Offset/800h
  14885   004h 4     Type (see below for info on different file types)
  14886   008h 4     Filesize in bytes
  14887   00Ch 4     Random (or 0 when Filesize=0)
  14888 Most of the .DAT file consists of groups of 3 files (with type 01h/40h, 20h and
  14889 400h; of which the files with type 20h and 400h may have Size=0=empty).
  14890   Type=00000001h Cubemap           ;\either one of these
  14891   Type=00000040h Cubemap.empty     ;/
  14892   Type=00000020h Cubemap.overlay?  ;\these have size=0 when unused
  14893   Type=00000400h Cubemap.sounds    ;/
  14894 There are some general purpose files with other types at end of .DAT file:
  14895   Type=00000000h Archive with TIMs         (Size=AB74h)  (" RSC3.1V")
  14896   Type=00000004h Unknown                   (Size=16164h) (00000064h)
  14897   Type=00000008h Related to DRACULA1.STR   (Size=1000h)  (" RTS1.1V")
  14898   Type=00001000h Unknown                   (Size=2000h)  ("BXFS1.1V")
  14899   Type=00008000h Unknown                   (Size=71Dh)   ("  CM1.1V")
  14900   Type=00020000h Unknown                   (Size=3B9h)   (" GSM0.1V")
  14901   Type=02000000h Unknown                   (Size=0h)     (empty)
  14902   Type=00000100h Related to DRACULA1.XA    (Size=1000h)  ("RAAX1.1V")
  14903   Type=00000010h Unknown                   (Size=450h)   (" HYP0.1V")
  14904   Type=00100000h Unknown                   (Size=4014h)  (" xFS1.1V") (x=A1h)
  14905   Type=00000080h Unknown                   (Size=258F4h) (00000010h)
  14906   Type=00000200h TIM (gui charset)         (Size=6E9Eh)  (TIM)
  14907   Type=00010000h TIM (gui buttons)         (Size=10220h) (TIM)
  14908   Type=00040000h Unknown                   (Size=2C4h)   (" TES0.1V")
  14909   Type=00002000h TIM (gui book pages)      (Size=1040h)  (TIM)
  14910   Type=00000800h Cubemap ;\as Type 01h,    (Size=4092Ch) (" RIV3.1V")
  14911   Type=00004000h Cubemap ;/but [10h,14h]=0 (Size=4092Ch) (" RIV3.1V", too)
  14912 Type 01h - Cubemap:
  14913   000h 8     Name, ASCII, padded with leading spaces (eg. " RIV3.1V")
  14914   008h 4     Something (0, 1 or 2) (unknown, this isn't number of list entries)
  14915   00Ch 4     Zero
  14916   010h 4     Offset to Ext data (ACh)                       ;\ext data
  14917   014h 4     Size of Ext data (eg. 0 or 84h)                ;/
  14918   018h 6*4   Offsets to Side 0-5                            ;\cubemap sides
  14919   030h 6*4   Sizes of Side 0-5 (0, 10220h, or 10820h)       ;/
  14920   048h 44h   Zerofilled
  14921   08Ch 20h   Name, ASCII (eg. "DEBUT0.VR", zeropadded)
  14922   0ACh ..    Ext Data (if any)
  14923   ...  ..    Cubemap TIM sides (if any)
  14924  Note: The cubemap TIMs have 100h or 400h colors (in the latter case: 100h 
  14925 colors for each quarter of the 8bpp bitmap).
  14926  Note: The TIMs can be arranged as 3D-cubemap with six sides, or as hires
  14927  2D-bitmap (composed of four TIMs, and 2 empty TIMs with size=0).
  14928 Type 40h - Empty Cubemap:
  14929   Same as Type 01h, but size is always 0ACh (and all seven Size entries are 0)
  14930 Type 400h - Sound VAG's:
  14931   000h 8     Name, ASCII, padded with leading spaces (eg. " XFS0.1V")
  14932   008h 4     Zero
  14933   00Ch 4     Number of Files (N) (max 10h)
  14934   010h N*10h File List (100h bytes, zeropadded when less than 10h files)
  14935   110h ..    File Data (VAG files)
  14936  File List entries:
  14937   000h 4     Unknown (55F0h, 255F0h or 20000h)
  14938   004h 4     File ID (01010000h, increasing, or other when above=2xxxxh)
  14939   008h 4     Offset in bytes                                ;\.VAG files
  14940   00Ch 4     Filesize in bytes                              ;/
  14941 Type 20h - Cubemap overlays, polygons, effects or so?:
  14942   000h 8      Name, ASCII, padded with leading dot (eg. ".MNA4.1V")
  14943   008h 4      Zero
  14944   00Ch 4      Random
  14945   010h 4      Unknown 01h
  14946   014h 4      Total Number of 40h-byte blocks (01h..[018h]) (H)
  14947   018h 4      Total Number of 120h-byte blocks (eg. 1Fh,31h) (N)
  14948   01Ch 4      Total Number of 1Ch-byte blocks (eg. 1Eh, 50h, F7h) (M)
  14949   020h 4      Unknown 0 or 1 (in file 4EAh)
  14950   024h 4      Unknown 01h
  14951   028h 6*4    Offsets to Side 0-5 (at end of file and up) (or 0)  ;\cubemap
  14952   040h 6*4    Sizes of Side 0-5   (10220h, or 10820h)     (or 0)  ;/sides
  14953   058h H*40h  40h-byte blocks
  14954   ...  N*120h 120h-byte blocks (related to offsets in 40h-byte blocks)
  14955   ...  M*1Ch  1Ch-byte blocks  (related to offsets in 120h-byte blocks)
  14956   ...  ..     Unknown data     (related to offsets in 1Ch-byte blocks)
  14957   ...  ..     Ext data         (related to Ext offsets in 40h-byte blocks)
  14958   FILE DOES END HERE!
  14959   (below is allocated in above header, but not actually stored in the file)
  14960   (maybe allocated as rendering buffer?)
  14961   ...  -      Cubemap TIM sides
  14962  The 40h-byte blocks are:
  14963   000h 20h    Name (eg. "FLAMMES", zeropadded)
  14964   020h 4      Unknown 01h or 00h
  14965   024h 4      Offset to 120h-byte blocks (usually 98h, or higher)
  14966   028h 4      Unknown 00h
  14967   02Ch 4      Number of 120h-byte blocks (01h..[018h])
  14968   030h 4      Unknown 01h
  14969   034h 4      Ext Offset                ;\usually all zero
  14970   038h 4      Ext Size (3C000h)         ; (except, nonzero in file 4EAh)
  14971   03Ch 4      Ext Random (checksum?)    ;/
  14972  The 120h-byte blocks are:
  14973   000h 18h*4  List with Offsets to 1Ch-byte blocks (usually 4 entries nonzero)
  14974   060h 18h*4  List with Zeroes
  14975   0C0h 18h*4  List with Numbers of 1Ch-byte blocks (usually max 4 entries)
  14976  The 1Ch-byte blocks are:
  14977   000h 4      Unknown 04h
  14978   004h 4      Width   20h or 10h
  14979   008h 4      Height  20h or 10h or 30h
  14980   00Ch 4      Unknown 60h or 10h
  14981   010h 4      Unknown 00h or 30h
  14982   014h 4      Offset to Unknown Data
  14983   018h 4      Size of Unknown Data (Width*Height*1)
  14984 Type 00h - TIMs:
  14985   000h 8      Name (" RSC3.1V")
  14986   008h 8      Zerofilled
  14987   010h 4      Number of used entries (1Fh) (max 80h)
  14988   014h 80h*4  Offset List    (offsets to files) (A14h and up)
  14989   214h 80h*4  Zero List      (zerofilled)
  14990   414h 80h*4  Size List      (filesizes)
  14991   614h 80h*4  Width List     (0Ch,18h,34h,2Ch) (in pixels)
  14992   814h 80h*4  Height List    (0Ch,24h,34h,2Ch)
  14993   A14h ..     Data (TIM files, with mouse pointers)
  14994 
  14995 CDROM File Archive Croc 1 (DIR, WAD, etc.)
  14996 ------------------------------------------
  14997 
  14998 Croc 1 (MagDemo02: CROC\*) (plus more files in retail version)
  14999 CROCFILE.DIR and CROCFILE.1:
  15000  CROCFILE.DIR:
  15001   000h 4     Number of Entries (N)
  15002   004h N*18h File List
  15003   ...  4     Checksum (sum of all of the above bytes)
  15004  CROCFILE.1:
  15005   000h ..    File Data (referenced from .DIR)
  15006  File List entries:
  15007   000h 0Ch   Filename ("FILENAME.EXT", zeropadded if shorter)
  15008   00Ch 4     File Size in bytes (can be odd) (including 8 byte for size/chksum)
  15009   010h 4     File Offset in .1 file (unaligned, can be odd, increasing)
  15010   014h 4     Zero (0)
  15011 CROCFILE.DIR\MP*.MAP (and MAP files inside of MAP*.WAD and MP090-100_*.WAD):
  15012   000h 4    Size-8 of whole file (or Size-0 for those in MP*.WAD)
  15013   004h 4    Flags? (usually 0Ch or 14h)
  15014   008h 1    Filename length                (including trailing 00h, if any)
  15015   009h ..   Filename ("P:\CROC\EDITOR\MAPS\..\*.MAP") (+00h in MAP05*.WAD)
  15016   ...  ..   Unknown
  15017   ...  1    Description length
  15018   ...  ..   Description (eg. "Default New Map")
  15019   ...  ..   Unknown
  15020   ...  (4)  Checksum of whole file (sum of all bytes) (not in MP*.WAD)
  15021 CROCFILE.DIR\*.WAD:
  15022  MAP*.WAD:
  15023   000h 4    Size-8 of whole file
  15024   004h ..   MAP file(s) (each with size/checksum, same format as MP*.MAP)
  15025   ...  4    Checksum of whole file (sum of all of the above bytes)
  15026  CROC.WAD, CROCSLID.WAD, EXCLUDE.WAD, MP*.WAD, OPTIONS.WAD, SWIMCROC.WAD:
  15027   000h 4    Size-8 of whole file
  15028   004h 4    Offset-8 to SPU-ADPCM data area
  15029   008h ..   Data File area (model.MOD anim.ANI, bytecode.BIN, header.CVG, etc.)
  15030   ...  ..   SPU-ADPCM data area (if any, note in CROCSLID.WAD and OPTIONS.WAD)
  15031   The Data File area contains several "files" but doesn't have any directory
  15032   with filename/offset/size. The only way to find the separate files seems to
  15033   be to detect the type/filesize of each file, and then advance to next file
  15034   (bytecode.BIN files start with a size entry, but files like .MOD or .ANI
  15035   require parsing their fileheader for computing filesize).
  15036   Note: The PC version reportedly has .WAD files bundled with .IDX file (that
  15037   makes it easier to find files and filenames).
  15038   Note: The STRAT.DIR file contains a list of filenames used in .WAD files
  15039   (but lacks info on offset/size, so it isn't really useful).
  15040 CROCFILE.DIR\*.BIN:
  15041  Sound.BIN Files (CROCFILE.DIR\AMBI*.BIN, MAP*.BIN, JRHYTHM.BIN, REVERB.BIN):
  15042   000h 4    Size of .SEQ file                   ;\if any (not in REVERB.BIN)
  15043   004h ..   SEQ file (starting with ID "pQES")  ;/
  15044   ...  4    Size of .VH file                    ;\always present
  15045   ...  ..   VH file (starting with ID "pBAV")   ;/
  15046   ...  ..   VB file (sample data, SPU-ADPCM data, up to end of file)
  15047  Music.BIN files (MAGMUS.BIN, MUSIC.BIN):
  15048   000h 4      Size-8 of whole file (118h)
  15049   004h ..     Increasing 32bit values ;sector numbers in PACK*.STR files or so?
  15050   ...  4      Unknown (2EEh or 258h) (aka 750 or 600 decimal)
  15051   ...  ..     Zeropadding
  15052   11Ch 4      Checksum (sum of all of the above bytes)
  15053   Note: MUSIC.BIN has an extra copy (without chksum) in EXCLUDE.WAD\MUSIC.BIN
  15054  Ascii.BIN files (CREDITS*.BIN, MNAME.BIN):
  15055   000h 4      Size-8 of whole file
  15056   004h (2)    Type or so? (02h,01h) (only in CREDITS*.BIN, not in MNAME.BIN)
  15057   ...  ..     Ascii strings (each string is: len,"text string",unknown)
  15058   ...  4      Checksum (sum of all of the above bytes)
  15059  Texture.BIN files (type 4) (STILLGO.BIN, STILLST.BIN, STILLTL.BIN):
  15060   000h 2      Type (4=Texture/uncompressed, with 0Eh-byte list entries)
  15061   002h 1      Zero (maybe Extra6byte as in type 5,6 Texture.BIN files)
  15062   003h 2      Number of List entries (N) (always 4B0h in all three files)
  15063   005h 2      Number of Texture Pages (usually 2)
  15064   007h 2      Zero (maybe Unknown/Animation as in type 5,6 Texture.BIN files)
  15065   009h N*0Eh  Polygon List (?,?,?,?,?,?, x1,y1, x2,y1, x1,y2, x2,y2)
  15066   ...  40000h Texture Page uncompressed data (two pages, 20000h bytes each)
  15067   ...  4      Checksum (sum of all of the above bytes)
  15068  Texture.BIN files (type 5,6) (ENDTEXT*.BIN, FONT.BIN, FRONTEND.BIN,
  15069  OUTRO.BIN, PUBLISH.BIN, STILL*.BIN, TB*.BIN, TK*.BIN, TPAGE213.BIN):
  15070   000h 4      Zero (0)               (in TPAGE213.BIN: Size-8 of whole file)
  15071   004h 2      Type (6=Texture/RLE16) (in TPAGE213.BIN: 5=Texture/uncompressed)
  15072   006h 1      Extra6byte flag/size (0=None, 3=Extra6byte: TB*.BIN, TPAGE*.BIN)
  15073   ...  (6)    Extra6byte data (unknown purpose, only present when [006h]=3)
  15074   ...  2      Number of Polygon List entries (N)
  15075   ...  2      Number of Texture Pages (usually 1) (in TK*_ENM.BIN: usually 2)
  15076   ...  2      Number of Unknown Blocks (0=None, or 1,2,4,8)
  15077   ...  (..)   Unknown Block(s), if any
  15078   ...  2      Number of Animation Blocks (0=None)
  15079   ...  (..)   Animation Block(s), if any
  15080   ...  N*0Ch  Polygon List (?,?,?,?, x1,y1, x2,y1, x1,y2, x2,y2)  ;x,y or y,x?
  15081   ...  (4)    Texture Page compressed size (T1) ;\only when [004h]=Type=6
  15082   ...  (T1)   Texture Page compressed data      ;/
  15083   ...  (4)    Texture Page compressed size (T2) ;\only when [004h]=Type=6
  15084   ...  (T2)   Texture Page compressed data      ;/     and NumPages=2
  15085   ...  20000h Texture Page uncompressed data    ;-only when [004h]=Type=5
  15086   ...  4      Checksum (sum of all of the above bytes)
  15087   Unknown Block(s):
  15088   (Unknown purpose, each Unknown Block has the format shown below)
  15089   000h 2    Unknown (looks like some index value, different for each entry)
  15090   002h 2    Number of Unknown Items (eg. 1 or 2 or 4)
  15091   004h ..   Unknown Items (NumItems*6 bytes) (three halfwords each?)
  15092   Animation Block(s):
  15093   (This is supposedly used to update portions of the Texture Page for
  15094   animated textures, each Animation Block has the format shown below)
  15095   000h 2    Number of Bitmap Frames in this Animation (usually 8)
  15096   002h 2    Bitmap Width (in halfword units)
  15097   004h 2    Bitmap Height
  15098   006h 2    Unknown (1 or 3)                    ;\
  15099   008h 2    Unknown (C10h, CC8h, 1E8h, or xxxh) ; maybe vram X,Y address?
  15100   00Ah 2    Unknown (0)                         ;/
  15101   00Ch ..   Bitmap Frames (Width*2*Height*NumFrames bytes, uncompressed)
  15102   Croc 1 RLE16 compression:
  15103   This is using unsigned little-endian 16bit LEN/DATA pairs, LEN can be:
  15104    0000h..7FFFh --> Load one halfword, fill 1..8000h halfwords
  15105    8000h..FFFFh --> Copy 1..8000h uncompressed halfwords
  15106   BUG: Texture pages should be 20000h bytes (256x256 halfwords), but for
  15107   whatever reason, the size of decompressed data can be 1FFEAh, 1FFF0h,
  15108   1FFFAh, 20000h, or 20002h.
  15109  Bytecode.BIN (inside of .WAD files):
  15110   000h 4    Size of whole file
  15111   004h ..   Whatever bytecode (starting with initial 16bit program counter?)
  15112  Unknown.BIN (last 1-2 file(s) in EXCLUDE.WAD file):
  15113   000h 4     Number of entries (N)
  15114   004h N*18h Whatever
  15115   ...  4     Checksum (sum of above bytes)
  15116   Unknown purpose, retail version has one such file (with 0Ah entries), demo
  15117   version has two such files (with 0Ah and 4Eh entries. The files start with:
  15118   0A,00,00,00,00,00,00,00,00,00,64,00,00,00,EB,FF,...  ;demo+retail
  15119   4E,00,00,00,00,00,64,00,00,00,50,00,00,00,64,00,...  ;demo
  15120 CROCFILE.DIR\*.MOD
  15121  Demo version has one .MOD file in CROCFILE.DIR (retail has more such files):
  15122   000h 2     Number of Models (N) (1 or more) (up to ECh exists)     ;\header
  15123   002h 2     Flags (0 or 1)                                          ;/
  15124   004h N*Var SubHeadersWithData  ;see below                          ;-data
  15125   ...  4     Checksum (sum of all of the above bytes)                ;-checksum
  15126   SubHeadersWithData(N*Var):
  15127   004h 4     Radius                                                  ;\
  15128   008h 48h   Bounding Box[9*8] (each 8byte are 4x16bit: X,Y,Z,0)     ; for each
  15129   050h 4     Number of Vertices (V)                                  ; model
  15130   054h V*8   Vectors (4x16bit: X,Y,Z,0)                              ;
  15131   ...  V*8   Normals (4x16bit: X,Y,Z,0)                              ;
  15132   ...  4     Number of Faces (F) (aka Polygons?)                     ;
  15133   ...  F*14h Faces   (8x16bit+4x8bit: X,Y,Z,0,V1,V2,V3,V4, Tex/RGB)  ;
  15134   ...  2     Number of collision info 1? (X)     ;\                  ;
  15135   ...  2     Number of collision info 2? (Y)     ; only if           ;
  15136   ...  X*2Ch Collision info 1?                   ; Flags.bit0=1      ;
  15137   ...  Y*2Ch Collision info 2?                   ;/                  ;/
  15138  There are further .MOD models inside of .WAD files, with slightly
  15139  re-arranged entries (and additional reserved/garbage fields):
  15140   000h 2     Number of Models (N) (1 or more) (up to ECh exists)     ;\
  15141   002h 2     Flags (0 or 1)                                          ; header
  15142   004h 4     Reserved/garbage (usually 224460h) (or 22C9F4h/22DF54h) ;/
  15143   008h (4)   Number of Models WITH Data arrays (M)                   ;\
  15144   00Ch (M*2) Model Numbers WITH Data arrays (increasing, 0..N-1)     ; ext.hdr
  15145   ...  (..)  Padding to 4-byte boundary (garbage, usually=M)         ;/
  15146   ...  N*68h Subheader(s)   ;see below                               ;-part 1
  15147   ...  N*Var DataArray(s)   ;see below                               ;-part 2
  15148   Subheaders(N*68h):
  15149   000h 4     Radius                                                  ;\
  15150   004h 48h   Bounding Box[9*8] (each 8byte are 4x16bit: X,Y,Z,0)     ; for each
  15151   04Ch 4     Number of Vertices (V)                                  ; model
  15152   050h 4     Reserved/garbage (usually 0022xxxxh)                    ;
  15153   054h 4     Reserved/garbage (usually 0022xxxxh)                    ;
  15154   058h 4     Number of Faces (F) (aka Polygons?)                     ;
  15155   05Ch 4     Reserved/garbage (usually 0022xxxxh)                    ;
  15156   060h 2     Number of collision info1? (X)                          ;
  15157   062h 2     Number of collision info2? (Y)                          ;
  15158   064h 4     Reserved/garbage (usually 0022xxxxh) or xxxxxxxxh)      ;/
  15159   DataArrays(N*Var) with sizes V,F,X,Y from corresponding Subheader:
  15160   (if ext.hdr is present, then below exists only for models listed in ext.hdr)
  15161   000h V*8   Vectors (4x16bit: X,Y,Z,0)                              ;\
  15162   ...  V*8   Normals (4x16bit: X,Y,Z,0)                              ; for each
  15163   ...  F*14h Faces   (8x16bit+4x8bit: X,Y,Z,0,V1,V2,V3,V4, Tex/RGB)  ; model
  15164   ...  X*2Ch Collision info 1?                                       ;
  15165   ...  Y*2Ch Collision info 2?                                       ;/
  15166  The ext.hdr mentioned above exists only in some .MOD files (usually in one of
  15167  the last chunks of MP*.WAD). Files with ext.hdr have N>1, Flags=1 (but files
  15168  without ext.hdr can also have those settings). Files with ext.hdr do usually
  15169  have uncommon garbage values at hdr[4], which isn't too helpful for detection.
  15170  The only way to detect models with ext.hdr seems to be to check if the ext.hdr
  15171  contains valid increasing entries in range 0..N-1.
  15172  WAD's that do contain a model with ext.hdr do usually also contain an extra
  15173  100h-byte file, that file contains N bytes for model 0..N-1 (plus zeropadding
  15174  to 100h-byte size), the bytes are supposedly redirecting models without Data
  15175  Arrays to some other data source.
  15176  The 100h-byte files don't have any header or checksum, they contain up to 9Ch
  15177  entries (so there's always some zeropadding to 100h), the existing 100h-byte
  15178  files contain following values in first 4 bytes (as 32bit value):
  15179   04141401h, 0C040017h, 01010101h, 09030503h, 0A0B0A0Bh, 03020102h, 0C060900h,
  15180   00060501h, 04040201h, 01010203h, 01030201h, 05000302h, 0C040317h, or Zero.
  15181   To distinguish from other files: BIN/MAP files start with a 4-byte aligned
  15182   Size value; if Size=0 or (Size AND 3)>0 or Size>RemainingSize then it's
  15183   probably a 100h-byte file. Best also check if last some bytes are zeropadded.
  15184  Exceptions:
  15185   Retail MP090..MP100_*.WAD has model with ext.hdr, but no 100h-byte file
  15186   Demo MP041_00.WAD has model with ext.hdr, with zerofilled 100h-byte file
  15187  Note: Some models have ALL models listed in ext.hdr (which is about same as
  15188  not having any ext.hdr at all; except, they ARE bundled with 100h-byte file).
  15189 CROCFILE.DIR\MP*.DEM
  15190  Some (not all) MP*.WAD files are bundled with MP*.DEM files, supposedly
  15191  containing data for demonstration mode. There are two versions:
  15192   demo version:   size 2584h (9604 decimal) (some files with partial checksum)
  15193   retail version: size 0E10h (3600 decimal) (without checksum)
  15194 CROCFILE.DIR\CROCWALK.ANI:
  15195  Animation data, there is only one such file in CROCFILE.DIR:
  15196   000h 2       Value (100h)
  15197   002h 2       Number of Triggers (T) (2)
  15198   004h (T*2)   Trigger List (with 2x8bit entries: FrameNo, TriggerID)
  15199   ...  ..      Probably, Padding to 4-byte boundary (when T=odd)
  15200   ...  4       Number of entries 1 (X)
  15201   ...  X*18h   Whatever Array 1
  15202   ...  4       Number of entries 2 (Y) (usually/always 64h)
  15203   ...  X*Y*4   Whatever Array 2
  15204   ...  4       Number of entries 3 (Z) (usually/always 0Ah)
  15205   ...  X*Z*18h Whatever Array 3
  15206  There are further .ANI files inside of .WAD files:
  15207   000h 2       Value (100h or 200h)                         ;Animation Speed?
  15208   002h 2       Number of Triggers (T) (0, 1, 2, 3, 5, or 9)
  15209   004h 4       Garbage/Pointer (usually 224460h) (or zero)
  15210   008h 4       Number of entries 1 (X) (1 or more)          ;Num Frames
  15211   00Ch 4       Garbage/Pointer (usually 22C9F4h) (or 224460h or 22DF54h)
  15212   010h 4       Number of entries 2 (Y) (usually 64h) (or 0) ;Num Vertices (?)
  15213   014h 4       Garbage/Pointer
  15214   018h 4       Number of entries 3 (Z) (usually 0Ah) (or 6 or 9)
  15215   01Ch 4       Garbage/Pointer
  15216   020h (T*2)   Trigger List (with 2x8bit entries: FrameNo, TriggerID)
  15217   ...  ..      Padding to 4-byte boundary (garbage, usually=X)
  15218   ...  X*18h   Whatever Array 1
  15219   ...  X*4     Garbage/Pointers (0021EE74h,0021EE74h,xxx,...)
  15220   ...  X*Y*4   Whatever Array 2   ;Vertex 3x10bit?            ;only if Y>0
  15221   ...  (X*4)   Garbage/Pointers (0021EE74h,0021EE74h,xxx,...) ;only if Y>0
  15222   ...  X*Z*18h Whatever Array 3
  15223 CROCFILE.DIR\TCLD.CVG:
  15224  There is only one such file in CROCFILE.DIR:
  15225   000h 4      Size-8 of whole file
  15226   004h 4      Unknown (0)
  15227   008h 4      Unknown (1)
  15228   00Ch ..     SPU-ADPCM data
  15229   ...  4      Checksum (sum of all of the above bytes)
  15230  There are further .CVG files inside of .WAD files, these consist of two
  15231  parts; 0Ch-byte Headers (in the data file area), and raw SPU-ADPCM data
  15232  (in the spu-adpcm data area at end of the .WAD file):
  15233   Header(0Ch):
  15234   000h 4      Size+8 of data part
  15235   004h 4      Unknown (0)
  15236   008h 4      Unknown (0 or 1)
  15237   Data(xxxx0h):
  15238   000h ..     SPU-ADPCM data (starting with sixteen 00h bytes)
  15239 STRAT.DIR (in retail version with extra copy in CROCFILE.DIR\STRAT.DIR):
  15240  This file contains a list of filenames for files inside of .WAD files, but
  15241  it does NOT tell where those files are (in which WAD at which offset).
  15242   000h 4     Number of Entries (N)
  15243   004h N*xxh File List (retail=14h bytes, or demo=18h bytes per entry)
  15244   ...  4     Checksum (sum of all of the above bytes)
  15245  List entries are:
  15246   demo:   entrysize=18h  ;Filename(0Ch)+Size(4)+Zeroes(8)
  15247   retail: entrysize=14h  ;Filename(0Ch)+        Zeroes(8)
  15248  The list contains hundreds of filenames, with following extensions:
  15249   *.BIN  byte-code strategies
  15250   *.MOD  models
  15251   *.ANI  animations
  15252   *.CVG  spu-adpcm voice data
  15253  These "filenames" seem to be actually solely used as "memory handle names":
  15254   MemoryHandle(#1) = LoadFile("FILENAME.BIN")  ;<-- names NOT used like this
  15255   MemoryHandle("FILENAME.BIN") = LoadFile(#1)  ;<-- names used like this
  15256 PACK*.STR (retail version only):
  15257   Huge files with XA-ADPCM audio data
  15258 MAGMUS.STR (demo version only):
  15259   Huge mis-mastered 24Mbyte file (contains several smaller XA-ADPCM blocks,
  15260   accidentally stored in 800h-byte FORM1 data sectors, instead of 914h-byte
  15261   FORM2 audio sectors).
  15262 ARGOLOGO.STR, FOXLOGO.STR
  15263   MDEC movies
  15264 COPYRIGHT.IMG, WARNING.IMG
  15265   Raw bitmaps (25800h bytes, uncompressed, 320x240x16bpp)
  15266 CUTS\*.AN2 (looks like cut-scenes with polygon-streaming):
  15267 --> CDROM File Video Polygon Streaming
  15268 Note: MOD/ANI files contain many Reserved/Garbage/Pointer entries which are
  15269 replaced by pointers after loading (the initial values seem to have no purpose;
  15270 they are aften set to constants with value 002xxxxxh which could be useful for
  15271 file type detection, but they vary in different game versions).
  15272 See also:
  15273 https://github.com/vs49688/CrocUtils/ (for PC version, PSX support in progress)
  15274 
  15275 CDROM File Archive Croc 2 (DIR, WAD, etc.)
  15276 ------------------------------------------
  15277 
  15278 Croc 2 (MagDemo22: CROC2\CROCII.DIR\T*.WAD+DEM)
  15279 Disney's The Emperor's New Groove (MagDemo39: ENG\KINGDOM.DIR\T*.WAD+DEM)
  15280 Disney's Aladdin in Nasira's Rev. (MagDemo46: ALADDIN\ALADDIN.DIR\T*.WAD+DEM)
  15281 Alien Resurrection, and Harry Potter 1 and 2 ... slightly different format?
  15282 Overall .WAD format:
  15283   000h 4      Total Filesize+/-xx (-4 or +800h or +1800h)
  15284   004h 4+4+.. XSPT Chunk        ;Textures
  15285   ...  4+4+.. XSPS Chunk        ;SPU-ADPCM Sound (if any, not in all .WAD's)
  15286   ...  4+4+.. XSPD Chunk        ;...whatever Data...?
  15287   ...  4+4    DNE Chunk         ;End marker (in Harry Potter: with data!)
  15288 XSPT Chunk (Textures):
  15289   000h 4        Chunk Name "XSPT" (aka TPSX backwards)
  15290   004h 4        Chunk Size (excluding 8-byte Name+Size)
  15291   008h 4        Chunk Flags (02h or 06h or 0Eh)  ;02h in Croc 2
  15292   00Ch (20h)    Name (eg. "Default new map", zeropadded)  ;\if Flags bit2=1
  15293   ...  (804h)   Unknown ... SAME as in XSPD chunk !!!     ;/
  15294   ...  4        Number of List 1 entries (N1) (xxh..xxxh) ;\
  15295   ...  4        Number of Texture Pages (1..4)            ; List 1 and NumPages
  15296   ...  N1*0Ch   List 1 Whatever (6B 2F xx 00..)           ;/
  15297   ...  4        Number of List 2 entries (N2) (0..xxh)    ;\
  15298   ...  4        Unknown (2 or 7)                          ; List 2
  15299   ...  N2*04h   List 2 Whatever (halfwords?) (if N2>0)    ;/
  15300   ...  (5*C00h) Whatever, 5*C00h, Palette+Stuff?          ;-if Flags bit3=1
  15301   ...  ..       RLE16 compressed Texture Pages            ;-Texture bitmap
  15302  RLE16 Texture notes:
  15303   Compressed data consists of signed little-endian 16bit LEN+DATA pairs:
  15304    LEN=0000h        --> invalid/unused
  15305    LEN=0001h..7FFFh --> copy LEN halfwords from src
  15306    LEN=8000h..FFFFh --> load ONE halfword as fillvalue, fill -LEN halfwords
  15307   Compressed size is everything up to end of XSPT chunk
  15308   Decompressed size is 20000h*NumTexturePages (=20000h,40000h,60000h or 80000h)
  15309   That is: Width=256 halfwords, height 256*NumTexturePages lines. There seems
  15310   to be only one RLE16 compression block for all Texture Pages, rather than one
  15311   RLE16 block for each Page.
  15312  BUG #1: Decompressed data in Aladding/Emperor does often contain only
  15313   1FFFEh,3FFFEh,5FFFEh,7FFFEh bytes (the decompressed data has correct size
  15314   when appending ONE halfword with random/zero value).
  15315  BUG #2: Compressed data in Croc 2 ends with a RLE16 length value (-LEN), but
  15316   lacks the corresponding RLE16 filldata (the decompressed data is 7FFFEh when
  15317   filling those LEN halfwords with random/zero values).
  15318 XSPS Chunk (SPU-ADPCM Sound) (if any, isn't present in all .WAD files):
  15319   000h 4      Chunk Name "XSPS" (aka SPSX backwards)       ;\
  15320   004h 4      Chunk Size (excluding 8-byte Name+Size)      ; header
  15321   008h 4      Chunk Flags (0 or 3 or 7)                    ;/
  15322   00Ch 4      Number of Sounds (N1) (1..xxh)               ;\always present
  15323   010h N1*14h Sound List                                   ;/
  15324   ...  (4)     VAB/VH Size                                 ;\if Flags=3 or 7
  15325   ...  (..)    VAB/VH Header                               ;/   (bit0 or bit1?)
  15326   ...  (4)     Unknown (2 or 4)                            ;-if Flags=3 or 7
  15327   ...  (4)     Whut (N2)                                   ;\if Flags.bit2=1
  15328   ...  (N2*10h) Whut List (4 words: xxh,10h,xxxx00h,xxxx0h);/
  15329   ...  4       Size of all Part 1 Sound Data blocks               ;\always
  15330   ...  ..      SPU-ADPCM Sound Data (referenced from Sound List)  ;/
  15331   ...  (4)     Size of all Part 2 Sound Data blocks (+8)          ;\if Flags=
  15332   ...  (..)    SPU-ADPCM Sound Data (referenced from Sound List?) ;    3 or 7
  15333   ...  (8)     Zero                                               ;/
  15334  Sound List entries (as in FESOUND.WAD):
  15335   000h 4    Sample Rate in Hertz (AC44h=44100Hz, 5622h=22050Hz, 3E80h=16000Hz)
  15336   004h 2    Sample Rate Pitch    (1000h=44100Hz, 0800h=22050Hz, 05CEh=16000Hz)
  15337   006h 2    Unknown (7Fh)
  15338   008h 4    Unknown (1)          (1)               (8)
  15339   00Ch 4    Unknown (42008Fh)    (1FC0001Fh)       (40008Fh)
  15340   010h 4    Filesize             (xxx0h)           (xxx0h)
  15341 XSPD Chunk:
  15342   000h 4     Chunk Name "XSPD" (aka DPSX backwards)
  15343   004h 4     Chunk Size (excluding 8-byte Name+Size)
  15344   008h 4     Flags-and/or-other stuff ? (eg. 00000094h or 0A801094h)
  15345   00Ch 804h  Unknown ... SAME as in XSPT chunk !!!
  15346   810h ..    Unknown ...
  15347 DNE Chunk (End marker):
  15348   000h 4     Chunk Name " DNE" (aka END backwards)
  15349   004h 4     Chunk Size (0)           (except, in Harry Potter: nonzero)
  15350   ...  ..    Data (usually none such) (except, in Harry Potter: with data!)
  15351 Additional DEM files (always 1774h bytes) (if any, not all .WAD's have .DEM's):
  15352   000h 4     Number of entries (N) (always 2EEh, aka 750 decimal)
  15353   004h N*8   Whatever entries... maybe data for demonstration mode?
  15354 See also:
  15355 http://wiki.xentax.com/index.php/Argonaut_WAD
  15356 
  15357 CDROM File Archive Headerless Archives
  15358 --------------------------------------
  15359 
  15360 Headerless Archives
  15361 Some games use files that contain several files badged together. For example,
  15362   PSX Resident Evil 2, COMMON\DATA\*.DIE contains TIM+VAB badged together
  15363   PSX Resident Evil 2, COMMON\DATA\*.ITP contains 1000h-byte aligned TIMs
  15364   Blaster Master, DATA\MENU\*\*.PRT contains three smaller TIMs badged together
  15365   Blaster Master, DATA\MENU\*\*.BG contains three bigger TIMs badged together
  15366   Misadventures of Tron Bonne, KATWA\*.BIN contains headerless archives (with
  15367 TIMs and audio)
  15368   Headerless BSS files contain several BS files with huge padding inbetween
  15369 To some level one could detect & resolve such cases, eg. TIM contains
  15370 information about the data block size(s), if the file is bigger, then there may
  15371 be further file(s) appended.
  15372 Some corner cases may be: Files with odd size may insert alignment padding
  15373 before next file. Archives with 800h-byte filesize resolution will have
  15374 zeropadding (or garbage) if the real size isn't a mutiple of 800h. Regardless
  15375 of that two cases, archives may use zeropadding to 800h-byte or even
  15376 10000h-byte boundaries (as workaround one could skip zeroes until reaching a
  15377 well-aligned nonzero word or double word (assuming that most files start with
  15378 nonzero values; though not always, eg. raw ADPCM or raw bitmaps).
  15379 
  15380 CDROM File Compression
  15381 ----------------------
  15382 
  15383 Compressed Bitmaps
  15384   .BS used by several games (and also in most .STR videos)
  15385   .GIF used by Lightspan Online Connection CD
  15386   .JPG used by Lightspan Online Connection CD
  15387   .BMP with RLE4 used by Lightspan Online Connection CD (MONOFONT, PROPFONT)
  15388   .BMP with RLE8+Delta also used by Online Connection CD (PROPFONT\ARIA6.BMP)
  15389   .PCX with RLE used by Jampack Vol. 1 (MDK\CD.HED\*.pcx)
  15390   .PCX with RLE used by Hot Wheels Extreme Racing (MagDemo52: US_01293\MISC\*)
  15391   .PCX with RLE used by Metal Gear Solid (slightly corrupted PCX files)
  15392 
  15393 Compressed Audio
  15394   .XA uses XA-ADPCM (and also used in .STR videos)
  15395   .VAG .VB .VAB uses SPU-ADPCM
  15396 
  15397 Compressed Files
  15398 --> CDROM File Compression LZSS (Moto Racer 1 and 2)
  15399 --> CDROM File Compression LZSS (Dino Crisis 1 and 2)
  15400 --> CDROM File Compression LZSS (Serial Experiments Lain)
  15401 --> CDROM File Compression ZOO/LZSS
  15402 --> CDROM File Compression Ulz/ULZ (Namco)
  15403 --> CDROM File Compression SLZ/01Z (chunk-based compressed archive)
  15404 --> CDROM File Compression LZ5 and LZ5-variants
  15405 --> CDROM File Compression PCK (Destruction Derby Raw)
  15406 --> CDROM File Compression GT-ZIP (Gran Turismo 1 and 2)
  15407 --> CDROM File Compression GT20 and PreGT20
  15408 --> CDROM File Compression HornedLZ
  15409 --> CDROM File Compression LZS (Gundam Battle Assault 2)
  15410 --> CDROM File Compression BZZ
  15411 --> CDROM File Compression RESOURCE (Star Wars Rebel Assault 2)
  15412 --> CDROM File Compression TIM-RLE4/RLE8
  15413 --> CDROM File Compression RLE_16
  15414 --> CDROM File Compression PIM/PRS (Legend of Mana)
  15415 --> CDROM File Compression BPE (Byte Pair Encoding)
  15416 --> CDROM File Compression RNC (Rob Northen Compression)
  15417 --> CDROM File Compression Darkworks
  15418 --> CDROM File Compression Blues
  15419 --> CDROM File Compression Z (Running Wild)
  15420 --> CDROM File Compression ZAL (Z-Axis)
  15421 --> CDROM File Compression EA Methods
  15422 --> CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  15423 --> CDROM File Compression LArc/LHarc/LHA (LZS/LZH)
  15424 Some other archvies that aren't used by any PSX games, but, anyways...
  15425 --> CDROM File Compression ARJ
  15426 --> CDROM File Compression ARC
  15427 --> CDROM File Compression RAR
  15428 --> CDROM File Compression ZOO
  15429 --> CDROM File Compression nCompress.Z
  15430 --> CDROM File Compression Octal Oddities (TAR, CPIO, RPM)
  15431 --> CDROM File Compression MacBinary, BinHex, PackIt, StuffIt, Compact Pro
  15432 
  15433 Compressed Archives
  15434 Some Archives have "built-in" compression.
  15435 --> CDROM File Archive WAD (Doom)
  15436 --> CDROM File Archive BIGFILE.DAT (Gex - Enter the Gecko)
  15437 
  15438 CDROM File Compression LZSS (Moto Racer 1 and 2)
  15439 ------------------------------------------------
  15440 
  15441 Moto Racer 1 ("LZSS" with len+2) (MagDemo03: MRDEMO\IMG\*.TIM)
  15442 Moto Racer 2 ("LZSS" with len+3) (MagDemo16: MR2DEMO\IMG\*.TIM and .TPK)
  15443   000h 4     ID "LZSS"
  15444   004h 4     Decompressed Size
  15445   008h ..    Compressed Data
  15446 This LZSS variant is unusually using 6bit len and 10bit disp. And, there are
  15447 two versions: Moto Racer 1 uses len+2, and Moto Racer 1 uses len+3. There is no
  15448 version information in the header, one workaround is to decompress the whole
  15449 file with len+2, and, if the resulting size is too small, retry with len+3.
  15450 Observe that the attempt with len+2 may cause page faults (eg. if the sum of
  15451 len values is smaller than disp; so allocate some extra space at begin of
  15452 compression buffer, or do error checks),
  15453   @@collect_more:
  15454    flagbits=[src]+100h, src=src+1    ;8bit flags
  15455   @@decompress_lop:
  15456    flagbits=flagbits SHR 1
  15457    if zero then goto @@collect_more
  15458    if carry=1 then
  15459      [dst]=[src], dst=dst+1, src=src+1
  15460    else
  15461      disp=([src]+[src+1]*100h) AND 3FFh, len=([src+1]/4)+2_or_3, src=src+2
  15462      if disp=0 then goto @@decompress_done
  15463      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  15464    endif
  15465    goto @@decompress_lop
  15466   @@decompress_done:
  15467    ret
  15468 
  15469 CDROM File Compression LZSS (Dino Crisis 1 and 2)
  15470 -------------------------------------------------
  15471 
  15472 Dino Crisis 1 and 2 (PSX\DATA\*.DAT and *.DBS and *.TEX, File type 7,8)
  15473 Dino Crisis LZSS Decompression for files with type 7 and 8:
  15474   @@collect_more:
  15475    flagbits=[src]+100h, src=src+1    ;8bit flags
  15476   @@decompress_lop:
  15477    flagbits=flagbits SHR 1
  15478    if zero then goto @@collect_more
  15479    if carry=1 then
  15480      [dst]=[src], dst=dst+1, src=src+1
  15481    else
  15482      disp=[src]+[src+1]*100h AND FFFh, len=[src+1]/10h+2, src=src+2
  15483      if disp=0 then error
  15484      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  15485    endif
  15486    if src<src_end then goto @@decompress_lop
  15487    ret
  15488 The compressed file & archive header don't contain any info on the decompressed
  15489 size (except, for compressed bitmaps, the archive header does contain
  15490 width/height entries, nethertheless the decompressed file is usually BIGGER
  15491 then width*height*2 (it can contain padding, plus 8 bytes).
  15492 
  15493 CDROM File Compression LZSS (Serial Experiments Lain)
  15494 -----------------------------------------------------
  15495 
  15496 Serial Experiments Lain is using LZSS compression for TIMs (in SITEA.BIN,
  15497 SITEN.BIN), and for Transparency Masks (in LAPKS.BIN).
  15498 
  15499 Serial Experiments Lain (7MB SITEA.BIN on Disc 1, 5MB SITEB.BIN on Disc 2)
  15500 These are huge 5-7 Mbyte files with hundreds of chunks. Each chunk contains one
  15501 compressed TIM.
  15502  Each chunk is having this format:
  15503   000h 4     Chunk ID "napk"
  15504   004h 4     Decompressed size
  15505   008h ..    LZSS compressed TIM data
  15506   ...  ..    Zeropadding to 800h-byte boundary
  15507 Unknown how the game is accessing chunks (there is no chunk size info, so one
  15508 would need read the whole file (or at least first 4-byte of each 800h-byte
  15509 sector) for finding chunks with ID="napk").
  15510 
  15511 Serial Experiments Lain (LAPKS.BIN on Disc 1 and 2)
  15512 This a huge 14Mbyte file with 59 chunks. Each chunk contains one or more 24bpp
  15513 .BS images with black background (the images in each chunk are forming a short
  15514 animation sequence; width/height may vary because all images are cropped to
  15515 rectangles containing non-black pixels).
  15516  Each chunk is having this format:
  15517   000h 4     Chunk ID "lapk"
  15518   004h 4     Chunk size (excluding 8-byte chunk header, excluding zeropadding)
  15519   008h 4     Number of Files in this Chunk (N)
  15520   00Ch N*0Ch File List
  15521   ...  ..    File Data (bitmaps in .BS v0 format with uncommon headers)
  15522   ...  ..    Zeropadding to 800h-byte boundary
  15523  File List entries:
  15524   000h 4     Offset in bytes (zerobased, from begin of File Data area)
  15525   004h 2     Bitmap Width/2 + some 3bit value in LSBs?
  15526   006h 2     Bitmap Height
  15527   00Ch 4     Zero
  15528  File Data (bitmaps in .BS v0 format with uncommon headers):
  15529   000h 2     Bitmap Width
  15530   002h 2     Bitmap Height
  15531   004h 2     Quant for Y1,Y2,Y3,Y4
  15532   006h 2     Quant for Cr,Cb
  15533   008h 4     Size of compressed BS Bitstream plus 4 ;Transparency at [008h]+0Ch
  15534   00Ch 2     Size/2 of MDEC data (after huffman decompression, without padding)
  15535   00Eh 2     BS Version (0) (actually MSBs of above Size, but it's always 0)
  15536   010h ..    BS Bitstream with DC and AC values (Huffman compressed MDEC data)
  15537   ...  4     Transparency Mask Decompressed Size (Width*Height*2/8) (=2bpp)
  15538   ...  ..    Transparency Mask LZSS-compressed data
  15539 BUG: The chunksize at C3A800h is set to 4C614h but should be 4D164h (the next
  15540 chunk starts at C88000h).
  15541 Unknown how the game is accessing chunks (crawling all chunks would be
  15542 exceptionally slow due to CDROM seek times, and won't work with the BUGGED
  15543 chunksize).
  15544 
  15545 Decompression function
  15546 This LZSS variant is unusually using 8bit len and 8bit disp.
  15547    dst_end=dst+[src], src=src+4   ;decompressed size
  15548   @@collect_more:
  15549    flagbits=([src] SHL 24)+800000h, src=src+1    ;8bit flags
  15550   @@decompress_lop:
  15551    if dst=dst_end then goto @@decompress_done
  15552    flagbits=flagbits SHL 1    ;32bit shift with carry-out/zeroflag
  15553    if zero then goto @@collect_more
  15554    if carry=0 then
  15555      [dst]=[src], dst=dst+1, src=src+1
  15556    else
  15557      disp=[src]+1, len=[src+1]+3, src=src+2
  15558      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  15559    endif
  15560    goto @@decompress_lop
  15561   @@decompress_done:
  15562    ret
  15563 
  15564 CDROM File Compression ZOO/LZSS
  15565 -------------------------------
  15566 
  15567 Jarret & LaBonte Stock Car Racing (MagDemo38: WTC\*.ZOO)
  15568   0000h 4     Decompressed Size                          ;\1st sector
  15569   0004h 7FCh  Garbage                                    ;/
  15570   0800h 4     Decompressed Size (same as above)          ;\2nd sector
  15571   0804h 7FCh  LZSS compressed data, part 1               ;/
  15572   1000h 800h  LZSS compressed data, part 2               ;-3rd sector
  15573   1800h 800h  LZSS compressed data, part 3               ;-4th sector
  15574   ...   ..    etc.
  15575 Note: The file format & compression method is unrelated to ZOO archives (to
  15576 distinguish between the formats: ZOO archives have [0014h]=FDC4A7DCh, the
  15577 ZOO/LZSS files have [0014h]=Garbage).
  15578 The decompressed WTC\*.ZOO files can contain large TIMs, or chunk-based
  15579 archives (where each chunk can contain one or more small TIMs), or other stuff.
  15580 
  15581 Decompression function
  15582   decompress_file:
  15583    if LittleEndian32bit[src+14h]=FDC4A7DCh then goto error ;refuse ZOO archives
  15584    if LittleEndian32bit[src]<>LittleEndian32bit[src+800h] then goto error
  15585    curr=src+800h
  15586    src=curr+4
  15587   @@sector_lop:
  15588    call decompress_sector
  15589    curr=curr+800h
  15590    src=curr
  15591    if src<src_end then goto @@sector_lop
  15592    ret
  15593   ;---
  15594   decompress_sector:
  15595   @@collect_more:
  15596    flagbits=([src] SHL 24)+800000h, src=src+1    ;8bit flags
  15597   @@decompress_lop:
  15598    flagbits=flagbits SHL 1    ;32bit shift with carry-out/zeroflag
  15599    if zero then goto @@collect_more
  15600    if carry=0 then
  15601      [dst]=[src], dst=dst+1, src=src+1
  15602    else
  15603      disp=[src]*100h+[src+1], src=src+2
  15604      if disp=FFFFh then goto @@decompress_done
  15605      len=(disp/800h)+3, disp=(disp AND 7FFh)+1
  15606      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  15607    endif
  15608    goto @@decompress_lop
  15609   @@decompress_done:
  15610    ret
  15611 
  15612 CDROM File Compression Ulz/ULZ (Namco)
  15613 --------------------------------------
  15614 
  15615 Ulz/ULZ uses fairly normal LZSS compression, unusually with variable Len/Disp
  15616 ratio, three separate data streams (flg/lz/dta), and rather weird end check in
  15617 version=0.
  15618 
  15619 Ulz Format (Ace Combat 3 Electrosphere, Namco)
  15620 Ulz Format (Klonoa, MagDemo08: KLONOA\FILE.IDX\*)
  15621   000h 4    ID ("Ulz",1Ah) (parts lowercase)
  15622   004h 3    Decompressed Size in bytes
  15623   007h 1    Version (0 or 2)
  15624   008h 3    Offset to Uncompressed data   <-- reportedly can be 0 in version=0?
  15625   00Bh 1    Number of Disp bits (DispBits=N, LenBits=16-N) (usually 0Ah..0Dh)
  15626   00Ch 4    Offset to Compressed data
  15627   010h ..   Compression Flags   (32bit entries)
  15628   ...  ..   Uncompressed data   (8bit entries)
  15629   ...  ..   Zeropadding to 4-byte boundary
  15630   ...  ..   Compressed data     (16bit entries)
  15631 Most files use version=2 (eg. US:ACE.BPH\0006h\000Fh contains DOT1 with TIMs).
  15632 Some files use version=0 (eg. US:ACE.BPH\0048h\*\* contains TIMs).
  15633 
  15634 ULZ Format (Time Crisis, Namco)
  15635   000h 4    ID ("ULZ",1Ah) (all uppercase)
  15636   004h 2    Zero
  15637   006h 1    Version (0 or 2)
  15638   007h 1    Number of Disp bits (DispBits=N, LenBits=16-N) (usually 0Ah..0Dh)
  15639   008h 4    Offset to Uncompressed data
  15640   00Ch 4    Offset to Compressed data
  15641   010h 4    Decompressed Size in bytes
  15642   014h ..   Compression Flags   (32bit entries)
  15643   ...  ..   Uncompressed data   (8bit entries)
  15644   ...  ..   Zeropadding to 4-byte boundary
  15645   ...  ..   Compressed data     (16bit entries)
  15646 Most files use version=2 (eg. EUR: AD*\TIM*.FHT\*)
  15647 Some files use version=0 (eg. EUR: AD4\TIM0_0.FHT\0018h, 0019h)
  15648 
  15649 Ulz/ULZ Decompression Function
  15650   if [src+00h]="Ulz",1Ah then
  15651     version   = Byte[src+07h]
  15652     disp_bits = Byte[src+0Bh]
  15653     dst_end   = LittleEndian24bit[src+04h] + dst
  15654     src_dta   = LittleEndian24bit[src+08h] + src
  15655     src_lz    = LittleEndian32bit[src+0Ch] + src
  15656     src_flg   = src + 10h
  15657     add_len   = 3
  15658     flg_1st   = 31  ;process flag bit31 first
  15659   if [src+00h]="ULZ",1Ah then
  15660     version   = Byte[src+06h]
  15661     disp_bits = Byte[src+07h]
  15662     src_dta   = LittleEndian32bit[src+08h] + src
  15663     src_lz    = LittleEndian32bit[src+0Ch] + src
  15664     dst_end   = LittleEndian32bit[src+10h] + dst
  15665     src_flg   = src + 14h
  15666     add_len   = 2
  15667     flg_1st   = 0   ;process flag bit0 first
  15668   collected = 80000000h   ;initially empty, plus stop bit
  15669  @@decompress_lop:
  15670   if version=2 AND dst=dst_end then goto @@decompress_done
  15671   flag = collected AND 80000000h
  15672   collected=collected*2
  15673   if collected=0
  15674     collected = LittleEndian32bit[src_flg], src_flg=src_flg+4
  15675     if flg_1st=0 then ReverseBitOrder(collected)  ;or make custom/faster code
  15676     flag = collected AND 80000000h
  15677     if version=0 AND collected=0 then goto @@decompress_done
  15678     if version=0 then collected=collected*2       ;<-- has implied stop bit
  15679     if version=2 then collected=collected*2 + 1   ;<-- shift-in stop bit
  15680   if flag=0     ;compressed
  15681     disp = LittleEndian16bit[src_lz], src_lz=src_lz+2
  15682     len  = (disp SHR disp_bits) + add_len
  15683     disp = (disp AND ((1 shl disp_bits)-1)) + 1
  15684     for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  15685   else          ;uncompressed
  15686     [dst]=[src_dta], dst=dst+1, src_dta=src_dta+1
  15687   goto @@decompress_lop
  15688  @@decompress_done:
  15689   ret
  15690 Note: Version=2 has 32 flags per 32bit. Version=0 has 31 flags and 1 stop bit
  15691 per 32bit, plus 32 null bits at end of data (which is all rather wasteful,
  15692 there's no good reason to use version=0).
  15693 
  15694 CDROM File Compression SLZ/01Z (chunk-based compressed archive)
  15695 ---------------------------------------------------------------
  15696 
  15697 SLZ/01Z files are Chunk-based archives with one or more compressed chunk(s).
  15698 Used by Hot Shots Golf 2 (retail: DATA\F0000.BIN\*, MagDemo31/42:
  15699 HSG2\MINGOL2.BIN\*)
  15700 
  15701 SLZ/01Z chunk headers
  15702 The archive consists of Chunk(s) in following format:
  15703   000h 3     ID (either "01Z" or "SLZ", both are used)
  15704   003h 1     Method (00h=Uncompressed, 01h=LZSS, 02h=LZSS+FILL)
  15705   004h 4     Compressed size (SIZ) (same as decompressed when Method=0)
  15706   008h 4     Decompressed size
  15707   00Ch 4     Distance to next chunk, if any (SIZ+10h+Align4, or 0=None)
  15708   010h SIZ   Compressed data
  15709 
  15710 SLZ/01Z  decompression function:
  15711    method=byre[src+3]
  15712    len=word[src+8]
  15713    src=src+10h
  15714    if method=0 then
  15715      for i=1 to len, [dst]=[src], dst=dst+1, src=src+1, next i
  15716      goto @@decompress_done
  15717    dst_end = dst+len
  15718   @@collect_more:
  15719    flagbits=[src]+100h, src=src+1    ;8bit flags
  15720   @@decompress_lop:
  15721    if method=2 AND dst=dst_end then goto @@decompress_done
  15722    flagbits=flagbits SHR 1
  15723    if zero then goto @@collect_more
  15724    if carry=1 then
  15725      [dst]=[src], dst=dst+1, src=src+1
  15726    else
  15727      disp=([src]+[src+1]*100h) AND 0FFFh, len=([src+1]/10h)+3, src=src+2
  15728      if method=1 AND disp=0 then goto @@decompress_done
  15729      if method=2 AND len=12h then     ;special fill mode...
  15730        len=disp/100h+3, val=disp AND FFh               ;len=3..12h
  15731        if len=3 then len=val+13h, val=[src], src=src+1 ;len=13h..112h
  15732        for i=1 to len, [dst]=val, dst=dst+1, next i    ;len=4..112h
  15733      else
  15734        for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  15735    endif
  15736    goto @@decompress_lop
  15737   @@decompress_done:
  15738    ret
  15739 
  15740 CDROM File Compression LZ5 and LZ5-variants
  15741 -------------------------------------------
  15742 
  15743 Original LArc LZ5 (method "-lz5-")
  15744 LZ5 was used by LArc compression tool from 1988/1989, decompression is also
  15745 supported by LHarc/LHA. LZ5 is basically LZSS compression, but with some
  15746 oddities:
  15747   LZ5 is often implemented with a ringbuf (instead of actual sliding window)
  15748   LZ5 uses absolute ringbuf indices (instead of relative sliding dest indices)
  15749   LZ5 requires the ringbuf to be initially prefilled with constants
  15750   LZ5 ringbuf is 1000h bytes tall and starts with write index FEEh
  15751 LArc was discontinued in 1989, but LZ5-variants have been kept used on PSX and
  15752 Nintendo DSi; those variants are just using the raw compression, without LArc
  15753 archive headers.
  15754 
  15755 DSi Dr. Mario (DSiware, Nintendo/Arika, 2008-2009)
  15756  INFO.DAT
  15757   encrypted directory with filename, offset and compressed/uncompressed size
  15758  GAME.DAT
  15759   000h 4   ID "ALZ1"
  15760   004h ... ALZ1 Compressed data (with size as defined in INFO.DAT)
  15761   ...  4   ID "ALZ1"
  15762   ...  ... ALZ1 Compressed data (with size as defined in INFO.DAT)
  15763   ...
  15764 
  15765 PSX Final Fantasy VII (FF7)
  15766 ALZ1 compression is used in various folders (ENEMY*, STAGE*, STARTUP, MAGIC,
  15767 FIELD, MINI, MOVIE, WORLD) with various filename extensions (.LZS .BSX .DAT
  15768 .MIM .TIZ .PRE .BSZ .TXZ).
  15769   000h 4   Compressed Size       ;=Filesize-4
  15770   004h ..  ALZ1 Compressed data (Filesize-4 bytes)
  15771 Detection can be more or less reliably done by checking [000h]=Filesize-4, one
  15772 could also check the filename extensions, although .DAT doesn't qualify as
  15773 unique extension.
  15774 The file doesn't contain any info on the decompressed size, so one cannot know
  15775 the decompression buffer size without first decompressing the file.
  15776 Note: For whatever reason, the game does also have one GZIP compressed file
  15777 (BATTLE\TITLE.BIN).
  15778 
  15779 PSX Final Fantasy VIII (FF8)
  15780 About same as FF7, but detection is less reliable because there are no
  15781 filenames or extensions, and the file header is somewhat randomly set to
  15782 [000h]=(Filesize-4)+0..7, unknown why, maybe it's allocating dummy bytes to
  15783 last some compression flags.
  15784   000h 4   Compressed Size+0..7  ;=(Filesize-4)+0..7
  15785   004h ..  ALZ1 Compressed data (Filesize-4 bytes)
  15786 ALZ1 is used in four Root files (0001h,0002h,0017h,001Ah), and in many Field
  15787 files, and maybe in further files elsewhere.
  15788 
  15789 PSX Ultimate Fighting Championship (MagDemo38: UFC\CU00.RBB\383h\*)
  15790   000h 8     ID "00zLATAD" (aka DATALz00 backwards)               ;\PreHeader
  15791   008h 4     Total Filesize excluding PreHeader+Padding (SIZ+0Ch) ;/
  15792   00Ch 4     Unknown (always 1000h)                               ;\
  15793   010h 4     Compressed data size                       (SIZ)     ; Header
  15794   014h 4     Decompressed data size                               ;/
  15795   018h SIZ   zLATAD Compressed data                               ;-Data
  15796   ...  ..    Padding to 4-byte boundary                           ;-Padding
  15797 
  15798 Ninja (MagDemo13: NINJA\LOADPICS\*.PAK and NINJA\VRW\FOREST.VRW\*)
  15799   000h 8     ID "VRAM-WAD"
  15800   008h 4     Compressed size (Filesize-Padding-10h)
  15801   00Ch 4     Decompressed size       (18000h, 28000h, 40000h bytes)
  15802   010h ..    VRAMWAD Compressed data (192x256, 320x256, 512x256 halfwords)
  15803   ...  (..)  Padding to 4-byte boundary (if any, in files in .VRW archives)
  15804 Observe that Ninja is using the same ID="VRAM-WAD" for .PAK files and .VRW
  15805 archives (if [008h]=Filesize-Padding-10h then it's a compressed .PAK file,
  15806 otherwise it's a .VRW archive; whereas, those .VRW archives do themselves
  15807 contain several .PAK files).
  15808 
  15809 PSX Power Spike (MagDemo43: POWER\GAME.IDX\*.BIZ)
  15810 BIZ compression is used in BIZ archives (which are nested in IDX/HUG archive).
  15811 The compressed & decompressed size is stored in the BIZ archive.
  15812 Note: Power Spike 20h-filled initial BIZ ringbuf is required for sky pixels in:
  15813   MagDemo43: POWER\GAME.IDX\PERSOS\PSX\CUSTOM\\TEXTURE\NFIELD.BIZ\LPORJ.PSI
  15814 
  15815 PSX Army Men Air Attack 2 (MagDemo40: AMAA2\*.PCK\*.PAK)
  15816 SCRATCH compression is used in PAK archives (which are nested in PCK archive).
  15817 The compressed & decompressed size is stored in the PAK archive.
  15818 Note: The decompressor uses half of the 1Kbyte Scratchpad RAM at 1F800000h as
  15819 ringbuf (hence the name and unusual small 200h-byte ringbuf size).
  15820 
  15821 Alice in Cyberland (ALICE.PAC\*.FA2)
  15822   000h ..   FA2 Compressed .FA archive
  15823 The decompressor is at 80093A3Ch (but the code isn't permanently in memory),
  15824 and it's by far one of the worst decompression functions in compilerland.
  15825 
  15826 Decompression
  15827    DEFAULT = ALZ1 or BIZ or LZ5
  15828    if DEFAULT then wr=0FEEh, mask=FFFh    ;\
  15829    if VRAMWAD then wr=0FEEh, mask=FFFh    ; initial ringbuf write index
  15830    if zLATAD  then wr=0000h, mask=FFFh    ; and ringbuf mask (size-1)
  15831    if SCRATCH then wr=01BEh, mask=1FFh    ;
  15832    if FA2     then wr=00EFh, mask=0FFh    ;/
  15833    if FA2     then len2=0
  15834    initialize_ringbuf_content (see below)
  15835    numbits=0
  15836   @@decompress_lop:
  15837    if dst>=dst.end then goto @@decompress_done
  15838    if numbits=0
  15839      flagbits=[src], numbits=8, src=src+1    ;8bit flags
  15840    numbits=numbits-1
  15841    if VRAMWAD or FA2 then flagbits SHL 1, else flagbits=flagbits SHR 1
  15842    if carry=1 then
  15843      dta=[src], [dst]=dta, ringbuf[wr AND mask]=dta
  15844      dst=dst+1, wr=wr+1, src=src+1
  15845    else
  15846      if DEFAULT then rd=[src]+([src+1]/10h)*100h), len=([src+1] AND 0Fh)+3
  15847      if zLATAD  then rd=[src]+([src+1] AND 0Fh)*100h), len=([src+1]/10h)+3
  15848      if SCRATCH then rd=[src]+([src+1]/80h)*100h), len=([src+1] AND 7Fh)+3
  15849      if VRAMWAD then rd=[src+1]+([src]/10h)*100h), len=([src] AND 0Fh)+3
  15850      if FA2     then rd=[src], len=len2, len2=0, src=src+1
  15851      if FA2 and len=0 then len=[src]/10h+2, len2=([src] AND 0Fh)+2, src=src+1
  15852      if FA2=0   then src=src+2
  15853      for i=1 to len   ;read ringbuf[rd] (instead of relative [dst-rd])
  15854        dta=ringbuf[rd AND mask], [dst]=dta, ringbuf[wr AND mask]=dta
  15855        dst=dst+1, wr=wr+1, rd=rd+1
  15856      next i
  15857    endif
  15858    goto @@decompress_lop
  15859   @@decompress_done:
  15860    ret
  15861 
  15862 Initial Ringbuf Content
  15863   if ALZ1 or zLATAD then
  15864     ringbuf[000h..FFFh]=(00h)              ;zeroes
  15865   if VRAMWAD then
  15866     ringbuf[000h..FEDh]=(00h)              ;zeroes
  15867     ringbuf[FEEh..FFFh]=(uninitialized)    ;uninitialized, don't use
  15868   if BIZ then
  15869     ringbuf[000h..FEDh]=(20h)              ;ascii space
  15870     ringbuf[FEEh..FFFh]=(uninitialized)    ;uninitialized, don't use
  15871   if SCRATCH then
  15872     ringbuf[000h..1BFh]=(00h)              ;zeroes
  15873     ringbuf[1C0h..1FFh]=(uninitialized)    ;uninitialized, don't use
  15874   if FA2 then
  15875     ringbuf[000h..0FFh]=(00h)              ;zeroes
  15876   if LZ5 then
  15877     ringbuf[000h..CFFh]=(000h..CFFh)/0Dh   ;increasing, repeated 0Dh times each
  15878     ringbuf[D00h..DFFh]=(00h..FFh)         ;increasing
  15879     ringbuf[E00h..EFFh]=(FFh..00h)         ;decreasing
  15880     ringbuf[F00h..F7Fh]=(00h)              ;zeroes
  15881     ringbuf[F80h..FEDh]=(20h)              ;ascii space
  15882     ringbuf[FEEh..FFFh]=(should be 00h)    ;see note, better don't use
  15883 Note: The last 12h bytes in LZ5 are 00h in LArc v3.33 (though unknown if that's
  15884 intended and stable), LHarc source code did accidentally set them to 20h (which
  15885 is reportedly fixed in later LHA versions).
  15886 
  15887 CDROM File Compression PCK (Destruction Derby Raw)
  15888 --------------------------------------------------
  15889 
  15890 Destruction Derby Raw (MagDemo35: DDRAW\*.PCK,EXE,DAT)
  15891   000h 3     Decompressed size (24bit, little-endian)
  15892   003h 1     Unused (0)
  15893   004h ...   LZSS compressed data, starting with 30bit+2bit flags
  15894 The compression is used in some ISO files, which can be detected as:
  15895   [03h]=00h, [04h]=00h, [08h]="PS-X EXE"                ;DDRAW\*.EXE
  15896   [03h]=00h, [04h] AND FCh=00h, [08h]="BC",04h,40h,0,0  ;DDRAW\LDPICS\*.PCK
  15897 The compression is also used in nested PTH+DAT archives (where the whole DAT is
  15898 compressed), which can be detected by checking if the sum of the PTH filesizes
  15899 exceeds the DAT filesize.
  15900 
  15901 Decompression function
  15902    dst_end=dst+LittleEndian24bit[src], src=src+4
  15903   @@collect_more:
  15904    flagbits=BigEndian32bit([src]), src=src+4
  15905    dispbits=14-(flagbits AND 03h), flagbits=(flagbits OR 3)-1
  15906    dispmask=(1 SHL dispbits)-1
  15907   @@decompress_lop:
  15908    flagbits=flagbits SHL 1    ;32bit shift with carry-out/zeroflag
  15909    if zero then goto @@collect_more
  15910    if carry=0 then
  15911      [dst]=[src], dst=dst+1, src=src+1
  15912    else
  15913      disp=BigEndian16bit[src], src=src+2
  15914      len=(disp SHR dispbits)+3
  15915      disp=(disp AND dispmask)+1
  15916      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  15917    endif
  15918    id dst<dst_end then goto @@decompress_lop
  15919   @@decompress_done:
  15920    ret
  15921 
  15922 CDROM File Compression GT-ZIP (Gran Turismo 1 and 2)
  15923 ----------------------------------------------------
  15924 
  15925 BS iki Video
  15926 IKI is a rather uncommon variant of the .STR video format (used by Gran Turismo
  15927 1 and 2, Legend of Legaia, Legend of Dragoon, Omega Boost, Um Jammer Lammy).
  15928 IKI videos have a custom .BS header, including some GT-ZIP compressed data:
  15929   000h 2   MDEC Size/4 (after huffman decompression) (rounded to 80h/4 bytes)
  15930   002h 2   File ID (3800h)
  15931   004h 2   Bitmap Width in pixels     ;instead quant
  15932   006h 2   Bitmap Height in pixels    ;instead version
  15933   008h 2   Size of GT-ZIP compressed data (plus 2-byte alignment padding)
  15934   00Ah ..  GT-ZIP compressed DC/Quant values (plus 2-byte alignment padding)
  15935   ...  ..  Huffman compressed AC data blocks (Cr,Cb,Y1,Y2,Y3,Y4, Cr,Cb,Y1,Y2..)
  15936 The number of blocks is NumBlocks=(Width+15)/16*(height+15)/16*6. The size of
  15937 the decompressed GT-ZIP data is NumBlocks*2.
  15938 
  15939 Gran Turismo 1 (MagDemo10: GT\*.DAT) - headerless
  15940 Gran Turismo 1 (MagDemo15: GT\*.DAT) - headerless
  15941   000h ..    Compressed Data (without header)
  15942 This is used for compressing files inside of GT-ARC archives (or in one case,
  15943 for compressing the whole GT-ARC archive). The GT-ARC directory contains
  15944 additional compression info, see GT-ARC description for details.
  15945 The file GT\GAMEFONT.DAT is also GT-ZIP compressed, but lacks any ID or info on
  15946 decompressed size, and there are at least two GAMEFONT.DAT versions (in
  15947 MagDemo10 va MagDemo15), both versions are 8000h byte when decompressed, and
  15948 compressed data starts with 00,FF,FF,00,00,00,80,00,00,01,17,07.
  15949 
  15950 Gran Turismo 2 (MagDemo27: GT2\GT2.VOL\arcade\arc_other.tim\*) - with header
  15951   000h 0Ch   ID "@(#)GT-ZIP",0,0
  15952   00Ch 4     Decompressed Size
  15953   010h ..    Compressed Data (unknown compressed size due to below padding)
  15954   ...  ..    Zeropadding to 4-byte boundary (when stored in DOT1 archives)
  15955 This is used for compressing some files in one DOT1 archive (most other files
  15956 in Gran Turismo 2 are using GZIP compression; with corrupted/zeropadded GZIP
  15957 footers).
  15958 
  15959 Decompression function
  15960    if [src]="@(#)GT-ZIP",0,0 then dst.end=dst+[src+0Ch], src=src+10h
  15961   @@collect_more:
  15962    flagbits=[src]+100h, src=src+1    ;8bit flags
  15963   @@decompress_lop:
  15964    if src>=src.end then goto @@decompress_done  ;(when src.end is known)
  15965    if dst>=dst.end then goto @@decompress_done  ;(when dst.end is known)
  15966    flagbits=flagbits SHR 1
  15967    if zero then goto @@collect_more
  15968    if carry=0 then
  15969      [dst]=[src], dst=dst+1, src=src+1
  15970    else
  15971      len=[src], src=src+1, disp=[src], src=src+1                 ;len, disp
  15972      if disp>=80h then disp=(disp-80h)*100h+[src], src=src+1     ;longer disp
  15973      for i=1 to (len+3), [dst]=[dst-(disp+1)], dst=dst+1, next i
  15974    endif
  15975    goto @@decompress_lop
  15976   @@decompress_done:
  15977    ret
  15978 
  15979 Notes
  15980 Depending on the source, only the compressed or decompressed size may be known:
  15981   Source                    Compressed Size           Decompressed Size
  15982   Compressed GAMEFONT.DAT   In ISO Filesystem         Unknown (n/a)
  15983   Compressed GT-ARC         In ISO Filesystem         Unknown (n/a)
  15984   Files in GT-ARC           In GT-ARC                 In GT-ARC
  15985   Files with GT-ZIP header  Unknown (due to padding)  In GT-ZIP
  15986   DC values in IKI videos   Unknown (due to padding)  From Width*Height
  15987 Gran Turismo 1 has ID "@(#)GT-ZIP" (and "@(#)G.T-ZIPB" whatever that is) stored
  15988 in Main RAM (though unknown if/which/any files do have those IDs).
  15989 Gran Turismo 2 has ID "@(#)GT-ZIP" in "GT2\GT2.VOL\arcade\arc_other.tim\*",
  15990 apart from that, it does mainly use GZIP compressed files.
  15991 
  15992 CDROM File Compression GT20 and PreGT20
  15993 ---------------------------------------
  15994 
  15995 GT20 Compressed Files
  15996 Used by Rollcage (MagDemo19: ROLLCAGE\SPEED.IMG\*)
  15997 Used by Rollcage Stage II (MagDemo31: ROLLCAGE\SPEED.IDX\*)
  15998 Used by Sydney 2000 (MagDemo37: OLY2000\DEMO.IDX\* and OLY2000\GTO\*.GTO)
  15999 Reportedly also Chill (PS1) (*.GTO)
  16000 Reportedly also Ducati World: Racing Challenge
  16001 Reportedly also Martian Gothic: Unification (PS1) (*.GT20)
  16002   000h 4     ID ("GT20"=Compressed) (or reportedly "NOGT"=Uncompressed)
  16003   004h 4     Size of decompressed data in bytes
  16004   008h 4     Overlap for in-situ decompression (usually 3, or sometimes 7)
  16005   00Ch 4     Size of Leading Zeropadding in bytes (0..7FFh)
  16006   010h ..    Leading Zeropadding (0..7FFh bytes)
  16007   ...  ..    Compressed Data
  16008 The Leading Zeropadding can be used to arrange the data to end on a sector
  16009 boundary (useful when loading the file in units of whole sectors, and wanting
  16010 to load it to the end of the decompression buffer).
  16011  DecompressGT20:
  16012   src=src+word[src+0Ch]+10h      ;skip header and any leading zeropadding
  16013   collected=00000001h  ;end-bit
  16014  @@lop:
  16015   if GetBit=0
  16016     [dst]=[src], dst=dst+1, src=src+1               ;uncompressed byte
  16017   else
  16018     if GetBit=0
  16019       disp=byte[src]-100h, src=src+1                ;disp=(-100h..-1)
  16020       len=(GetBit*2)+(GetBit*1)+2                   ;len=(2..5)
  16021     else
  16022       tmp=halfword[src], src=src+2
  16023       disp=(tmp/8)-2000h                            ;disp=(-2000h..-1)
  16024       len=(tmp AND 7)+2                             ;len=(2..9)
  16025       if len=2
  16026         tmp=byte[src], src=src+1
  16027         if (tmp AND 80h) then disp=disp-2000h       ;disp=(-4000h..-1)
  16028         len=(len AND 7Fh)+2                         ;len=(2..81h)
  16029         if len=3 then goto decompression_done
  16030         if len=2 then len=halfword[src], src=src+2  ;len=(0..FFFFh)
  16031     for i=1 to len, [dst]=[dst+disp], dst=dst+1, next i
  16032   goto @@lop
  16033  ;---
  16034  GetBit:
  16035   collected=collected SHR 1
  16036   if zero then collected=(word[src] SHR 1)+80000000h, src=src+4
  16037   return carry (from shift right)
  16038 Note: Uncompressed files can reportedly contain "NOGT" in the header, however,
  16039 Rollcage does have compressed files (with GT20 header), and raw uncompressed
  16040 files (without any NOGT header).
  16041 See also: https://zenhax.com/viewtopic.php?t=13175 (specs)
  16042 See also: http://wiki.xentax.com/index.php/GT20_Archive (blurp)
  16043 
  16044 Pre-GT20 Compressed Files
  16045 Used by Bloody Roar 1 (MagDemo06: BL\*.DAT\*)
  16046 Used by Bloody Roar 2 (MagDemo22: ASC,CMN,EFT,LON,SND,ST5,STU\*.DAT\*)
  16047   000h 4    Compression Method (0=None, 2=Compressed, Other=Invalid)
  16048   004h 4    Compressed Size (SIZ) (same as decompressed when method=0)
  16049   008h 4    Decompressed Size
  16050   00Ch SIZ  Compressed Data
  16051   ...  ..   Garbagepadding to 4-byte boundary (in 4-byte aligned DAT files)
  16052 This is apparently on older version of what was later called GT20. The PreGT20
  16053 decompression works as so:
  16054  DecompressPreGT20:
  16055   src=src+0Ch                    ;skip header
  16056   collected=80h  ;end-bit
  16057  @@lop:
  16058   if GetBit=1
  16059     [dst]=[src], dst=dst+1, src=src+1               ;uncompressed byte
  16060   else
  16061     if GetBit=0
  16062       len=(GetBit*2)+(GetBit*1)+2                   ;len=(2..5)
  16063       disp=byte[src]-100h, src=src+1                ;disp=(-100h..-1)
  16064     else
  16065       tmp=bigendian_halfword[src], src=src+2
  16066       disp=(tmp/8)-2000h                            ;disp=(-2000h..-1)
  16067       len=(tmp AND 7)+2                             ;len=(2..9)
  16068       if len=2
  16069         len=byte[src]+1, src=src+1                  ;len=(1..100h)
  16070         if len=1 then goto decompression_done
  16071     for i=1 to len, [dst]=[dst+disp], dst=dst+1, next i
  16072   goto @@lop
  16073  ;---
  16074  GetBit:
  16075   collected=collected SHL 1    ;8bit shift
  16076   if zero then collected=(byte[src] SHL 1)+01h, src=src+1
  16077   return carry (from 8bit shift left)
  16078 Note: Uncompressed files with Method=0 exist in Bloody Roar 2 (CMN\SEL01.DAT).
  16079 Bloody Roar 1 (MagDemo06) has decompressor at 8016DD64h (method 0 and 2).
  16080 Bloody Roar 2 (MagDemo22) has decompressor at 8015C8C0h (method 0 and 2).
  16081 
  16082 CDROM File Compression HornedLZ
  16083 -------------------------------
  16084 
  16085 Used by Project Horned Owl (*.BIN\*) (and within self-decompressing EXE)
  16086 
  16087 HornedLZ Detection
  16088 The easiest way to detect HornedLZ files is to check first 4 bytes:
  16089   B3 10 00 4F ..    Compressed TIM with TIM Type=00h (4bpp without CLUT)
  16090   DB 10 00 3F ..    Compressed TIM with TIM Type=08h,09h,etc.
  16091 Alternately, one could check the Chunktype (in the parent archive):
  16092   Type=05h can be uncompressed .TXT or HornedLZ-compressed .TIM
  16093     (check if 2nd data byte is ASCII or 10h)
  16094   Type=0Fh is a DOT1 archive with HornedLZ-compressed .TIMs
  16095     (parse the DOT1 archive and treat its contents as compressed .TIMs)
  16096   Type=10h contains Deflated TIMs
  16097     (a completely different compression method)
  16098 
  16099 DecompressHornedLZ:
  16100   collected=01h  ;end-bit
  16101  @@lop:
  16102   if GetBit=1
  16103     [dst]=[src], dst=dst+1, src=src+1               ;uncompressed byte
  16104   else
  16105     if GetBit=1
  16106       tmp=[src], src=src+1
  16107       len=tmp/40h+2, disp=tmp or (-40h)       ;len=(2..05h), disp=(-40h..-1)
  16108     else
  16109       tmp=[src]*100h+[src+1], src=src+2
  16110       len=tmp/1000h+2, disp=tmp or (-1000h)   ;len=(2..11h), disp=(-1000h..-1)
  16111       if len=2 then
  16112         len=[src]+2, src=src+1                ;len=(2..101h)
  16113         if len=2 then goto decompression_done
  16114     for i=1 to len, [dst]=[dst+disp], dst=dst+1, next i
  16115   goto @@lop
  16116  ;---
  16117  GetBit:
  16118   collected=collected SHR 1
  16119   if zero then collected=([src] SHR 1)+80h, src=src+1
  16120   return carry (from shift right)
  16121 Note: The end code has all bits zero, except, disp is don't care (it's usually
  16122 FFFh).
  16123 
  16124 CDROM File Compression LZS (Gundam Battle Assault 2)
  16125 ----------------------------------------------------
  16126 
  16127 Gundam Battle Assault 2 (DATA\*.PAC\*, with ID="lzs")
  16128   000h 4     ID ("lzs",00h)
  16129   004h 4     Zerofilled
  16130   008h 4     Fixed (must be 1) (method/version?)
  16131   00Ch 14h   Zerofilled
  16132   020h 2     Fixed (must be 3) (method/version?)
  16133   022h 2     Offset to Compressed Data minus 20h (usually 38h-20h)
  16134   024h 4     Decompressed Size
  16135   028h 2     Flagsize (must be 08h, 10h, or 20h) (usually 20h=32bit)
  16136   02Ah 2     Lensize  (must be 02h..07h)         (usually 05h=5bit)
  16137   02Ch 4     Compressed Size (total filesize, including "lzs" header)
  16138   030h 8     Name? (always "000000",00h,00h)
  16139   038h ..    Compressed data (usually at offset 38h)
  16140 decompress_gundam_lzs:
  16141    dst_end = dst+littleendian32bit[src+24h]
  16142    flg_bits = littleendian16bit[src+28h]   ;8,16,32
  16143    len_bits = littleendian16bit[src+2Ah]   ;2..7
  16144    len_mask = (1 shl len_bits)-1           ;03h..7Fh
  16145    src=src+littleendian16bit[src+22h]+20h
  16146    collected_bits=0
  16147   @@collect_more:
  16148    for i=0 to flg_bits/8-1    ;read 8bit/16bit/32bit little-endian
  16149      collected_bits=collected_bits+([src] SHL (i*8)), src=src+1
  16150    num_collected=flg_bits
  16151   @@decompress_lop:
  16152    if dst=dst_end then goto @@decompress_done
  16153    if num_collected=0 then goto @@collect_more
  16154    num_collected=num_collected-1
  16155    flagbits=flagbits SHR 1
  16156    if carry=1 then
  16157      [dst]=[src], dst=dst+1, src=src+1
  16158    else
  16159      temp=bigendian16bit[src], src=src+2
  16160      len=(temp AND len_mask)+3
  16161      disp=(temp SHR len_bits), if disp=0 then goto @@decompress_error
  16162      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  16163    endif
  16164    goto @@decompress_lop
  16165   @@decompress_done:
  16166    ret
  16167 
  16168 CDROM File Compression BZZ
  16169 --------------------------
  16170 
  16171 Used in .BZZ archives. Note that there are three slightly different .BZZ
  16172 archive formats (they are all using the same BZZ compression, only the BZZ
  16173 archive headers are  different).
  16174   Jersey Devil .BZZ (MagDemo10: JD\*.BZZ)
  16175   Bugs Bunny: Lost in Time (MagDemo25: BBLIT\*.BZZ)
  16176   The Grinch (MagDemo40: GRINCH\*.BZZ)
  16177 Neither the file header nor the archive directory entries do contain any
  16178 information about the decompressed size. Best workaround might be to decompress
  16179 the file twice (without storing the output in 1st pass, to determine the size
  16180 of the decompression buffer for 2nd pass).
  16181 
  16182 BZZ Decompression
  16183 The compression is fairly standard LZSS, except that it supports non-linear
  16184 length values, and it does support uncommon Len/Disp pairs like
  16185 7bitLen/9bitDisp (though usually, it does use standard 4bitLen/12bitDisp).
  16186   decompress_bzz:
  16187    method=byte[src], src=src+1       ;method (00h..1Fh) ;usually/always 0Bh)
  16188    shifter  = ((method/8) and 3)     ;00h..03h                ;usually 1
  16189    len_bits = ((method and 7) xor 7) ;07h..00h                ;usually 4
  16190    len_mask = (1 shl len_bits)-1     ;7Fh..00h                ;usually 0Fh
  16191    threshold=len_mask/2, if threshold>07h then threshold=13h  ;usually 07h
  16192    for i=0 to len_mask
  16193      if i>threshold then len_table[i] = ((i-threshold) shl shifter)+threshold+3
  16194      else len_table[i] = i+3 ;method=18h max=(7Fh-13h)*8+13h+3=376h=886 decimal
  16195    next i                    ;method=0Hh max=(0Fh-07h)*2+07h+3=1Ah=26 decimal
  16196    num_flags=bigendian24bit[src]+1, src=src+3   ;NUM24+1
  16197   @@collect_more:
  16198    if src>=src_end then goto @@decompress_error
  16199    flagbits=[src]+100h, src=src+1    ;8bit flags
  16200   @@decompress_lop:
  16201    flagbits=flagbits SHR 1
  16202    if zero then goto @@collect_more
  16203    if carry=1 then
  16204      if src>=src_end then goto @@decompress_error
  16205      [dst]=[src], dst=dst+1, src=src+1
  16206    else
  16207      if src+1>=src_end then goto @@decompress_error
  16208      temp=bigendian16bit[src], src=src+2
  16209      len=len_table[temp AND len_mask]
  16210      disp=temp SHR len_bits, if disp=0 then goto @@decompress_error
  16211      for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  16212    endif
  16213    num_flags=num_flags-1, if num_flags>0 then goto @@decompress_lop
  16214   @@decompress_error:
  16215    ret
  16216 Bug: Files can randomly contain NUM24 or NUM24+1 codes (that seems to be due to
  16217 a compressor bug or different compressor versions; the two variants are
  16218 unfortunately randomly mixed even within the same game).
  16219 And, compressed files are padded to 4-byte boundary (making it impossible to
  16220 distinguish between "NUM24+1" and "NUM24+padding").
  16221   Case 1) source has NUM24+1 codes
  16222            --> decode all NUM24+1 codes (otherwise output will be too small)
  16223   Case 2) source has NUM24 codes (and enough padding for another code)
  16224            --> decode all NUM24+1 codes (for compatibility with case 1)
  16225            --> output will have some constant garbage byte(s) appended
  16226            --> exception: omit last code if it contains invalid disp=0
  16227   Case 3) source has NUM24 codes (and not enough padding for another code)
  16228            --> decode only NUM24 codes (abort if NUM24+1 exceeds src_end)
  16229            --> output should (probably) have correct size
  16230            --> never exceed src_end which would be highly unstable
  16231 
  16232 CDROM File Compression RESOURCE (Star Wars Rebel Assault 2)
  16233 -----------------------------------------------------------
  16234 
  16235 Star Wars Rebel Assault 2 (RESOURCE.*\*)
  16236 BallBlazer Champions (*.DAT)
  16237  decompression function:
  16238   base=src, method=[src], dst_end=dst+BigEndian24bit[src+1], src=src+4
  16239  @@decompress_lop:
  16240   if dst>=dst_end then goto @@decompress_done
  16241   if [src] AND 80h then
  16242     if method=01h then
  16243       len=([src]-80h)/8+3, disp=(BigEndian16bit[src] AND 7FFh)+1, src=src+2
  16244     else  ;method=02h
  16245       len=([src]-80h)+4, disp=(BigEndian16bit[src+1])+1, src=src+3
  16246     for i=1 to len, [dst]=[dst-disp], dst=dst+1
  16247   else    ;uncompressed
  16248     len=[src]+1, src=src+1
  16249     for i=1 to len, [dst]=[src], src=src+1, dst=dst+1
  16250   goto @@decompress_lop
  16251  @@decompress_done:
  16252   src=(src+3) AND NOT 3
  16253   if LittleEndian32bit[src]<>crc(base, src-base) then error
  16254   ret
  16255 Note: Compression is (normally) used only in Top-level RESOURCE.* and *.DAT
  16256 archives (not in Nested archives). The Top-level archives do also contain some
  16257 uncompressed files (which contain data that is compressed on its own: SPU-ADPCM
  16258 audio, or encrypted BS bitmaps).
  16259 
  16260 Special case for BallBlazer Champions
  16261 Normally only Top-level archives contain compression, however, there are also
  16262 some Nested archives with compression in BallBlazer Champions:
  16263   STD_BBX.DAT\s*t\tp_a\*    ;\double compression, Top-level is ALSO compressed
  16264   BBX_INTR.DAT\data1\pics\* ;/
  16265   BBX_INTR.DAT\Stad\pics\*  ;\
  16266   BBX_INTR.DAT\Stad\wire\*  ; Nested archives with compression
  16267   BBX_INTR.DAT\Subtitl\*    ;
  16268   BBX_INTR.DAT\Subtitl\sub\*;/
  16269 The Nested archives don't have any compression flag or decompressed size
  16270 entries (so there's no good way for detecting compression in nested files).
  16271 
  16272 CDROM File Compression TIM-RLE4/RLE8
  16273 ------------------------------------
  16274 
  16275 Ape Escape (Sony 1999) (MagDemo22: KIDZ\*) has several compressed and
  16276 uncompressed TIMs in headerless archives, the archives can contain:
  16277   Compressed 4bpp RLE4-TIM with uncompressed CLUT ;\only 4bpp can be compressed
  16278   Compressed 4bpp RLE8-TIM with uncompressed CLUT ;/
  16279   Uncompressed 4bpp TIM with uncompressed CLUT    ;\only this type/combinations
  16280   Uncompressed 8bpp TIM with uncompressed CLUT    ; are allowed if uncompressed
  16281   Uncompressed 16pp TIM without CLUT              ;/
  16282   End code 00000000h (plus more zeropadding)      ;-end of headerless archive
  16283 The compression method is indicated by changing a reserved halfword in the TIM
  16284 header:
  16285   hdr[02h]=Method (0000h=Uncompressed, 0001h=RLE4, 0002h=RLE8)
  16286 The rest of the bytes in TIM header and in CLUT section are same as for normal
  16287 TIMs. The Bitmap section is as follows:
  16288 Decompressed size must be computed as Width*Height*2. The Section Size entry
  16289 contains Section header size, plus compressed size, plus padding to 4-byte
  16290 boundary.
  16291 Method=0001h (RLE4):
  16292  @@decompress_lop:
  16293   color=[src]/10h, len=([src] AND 0Fh)+1, src=src+1
  16294   for i=1 to len, putpixel(color), next i               ;len=1..10h
  16295   if numpixels<Width*Height*4 then goto @@decompress_lop
  16296 Method=0002h (RLE8):
  16297  @@decompress_lop:
  16298   color1=[src]/10h, color2=[src] AND 0Fh, src=src+1
  16299   if color1=color2
  16300     len=[src]+2, src=src+1
  16301     for i=1 to len, putpixel(color1), next i            ;len=2..101h
  16302   else
  16303     putpixel(color1), if numpixels<Width*Height*4 then putpixel(color2)
  16304   for i=1 to len, putpixel(color)       ;len=1..10h
  16305   if numpixels<Width*Height*4 then goto @@decompress_lop
  16306 The decompression functions in Ape Escape (MagDemo22: KIDZ\*) are found at:
  16307   80078760h ape_escape_load_tim_archive
  16308   8007894Ch ape_escape_decompress_with_4bit_lengths
  16309   800789FCh ape_escape_decompress_with_8bit_lengths
  16310 Examples for compressed TIMs are found at:
  16311   RLE8: Ape Escape, MagDemo22: KIDZ\KKIIDDZZ.HED\DAT\file004h\1stTIM
  16312   RLE4: Ape Escape, MagDemo22: KIDZ\KKIIDDZZ.HED\DAT\file135h\1stTIM
  16313   RLE8: Ape Escape, MagDemo22: KIDZ\KKIIDDZZ.HED\DAT\file139h\1stTIM
  16314 Being made by Sony, this might be an official (but late) TIM format extension,
  16315 unknown if there are any other games using that compression.
  16316 
  16317 CDROM File Compression RLE_16
  16318 -----------------------------
  16319 
  16320 Apocalypse (MagDemo16: APOC\CD.HED\*.RLE)
  16321 Spider-Man (MagDemo31,40: SPIDEY\CD.HED\*.RLE)
  16322 Spider-Man 2 (MagDemo50: HARNESS\CD.HED\*.RLE)
  16323   000h 8     ID "_RLE_16_"
  16324   008h 4     Decompressed Size (usually 3C008h) (33408h=Apocalypse warning.rle)
  16325   00Ch ..    RLE Compressed Data (usually a .BMR bitmap)
  16326 This is using simple RLE compression with 16bit len/data units (suitable for
  16327 16bpp VRAM data). The compression ratio ranges from not so bad to very bad.
  16328 
  16329 Decompression
  16330   src=src+0Ch                                       ;skip ID and size
  16331  @@decompress_lop:
  16332   len=halfword[src], src=src+2
  16333   if len=0000h then goto @@decompress_done          ;end-code
  16334   if (len AND 8000h)=0 then
  16335     for i=1 to len, halfword[dst]=halfword[src], dst=dst+2, src=src+2, next i
  16336   else
  16337     fillvalue=halfword[src], src=src+2
  16338     for i=1 to len-8000h, halfword[dst]=fillvalue, dst=dst+2, next i
  16339   goto @@decompress_lop
  16340  @@decompress_done:
  16341   ret
  16342 
  16343 Other RLE16 variants
  16344 A similar RLE16 variant is used in Croc 1, and another variant in Croc 2.
  16345 --> CDROM File Archive Croc 1 (DIR, WAD, etc.)
  16346 --> CDROM File Archive Croc 2 (DIR, WAD, etc.)
  16347 
  16348 CDROM File Compression PIM/PRS (Legend of Mana)
  16349 -----------------------------------------------
  16350 
  16351 Legend of Mana (.PIM/.PRS)
  16352   000h 1   Unknown (always 01h) (maybe File ID or Compression method)
  16353   001h ..  Compressed data  ;for TIM: usually 00,10, F0,00, 00,0x, F0,00, ...
  16354 Compression codes are:
  16355   nn,data[nn+1]  ;nn=00..EF len=nn+1   [dst]=data[1]             ;-uncompressed
  16356   F0,xn                     len=n+3    [dst]=0x         ;1x4bit  ;\
  16357   F1,nn,xx                  len=nn+4   [dst]=xx         ;1x8bit  ;
  16358   F2,nn,yx                  len=nn+2   [dst]=0x,0y      ;2x4bit  ; RLE fill
  16359   F3,nn,xx,yy               len=nn+2   [dst]=xx,yy      ;2x8bit  ;
  16360   F4,nn,xx,yy,zz            len=nn+2   [dst]=xx,yy,zz   ;3x8bit  ;/
  16361   F5,nn,xx,data[nn+4]       len=nn+4   [dst]=xx,data[1]          ;\interleaved
  16362   F6,nn,xx,yy,data[nn+3]    len=nn+3   [dst]=xx,yy,data[1]       ; fill combo
  16363   F7,nn,xx,yy,zz,data[nn+2] len=nn+2   [dst]=xx,yy,zz,data[1]    ;/
  16364   F8,nn,xx                  len=nn+4   [dst]=xx    ;xx=xx+1      ;\
  16365   F9,nn,xx                  len=nn+4   [dst]=xx    ;xx=xx-1      ; fill with
  16366   FA,nn,xx,ss               len=nn+5   [dst]=xx    ;xx=xx+ss     ; signed step
  16367   FB,nn,xx,yy,ss ;ss=signed len=nn+3   [dst]=xx,yy ;yyxx=yyxx+ss ;/
  16368   FC,xx,ny                  len=n+4    [dst]=[dst-yxx-1]         ;\
  16369   FD,xx,nn                  len=nn+14h [dst]=[dst-xx-1]          ; LZ compress
  16370   FE,xn                     len=n+3    [dst]=[dst-x*8-8]         ;/
  16371   FF                        len=0      end                       ;-end code
  16372 The compression is used for several files in Legend of Mana:
  16373   BIN\*.BIN       ---> packed misc binary
  16374   MAP\*\FDATA.PRS ---> packed resource, whatever
  16375   MAP\*\MAP*.PRS  ---> packed MPD resource, "SKmapDat"
  16376   WM\WMTIM\*.PIM  ---> packed TIM image, 384x384x4bpp, bad compression ratio
  16377   WM\WMAP\*.PAT   ---> packed loaddata
  16378   WM\WMAP\*.PIM   ---> packed TIM image, 320x256x16bit, with UNCOMPRESSED dupe
  16379 
  16380 CDROM File Compression BPE (Byte Pair Encoding)
  16381 -----------------------------------------------
  16382 
  16383 Byte Pair Encoding (BPE) does replace the most common byte-pairs with bytes
  16384 that don't occur in the data. That does work best if there are unused bytes
  16385 (eg. ASCII text, or 8bpp bitmaps with less than 256 colors).
  16386 
  16387 Bust A Groove (MagDemo18: BUSTGR_A\*.BPE)
  16388 Bust-A-Groove 2 (MagDemo37: BUSTAGR2\BUST2.BIN\*)
  16389   000h 4     ID "BPE_"
  16390   004h 4     Total Filesize of compressed file including header (big-endian)
  16391   ...  ..    Compression block(s)
  16392  Each compression block contains:
  16393   000h ..    Dictionary info
  16394   ...  2     Size of compressed data (big-endian)
  16395   ...  ..    Compressed data
  16396 The decompression function in Bust A Groove (MagDemo18) is at 80023860h, the
  16397 heap is in 1Kbyte Scratchpad RAM at 1F800208h, so heap size should be max 1F8h
  16398 bytes (assuming that the remaining Scratchpad isn't used for something else).
  16399 The fileheader lacks info about the decompressed size.
  16400 
  16401 Legend of Dragoon (MagDemo34: LOD\OVL\*.OV_ and LOD\SECT\*.BIN\*)
  16402   000h 4     Decompressed size (little-endian)
  16403   004h 4     ID "BPE",1Ah
  16404   008h ..    Compression block(s)
  16405   ...  ..    End code (00000000h) (aka last block with Blocksize=0)
  16406  Each compression block contains:
  16407   000h 4     Size of decompressed block (little-endian) (or 0=End code)
  16408   004h ..    Dictionary info
  16409   ...  ..    Compressed data
  16410   ...  ..    Padding to 4-byte boundary
  16411 Max nesting appears to be 2Ch, the decompression function allocates a 30h-byte
  16412 heap on stack, and fetches source data in 32bit units (occupying 4 heap bytes),
  16413 the decompressor does then remove 1 byte from heap, and adds 2 bytes in case of
  16414 nested codes.
  16415 
  16416 BPE Decompression for Bust-A-Groove and Legend of Dragoon
  16417   if [src+0]="BPE_" then type=GROOVE                                    ;\
  16418   if [src+4]="BPE",1Ah then type=DRAGOON                                ;
  16419   if type=GROOVE then src_end = src+BigEndian32bit[src+4]               ; hdr
  16420   if type=DRAGOON then dst_end = dst+LittleEndian32bit[src+0]           ;
  16421   src=src+8                                                             ;/
  16422  @@block_lop:
  16423   if type=DRAGOON then                                                  ;\blk
  16424     dst_blk_end = dst+LittleEndian32bit[src]+4, src=src+4               ; len
  16425     if dst=dst_blk_end then goto @@decompress_done                      ;/
  16426   for i=00h to FFh, dict1[i]=i, next i                                  ;\
  16427   i=00h                                                                 ;
  16428  @@dict_lop:                                                            ; dict
  16429   num=[src], src=src+1                                                  ;
  16430   if num>7Fh then i=i+(num-7Fh), num=0, if i=100h then goto @@dict_done ;
  16431   for j=0 to num                                                        ;
  16432     a=[src], src=src+1                                                  ;
  16433     if a<>i then b=[src], src=src+1, dict1[i]=a, dict2[i]=a             ;
  16434     i=i+1                                                               ;
  16435   if i<100h then goto @@dict_lop                                        ;
  16436  @@dict_done:                                                           ;/
  16437   if type=GROOVE then                                                   ;\blk
  16438     src_blk_end = src+BigEndian16bit[src]+2, src=src+2                  ;/len
  16439   i=0                                                                   ;\
  16440  @@data_lop:                                                            ;
  16441   if i=0 then                                                ;\         ; data
  16442     if type=GROOVE and src=src_blk_end then goto @@data_done ; get data ;
  16443     if type=DRAGOON and dst=dst_blk_end then goto @@data_done; from src ;
  16444     x=[src], src=src+1                                       ; or heap  ;
  16445   else                                                       ;          ;
  16446     i=i-1, x=heap[i]                                         ;/         ;
  16447   a=dict1[x]                                    ;-xlat                  ;
  16448   if a=x then                                   ;\                      ;
  16449     [dst]=x, dst=dst+1                          ; output data to        ;
  16450   else                                          ; dst or heap           ;
  16451     b=dict2[x], heap[i]=b, heap[i+1]=a, i=i+2   ;/                      ;
  16452   goto @@data_lop                                                       ;
  16453  @@data_done:                                                           ;/
  16454   if type=GROOVE and src<src_end then goto @@block_lop                  ;\next
  16455   if type=DRAGOON then src=(src+3) AND not 3, goto @@block_lop          ;/blk
  16456  @@decompress_done:
  16457   if type=DRAGOON and dst<>dst_end then error
  16458   ret
  16459 
  16460 Electronic Arts
  16461 Electronic Arts games support several compression methods, including a BPE
  16462 variant. That BPE variant is a bit unusual: It does have only one compression
  16463 block (with a single dictionary for the whole file), and uses escape codes for
  16464 rarely used bytes.
  16465 --> CDROM File Compression EA Methods
  16466 
  16467 CDROM File Compression RNC (Rob Northen Compression)
  16468 ----------------------------------------------------
  16469 
  16470 Rob Northen compression
  16471 Rob Northen compression (RNC) is a LZ/Huffman compression format used by
  16472 various games for PC, Amiga, PSX, Mega Drive, Game Boy, SNES and Atari Lynx.
  16473 Most RNC compressed files come in a standard 12h-byte header:
  16474   000h 3   Signature ("RNC") (short for Rob Northen Computing compression)
  16475   003h 1   Compression Method (01h or 02h)
  16476   004h 4   Size of Uncompressed Data                             ;big-endian
  16477   008h 4   Size of Compressed Data (SIZ)                         ;big-endian
  16478   00Ch 2   CRC16 on Uncompressed Data (with initial value 0000h) ;big-endian
  16479   00Eh 2   CRC16 on Compressed Data   (with initial value 0000h) ;big-endian
  16480   010h 1   Leeway (difference between compressed and uncompressed data in
  16481                    largest pack chunk, if larger than decompressed data)
  16482   011h 1   Number of pack chunks
  16483   012h SIZ Compressed Data
  16484   ... (..) Zeropadding to 800h-byte boundary-4 ;\as so in PSX Heart of Darkness
  16485   ... (4)  Unknown                             ;/
  16486 The compressed data consists of interleaved bit- and byte-streams, the first 2
  16487 bits of the bit stream are ignored.
  16488 
  16489 RNC Method 1 - with custom Huffman trees
  16490 The bit-stream is read in 16bit units (the 1st bit being in bit0 of 1st byte).
  16491   Each pack chunk contains the following:
  16492   * 3 Huffman trees (one for literal data sizes, one for distance values,
  16493     and one for length values) in the bit stream. These consist of:
  16494       o A 5 bit value for the amount of leaf nodes in the tree
  16495       o 4 bit values for each node representing their bit depth.
  16496   * One 16 bit value in the bitstream for the amount of subchunks in the
  16497     pack chunk.
  16498   * The subchunk data, which contains for each subchunk:
  16499       o A Huffman code value from the first tree in the bit stream for the
  16500         amount of literals in the byte stream.
  16501       o Literals from the byte stream.
  16502       o A Huffman code from the bit stream that represents the distance - 1
  16503         of a distance/length pair.
  16504       o A Huffman code from the bit stream that represents the length - 2
  16505         of a distance/length pair.
  16506 Unknown how that works exactly (see source code for details), unknown if method
  16507 1 was used on PSX.
  16508 
  16509 RNC Method 2 - with hardcoded Huffman trees
  16510 The bit-stream is read in 8bit units (the 1st bit being in bit7).
  16511   0     + Byte(DATA[1])              Copy 1 Byte from Source
  16512   1000  + Dist + Byte(X)             Copy 4 Bytes from Dest-(Dist+X+1)
  16513   10010 + Dist + Byte(X)             Copy 6 Bytes from Dest-(Dist+X+1)
  16514   10011 + Dist + Byte(X)             Copy 7 Bytes from Dest-(Dist+X+1)
  16515   1010  + Dist + Byte(X)             Copy 5 Bytes from Dest-(Dist+X+1)
  16516   10110 + Dist + Byte(X)             Copy 8 Bytes from Dest-(Dist+X+1)
  16517   10111 + nnnn + Byte(DATA[12..72])  Copy nnnn*4+12 Bytes from Source
  16518   110   + Byte(X)                    Copy 2 Bytes from Dest-(X+1)
  16519   1110  + Dist + Byte(X)             Copy 3 bytes from Dest-(Dist+X+1)
  16520   1111  + Byte(0) + 0 + zeropadding  End of last pack chunk
  16521   1111  + Byte(0) + 1                End of non-last pack chunk
  16522   1111  + Byte(L) + Dist + Byte(X)   Copy L+8 Bytes from Dest-(Dist+X+1) ;L>00h
  16523 Dist values:
  16524   0      = 0000h            1000   = 0200h
  16525   110    = 0100h            1001   = 0300h
  16526   111000 = 0C00h            101000 = 0800h
  16527   111001 = 0D00h            101001 = 0900h
  16528   11101  = 0600h            10101  = 0400h
  16529   111100 = 0E00h            101100 = 0A00h
  16530   111101 = 0F00h            101101 = 0B00h
  16531   11111  = 0700h            10111  = 0500h
  16532 The purpose of the pack chunks isn't quite clear, it might be related to memory
  16533 restrictions on old CPUs. In PSX Heart of Darkness they are chosen so that the
  16534 decompressed data is max 3000h bytes per chunk. Unknown if the next chunk may
  16535 copy data from previous chunk.
  16536 
  16537 Links
  16538   http://aminet.net/package/util/pack/RNC_ProPack - official tool & source code
  16539   https://segaretro.org/Rob_Northen_compression - description (contains bugs)
  16540 
  16541 RNC is used in a number of games by UK developers (notably Bullfrog and
  16542 Traveller's Tales), including Sonic 3D: Flickies' Island, Blam! Machinehead,
  16543 Dungeon Keeper 2, Magic Carpet, Syndicate and Syndicate Wars.
  16544 
  16545 RNC in PSX Games
  16546   Method 2: Demolition Racer (MagDemo27: DR\DD.DAT\*.RNC)
  16547   Method 2: Heart of Darkness (IMAGES\US.TIM)
  16548   Method 2: Jonah Lomu Rugby (LOMUDEMO\GFX\*.PAK)
  16549   Method 2: NBA Jam: Tournament Edition (*.RNC, headerless .BIN/.GFX archives)
  16550   Method 2: Test Drive 5 (MagDemo13: TD5.DAT\*.RNC)
  16551   Method 2: Test Drive Off-Road 3 (MagDemo27: TDOR3\TDOR3.DAT\*.rnc)
  16552 
  16553 RNC in Mega Drive games
  16554   3 Ninjas Kick Back
  16555   Addams Family
  16556   Addams Family Values
  16557   The Adventures of Mighty Max
  16558   Ast‚rix and the Great Rescue
  16559   Ast‚rix and the Power of the Gods
  16560   The Incredible Hulk
  16561   The Itchy & Scratchy Game (unreleased)
  16562   Marsupilami
  16563   Mortal Kombat
  16564   Mr. Nutz
  16565   Outlander
  16566   The Pagemaster
  16567   RoboCop 3
  16568   Spirou
  16569   Spot Goes to Hollywood
  16570   Stargate
  16571   Street Racer
  16572   Tinhead
  16573   Tintin in Tibet
  16574   World Championship Soccer II
  16575 
  16576 CDROM File Compression Darkworks
  16577 --------------------------------
  16578 
  16579 Used by Alone in the Dark The New Nightmare (FAT.BIN\LEVELS\*\chunks)
  16580 
  16581 Decompression
  16582 The decompressor is designed to hook the sector loading function: It does
  16583 decompress incoming sectors during loading, and forwards the decompressed data
  16584 to the original sector loading function. The decompressed data is temporarily
  16585 stored in two small Dict buffers (which do also serve as compression
  16586 dictionary).
  16587  decompress:
  16588   dictsize=1000h, dict0=alloc(dictsize), dict1=alloc(dictsize)
  16589   src=load_next_800h_byte_sector  ;load first sector
  16590   dst=dict0                       ;temp dest in current dict
  16591   dst_base=dst                    ;memorize start of newly decompressed data
  16592  @@decompress_lop:
  16593   if [src]=00h then                                             ;\
  16594     esc=[src+1], src=src+1                                      ;
  16595     forward_to_actual_dest(source=dst_base, len=dst-dst_base)   ; escape
  16596     if esc=0 or esc>4 then esc=2 (or warn_invalid_escape_code)  ;
  16597     if esc=1 then goto @@decompress_done                        ;
  16598     if esc=2 or esc=4 then src=load_next_800h_byte_sector       ;
  16599     if esc=3 or esc=4 then swap(dict0,dict1), dst=dict0         ;
  16600     dst_base=dst                                                ;/
  16601   elseif ([src] AND 03h)=0 then                                 ;\
  16602     len=[src]/4+2, dat=[src+1], src=src+2                       ; fill 8bit
  16603     for i=1 to len, [dst]=dat, dst=dst+1                        ;/
  16604   elseif ([src] AND 03h)=1 then                                 ;\
  16605     len=[src]/4+([src+2] AND 40h)+4                             ;
  16606     ptr=[src+1]+([src+2] AND 3Fh)*100h                          ; LZ compressed
  16607     if ptr+len>dictsize then error (exceeds allocated dictsize) ;
  16608     if ([src+2] AND 80h) then ptr=ptr=dict1 else ptr=ptr=dict0  ;
  16609     src=src+3                                                   ;
  16610     for i=1 to len, [dst]=[ptr], ptr=ptr+1, dst=dst+1           ;/
  16611   elseif ([src] AND 03h)=2 then                                 ;\
  16612     len=[src]/4+3, dat0=[src+1], dat1=[src+2], src=src+3        ; fill 16bit
  16613     for i=1 to len, [dst]=dat0, [dst+1]=dat1, dst=dst+2         ;/
  16614   elseif ([src] AND 03h)=3 then                                 ;\
  16615     len=[src]/4+1, src=src+1                                    ; uncompressed
  16616     for i=1 to len, [dst]=[src], src=src+1, dst=dst+1           ;/
  16617   goto @@decompress_lop
  16618  @@decompress_done:
  16619   dealloc(dict0), dealloc(dict1)
  16620   ret
  16621 There are one or more escape codes per sector (one to indicate the of the
  16622 sector, plus further escape codes to swap the Dict buffers whenever the current
  16623 Dict is full).
  16624 The original decompressor is doing the forwarding in 800h-byte units, so Dict
  16625 swapping may be only done when dict0 contains a multiple of 800h bytes (aka
  16626 dictsize bytes).
  16627 For whatever reason, there are only 4Kbyte per Dict allocated (although the
  16628 14bit LZ indices could have addressed up to 16Kbyte per Dict).
  16629 
  16630 CDROM File Compression Blues
  16631 ----------------------------
  16632 
  16633 Blue's Clues: Blue's Big Musical (VRAM and FRAM chunks in *.TXD)
  16634 Decompression function:
  16635   if LittleEndian32bit[src+08h]<>1 then error  ;compression flag
  16636   dst_end=dst+LittleEndian32bit[src+14h], src=src+18h, num_collected=0
  16637  @@decompress_lop:
  16638   if GetBit=1 then
  16639     [dst]=[src], src=src+1, dst=dst+1           ;code 1 uncompressed byte
  16640   elseif GetBit=1 then
  16641     len=[src], src=src+1                        ;code 01 fill or end code
  16642     if len=00h then goto @@decompress_done
  16643     len=len+1, fillvalue=[dst-1]
  16644     for i=1 to len, [dst]=fillvalue, dst=dst+1
  16645   else
  16646     len=GetBit*2+GetBit
  16647     if len=0 then                               ;code 0000 long LZ range
  16648       len=[src] AND 0Fh, disp=[src]/10h+[src+1]*10h-1000h, src=src+2
  16649     else                                        ;code 00xx short LZ range
  16650       disp=[src]-100h, src=src+1
  16651     len=len+1
  16652     for i=1 to len, [dst]=[dst+disp], dst=dst+1
  16653   goto @@decompress_lop
  16654  @@decompress_done:
  16655   if dst<>dst_end then error
  16656   ret
  16657  ;---
  16658  GetBit:
  16659   if num_collected=0 then collected=[src], src=src+1, num_collected=8
  16660   collected=collected*2
  16661   return (collected/100h) AND 1
  16662 
  16663 CDROM File Compression Z (Running Wild)
  16664 ---------------------------------------
  16665 
  16666 Running Wild (MagDemo15: RUNWILD\*.BIN\*.Z and *.z)
  16667   decompress_z:
  16668    src=src+4            ;skip 32bit decompressed size entry
  16669   @@reload_lop:
  16670    load_table1          ;table for first 9bits
  16671    load_table2          ;table for codes longer than 9bits
  16672   @@decompress_lop:
  16673    sym=get_symbol()
  16674    if sym<100h then [dst]=sym, dst=dst+1, goto @@decompress_lop
  16675    if sym=100h then goto @@escape
  16676    len=sym-0FCh                         ;change 101h..140h to 05h..44h
  16677    disp=((get_symbol()-101h)*40h)       ;change 101h..140h to 00h..3Fh*40h
  16678    disp=((get_symbol()-101h) or disp)+1 ;change 101h..140h to 00h..3Fh+above+1
  16679    copy len bytes from dst-disp to dst
  16680    goto @@decompress_lop
  16681   @@escape:
  16682    if GetBits(1)=0 then goto @@reload_lop
  16683    ret
  16684   ;-----
  16685   load_table1:
  16686    t=0
  16687   @@load_lop:
  16688    x=GetBits(10h)
  16689    if x and 8000h then num=1 else num=(1 shl (9-(x/400h)))
  16690    for i=1 to num, table1[t]=x, t=t+1, next i
  16691    if t<200h then goto @@load_lop
  16692    ret
  16693   ;-----
  16694   load_table2:
  16695    num=GetBits(9)*2      ;can be 0=none, max=3FEh
  16696    if num>0 then for i=0 to num-1, table2[i]=GetBits(9), next i
  16697    ret
  16698   ;-----
  16699   get_symbol:
  16700    ;returns a value in range 0..140h:
  16701    ;  00h..FFh   = data 00h..FFh   (or unused for disp codes)
  16702    ;  100h       = escape          (or unused for disp codes)
  16703    ;  101h..140h = length 05h..44h (or 6bit fraction of 12bit disp)
  16704    ;  141h..3FFh = would be possible for short codes, but shouldn't be used
  16705    x=table1[PeekBits(9)]
  16706    if (x and 8000h)=0 then SkipBits(x/400h), return (x and 3FFh)  ;-short code
  16707    SkipBits(9)   ;skip first 9 bits, and process futher bit(s)..  ;\
  16708    x=x-0C000h    ;change C000h..C1FFh and up to 000h..1FFh        ; long code
  16709   @@lop:                                                          ; (with more
  16710    x=table2[x*2+GetBits(1)]             ;branch node0/node1       ; than 9bit)
  16711    if x>=141h then x=x-141h, goto @@lop                           ;
  16712    return x                                                       ;/
  16713 The bitstream is fetched in little endian 16bit units (the first bit is in bit7
  16714 of second byte). PeekBits returns the next some bits without discarding them,
  16715 SkipBits does discard them, GetBits does combine PeekBits+SkipBits.
  16716 Note: The decompression function in Running Wild (MagDemo15) is at 80029D10h.
  16717 
  16718 CDROM File Compression ZAL (Z-Axis)
  16719 -----------------------------------
  16720 
  16721 Thrasher: Skate and Destroy (MagDemo27: SKATE\ASSETS\*.ZAL) (Z-Axis)
  16722 Dave Mirra Freestyle BMX (MagDemo36: BMX\ASSETS\*.ZAL) (Z-Axis)
  16723 Dave Mirra Freestyle BMX (MagDemo46: BMX\ASSETS\*.ZAL) (Z-Axis)
  16724 ZAL compression is used in ZAL archives. The archive header contains compressed
  16725 and decompressed size for each file (and a compression flag indicating whether
  16726 the archive is compressed at all).
  16727 
  16728 ZAL Decompression
  16729   if src_len=0 then goto @@decompress_done      ;empty (without end code)
  16730   lzlen=0, rawlen=0
  16731   if [src]=10h..FFh then                                ;\special handling
  16732     rawlen=[src]-11h, src=src+1                         ; for code=10h..FFh
  16733     if rawlen<=0 then goto @@decompress_error           ;/at begin of source
  16734  @@decompress_lop:
  16735   memcopy(dst-disp,dst,lzlen)   ;copy compressed bytes
  16736   memcopy(src,dst,rawlen)       ;copy uncompressed bytes
  16737   code=[src], src=src+1
  16738   if code=00h..0Fh then
  16739     if rawlen=0   ;when OLD rawlen=0...
  16740       lzlen=0, rawlen=code+3                            ;\
  16741       if rawlen=3 then                                  ;
  16742         while [src]=00h, rawlen=rawlen+FFh, src=src+1   ;
  16743         rawlen=rawlen+[src]+0Fh, src=src+1              ;/
  16744     else          ;when OLD rawlen>0, and depending on OLD lzlen...
  16745       rawlen=code AND 03h
  16746       disp=code/4+[src]*4, src=src+1
  16747       if lzlen=0 then disp=disp+801h, lzlen=3, else then disp=disp+1h, lzlen=2
  16748   if code=10h..1Fh then
  16749     lzlen=(code AND 07h)+2
  16750     if lzlen=2 then
  16751       while [src]=00h, lzlen=lzlen+FFh, src=src+1
  16752       lzlen=lzlen+[src]+07h, src=src+1
  16753     rawlen=[src] AND 03h, disp=[src]/4+[src+1]*40h+(code/8 AND 1)*4000h+4000h
  16754     src=src+2
  16755     if disp=4000h AND code=11h then goto @@decompress_done    ;end code
  16756     if disp=4000h AND code<>11h then goto @@decompress_error
  16757   if code=20h..3Fh then
  16758     lzlen=code-20h+2
  16759     if lzlen=2 then
  16760       while [src]=00h, lzlen=lzlen+FFh, src=src+1
  16761       lzlen=lzlen+[src]+1Fh, src=src+1
  16762     rawlen=[src] AND 03h, disp=[src]/4+[src+1]*40h+1, src=src+2
  16763   if code=40h..FFh then
  16764     rawlen=code AND 03h
  16765     lzlen=(code/20h)+1
  16766     disp=((code/4) AND 07h)+([src]*8)+1, src=src+1
  16767   goto @@decompress_lop
  16768  @@decompress_done:
  16769   ret
  16770 
  16771 CDROM File Compression EA Methods
  16772 ---------------------------------
  16773 
  16774 Electronic Arts Compression Headers
  16775 The files start with a 16bit big-endian Method value, with following bits:
  16776   0-7     ID (usually FBh) (or 31h for Method 4A31h with 16bit sizes)
  16777   8       Extended Header (usually 0) (or 1 for headers with extra entries)
  16778   9-14    Used to distinguish different methods
  16779   15      Extended Size (usually 0 for 24bit sizes) (or 1 for 32bit sizes)
  16780 The most common Method values are:
  16781   10FBh = LZSS Compression (RefPack)
  16782   90FBh = LZSS Compression (RefPack, with 32bit size) (not on PSX)
  16783   30FBh = Huffman Compression
  16784   32FBh = Huffman Compression with filter
  16785   34FBh = Huffman Compression with dual filter
  16786   46FBh = BPE Byte-Pair Encoding
  16787   4AFBh = RLE Run-Length Encoding
  16788   4A31h = RLE Run-Length Encoding, with 16bit size
  16789   C0FBh = File Archive (not a compression method)
  16790 Most or all PSX files have Bit8=0, but anyways, the decompressor does support
  16791 skipping extra header entries in files with Bit8=1 (with all methods except
  16792 RLE).
  16793 Most or all PSX files have Bit15=0, games for newer consoles can reportedly
  16794 have Method=90FBh (unknown if anything like B2FBh or CAFBh does also exist).
  16795 Most or all PSX files have Bit0-7=FBh (supposedly short for Frank Barchard),
  16796 the 16bit mode with Bit0-7=31h is supported for Method=4A31h only (the
  16797 decompressor would also accept invalid methods like 1031h or 3431h, but doesn't
  16798 actually support 16bit mode for those).
  16799 
  16800 Compression Formats
  16801 --> CDROM File Compression EA Methods (LZSS RefPack)
  16802 --> CDROM File Compression EA Methods (Huffman)
  16803 --> CDROM File Compression EA Methods (BPE)
  16804 --> CDROM File Compression EA Methods (RLE)
  16805 
  16806 Usage in PSX games
  16807 The compression can be used to compress whole files:
  16808   PGA Tour 96, 97, 98 (*.* and *.VIV\*) (with method 10FBh)
  16809   Need for Speed 3 Hot Pursuit (*.Q* with method 10FBh, 30FBh, 32FBh)
  16810 Or to compress texture bitmaps inside of .PSH file chunks:
  16811   FIFA - Road to World Cup 98 (*.PSH chunk C0h/C1h with method 10FBh)
  16812   Sled Storm (MagDemo24: ART3\LOAD*.PSH chunk C0h/C1h with method 10FBh)
  16813   WCW Mayhem (MagDemo28: WCWDEMO\*.BIG\*.PSH with chunk C0h/C1h with 10FBh)
  16814 The decompressor supports further methods (like 34FBh, 46FBh, 4AFBh), but there
  16815 aren't any files or chunks known to actually use those compression formats.
  16816 
  16817 Note: Some compressed files are slightly larger than uncompressed files (eg.
  16818 filesizes for PGA Tour 96, 97, 98 COURSES\*\*.VIV\*.mis are compressed=58h,
  16819 uncompressed=50h).
  16820 
  16821 See also
  16822 http://wiki.niotso.org/RefPack - LZ method
  16823 
  16824 CDROM File Compression EA Methods (LZSS RefPack)
  16825 ------------------------------------------------
  16826 
  16827 RefPack
  16828   000h 2     Method (10FBh, or 11FBh,90FBh,91FBh) (big-endian)
  16829   ...  (3/4) Compressed size   (24bit or 32bit)   (optional)
  16830   ...  3/4   Uncompressed size (24bit or 32bit)   (big-endoan)
  16831   ...  ..    Compressed data
  16832 The compression is some kind of LZSS/LZH variant (similar to Z-Axis .ZAL
  16833 files). The compressed data consists of a big-endian bit-stream (or
  16834 byte-stream, as all codes are multiples of 8bits). The Compression codes are:
  16835   0ddzzzrrdddddddd                  rawlen=r(2), lzlen=z(3)+3,  disp=d(10)+1
  16836   10zzzzzzrrdddddddddddddd          rawlen=r(2), lzlen=z(6)+4,  disp=d(14+1
  16837   110dzzrrddddddddddddddddzzzzzzzz  rawlen=r(2), lzlen=z(10)+5, disp=d(17)+1
  16838   111rrrrr                          rawlen=r(5)*4+4, lzlen=0
  16839   111111rr                          rawlen=r(2), lzlen=0, endflag=1
  16840 refpack_decompress:
  16841   method=BigEndian16bit[src], src=src+2
  16842   if (method AND 100h)>0 then src=src+3+method/8000h ;compressed size, if any
  16843   if (method AND 8000h]=0 then dst_size=BigEndian24bit[src], src=src+3
  16844   if (method AND 8000h)>0 then dst_size=BigEndian32bit[src], src=src+4
  16845   endflag=0
  16846  @@decompress_lop:
  16847   if ([src] AND 80h)=0 then
  16848     rawlen=[src] AND 03h
  16849     lzlen=([src] AND 1Fh)/4+3
  16850     disp=([src] AND 60h)*8+[src+1]+1
  16851     src=src+2
  16852   elseif ([src] AND 40h)=0 then
  16853     rawlen=[src+1]/40h
  16854     lzlen=[src] AND 3Fh+4
  16855     disp=([src+1] AND 3Fh)*100h+[src+2]+1
  16856     src=src+3
  16857   elseif ([src] AND 20h)=0 then
  16858     rawlen=[src] AND 03h
  16859     lzlen=([src] AND 0Ch)*40h+[src+3]+5
  16860     disp=([src] AND 10h)*1000h+[src+1]*100h+[src+2]+1
  16861     src=src+4
  16862   elseif ([src] AND FCh)=FCh then
  16863     rawlen=[src] AND 03h
  16864     lzlen=0
  16865     src=src+1, endflag=1
  16866   else
  16867     rawlen=([src] AND 1Fh)*4+4
  16868     lzlen=0
  16869     src=src+1
  16870   for i=1 to rawlen, [dst]=[src], src=src+1, dst=dst+1, next i
  16871   for i=1 to lzlen, [dst]=[dst-disp], dst=dst+1, next i
  16872   if endflag=0 then goto @@decompress_lop
  16873   if (dst-dst_base)<>dst_size then error
  16874   ret
  16875 
  16876 CDROM File Compression EA Methods (Huffman)
  16877 -------------------------------------------
  16878 
  16879 Huffman
  16880   000h 2    Method (30FBh..35FBh) (big-endian)
  16881   ...  (3)  Extra 3 bytes (only present if Method.bit8=1)
  16882   ...  3    Decompressed Size     (big-endian)
  16883   ...  1    Escape code
  16884   ...  ..   Number of codes per width
  16885   ...  ..   Data placement for each code
  16886   ...  ..   Compressed Data
  16887 
  16888 Huffman
  16889   decompress_ea_huffman:
  16890    method=GetBits(16)    ;3xFBh                     ;-get method (30FBh..35FBh)
  16891    if method AND 100h then dummy=GetBits(24)        ;-skip extra (if any)
  16892    dst_size=GetBits(24)                             ;-get uncompressed size
  16893    ESC=GetBits(8)                                   ;-get escape code
  16894    huffwidth=0, huffcode=0, totalnumcodes=0         ;\
  16895    while (huffcode shl (10h-huffwidth))<10000h      ;
  16896      num=GetVarLenCode                              ; get num codes per width
  16897      huffwidth=huffwidth+1                          ;
  16898      numcodes_per_width[width]=num                  ;
  16899      totalnumcodes=totalnumcodes+num                ;
  16900      huffcode=(huffcode*2)+num                      ;/
  16901    for i=0 to FFh, data_defined_flags[i]=00h        ;\
  16902    dat=FFh, index=0                                 ;
  16903    while index<totalnumcodes                        ;
  16904      n=GetVarLenCode+1               ;-             ; get/assign data values
  16905      while n>0  ;search Nth notyet defined entry    ;
  16906        dat=(dat+1) AND FFh  ;wrap in 8bit range!    ;
  16907        if data_defined_flags[dat]=0 then n=n-1      ;
  16908      data_defined_flags[dat]=1                      ;
  16909      data_values[index]=dat, index=index+1          ;/
  16910    huffcode=0000h, index=0                          ;\
  16911    InitEmptyHuffTree(data_tree)                     ;
  16912    for width=1 to huffwidth                         ;
  16913      for i=1 to numcodes_per_width[width]           ; create huffman tree
  16914        dat=data_values[index], index=index+1        ;
  16915        CreateHuffCode(data_tree,dat,huffcode,width) ;
  16916        huffcode=huffcode+(1 shl (10h-width)         ;/
  16917   @@decompress_lop:                                 ;\
  16918    dat=GetHuffCode(data_tree)                       ;
  16919    if dat<>ESC                                      ;
  16920      [dst]=dat, dst=dst+1                           ; decompress
  16921    else                                             ;
  16922      num=GetVarLenCode                              ;
  16923      if num=0 then                                  ;
  16924        if GetBits(1)=1 then goto @@decompress_done  ;
  16925        [dst]=GetBits(8), dst=dst+1                  ;
  16926      else                                           ;
  16927        dat=[dst-1]                                  ;
  16928        for i=0 to num-1, [dst]=dat, dst=dst+1       ;
  16929    goto @@decompress_lop                            ;/
  16930   @@decompress_done:
  16931    if (dst-dst_base)<>dst_size then error                 ;-error check
  16932    dst=dst_base, x=00h, y=00h                             ;\
  16933    if (method AND FEFFh)=32FBh                            ; optional final
  16934      for i=0 to dst_size-1, x=x+[dst+i], [dst+i]=x        ; unfiltering
  16935    if (method AND FEFFh)=34FBh                            ;
  16936      for i=0 to dst_size-1, x=x+[dst+i], y=y+x, [dst+i]=y ;/
  16937    ret
  16938   ;------------------
  16939   GetVarLenCode:
  16940    num=2
  16941    while GetBits(1)=0, num=num+1
  16942    return (GetBits(num)+(1 shl num)-4)
  16943   GetBits(num):
  16944    return "num" bits, fetched from big-endian bitstream
  16945   GetHuffCode(data_tree):
  16946    ...
  16947   InitEmptyHuffTree(data_tree):
  16948    ...
  16949   CreateHuffCode(data_tree,dat,huffcode,width):
  16950    ...
  16951   numcodes_per_width[10h]   ;9bit numcodes per width 0..15 (entry[0]=unused)
  16952   data_values[100h]         ;8bit data values for up to 100h huffman codes
  16953   data_defined_flags[100h]  ;1bit flags for data(00h..FFh)
  16954 
  16955 
  16956 CDROM File Compression EA Methods (BPE)
  16957 ---------------------------------------
  16958 
  16959 Byte-Pair Encoding
  16960   000h 2    Method (46FBh or 47FBh) (big-endian)
  16961   ...  (5)  Extra 5 bytes (only present if Method=47FBh)
  16962   ...  3    Decompressed Size       (big-endian)
  16963   ...  1    Escape code
  16964   ...  1    Number of Dict entries (N)
  16965   ...  N*3  Dict (each 3 bytes: Index,Dat1,Dat2)
  16966   ...  ..   Compressed Data
  16967 decompress_bpe:
  16968   method=BigEndian16bit[src], src=src+2
  16969   if method=47FBh then src=src+5
  16970   dst_size=BigEndian24bit[src], src=src+3
  16971   esc=[src], src=src+1
  16972   num=[src], src=src+1
  16973   for i=0 to FFh, dict1[i]=i    ;initially default=self (uncompressed bytes)
  16974   for i=1 to num, j=[src], dict1[j]=[src+1], dict2[j]=[src+2], src=src+3
  16975  @@decompress_lop:
  16976   x=[src], src=src+1
  16977   if x=dict1[x] then
  16978     if x=esc then x=[src], src=src+1, if x=00h then goto @@decompress_done
  16979     [dst]=x, dst=dst+1
  16980   else
  16981     heap[0]=x, i=1
  16982     while i>0
  16983       i=i-1, x=heap[i], a=dict1[x]
  16984       if a=x then [dst]=x, dst=dst+1                    ;\output data to
  16985       else b=dict2[x], heap[i]=b, heap[i+1]=a, i=i+2    ;/dst or heap
  16986   goto @@decompress_lop
  16987  @@decompress_done:
  16988   if (dst-dst_base)<>dst_size then error
  16989   ret
  16990 
  16991 CDROM File Compression EA Methods (RLE)
  16992 ---------------------------------------
  16993 
  16994 Run-Length Encoding
  16995   000h 2    Method (4AFBh=24bit or 4A31h=16bit) (big-endian)
  16996   ...  2/3  Decompressed Size (24bit or 16bit)  (big-endian)
  16997   ...  ..   Compressed Data
  16998 Compression codes are:
  16999   00h..3Fh  Copy 0..3Fh uncompressed bytes
  17000   40h..7Fh  Load new fillbyte and fill 0..3Fh bytes
  17001   80h..BFh  Use old fillbyte and fill 0..3Fh bytes (initial fillbyte=00h)
  17002   C0h..FFh  Copy 0..3Fh bytes with constant value in upper 4bit
  17003 decompress_bpe:
  17004   method=BigEndian16bit[src], src=src+2
  17005   if (method AND 00FFh)=31h then dst_size=BigEndian16bit[src], src=src+2
  17006   if (method AND 00FFh)<>31h then dst_size=BigEndian24bit[src], src=src+3
  17007   fillbyte=00h  ;initially zero
  17008  @@decompress_lop:
  17009   type=[src]/40h, len=[src] AND 3Fh, src=src+1, dst_size=dst_size-len
  17010   if type=0 then                                          ;\uncompressed bytes
  17011     for i=1 to len, [dst]=[src], src=src+1, dst=dst+1     ;/
  17012   elseif type=1 then                                      ;\
  17013     fillbyte=[src], src=src+1                             ; fill with new dat
  17014     for i=1 to len, [dst]=fillbyte, dst=dst+1             ;/
  17015   elseif type=2 then                                      ;\fill with old dat
  17016     for i=1 to len, [dst]=fillbyte, dst=dst+1             ;/
  17017   elseif type=3 then
  17018     x=[src], [dst]=x, src=src+1, dst=dst+1, x=x AND F0h
  17019     for i=2 to len      ;<-- or so?
  17020       if (i AND 1)=0 then [dst]=x+([src]/10h) dst=dst+1
  17021       if (i AND 1)=1 then [dst]=x+([src] AND 0Fh), dst=dst+1, src=src+1
  17022   if dst_size<>0 then goto @@decompress_lop
  17023   ret
  17024 
  17025 CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  17026 ------------------------------------------------------
  17027 
  17028 Inflate/Deflate is a common (de-)compression algorithm, used by ZIP, ZLIB, and
  17029 GZIP.
  17030 
  17031 --> Inflate - Core Functions
  17032 --> Inflate - Initialization & Tree Creation
  17033 --> Inflate - Headers and Checksums
  17034 
  17035 In PSX cdrom-images, ZLIB is used by the .CDZ cdrom-image format:
  17036 --> CDROM Disk Image/Containers CDZ
  17037 In PSX games, ZLIB is used by:
  17038   Twisted Metal 4 (MagDemo30: TM4DATA\*.MR\* and *.IMG\*)
  17039   Kula Quest / Kula World / Roll Away (*.PAK) (*.PAK\*)
  17040   (and probably more games... particulary files starting with "x")
  17041 In PSX games, GZIP is used by:
  17042   Final Fantasy VII (FF7) (BATTLE\TITLE.BIN)
  17043   Gran Turismo 2 (MagDemo27: GT2\*) (with corrupted/zeropadded GZIP footers)
  17044   Mat Hoffman's Pro BMX (old demo) (MagDemo39: BMX\BMXCD.HED\TITLE_H.ZLB)
  17045 In PSX games, Inflate (with slightly customized block headers) is used by:
  17046   Mat Hoffman's Pro BMX (new demo) (MagDemo48: MHPB\FE.WAD+STR)
  17047 In PSX games, Inflate (with ignored block type, dynamic tree only) is used by:
  17048   Project Horned Owl (COMDATA.BIN, DEMODATA.BIN, ROLL.BIN, ST*DATA.BIN)
  17049 
  17050 Inflate - Core Functions
  17051 ------------------------
  17052 
  17053 tinf_uncompress(dst,src)
  17054  tinf_init()                    ;init constants (needed to be done only once)
  17055  tinf_align_src_to_byte_boundary()
  17056  repeat
  17057   bfinal=tinf_getbit()          ;read final block flag (1 bit)
  17058   btype=tinf_read_bits(2)       ;read block type (2 bits)
  17059   if btype=0 then tinf_inflate_uncompressed_block()
  17060   if btype=1 then tinf_build_fixed_trees(), tinf_inflate_compressed_block()
  17061   if btype=2 then tinf_decode_dynamic_trees(), tinf_inflate_compressed_block()
  17062   if btype=3 then ERROR         ;reserved
  17063  until bfinal=1
  17064  tinf_align_src_to_byte_boundary()
  17065  ret
  17066 
  17067 tinf_inflate_uncompressed_block()
  17068  tinf_align_src_to_byte_boundary()
  17069  len=LittleEndian16bit[src+0]                             ;get len
  17070  if LittleEndian16bit[src+2]<>(len XOR FFFFh) then ERROR  ;verify inverse len
  17071  src=src+4                                                ;skip len values
  17072  for i=0 to len-1, [dst]=[src], dst=dst+1, src=src+1, next i    ;copy block
  17073  ret
  17074 
  17075 tinf_inflate_compressed_block()
  17076  repeat
  17077   sym1=tinf_decode_symbol(tinf_len_tree)
  17078   if sym1<256
  17079    [dst]=sym1, dst=dst+1
  17080   if sym1>256
  17081    len  = tinf_read_bits(length_bits[sym1-257])+length_base[sym1-257]
  17082    sym2 = tinf_decode_symbol(tinf_dist_tree)
  17083    dist = tinf_read_bits(dist_bits[sym2])+dist_base[sym2]
  17084    for i=0 to len-1, [dst]=[dst-dist], dst=dst+1, next i
  17085  until sym1=256
  17086  ret
  17087 
  17088 tinf_decode_symbol(tree)
  17089  sum=0, cur=0, len=0
  17090  repeat                         ;get more bits while code value is above sum
  17091   cur=cur*2 + tinf_getbit()
  17092   len=len+1
  17093   sum=sum+tree.table[len]
  17094   cur=cur-tree.table[len]
  17095  until cur<0
  17096  return tree.trans[sum+cur]
  17097 
  17098 tinf_read_bits(num)     ;get N bits from source stream
  17099  val=0
  17100  for i=0 to num-1, val=val+(tinf_getbit() shl i), next i
  17101  return val
  17102 
  17103 tinf_getbit()           ;get one bit from source stream
  17104  bit=tag AND 01h, tag=tag/2
  17105  if tag=00h then tag=[src], src=src+1, bit=tag AND 01h, tag=tag/2+80h
  17106  return bit
  17107 
  17108 tinf_align_src_to_byte_boundary()
  17109  tag=01h   ;empty/end-bit (discard any bits, align src to byte-boundary)
  17110  ret
  17111 
  17112 Inflate - Initialization & Tree Creation
  17113 ----------------------------------------
  17114 
  17115 tinf_init()
  17116  tinf_build_bits_base(length_bits, length_base, 4, 3)
  17117  length_bits[28]=0, length_base[28]=258
  17118  tinf_build_bits_base(dist_bits, dist_base, 2, 1)
  17119  ret
  17120 
  17121 tinf_build_bits_base(bits,base,delta,base_val)
  17122  for i=0 to 29
  17123   bits[i]=min(0,i-delta)/delta
  17124   base[i]=base_val
  17125   base_val=base_val+(1 shl bits[i])
  17126  ret
  17127 
  17128 tinf_build_fixed_trees()
  17129  for i=0 to 6, tinf_len_tree.table[i]=0, next i       ;[0..6]=0   ;len tree...
  17130  tinf_len_tree.table[7,8,9]=24,152,112                ;[7..9]=24,152,112
  17131  for i=0 to 23,  tinf_len_tree.trans[i+0]  =i+256, next i  ;[0..23]   =256..279
  17132  for i=0 to 143, tinf_len_tree.trans[i+24] =i+0,   next i  ;[24..167] =0..143
  17133  for i=0 to 7,   tinf_len_tree.trans[i+168]=i+280, next i  ;[168..175]=280..287
  17134  for i=0 to 111, tinf_len_tree.trans[i+176]=i+144, next i  ;[176..287]=144..255
  17135  for i=0 to 4, tinf_dist_tree.table[i]=0, next i   ;[0..4]=0,0,0,0,0 ;\dist
  17136  tinf_dist_tree.table[5]=32                        ;[5]=32           ; tree
  17137  for i=0 to 31, tinf_dist_tree.trans[i]=i, next i  ;[0..31]=0..31    ;/
  17138  ret
  17139 
  17140 tinf_decode_dynamic_trees()
  17141  hlit  = tinf_read_bits(5)+257           ;get 5 bits HLIT (257-286)
  17142  hdist = tinf_read_bits(5)+1             ;get 5 bits HDIST (1-32)
  17143  hclen = tinf_read_bits(4)+4             ;get 4 bits HCLEN (4-19)
  17144  for i=0 to 18, lengths[i]=0, next i
  17145  for i=0 to hclen-1                      ;read lengths for code length alphabet
  17146   lengths[clcidx[i]]=tinf_read_bits(3)   ;get 3 bits code length (0-7)
  17147  tinf_build_tree(code_tree, lengths, 19) ;build code length tree
  17148  for num=0 to hlit+hdist-1               ;decode code lengths for dynamic trees
  17149   sym = tinf_decode_symbol(code_tree)
  17150   len=1, val=sym                         ;default (for sym=0..15)
  17151   if sym=16 then len=tinf_read_bits(2)+3, val=lengths[num-1] ;3..6 previous
  17152   if sym=17 then len=tinf_read_bits(3)+3, val=0              ;3..10 zeroes
  17153   if sym=18 then len=tinf_read_bits(7)+11, val=0             ;11..138 zeroes
  17154   for i=1 to len, lengths[num]=val, num=num+1, next i
  17155  tinf_build_tree(tinf_len_tree,  0,      hlit)    ;\build trees
  17156  tinf_build_tree(tinf_dist_tree, 0+hlit, hdist)   ;/
  17157  ret
  17158 
  17159 tinf_build_tree(tree, first, num)
  17160  for i=0 to 15, tree.table[i]=0, next i     ;clear code length count table
  17161  ;scan symbol lengths, and sum code length counts...
  17162  for i=0 to num-1, x=lengths[i+first], tree.table[x]=tree.table[x]+1, next i
  17163  tree.table[0]=0
  17164  sum=0          ;compute offset table for distribution sort
  17165  for i=0 to 15, offs[i]=sum, sum=sum+tree.table[i], next i
  17166  for i=0 to num-1  ;create code to symbol xlat table (symbols sorted by code)
  17167   x=lengths[i+first], if x<>0 then tree.trans[offs[x]]=i, offs[x]=offs[x]+1
  17168  next i
  17169  ret
  17170 
  17171 tinf_data
  17172  clcidx[0..18] = 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15   ;constants
  17173 
  17174  typedef struct TINF_TREE:
  17175    unsigned short table[16]     ;table of code length counts
  17176    unsigned short trans[288]    ;code to symbol translation table
  17177 
  17178  TINF_TREE tinf_len_tree   ;length/symbol tree
  17179  TINF_TREE tinf_dist_tree  ;distance tree
  17180  TINF_TREE code_tree       ;temporary tree (for generating the dynamic trees)
  17181  unsigned char lengths[288+32]   ;temporary 288+32 x 8bit ;\for dynamic tree
  17182  unsigned short offs[16]         ;temporary 16 x 16bit    ;/creation
  17183 
  17184  unsigned char  length_bits[30]
  17185  unsigned short length_base[30]
  17186  unsigned char  dist_bits[30]
  17187  unsigned short dist_base[30]
  17188 
  17189 Inflate - Headers and Checksums
  17190 -------------------------------
  17191 
  17192 tinf_gzip_uncompress(dst, destLen, src, sourceLen)
  17193  src_start=src, dst_start=dst                 ;memorize start addresses
  17194  if (src[0]<>1fh or src[1]<>8Bh) then ERROR   ;check id bytes
  17195  if (src[2]<>08h) then ERROR                  ;check method is deflate
  17196  flg=src[3]                                   ;get flag byte
  17197  if (flg AND 0E0h) then ERROR                 ;verify reserved bits
  17198  src=src+10                                                 ;skip base header
  17199  if (flg AND 04h) then src=src+2+LittleEndian16bit[src]     ;skip extra data
  17200  if (flg AND 08h) then repeat, src=src+1, until [src-1]=00h ;skip file name
  17201  if (flg AND 10h) then repeat, src=src+1, until [src-1]=00h ;skip file comment
  17202  hcrc=(tinf_crc32(src_start, src-src_start) & 0000ffffh))   ;calc header crc
  17203  if (flg AND 02h) then x=LittleEndian16bit[src], src=src+2  ;get header crc
  17204  if (flg AND 02h) then if x<>hcrc then ERROR                ;verify header
  17205  tinf_uncompress(dst, destLen, src, src_start+sourceLen-src-8)  ;----> inflate
  17206  crc32=LittleEndian32bit[src], src=src+4   ;get crc32 of decompressed data
  17207  dlen=LittleEndian32bit[src], src=src+4    ;get decompressed length
  17208  if (dlen<>destLen) then ERROR                              ;verify dest len
  17209  if (crc32<>tinf_crc32(dst_start,dlen)) then ERROR          ;verify crc32
  17210  ret
  17211 
  17212 tinf_zlib_uncompress(dst, destLen, src, sourceLen)
  17213  src_start=src, dst_start=dst         ;memorize start addresses
  17214  hdr=BigEndian16bit[src], src=src+2   ;get header
  17215  if (hdr MOD 31)<>0 then ERROR        ;check header checksum (modulo)
  17216  if (hdr AND 20h)>0 then ERROR        ;check there is no preset dictionary
  17217  if (hdr AND 0F00h)<>0800h then ERROR ;check method is deflate
  17218  if (had AND 0F000h)>7000h then ERROR ;check window size is valid
  17219  tinf_uncompress(dst, destLen, src, sourceLen-6)      ;------> inflate
  17220  chk=BigEndian32bit[src], src=src+4                   ;get data checksum
  17221  if src-src_start<>sourceLen then ERROR               ;verify src len
  17222  if dst-dst_start<>destLen then ERROR                 ;verify dst len
  17223  if a32<>tinf_adler32(dst_start,destLen)) then ERROR  ;verify data checksum
  17224  ret
  17225 
  17226 tinf_adler32(src, length)
  17227  s1=1, s2=0
  17228  while (length>0)
  17229   k=max(length,5552)    ;max length for avoiding 32bit overflow before mod
  17230   for i=0 to k-1, s1=s1+[src], s2=s2+s1, src=src+1, next i
  17231   s1=s1 mod 65521, s2=s2 mod 65521, length=length-k
  17232  return (s2*10000h+s1)
  17233 
  17234 
  17235 CDROM File Compression LArc/LHarc/LHA (LZS/LZH)
  17236 -----------------------------------------------
  17237 
  17238 LHA (formerly LHarc) is an old DOS compression tool with backwards
  17239 compatibility for LArc. LHA appears to have been particulary popular in Japan,
  17240 and in the Amiga scene.
  17241 LHA archives are used by at least one PSX game:
  17242   PSX Championship Surfer (MagDemo43: HWX\*.DAT)    ;method lh5
  17243 And, there are various PSX games with compression based on LArc's method lz5:
  17244 --> CDROM File Compression LZ5 and LZ5-variants
  17245 
  17246 Overall File Format
  17247 Default archive filename extension is .LZH for LHarc/LHA (lh*-methods), or .LZS
  17248 for LArc (lz*-methods).
  17249 Archives can contain multiple files, and are usually terminated by a 00h-byte:
  17250   LHA Header+Data for 1st file
  17251   LHA Header+Data for 2nd file
  17252   End Marker (00h)
  17253 There is no central directory, one must crawl all headers to create a list of
  17254 files in the archive.
  17255 Caution: There is a hacky test file (larc333\initial.lzs) with missing end byte
  17256 (it does just end at filesize).
  17257 LHA Header v2 Headersize=xx00h would conflict with End Byte (as workaround,
  17258 insert a Nullbyte between Ext.Headers and Data to change Headersize to xx01h.
  17259 
  17260 LHA Header v0 (with [14h]=00h)
  17261   00h     1   Header Size (Method up to including Extended Area) (=16h+F+E)
  17262   01h     1   Header Checksum, sum of bytes at [02h+(0..15h+F+E)]
  17263   02h     5   Compression Method (eg. "-lh0-"=Uncompressed)
  17264   07h     4   Compressed Size
  17265   0Bh     4   Uncompressed Size
  17266   0Fh     2   Last modified time (in MS-DOS format)
  17267   11h     2   Last modified date (in MS-DOS format)
  17268   13h     1   MS-DOS File attribute (usually 20h)
  17269   14h     1   Header level (must be 00h for v0)
  17270   15h     1   Path\Filename Length
  17271   16h     (F) Path\Filename (eg. "PATH\FILENAME.EXT")
  17272                      '\' may apper in the 2nd byte of Shift_JIS, processing
  17273                      of Shift_JIS is indispensable when you need full
  17274                      implementation of reading Pathname.
  17275   16h+F   2   CRC16 (with initial value 0000h) on uncompressed file
  17276   18h+F   (E) Extended area (used by UNIX in v0)
  17277   18h+F+E ..  Compressed data
  17278 Note: Reportedly, old LArc files don't have CRC16 (unknown if that is true, the
  17279 ONLY known version is LArc v3.33, which DOES have CRC16, if older versions
  17280 didn't have that CRC then they did perhaps behave as if E=(-2)?).
  17281 
  17282 LHA Header v1 (with [14h]=01h)
  17283   00h     1   Header Size (Method up to including 1st Ext Size) (=19h+F+E)
  17284   01h     1   Base Header Checksum, sum of bytes at [02h+(0..18h+F+E)]
  17285   02h     5   Compression Method (eg. "-lh0-"=Uncompressed)
  17286   07h     4   Skip size (size of all Extended Headers plus Uncompressed Size)
  17287   0Bh     4   Uncompressed Size
  17288   0Fh     2   Last modified time (in MS-DOS format)
  17289   11h     2   Last modified date (in MS-DOS format)
  17290   13h     1   Reserved     (must be 20h) (but is 02h on Amiga)
  17291   14h     1   Header level (must be 01h for v1)
  17292   15h     1   Length of Filename (or 00h when name is in Extended Header)
  17293   16h     (F) Filename (eg. "FILENAME.EXT; path (if any) is in Extended Header)
  17294   16h+F   2   CRC16 (with initial value 0000h) on uncompressed file
  17295   18h+F   1   Compression Tool OS ID (eg. "M"=MSDOS)
  17296   19h+F   (E) Extended area (unused in v1, use Ext Headers instead)
  17297   19h+F+E 2   Size of 1st Extended Header (0000h=None)
  17298   1Bh+F+E ..  Extended Header(s) (optional stuff)
  17299   ...     ..  Compressed data
  17300 
  17301 LHA Header v2 (with [14h]=02h)
  17302   00h     2   Header Size (whole Header including all Extended Headers)
  17303   02h     5   Compression Method (eg. "-lh0-"=Uncompressed)
  17304   07h     4   Compressed Size
  17305   0Bh     4   Uncompressed Size
  17306   0Fh     4   Last modified date and time (seconds since 1st Jan 1970 UTC)
  17307   13h     1   Reserved     (must be 20h) (but is 02h on Amiga)
  17308   14h     1   Header level (must be 02h for v2)
  17309   15h     2   CRC16 (with initial value 0000h) on uncompressed file
  17310   17h     1   Compression Tool OS ID (eg. "M"=MSDOS)
  17311   18h     2   Size of first Extended Header (0000h=None)
  17312   1Ah     ..  Extended Header(s) (filename and optional stuff)
  17313   ...     0/1 Nullbyte (End-Marker conflict: change Headersize xx00h to xx01h)
  17314   ...     ..  Compressed data
  17315 
  17316 LHA Header v3 (with [14h]=03h)
  17317 Kinda non-standard (supported only in late japanese LHA beta versions): Allows
  17318 Header and Ext.Headers to exceed 64Kbyte, which is rather useless.
  17319   00h     2   Word size for 32bit Header entries (always 4=32bit)
  17320   02h     5   Compression Method (eg. "-lh0-"=Uncompressed)
  17321   07h     4   Compressed Size
  17322   0Bh     4   Uncompressed Size
  17323   0Fh     4   Last modified date and time (seconds since 1st Jan 1970 UTC)
  17324   13h     1   Reserved     (must be 20h)
  17325   14h     1   Header level (must be 03h for v3)
  17326   15h     2   CRC16 (with initial value 0000h) on uncompressed file
  17327   17h     1   Compression Tool OS ID (eg. "M"=MSDOS)
  17328   18h     4   Header Size (whole Header including all Extended Headers)
  17329   1Ch     4   Size of first Extended Header (00000000h=None)
  17330   20h     ..  Extended Header(s) (filename and optional stuff)
  17331   ...     ..  Compressed data
  17332 
  17333 Compression Methods
  17334   Method Len    Window
  17335   -lz4-  -  -   -        LArc Uncompressed File
  17336   -lh0-  -  -   -        LHA  Uncompressed File
  17337   -lhd-  -  -   -        LHA  Uncompressed Directory name entry
  17338   -lzs-  2..17  2Kbyte   LArc LZSS-Compressed  (rare, very-very old)    ;-15bit
  17339   -lz5-  3..17  4Kbyte   LArc LZSS-Compressed  (LArc srandard)          ;-16bit
  17340   -lh1-  3..60  4Kbyte   LHA  LZHUF-Compressed (old LHA standard)
  17341   -lh2-  3..256 8Kbyte   LHA  Obscure test     (used in self-extractor)
  17342   -lh3-  3..256 8Kbyte   LHA  Obscure test     (experimental)
  17343   -lh4-  3..256 4Kbyte   LHA  AR002-Compressed (rare, for small RAM)    ;\4bit
  17344   -lh5-  3..256 8Kbyte   LHA  AR002-Compressed (new LHA standard)       ;/
  17345   -lh6-  3..256 32Kbyte  LHA  AR002-Compressed (rare)                   ;\
  17346   -lh7-  3..256 64Kbyte  LHA  AR002-Compressed (rare)                   ; 5bit
  17347   -lh8-  3..256 64Kbyte  LHA  AR002-Compressed (accidently same as lh7) ;
  17348   -lh9-  3..256 128Kbyte LHA  AR002-Compressed (unimplemented proposal) ;
  17349   -lha-  3..256 256Kbyte LHA  AR002-Compressed (unimplemented proposal) ;
  17350   -lhb-  3..256 512Kbyte LHA  AR002-Compressed (unimplemented proposal) ;
  17351   -lhc-  3..256 1Mbyte   LHA  AR002-Compressed (unimplemented proposal) ;
  17352   -lhe-  3..256 2Mbyte   LHA  AR002-Compressed (unimplemented proposal) ;
  17353   -lhx-  3..256 512Kbyte LHA  AR002-Compressed (rare)                   ;/
  17354 Apart from above methods, there are various other custom hacks/extensions.
  17355 
  17356 Extended Headers
  17357   00h     1   Extension Type (00h..FFh, eg. 01h=Filename)
  17358   01h     ..  Extension Data
  17359   ...     2/4 Size of next Extended Header (0=None) (v1/v2=16bit, v3=32bit)
  17360 Extension Type values:
  17361   00h   CRC16 on whole Header with InitialValue=0000h and InitialCrcEntry=0000h
  17362   01h   Filename
  17363   02h   Directory name (with FFh instead of "\", and usually with trailing FFh)
  17364   3Fh   Comment (unspecified format/purpose)
  17365   40h   MS-DOS File attribute of MS-DOS format
  17366   41h   Windows FILETIME for last access, creation, and modification
  17367   42h   Filesize (uncompressed and compressed size, when exceeding 32bit)
  17368   50h   Unix Permission
  17369   51h   Unix User ID and Group ID
  17370   52h   Unix Group name
  17371   53h   Unix User name (owner)
  17372   54h   Unix Last modified time in time_t format
  17373   7Dh   Capsule offs/size (if the OS adds extra header/footer to the filebody)
  17374   7Eh   OS/2 Extended attribute
  17375   7Fh   Level 3 Attribute in Unix form and MS-DOS form
  17376   FFh   Level 3 Attribute in Unix form
  17377 Note: There appears to be no MAC specific format (instead, the LHA MAC version
  17378 is including a MacBinary header in the compressed files).
  17379 
  17380 See also
  17381 The site below has useful links with info about headers (see LHA Notes), source
  17382 code, and test archives:
  17383   http://fileformats.archiveteam.org/wiki/LHA
  17384 
  17385 CDROM File Compression ARJ
  17386 --------------------------
  17387 
  17388 ARJ archives contain several chunks
  17389   Main header chunk
  17390   Local file chunk(s)
  17391   Chapter chunk(s), backup related, exist only in newer archives
  17392   End Marker
  17393 
  17394 ARJ main "comment" header, with [00Ah]=2
  17395 This is stored at the begin of the archive. The format is same as for local
  17396 file header (but with file-related entries set to zero, or to global security
  17397 settings).
  17398   000h 2   ARJ ID (EA60h, aka 60000 decimal)
  17399   002h 2   Header size (from 004h up to including Filename+Comment) (max 2600)
  17400   004h 1   Header size (from 004h up to including Extra Data) (1Eh+extra)
  17401   005h 1   Archiver version number (01h..0xh)
  17402   006h 1   Minimum archiver version to extract (usually 01h)
  17403   007h 1   Host OS
  17404   008h 1   ARJ Flags (bit0-7, see below)
  17405   009h 1   Security version (2 = current)
  17406   00Ah 1   File Type        (must be 2=ARJ Comment in main header)
  17407   00Bh 1   Reserved/Garbage (LSB of Archive creation Date/Time, same as [00Ch])
  17408   00Ch 4   Date/Time when archive was created
  17409   010h 4   Date/Time when archive was last modified
  17410   014h 4   Zero  (or Secured Archive size, excluding Security and Protection)
  17411   018h 4   Zero  (or Security envelope file position) (after End Marker)
  17412   01Ch 2   Zero  (or Filespec position in filename) (0) (what is that??)
  17413   01Eh 2   Zero  (or Security envelope size in bytes) (78h, if any)
  17414   020h 1   Zero  (or >2.50?: Encryption version, 0-1=Old, 2=New, 4=40bit GOST)
  17415   021h 1   Zero  (or >2.50?: Last chapter (eg. 4 when having chapter 1..4)
  17416   022h (1) Extra data: ARJ Protection factor                         ;\extra,
  17417   023h (1) Extra data: ARJ Flags (bit0=ALTVOLNAME, bit1=ReservedBit) ; if any
  17418   024h (2) Extra data: Spare bytes                                   ;/
  17419   ...  ..  Filename, max 500 bytes ("FILENAME.ARJ",00h)
  17420   ...  ..  Comment, max 2048 bytes ("ASCII Comment",00h)
  17421   ...  4   CRC32 on Header (from 004h up to including Comment)
  17422   ...  2   Size of 1st extended header (usually 0=none)
  17423   ...  (0) Extended Header(s?) (usually none such)
  17424 
  17425 ARJ local file header, with [00Ah]=0,1,3,4
  17426 This occurs at the begin of each file in the archive.
  17427   000h 2   ARJ ID (EA60h, aka 60000 decimal)
  17428   002h 2   Header size (from 004h up to including Filename+Comment) (max 2600)
  17429   004h 1   Header size (from 004h up to including Extra Data) (1Eh+extra)
  17430   005h 1   Archiver version number
  17431   006h 1   Minimum archiver version to extract (usually 01h)
  17432   007h 1   Host OS
  17433   008h 1   ARJ Flags (bit0,2-5)
  17434   009h 1   Method
  17435   00Ah 1   File Type (0=Binary, 1=Text, 3=Directory Name, 4=Volume Name)
  17436   00Bh 1   Reserved/Garbage (LSB of Archive update Date/Time?)
  17437   00Ch 4   Date/Time modified
  17438   010h 4   Filesize, compressed (max 7FFFFFFFh)
  17439   014h 4   Filesize, uncompressed
  17440   018h 4   CRC32 on uncompressed file data
  17441   01Ch 2   Zero  (or Filespec position in filename) (what is that??)
  17442   01Eh 2   File access mode (aka MSDOS file attribute) (20h=Normal)
  17443   020h 1   Zero  (or >2.50?: first chapter of file's lifespan)
  17444   021h 1   Zero  (or >2.50?: last chapter of file's lifespan)
  17445   022h (4) Extra data: Extended file position (maybe for split?)  ;\extra,
  17446   026h (4) Extra data: Date/Time accessed                  ;\ARJ  ; 0,4 or 10h
  17447   03Ah (4) Extra data: Date/Time created                   ; 2.62 ; bytes
  17448   03Eh (4) Extra data: Original file size even for volumes ;/     ;/
  17449   ...  ..  Filename, max 500 bytes ("PATH/FILENAME.EXT",00h)
  17450   ...  ..  Comment, max 2048 bytes ("ASCII Comment",00h)
  17451   ...  4   CRC32 on Header (from 004h up to including Comment)
  17452   ...  2   Size of 1st extended header (usually 0=none)
  17453   ...  (0) Extended Header(s?) (usually none such)
  17454   ...  ..  Compressed file data
  17455 Entry 3Eh might be meant to contain Original Size of TEXT files (with CR,LFs),
  17456 however, the entry is just set to 00000000h in ARJ 2.75a. Or maybe it's meant
  17457 to mean size of whole file (in split-volumes)?
  17458 
  17459 ARJ backup "chapter" header (ARJ >2.50?) (exists in 2.75a), with [00Ah]=5
  17460 This is rarely used and supported only in newer ARJ versions. The format is
  17461 same as for local file header (but with file-related entries being nonsense in
  17462 TECHNOTE; in practice, those nonsense values seem to be zero).
  17463   000h 2   ARJ ID (EA60h, aka 60000 decimal)
  17464   002h 2   Header size (from 004h up to including Filename+Comment) (max 2600)
  17465   004h 1   Header size (from 004h up to including Extra Data) (1Eh+extra)
  17466   005h 1   Archiver version number (eg. 0Ah=2.75a)
  17467   006h 1   Minimum archiver version to extract (usually 01h)
  17468   007h 1   Host OS
  17469   008h 1   ARJ Flags (usually 00h)
  17470   009h 1   Method (usually 01h, although chapters have no data)  what file???
  17471   00Ah 1   File Type (must be 5=ARJ Chapter)
  17472   00Bh 1   Reserved/Garbage (LSB of Chapter Date/Time, same as [00Ch])
  17473   00Ch 4   Date/Time stamp created
  17474   010h 4   Zero  (or reportedly, ?)                              what question?
  17475   014h 4   Zero  (or reportedly, ?)                              what question?
  17476   018h 4   Zero  (or reportedly, original file's CRC32)          what file???
  17477   01Ch 2   Zero  (or reportedly, entryname position in filename) what file???
  17478   01Eh 2   Zero  (or reportedly, file access mode)               what file???
  17479   020h 1   Chapter range start (01h=First chapter?)              what range???
  17480   021h 1   Chapter range end   (contains same value as above)    what range???
  17481   022h (4) Extra data: Extended file position (usually none such)what extra???
  17482   ...  ..  Filename ("<<<001>>>",00h for First chapter)
  17483   ...  ..  Comment  ("",00h)
  17484   ...  4   CRC32 on Header (from 004h up to including Comment)
  17485   ...  2   Size of 1st extended header (usually 0=none)
  17486   ...  (0) Extended Header(s?) (usually none such)
  17487 
  17488 ARJ End Marker (with [002h]=0000h)
  17489 This is stored at the end of the archive.
  17490   000h 2   ARJ ID (EA60h, aka 60000 decimal)
  17491   002h 2   Header size (0=End)
  17492 Note: The End Marker may be followed by PROTECT info and Security envelope.
  17493 
  17494 ARJ Method [009h]
  17495   0 = stored (uncompressed)
  17496   1 = compressed most (default) (Window=6800h=26Kbyte, Chars=255, Tree=31744)
  17497   2 = compressed medium         (Window=5000h=20Kbyte, Chars=72, Tree=30720)
  17498   3 = compressed less           (Window=2000h=8Kbyte, Chars=32, Tree=30720)
  17499   4 = compressed least/fastest  (Window=6800h? or 8000h?)
  17500   8 = no data, no CRC  ;\unknown if/where that is used (maybe only used
  17501   9 = no data          ;/internally, and never stored in actual files?)
  17502 
  17503 ARJ File Type [00Ah]
  17504   0 = binary file (default)
  17505   1 = text file (with converted line breaks, via -t1 switch)
  17506   2 = ARJ comment header (aka ARJ main file header)
  17507   3 = directory name
  17508   4 = volume label (aka disc name)
  17509   5 = ARJ chapter label (aka begin of newer backup sections)
  17510 
  17511 ARJ Flags (in Main [008h])
  17512   0  GARBLED
  17513   1  OLD_SECURED   has old signature (with signature in Main Header?)
  17514   1  ANSIPAGE      ANSI codepage used by ARJ32 (for what? for "FILENAME.ARJ"?)
  17515   2  VOLUME        presence of succeeding volume
  17516   3  ARJPROT
  17517   4  PATHSYM       archive name translated ("\" changed to "/")
  17518   5  BACKUP        obsolete
  17519   6  SECURED       has new signature (in security envelope?)
  17520   7  ALTNAME       dual-name archive
  17521 ARJ Flags (in Local [008h])
  17522   0  GARBLED       passworded file
  17523   1  NOT USED
  17524   2  VOLUME        continued file to next volume (file is split)
  17525   3  EXTFILE       file starting position field (for split files)
  17526   4  PATHSYM       filename translated ("\" changed to "/")
  17527   5  BACKUP_FLAG   obsolete
  17528 ARJ Flags (in Chapter [008h])
  17529   0  GARBLED                          ;\
  17530   1  RESERVED                         ;
  17531   2  VOLUME                           ; what does that mean in Chapters???
  17532   3  EXTFILE                          ;
  17533   4  PATHSYM                          ;/
  17534   5  BACKUP        obsolete < 2.50a   ;-how can obsolete exist in Chapters???
  17535   6  RESERVED
  17536 
  17537 Host OS [007h]
  17538   0=MSDOS, 1=PRIMOS, 2=UNIX, 3=AMIGA, 4=MACDOS (aka MAC-OS)
  17539   5=OS/2, 6=APPLE GS, 7=ATARI ST, 8=NEXT
  17540   9=VAX VMS, 10=WIN95, 11=WIN32 (aka WinNT or so?)
  17541 
  17542 ARJ Method 1-3 (LHA/LZH compression)
  17543 These methods are same as LHA's "-lh6-" compression method (albeit the three
  17544 ARJ methods are allocating slighly less memory for the sliding window).
  17545 
  17546 ARJ Method 4 (custom fastest compression)
  17547  @@decompress_lop:
  17548   if dst>=dst_end then goto @@decompress_done
  17549   width=count_ones(max=7), len = get_bits(width) + (1 shl width)+1
  17550   if len=2 then
  17551     [dst]=get_bits(8), dst=dst+1
  17552   else ;len>=3
  17553     width=count_ones(max=4)+9, disp = get_bits(width) + (1 shl width)-1FFh
  17554     for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  17555   goto @@decompress_lop
  17556  @@decompress_done:
  17557   ret
  17558  ;---
  17559  count_ones(max):
  17560   num=0
  17561  @@lop:
  17562   if get_bits(1)=1 then
  17563     num=num+1, if num<max then goto @@lop
  17564   return num
  17565 get_bits(N) is same as in method 1-3 (fetching N bits, MSB first, starting with
  17566 bit7 of first byte).
  17567 
  17568 ARJ Glossary & Oddities
  17569 BACKUPs seem to keep old files (instead overwrting them by newer files)
  17570 CHAPTERs seems to be a new backup type (instead of [008h].Bit5=Backup flag).
  17571 COMMENTS can be text... with ANSI.SYS style ANSI escape codes?
  17572 DATE/TIME stamps seem to be MSDOS format (16bit date plus 16bit time)
  17573 EXTENDED headers seem to be unused, somewhat inspired on LHA format but with
  17574 CRC32 instead CRC16 (unknown if the "1st extended header" can be followed by
  17575 2nd, 3rd, and further extended headers in LHA fashion) (bug: older ARJ versions
  17576 are reportedly treating the extended CRC32 as 16bit value).
  17577 GARBLED seems to refer to encrypted password protected archives.
  17578 PROTECTED seems to mean Error Correction added in newer ARJ archives.
  17579 SECURED seems to mean archive with signature from registered manufacturers.
  17580 SPLIT aka VOLUMEs means large ARJ's stored in fragments on multiple disks.
  17581 TEXT (aka [00Ah]=1 aka -t1 switch aka "C Text" aka "7-bit text") converts
  17582 linebreaks from CR,LF to LF to save memory (the uncompressed size and
  17583 uncompressed CRC32 entries refer to that converted LF format, not to the
  17584 original CR,LF format; the official name "7-bit text" is nonsense: All
  17585 characters are stored as 8bit values, not 7bit values).
  17586 TIMEBOMB causes newer ARJ versions to refuse to work (and request the user to
  17587 check for non-existing newer updates) (eg. ARJ 2.86 is no longer working, ARJ
  17588 2.75a does still work without timebomb).
  17589 
  17590 See also
  17591 The various ARJ versions include .TXT or .DOC files (notably, ARJ.TXT is user
  17592 manual, TECHNOTE.TXT contains hints on the ARJ file format). There's also an
  17593 open source version.
  17594 
  17595 CDROM File Compression ARC
  17596 --------------------------
  17597 
  17598 ARC Archives
  17599 ARC is an old DOS and CP/M compression tool from 1985-1990. ARC files contain
  17600 chunks in following format:
  17601   000h 1     Fixed ID (1Ah)
  17602   001h 1     Compression Method (00h..1Fh)
  17603   002h 13    Filename ("FILENAME.EXT",00h) (garbage-padded if shorter)
  17604   00Fh 4     Filesize, compressed
  17605   013h 4     File Timestamp in MSDOS format
  17606   017h 2     CRC16 with initial value 0000h on uncompressed/decrypted file
  17607   019h (4)   Filesize, uncompressed  ;<-- not present for Method=1
  17608   ...  ..    Compressed file data (size as stored in [00Fh])
  17609 The chunksize depends on the Method:
  17610   Method 00h and 1Fh --> Chunksize=02h       (archive/subdir end markers)
  17611   Method 01h         --> Chunksize=19h+[0Fh] (old uncompressed ARC archives)
  17612   Others Methods     --> Chunksize=1Dh+[0Fh] (normal case)
  17613 Compression Methods (aka "header versions"):
  17614   00h     End-of-archive marker (1Ah,00h)
  17615   01h     ARC v?     Uncompressed (with short 19h-byte header)
  17616   02h     ARC v?     Uncompressed (with normal 1Dh-byte header)
  17617   03h     ARC v?     Packed    (RLE90)                   Used for small files
  17618   04h     ARC v?     Squeezed  (RLE90+Huffman)           Based on CP/M Squeeze
  17619   05h     ARC v4.00  Crunched  (OldRandomizedLZW)        Derived from LZWCOM
  17620   06h     ARC v4.10  Crunched  (RLE90+OldRandomizedLZW)  Alike CP/M Crunch v1.x
  17621   07h     ARC vBeta? Crunched  (RLE90+NewRandomizedLZW)  Leaked beta version?
  17622   08h     ARC v5.00  Crunched  (RLE90+ClearGap12bitLZW)  Most common ARC method
  17623   09h     Inofficial Squashed  (ClearGap13bitLZW)        Used by PKARC/PKPAK
  17624   0Ah     ARC v7.xx  Trimmed   (RLE90+LZHUF)             Based on LHArc lh1
  17625   0Ah     Inofficial Crushed   (RLE90+LZW/LZMW?)         PAK
  17626   0Bh     Inofficial Distilled (LZ77+Huffman)            PAK v2.0
  17627   14h-1Dh ARC v6.0 Used/reserved for Information items:
  17628   14h     Archive info
  17629   15h     Extended File info (maybe a prefix(?) for actual file entries?)
  17630   16h     OS-specific info
  17631   1Eh-27h ARC v6.0 Used/reserved for Control items:
  17632   1Eh     ARC v6.00 Subdir (nested ARC-like format, created by the "z" option)
  17633   1Fh     ARC v6.00 End-of-subdir marker (1Ah,1Fh)
  17634   48h     Not used in ARC  ;\Hyper archives start with 1Ah,48h or 1Ah,53h
  17635   53h     Not used in ARC  ;/(an unrelated format that also starts with 1Ah)
  17636   80h-xxh Not used in ARC  ;-Spark archives (ARC-like, with extended headers)
  17637 Information items use standard 1Dh-byte headers (with [002h]="",00h,
  17638 [00Fh]=SizeOfAllItem(s), [019h]=Junk. The data part at offset 01Dh can contain
  17639 one or more item(s) in following format:
  17640   000h 2     Item size (LEN)
  17641   002h 1     Item Subtype
  17642   003h ..    Item Data (LEN-3 bytes)
  17643 Information item types as used by ARC 6.0:
  17644   Method=14h, Subtype=0  Archive description          (eg. "Comment blah",00h)
  17645   Method=14h, Subtype=1  Archive creator program name (eg. "ARC 7.12 ...",00h)
  17646   Method=14h, Subtype=2  Archive modifier program name
  17647   Method=15h, Subtype=0  File description             (eg. "Comment blah",00h)
  17648   Method=15h, Subtype=1  File long filename (if not MS-DOS "8.3" filename)
  17649   Method=15h, Subtype=2  File extended date-time info (reserved)
  17650   Method=15h, Subtype=3  File Icon                    (reserved)
  17651   Method=15h, Subtype=4  File attributes (see below)  (eg. "RWHSN",00h)
  17652   Method=16h, Subtype=.. Operating system info        (reserved)
  17653 File attributes can contain following uppercase chars:
  17654   R=ReadAccess, W=WriteAccess, H=HiddenFile, 1=SystemFile, N=NetworkShareable
  17655 
  17656 Sub-directories
  17657 Sub-directories are implemented as nested ARC files - about same as when
  17658 storing the sub-directory files in SUBDIR.ARC, and including that SUBDIR.ARC
  17659 file in the main archive with Method 02h. Except that:
  17660 It's using Method 1Eh (instead Method 02h), with filename SUBDIR (instead
  17661 SUBDIR.ARC), and with [019h]=Nonsense (instead uncompressed size), and the
  17662 nested file ends with Method 1Fh (instead Method 00h).
  17663 
  17664 RLE90 (run-length compression with value 90h used as escape code)
  17665 ARC does use raw RLE90 for small files (eg. 4-byte "aaaa"). ARC does also use
  17666 RLE90 combined with other methods (perhaps because ARC wasn't very fast,
  17667 compressing 100Kbytes could reportedly take several minutes; and without RLE90
  17668 pre-compression it might have been yet slower).
  17669   90h,00h       Output 90h, but DON'T change prevbyte    ;<-- ARC
  17670   90h,00h       Output 90h, and DO set prevbyte=90h      ;<-- BinHex
  17671   90h,00h       Output 90h, and UNKNOWN what to do       ;<-- StuffIt
  17672   90h,01h..03h  Output prevbyte 00h..02h times (this is not useful)
  17673   90h,04h..FFh  Output prevbyte 03h..FEh times (this does save memory)
  17674   xxh           Output xxh, and memorize prevbyte=xxh
  17675  arc_decompress_rle90:
  17676   src_end = src+src_size
  17677   prevbyte = <initially undefined in ARC source code>
  17678  @@decompress_lop:
  17679   if src>=src_end then goto @@decompress_done
  17680   x=[src], src=src+1
  17681   if x<>90h then
  17682     [dst]=x, dst=dst+1, prevbyte=x    ;output x, and memorize prevbyte=x
  17683   else  ;x=90h
  17684     x=[src], src=src+1
  17685     if x=00h then
  17686       [dst]=90h, dst=dst+1            ;output 90h, but DO NOT change prevbyte
  17687       if BinHex then prevbyte=90h     ;for BinHex, DO change prevbyte
  17688     else
  17689       for i=1 to x-1, [dst]=prevbyte, dst=dst+1, next i
  17690   goto @@decompress_lop
  17691 RLE90 is used by ARC (and Spark and ArcFS), StuffIt, and BinHex (some of these
  17692 may handle "prevbyte" differently; the handling in ARC is somewhat stupid as it
  17693 cannot compress repeating 90h-bytes).
  17694 
  17695 Squeeze
  17696   000h 2    Number of Tree entries (0..100h) (when 0, assume tree=FEFFh,FEFFh)
  17697   002h N*4  Tree entries (16bit node0, 16bit node1)
  17698   ...  ..   Huffman bitstream (starting in bit0 of first byte)
  17699   ...  ..   Maybe supposedly padding to byte boundary?
  17700  The 16bit nodes are:
  17701   0000h..00FFh  Next Tree index
  17702   0100h..FEFEh  Invalid
  17703   FEFFh         End of compressed data
  17704   FF00h..FFFFh  Data values FFh..00h (these are somewhat inverted/reversed)
  17705  arc_decumpress_squeeze:
  17706   if [src]=0000h then tree=empty_tree, else tree=src+2  ;-start tree
  17707   InitBitstreamLsbFirst(src+2+[src]*4)                  ;-start bitstream
  17708  @@decompress_lop:
  17709   index=0000h                                           ;\
  17710   while index<FEFFh                                     ; huffman decode
  17711     index=[tree+index*4+GetBits(1)*2]                   ;/
  17712   if index>FEFFh then                                   ;-check end code
  17713     [dst]=(index XOR FFh) AND FFh), dst=dst+1           ;-store data
  17714     goto @@decompress_lop
  17715   return
  17716  empty_tree dw FEFFh,FEFFh   ;upen empty tree, ARC defines two 1bit END codes
  17717 http://fileformats.archiveteam.org/wiki/Squeeze
  17718 
  17719 Randomized LZW
  17720  arc_decompress_randomized_lzw:
  17721   num_free=1000h, stack=empty, oldcode=-1
  17722   for i=0 to FFFh, lzw_parent[i]=EEEEh    ;mark all codes as unused
  17723   for i=0 to FFh, create_code(FFFFh,i)    ;codes for 00h..FFh with parent=none
  17724  @@decompress_lop:
  17725   if src>=src_end then goto @@decompress_done
  17726   code=GetBitsMsbFirst(12), i=code
  17727   if lzw_parent[i]=EEEEh then i=oldcode, push(oldbyte)  ;-for KwKwK strings
  17728   while lzw_parent[i]<>FFFFh, push(lzw_data[i]), i=lzw_parent[i]
  17729   oldbyte=lzw_data[i], [dst]=oldbyte, dst=dst+1
  17730   if oldcode<>-1 then create_code(oldcode,oldbyte)
  17731   oldcode=code
  17732   while stack<>empty, [dst]=pop(), dst=dst+1
  17733   goto @@decompress_lop
  17734  @@decompress_done:
  17735   ret
  17736  ;---
  17737  create_code(parent,data):
  17738   if num_free=0 then goto @@no_further_codes, else num_free=num_free-1  ;-full
  17739   i=(parent+data) AND 0000FFFFh                                         ;\
  17740   if method=7 then i=(i*3AE1h) AND FFFh         ;new "fast" randomizer  ;
  17741   else i=(sqr(i OR 800h)/40h) AND FFFh          ;old "slow" randomizer  ;
  17742   if lzw_parent[i]=EEEEh then goto @@found_free                         ; alloc
  17743   while lzw_sibling[i]>0000h, do i=lzw_sibling[i]    ;find chain end    ; code
  17744   e=i, i=(i+65h) AND FFFh     ;memorize chain end & do some random skip ;
  17745   while lzw_parent[i]<>EEEEh, do i=(i+1) AND FFFh    ;find a free code  ;
  17746   lzw_sibling[e]=i    ;weirdly, i=0 will make it behave as sibling=none ;
  17747  @@found_free:                                                          ;/
  17748   lzw_data[i]=data, lzw_parent[i]=parent, lzw_sibling[i]=0000h          ;-apply
  17749  @@no_further_codes:
  17750   ret
  17751 Codes are always 12bit (unlike normal LZW that often starts with 9bit codes).
  17752 There won't be any new codes created if the table is full, the existing codes
  17753 can be kept used if they do match the remaining data (unfortunatly this LZW
  17754 variant has no Clear code for resetting the table when they don't match).
  17755 Instead of just using the first free entry, code allocation is using some weird
  17756 pseudo-random-sibling logic (which is totally useless and will slowdown
  17757 decompression, but compressed files do contain such randomized codes, so it
  17758 must be reproduced here).
  17759 
  17760 ClearGap LZW
  17761 This is more straight non-randomized LZW with Clear codes (and weird gaps after
  17762 Clear codes). The compression (and gaps) are same as for nCompress (apart from
  17763 different headers):
  17764 --> CDROM File Compression nCompress.Z
  17765   ARC Method 8 with 1-byte header (0Ch) --> nCompress 3-byte header 1Fh,9Dh,8Ch
  17766   ARC Method 9 without header           --> nCompress 3-byte header 1Fh,9Dh,8Dh
  17767 Method 8 does have 0Ch as first byte (indicating max 12bit codesize, this must
  17768 be always 0Ch, the ARC decoder supports only that value). Method 9 uses max
  17769 13bit codesize (but doesn't have any leading codesize byte).
  17770 
  17771 LZHUF
  17772 This is based on LHArc lh1. Like lh1, it does have 13Ah data/len codes, and
  17773 1000h distance codes. There are two differences:
  17774   Differences          LHArc method lh1        ARC method 0Ah
  17775   Data/len codes:      100h..139h=Len(3..3Ch)  100h=End, 101h..139h=Len(3..3Bh)
  17776   Initial dictionary:  20h-filled              Uninitialized
  17777 
  17778 Notes
  17779 ARC file/directory names are alphabetically sorted, that does apply even when
  17780 adding files to an existing archive (they are inserted at alphabetically sorted
  17781 locations rather than being appended at end of archive).
  17782 ARC files can be encrypted/garbled with password (via "g" option), the chunk
  17783 header doesn't contain any flags for indicating encrypted files (except, the
  17784 CRC16 will be wrong when not supplying the correct password).
  17785 ARC end-marker (1Ah,00h) may be followed by additional padding bytes, or by
  17786 additional information from third-party tools:
  17787   PKARC/PKPAK adds comments (starting with "PK",AAh,55h)
  17788   PAK adds extended records (described in PAK.DOC file in the v2.51)
  17789 
  17790 See also
  17791 http://fileformats.archiveteam.org/wiki/ARC_(compression_format)
  17792 https://www.fileformat.info/format/arc/corion.htm
  17793 http://cd.textfiles.com/pcmedic/utils/compress/arc520s.zip - source code
  17794 https://github.com/ani6al/arc - source code, upgraded with method 9 and 4
  17795 https://entropymine.wordpress.com/2021/05/11/arcs-trimmed-compression-scheme/
  17796 http://www.textfiles.com/programming/FORMATS/arc-lbr.pro - benchmarks
  17797 
  17798 CDROM File Compression RAR
  17799 --------------------------
  17800 
  17801 RAR is a compression format for enthusiastic users (who love to download the
  17802 latest RAR version before being able to decompress those RAR files).
  17803 
  17804 RAR v1.3 (March 1994, used only in RAR 1.402)
  17805 This format was only used by RAR 1.402, and discontinued after three months
  17806 when RAR 1.5 got released.
  17807  File Header:
  17808   000h 4     ID "RE~^" (aka 52h,45h,7Eh,5Eh)
  17809   004h 2     Header Size  (usually 0007h, or bigger when Comment/Ext1 exist)
  17810   006h 1     Archive Flags (80h or xxh)
  17811   ...  (2)   Archive Comment Size   ;\Only present when ArchiveFlags.bit1=1
  17812   ...  (..)  Archive Comment Data   ;/
  17813   ...  (2)   Ext1 Size              ;\Only present when ArchiveFlags.bit5=1
  17814   ...  (..)  Ext1 Data              ;/
  17815   ...  ..    Unknown (TECHNOTE hints sth can be here, when bigger HeaderSize?)
  17816  Archive Flags:
  17817   0   Volume   (maybe related to split-volume on several floppies?)
  17818   1   Comment
  17819   2   Unknown? (non-english description is in 1.402's TECHNOTE.DOC)
  17820   3   Unknown? (non-english description is in 1.402's TECHNOTE.DOC)
  17821   4   Unknown? (non-english description is in 1.402's TECHNOTE.DOC)
  17822   5   EXT1
  17823   6   Unspecified (maybe unused)
  17824   7   Unspecified (maybe unused, but... it's usually 1)
  17825  File Data blocks:
  17826   000h 4     Filesize, compressed
  17827   004h 4     Filesize, uncompressed
  17828   008h 2     Checksum on uncompressed? file (sum=LeftRotate16bit(sum+byte[i])
  17829   00Ah 2     Header Size (usually 0015h+FilenameLength)
  17830   00Ch 4     File Modification Timestamp in MSDOS format
  17831   010h 1     File Attribute in MSDOS format (20h=Normal)
  17832   011h 1     Flags
  17833   012h 1     Version (0=0.99, 1=1.00, 2=1.30) (always 2 in public version)
  17834   013h 1     Filename Length
  17835   014h 1     Method (00h=m0a=Stored, 03h=m3a=Default) (1..5 = fastest..best)
  17836   ...  (2)   File Comment Length        ;\Only present if FileFlags.bit3=1
  17837   ...  (..)  File Comment Data          ;/
  17838   ...  ..    Filename ("PATH\FILENAME.EXT", without any end marker)
  17839   ...  ..    Unknown (TECHNOTE hints sth can be here, when bigger HeaderSize?)
  17840   ...  ..    Compressed file data
  17841  File Flags:
  17842   0   Unknown? (non-english description is in 1.402's TECHNOTE.DOC)
  17843   1   Unknown? (non-english description is in 1.402's TECHNOTE.DOC)
  17844   2   Unknown? (non-english description is in 1.402's TECHNOTE.DOC)
  17845   3   Comment  (non-english description is in 1.402's TECHNOTE.DOC)
  17846   4-7 Unspecified (maybe unused)
  17847 
  17848 RAR 1.5 (June 1994) and newer
  17849 Overall Chunk Format:
  17850   000h 2    Chunk Header CRC; Lower 16bit of CRC32 on [002h..HdrSize-1 or less]
  17851   002h 1    Chunk Type (72h..7Ah)
  17852   003h 2    Chunk Flags
  17853   005h 2    Chunk Header Size
  17854   007h (4)  Data block size    ;<-- Only present if Flags.bit15=1
  17855   ...  ..   Header values (depending on Chunk Type and Chunk Header Size)
  17856   ...  ..   Data block         ;<-- Only present if Flags.bit15=1
  17857  Chunk Types:
  17858   72h="r"=Marker block (with "r" being 3rd byte in ID "Rar!",1Ah)
  17859   73h="s"=Archive header
  17860   74h="t"=File header
  17861   75h="u"=Old style Comment header (nested within Type 73h/74h)
  17862   76h="v"=Old style Authenticity information
  17863   77h="w"=Old style Subblock
  17864   78h="x"=Old style Recovery record
  17865   79h="y"=Old style Authenticity information
  17866   7AH="z"=Subblock
  17867  Chunk Flags:
  17868   0-13   Flags, meaning depends on Chunk Type
  17869   14     If set, older RAR versions (before 1.52 or so?) will ignore the
  17870                block and remove it when the archive is updated. If clear, the
  17871                block is copied to the new archive file when the archive is
  17872                updated;
  17873                or does "older" mean older than the "archiver version"?
  17874   15     Data Block present (0=No, 1=Yes, with size at [007h])
  17875 
  17876 Type 72h, Marker Block (MARK_HEAD)
  17877 This 7-byte ID occurs at the begin of RAR files (or after the executable in
  17878 case of self-extracting files).
  17879   000h 7       ID ("Rar!",1Ah,07h,00h) (or "Rar!",1Ah,07h,01h for RAR 5.0)
  17880  The above ID can be somewhat parsed as normal chunk header, as so:
  17881   000h 2       Faux CRC          (6152h, no actual valid CRC)
  17882   002h 1       Chunk Type        (72h)
  17883   003h 2       Faux Flags        (1A21h, no actual meaning)
  17884   005h 2       Chunk Header size (0007h)
  17885 
  17886 Type 73h, Archive Header (MAIN_HEAD)
  17887   000h 2       CRC32 AND FFFFh of fields HEAD_TYPE to RESERVED2
  17888   002h 1       Chunk Type: 73h
  17889   003h 2       Archive HeaderFlags
  17890   005h 2       Header size (usually 000Dh) (plus Comment Block, if any)
  17891   007h 2       RESERVED1 (0000h)
  17892   009h 4       RESERVED2 (0000011Dh)
  17893   ...  (..)    Comment block ;<-- only present if Flags.bit1=1
  17894   ...  (..)    Reserved for additional blocks
  17895  Archive Header Chunk Flags:
  17896   0     Volume attribute (archive volume) (split-volume? volume-label? what?)
  17897   1     Archive comment present              ;<-- used only before RAR 3.x
  17898           RAR 3.x uses "the separate comment block" and does not set this flag.
  17899   2     Archive lock attribute
  17900   3     Solid attribute (solid archive)
  17901   4     New volume naming scheme (0=Old="name.???", 1=New="name.partN.rar")
  17902   5     Authenticity information present     ;<-- used only before RAR 3.x
  17903   6     Recovery record present
  17904   7     Chunk headers are encrypted
  17905   8     First volume                         ;<-- set only by RAR 3.0 and later
  17906   9-13  Reserved for internal use
  17907   14-15 See overall Chunk Format
  17908 
  17909 Type 74h, File Header (File in Archive)
  17910   000h 2     CRC32 AND FFFFh on HEAD_TYPE to FILEATTR and file name
  17911   002h 1     Header Type: 74h
  17912   003h 2     Bit Flags
  17913   005h 2     File header full size including file name and comments
  17914   007h 4     Compressed file size (can be bigger than uncompressed)
  17915   00Bh 4     Uncompressed file size
  17916   00Fh 1     Operating system used for archiving
  17917   010h 4     CRC32 on uncompressed file
  17918   014h 4     File Modification Timestamp in MSDOS format
  17919   018h 1     RAR version needed to extract file (Major*10+Minor) (min=0Fh=1.5)
  17920   019h 1     Compression Method (usually 35h in RAR 1.52)
  17921   01Ah 2     Filename size
  17922   01Ch 4     File Attribute in MSDOS format (20h=Normal, Upper24bit=whatever=0)
  17923   ...  (..)  Comment block                      ;-Only present if Flags.bit3=1
  17924   ...  (4)   MSBs of compressed file size       ;\Only present if Flags.Bit8=1
  17925   ...  (4)   MSBs of uncompressed file size     ;/
  17926   ...  ..    Filename ("PATH\FILENAME.EXT")
  17927   ...  (..)  Filename extra fields (see Flags.bit9+bit11)
  17928   ...  (8)   Encryption SALT                    ;-Only present if Flags.Bit10=1
  17929   ...  (..)  Extended Time, variable size       ;-Only present if Flags.Bit12=1
  17930   ...  (..)  * other new fields may appear here.
  17931   ...  ..    Compressed file data
  17932  File Chunk Flags:
  17933   0     File continued from previous volume
  17934   1     File continued in next volume
  17935   2     File encrypted with password
  17936   3     File comment present              ;<-- used only before RAR 3.x
  17937           RAR 3.x uses the separate comment block and does not set this flag.
  17938   4     Information from previous files is used (solid flag) ;RAR 2.0 and later
  17939   5-7   Dictionary bits (for RAR 2.0 and later)
  17940   8     64bit Filesizes (for files "larger than 2Gb")
  17941   9     Unicode Filename, this can be in Dual or Single name form:
  17942           Dual name:   "NormalName",00h,"UnicodeName"   ;<-- in UTF-8 or what?
  17943           Single name: "UnicodeName"                    ;<-- in UTF-8
  17944   10    Header contains 8-byte Encryption SALT entry
  17945   11    Backup File (with version number ";n" appended to filename)
  17946   12    Extended Time field present
  17947   13-14 -
  17948   15    Data Block present (always 1=With 32bit size at [007h], or 64bit size)
  17949  Dictionary Bits (bit5-7)
  17950   00h=Dictionary Size 64 Kbyte
  17951   01h=Dictionary Size 128 Kbyte   ;\
  17952   02h=Dictionary Size 256 Kbyte   ; RAR 2.0 and up
  17953   03h=Dictionary Size 512 Kbyte   ;
  17954   04h=Dictionary Size 1024 Kbyte  ;/
  17955   05h=Dictionary Size 2048 Kbyte  ;\RAR ?? and up
  17956   06h=Dictionary Size 4096 Kbyte  ;/
  17957   07h=File is a directory         ;-RAR 2.0 and up
  17958  Operating System Indicators:
  17959   00h=MS DOS
  17960   01h=OS/2
  17961   02h=Windows
  17962   03h=Unix
  17963   04h=Mac OS
  17964   05h=BeOS
  17965   ??h=Android?
  17966  Compression Method:
  17967   35h=Default in RAR 1.52 (used even when file is too small to be compressed)
  17968   xxh=Other methods (unknown values)
  17969   30h=Stored (RAR 2.00 supports uncompressed small files and -m0 switch)
  17970   N/A=Stored (RAR 1.52 simply ignores "-m0" switch, and enforces "-m1" or so)
  17971 
  17972 Type 75h, Comment block:
  17973   000h 2    Header CRC of fields from HEAD_TYPE to COMM_CRC
  17974   002h 1    Chunk Type: 75h
  17975   003h 2    Chunk Flags (unknown if/which flags are used)
  17976   005h 2    Chunk Header size (0Eh+Compressed comment size)
  17977   007h 2    Uncompressed comment size
  17978   009h 1    RAR version needed to extract comment
  17979   00Ah 1    Packing Method
  17980   00Ch 2    Comment CRC
  17981   00Eh ..   Compressed comment data
  17982 
  17983 Sub-formats
  17984 The RAR format is comprised of many sub-formats that have changed over the
  17985 years. The different formats and their descriptions are as follows:
  17986   * 1.3 (Does not have the RAR! signature)
  17987         o There is difficulty finding information regarding this sub-format.
  17988   * 1.5
  17989         o Utilizes a proprietary compression method that is not public.
  17990         o Considered the root model of subsequent formats.
  17991         o A detailed list of information can be found here.
  17992   * 2.0
  17993         o Utilizes a proprietary compression method that is not public.
  17994         o Based off of version 1.5 of the RAR file format.
  17995   * 3.0
  17996         o Utilizes the PPMII and Lempel-Ziv (LZSS)] algorithms.
  17997         o Encryption now uses cipher block chaining (AES?-CBC) instead of AES
  17998         o Based off of version 1.5 of the RAR file format.
  17999 
  18000 See also
  18001 Older RAR versions did include a TECHNOTE file describing the file format of
  18002 those versions (TECHNOTE for 1.402 exist in unknown-language only, perhaps
  18003 russian, and TECHNOTE was discontinued somewhere between 2.5 and 2.9).
  18004 There is official decompression source code for newer RAR versions.
  18005 
  18006 CDROM File Compression ZOO
  18007 --------------------------
  18008 
  18009 ZOO Archives
  18010  File Header:
  18011   000h 20   Text Message (usually "ZOO #.## Archive.",1Ah,00h,00h)
  18012   014h 4    ID (FDC4A7DCh) (use this ID for detection, and ignore above text)
  18013   018h 4    Offset to first Chunk          (22h or 2Ah+commentsize?)
  18014   01Ch 4    Offset to first Chunk, negated (-22h or -2Ah-commentsize?)
  18015   020h 1+1  Version needed to extract (Major,Minor) (usually 1,01 or 2,00)
  18016   022h (1)  Archive Header Type (01h)                           ;\
  18017   023h (4)  Offset to Archive Comment (0=None)                  ; v2.00 and
  18018   027h (2)  Length of Archive Comment (0=None)                  ; up only
  18019   029h (1)  Version Data (01h or 03h)          "HVDATA"         ;/
  18020  File Chunks:
  18021   000h 4    ID (FDC4A7DCh)
  18022   004h 1    Type of directory entry (1=Old, 2=New, with extra entries)
  18023   005h 1    Compression method (0=Stored, 1=LZW/default, 2=LZH)
  18024   006h 4    Offset to next Chunk
  18025   00Ah 4    Offset to File Data
  18026   00Eh 4    File Modification Date/time in MSDOS format
  18027   012h 2    CRC16 on uncompressed file (with initial value 0000h)
  18028   014h 4    Filesize, uncompressed
  18029   018h 4    Filesize, compressed
  18030   01Ch 1+1  Version needed to extract (Major,Minor) (usually 1,00 or 2,01)
  18031   01Eh 1    Deleted flag (0=Normal, 1=Deleted)
  18032   01Fh 1    File structure (unknown purpose)
  18033   020h 4    Offset of comment field (0=None)
  18034   024h 2    Length of comment field (0=None)
  18035   026h 13   Short Filename ("FILENAME.EXT",00h, garbage padded if shorter)
  18036   033h (1)  Unknown (4Fh) (or 00h when with comment?)              ;-Type=1
  18037   033h (2)  Length of 038h and up (0Ah+longname+dirname)           ;\
  18038   035h (1)  Timezone (signed) (7Fh=Unknown)                        ;
  18039   036h (2)  CRC16 on Header (000h..037h+[033h], with [036h]=0000h) ;
  18040   038h (1)  Length of Long Filename (0=None, use Short Filename)   ;
  18041   039h (1)  Length of Directory name (0=None)                      ; Type=2
  18042   03Ah (..) Long Filename  ("longfilename.ext",00h) (if any)       ;
  18043   ...  (..) Directory name ("/path",00h)            (if any)       ;
  18044   ...  (2)  System ID (0=Unix, 1=DOS, 2=Portable) (but for DOS=0)  ;
  18045   ...  (3)  File Attributes (24bit)               (but for DOS=0)  ;
  18046   ...  (1)  Backup Flags (bit7=On, bit6=Last, bit0-3=Generation)   ;
  18047   ...  (2)  Backup File Version Number (for backup copies)         ;/
  18048   ...  5    File Leader aka Fudge Factor ("@)#(",00h)              ;\
  18049   ...  ..   File Data                                              ; All types
  18050   ...  ..   File Comment (if any) (ASCII, "Text string",0Ah)       ;/
  18051  Last Chunk:
  18052   000h 4     ID (FDC4A7DCh)
  18053   004h (30h) Zerofilled                                            ;-Type 1
  18054   004h (1)   Fixed (02h)                                           ;\
  18055   005h (31h) Zerofilled                                            ; Tyoe 2
  18056   036h (2)   CRC16 on Header (with [036h]=0000h) (always 83FCh)    ;/
  18057   ...  (..)  Comments may be stored here (if added after archive creation)
  18058   ...  (..)  Padding, if any (1Ah-filled in some files)
  18059 
  18060 Notes:
  18061 Method LZW is quite straight, the bitstream is fetched LSB first, codesize is
  18062 initially 9bit, max 13bit, with two special codes (100h=Clear, 101h=Stop),
  18063 there aren't any gaps after clear codes, the unusual part is that the bitstream
  18064 does start with a clear code.
  18065 Method LZH is slower, requires Zoo 2.10, and is used only when specifiying "h"
  18066 option in commandline. LZH has 8Kbyte window, same as LHA's "lh5", with an
  18067 extra end marker (blocksize=0000h=end).
  18068 Comments may be stored anywhere in the middle or at the end of the archive
  18069 (even after the zerofilled last chunk) (depending on whether the comment or
  18070 further files where last added to the archive).
  18071 Zoo is from 1986-1991, long filenames were supported only for OSes that did
  18072 support them at that time (ie. not for DOS/Windows).
  18073 When adding new files, Zoo defaults to maintain backups of old files in the
  18074 archive (older files are marked as "deleted" via [01Eh]=1, but are kept in the
  18075 archive; until the user issues command "P" for repacking/removing deleted
  18076 files) (Zoo 2.xx can additionally use a "generation" limit of 0..15, which
  18077 means to keep 0..15 older copies).
  18078 All offsets are originated from begin of archive.
  18079 
  18080 Zoo Tiny format (single-file) (commandline "z" option)
  18081 This format is called Tiny in Zoo source code, but isn't documented in the Zoo
  18082 manual or Zoo help screen. Tiny can contain only a single file (alike gzip).
  18083 The purpose appears to be using Tiny as temporary files when moving files from
  18084 one archive to another (without needing to decompress & recompress the file),
  18085 for example:
  18086   zoo xz source.too testfile.txt     ;extract to tiny/temp file testfile.tzt
  18087   zoo az dest.zoo   testfile.txt     ;import from tiny/temp file testfile.tzt
  18088 The tiny/temp file extensions have the middle character changed to "z" (eg.
  18089 "tzt" instead of "txt").
  18090 Going by zoo source code, the format should look as so:
  18091   000h 2   Zoo Tiny ID (07FEh)
  18092   002h 1   Type (01h)
  18093   003h 1   Compression Method
  18094   004h 4   Date/time in MSDOS format
  18095   008h 2   CRC16 on uncompressed file, or what (?)
  18096   00Ah 4   Filesize, uncompressed
  18097   00Eh 4   Filesize, compressed
  18098   012h 1   Major_ver
  18099   013h 1   Minor_ver
  18100   014h 2   Comment size (0=None)
  18101   016h 13  Short Filename
  18102   023h ..  File data     ... plus comment, if any?
  18103 But, files from Zoo DOS version are reportedly starting with 07h,01h (instead
  18104 FEh,07h,01h).
  18105 And, using Zoo DOS version with "z" option in Win98 does merely display "Zoo:
  18106 FATAL: I/O error or disk full."
  18107 
  18108 Zoo Filter format (for modem streaming) (commandline "f" command)
  18109 This command is documented in the Zoo manual, although it isn't actually
  18110 supported in Zoo DOS version. The intended purpose is to use Zoo as a filter to
  18111 speedup modem transfers.
  18112 Going by some information snippets, the transfer format appears to be somewhat
  18113 as so:
  18114   000h 2   Zoo Filter ID (32h,5Ah)
  18115   ...  ..  Compressed data
  18116   ...  2   CRC16 on uncompressed file, or what (?)
  18117 The transfer uses stdin/stdout instead of source/dest filenames (although, the
  18118 OS commandline interface may allow to assign filenames via ">" and "<").
  18119 There is no compression method entry (so both sides must know whether they
  18120 shall use LZW or LZH).
  18121 Unknown if there are any transfer size entries, or LZW/LZH end codes, or maybe
  18122 the streaming is infinite (with CRCs inserted here ot there)?
  18123 
  18124 CDROM File Compression nCompress.Z
  18125 ----------------------------------
  18126 
  18127 nCompress is some kind of a Gzip predecessor. The program was originally called
  18128 "compress" and later renamed to "ncompress" (and sometimes called
  18129 "(n)compress"). Compressed files have uppercase ".Z" attached to their original
  18130 name.
  18131 
  18132 nCompress.Z
  18133 The header is rather small and lacks info on decompressed size (ie. the one
  18134 must process the whole bitstream to determine the size, and accordingly, the
  18135 fileformat doesn't allow padding to be appended at end of file). To detect .Z
  18136 files, examine the first three bytes, and best also check that the leading 9bit
  18137 codes don't exceed num_codes (with num_codes increasing from 101h and up for
  18138 each new code).
  18139   000h 2    ID (1Fh,9Dh)
  18140   002h 1    Mode (MaxBits(9..16) + bit7=WithClearCode) (usually 90h)
  18141   003h ..   ClearGap LZW compressed data (or raw LZW when mode.bit7=0)
  18142 Compression is relative straight LZW, resembling 8bit GIFs, with 9bit initial
  18143 codesize, with preset codes 000h..0FFh=Data and (optional) 100h=Clear code
  18144 (there is no End code). Codes are allocated from 101h and up (100h and up if
  18145 without Clear code).
  18146 The bitstream is fetched LSB first (starting in bit0 of first byte). The
  18147 decoder is prefetching groups of eight codes (N-bytes with eight N-bit codes),
  18148 the odd part is that Clear codes are discarding those prefetched bytes (so
  18149 Clear codes will be followed by Gaps with unused bytes).
  18150 ClearGap LZW is also used by ARC Method 8 and 9.
  18151 
  18152 CDROM File Compression Octal Oddities (TAR, CPIO, RPM)
  18153 ------------------------------------------------------
  18154 
  18155 Below are file formats with unix/linux-style octal numbers (unknown if they are
  18156 serious about using that formats, or if they do consider them as decently
  18157 amusing, or whatever).
  18158 
  18159 Compression
  18160 TAR and CPIO are uncompressed archives, however, they are usually enclosed in a
  18161 compressed Gzip file (or some other compression format like nCompress, Bzip2).
  18162 
  18163 TAR format (1979)
  18164   0000h ..        TAR Chunk(s)
  18165   ...   400h      TAR End Marker (400h bytes zerofilled)
  18166   ...   ..        Zerofilled (whatever further padding)
  18167 TAR Chunk format:
  18168   000h 100 text   Filename ("path/filename.ext",00h)
  18169   064h 8   octal  Mode Flags
  18170   06Ch 8   octal  User ID
  18171   074h 8   octal  Group ID
  18172   07Ch 12  octal  Filesize
  18173   088h 12  octal  File modification time (seconds since 01 Jan 1970)
  18174   094h 8   octal  Header Checksum (sum of byte[0..1F3h], with [94h..9Bh]=20h)
  18175   09Ch 1   text   Type (00h or "0" for normal files)
  18176   09Dh 100 text   Whatever link name
  18177   101h 8   text   Tar ID (6x00h or "ustar",00h,"00" or "ustar  ",00h)
  18178   109h 32  text   User Name (owner)
  18179   129h 32  text   Group Name
  18180   149h 8   octal  Device major  ;\device number (when Type="4")
  18181   151h 8   octal  Device minor  ;/
  18182   159h 155 ?      Whatever prefix         ;-when ID="ustar",00h,"00" or 6x00h
  18183   159h 131 ?      Whatever prefix         ;\
  18184   1DCh 12  octal  File access time        ; when ID="ustar  ",00h
  18185   1E8h 12  octal  File status-change time ;/
  18186   1F4h 12  -      Zeropadding to 200h-byte boundary
  18187   200h ..  -      File data (Filesize bytes)
  18188   ...  ..  -      Zeropadding to 200h-byte boundary
  18189 TAR numeric values are weirdly stored as octal ASCII strings, often decorated
  18190 with leading or trailing spaces. For example, 8-byte octal value 123o (53h) can
  18191 look as so (with "." meaning 00h end-byte):
  18192   "0000123."  <-- normal weirdness, with leading zeroes and end-byte ("."=00h)
  18193   "  123 . "  <-- extra weird, leading/trailing spaces, mis-placed end-byte
  18194   "   123  "  <-- extra weird, leading/trailing spaces, without end-byte
  18195 See also: https://www.gnu.org/software/tar/manual/html_node/Standard.html
  18196 
  18197 CPIO Format (1977) (and MAC .PAX files)
  18198   0000h ..        CPIO Chunk(s) (with actual files)
  18199   ...   57h       CPIO Chunk    (with filename "TRAILER!!!",00h)
  18200   ...   ..        Zeropadding to 200h-byte boundary (not always present)
  18201 The chunks are simple, but they do exist in five weirdly different variants:
  18202   Align 2, Binary, little-endian (but partial "big-endian" for 2x16bit pairs)
  18203   Align 2, Binary, big-endian
  18204   Align 1, Ascii, octal strings
  18205   Align 4, Ascii, hexadecimal lowercase strings, checksum=0)
  18206   Align 4, Ascii, hexadecimal lowercase strings, checksum=sum of bytes in file)
  18207 Binary, little-or-big-endian:
  18208   000h 2   binary 16bit ID (71C7h)                      ;-little-or big endian
  18209   002h 2   binary 16bit  dev                                    ;\
  18210   004h 2   binary 16bit  ino                                    ; same
  18211   006h 2   binary 16bit  mode                                   ; endianness
  18212   008h 2   binary 16bit  uid                                    ; as in ID
  18213   00Ah 2   binary 16bit  gid                                    ;
  18214   00Ch 2   binary 16bit  nlink                                  ; (but be aware
  18215   00Eh 2   binary 16bit  rdev                                   ; of the fixed
  18216   010h 2   binary 16bit File modification time, upper 16bit  ;\ ; upper/lower
  18217   012h 2   binary 16bit File modification time, lower 16bit  ;/ ; 16bit order
  18218   014h 2   binary 16bit Filename size (including ending 00h)    ; for time and
  18219   016h 2   binary 16bit Filesize, upper 16bit                ;\ ; filesize)
  18220   018h 2   binary 16bit Filesize, lower 16bit                ;/ ;/
  18221   01Ah ..  text   Filename, terminated by 00h ("path/filename",00h)
  18222   ...  ..  binary Zeropadding to 2-byte boundary
  18223   ...  ..  binary File data (Filesize bytes)
  18224   ...  ..  binary Zeropadding to 2-byte boundary
  18225 Ascii/octal CPIO Chunk format:
  18226   000h 6   octal  18bit ID "070707" (=71C7h)
  18227   006h 6   octal  18bit dev    ;\unique file id
  18228   00Ch 6   octal  18bit ino    ;/within archive
  18229   012h 6   octal  18bit Mode (file attributes)
  18230   018h 6   octal  18bit User ID of owner
  18231   01Eh 6   octal  18bit Group ID
  18232   024h 6   octal  18bit nlink (related to duplicated dev/ino?)
  18233   02Ah 6   octal  18bit rdev (system-defined info on char/blk devices)
  18234   030h 11  octal  33bit File modification time
  18235   03Bh 6   octal  18bit Filename size (including ending 00h)
  18236   041h 11  octal  33bit Filesize
  18237   04Ch ..  text   Filename, terminated by 00h ("path/filename",00h)
  18238   ...  ..  binary File data (Filesize bytes)
  18239 Ascii/hex CPIO Chunk format:
  18240   000h 6   hex    24bit ID "070701"=Without Checksum, or "070702"=With Checksum
  18241   006h 8   hex    32bit  ino (does that 32bit value include 16bit "dev"?)
  18242   00Eh 8   hex    32bit  mode
  18243   016h 8   hex    32bit  uid
  18244   01Eh 8   hex    32bit  gid
  18245   026h 8   hex    32bit  nlink
  18246   02Eh 8   hex    32bit  mtime
  18247   036h 8   hex    32bit Filesize
  18248   03Eh 8   hex    32bit  devmajor
  18249   046h 8   hex    32bit  devminor
  18250   04Eh 8   hex    32bit  rdevmajor
  18251   056h 8   hex    32bit  rdevminor
  18252   05Eh 8   hex    32bit Filename size (including ending 00h)
  18253   066h 8   hex    32bit Checksum, sum of all bytes in file, zero when ID=070701
  18254   06Eh ..  text   Filename, terminated by 00h ("path/filename",00h)
  18255   ...  ..  binary Zeropadding to 4-byte boundary
  18256   ...  ..  binary File data (Filesize bytes)
  18257   ...  ..  binary Zeropadding to 4-byte boundary
  18258 CPIO numeric values are weird octal ASCII strings (eg. 6-byte "000123"), but,
  18259 unlike TAR, without extra oddities like spaces or end-bytes.
  18260 https://www.systutorials.com/docs/linux/man/5-cpio/
  18261 
  18262 RPM Format (1997) (BIG-ENDIAN)
  18263 RPM files contain Linux installation packages. The RPM does basically contain a
  18264 CPIO archive bundled with additional header/records with installation
  18265 information.
  18266   000h 60h File Header      (officially called "Lead" instead of "Header")
  18267   060h ..  Signature Record (contains "Header Record" in "Signature format")
  18268   ...  ..  Padding          (to 8-byte boundary)
  18269   ...  ..  Info Record      (called "Header" and also uses "Signature format")
  18270   ...  ..  Archive file     (usually a GZIP compressed CPIO) (called "Payload")
  18271 File Header (aka Lead) (60h bytes):
  18272   000h 4    File ID (EDh,ABh,EEh,DBh)     (aka octal string "\355\253\356\333")
  18273   004h 1    Major version (3)
  18274   005h 1    Minor version (0)
  18275   006h 2    Type (0=Binary Package, 1=Source Package)
  18276   008h 2    Architecture ID (defined in ISO/IEC 23360)
  18277   00Ah 66   Package name, terminated by 00h
  18278   04Ch 2    Operating System ID (1)
  18279   04Eh 2    Signature Type (5)
  18280   050h 16   Reserved space (officially undefined, usually zerofilled)
  18281 Signature/Info Records (10h+N*10h+SIZ bytes):
  18282   000h 4     Record ID (8Eh,ADh,E8h,01h)  (aka octal string "\216\255\350\001")
  18283   004h 4     Reserved (zerofilled)        (aka octal string "\000\000\000\000")
  18284   008h 4     Number of Item List entries  (N)
  18285   00Ch 4     Size of Item Data            (SIZ)
  18286   010h N*10h Item List (4x32bit each: Tag, Type, Offset, Size)
  18287   ...  SIZ   Item Data (referenced via Offset/Size entries in above list)
  18288 Item Type values:
  18289   00h=NULL         Not Implemented
  18290   01h=CHAR         Unknown, maybe unsigned 8bit         (unaligned)
  18291   02h=INT8         Unknown, maybe signed 8bit           (unaligned)
  18292   03h=INT16        Unknown, maybe signed 16bit          (align2)
  18293   04h=INT32        Unknown, maybe signed 323bit         (align4)
  18294   05h=INT64        Reserved, maybe signed 643bit        (maybe align8)
  18295   06h=STRING       Variable, NUL terminated string      (unaligned)
  18296   07h=BIN          Unknown, reportedly 1-byte size???   (unaligned)
  18297   08h=STRING_ARRAY Variable, Sequence of NUL terminated strings (unaligned)
  18298   09h=I18NSTRING   Variable, Sequence of NUL terminated strings (unaligned)
  18299 Item Tag values:
  18300   There are dozens of required & optional tag values defined.
  18301 RPM source code packages are often bundled with a .spec file (inside of the
  18302 CPIO archive), that .spec file contains source code in text format for creating
  18303 the RPM header/records.
  18304 
  18305 File Extensions
  18306  Basic extensions:
  18307   .cpio (CPIO)
  18308   .pax  (CPIO for MAC)
  18309   .rpm  (RPM installation package for RPM package manager)
  18310   .spec (RPM source file for creating RPM header/records)
  18311   .tar  (TAR, tape archive)
  18312  Double extensions (and short forms like tgz):
  18313   .tgz short for .tar.gz  (gzip)
  18314   .tbz short for .tar.bz2 (bzip2)
  18315   .txz short for .tar.xz  (XZ)
  18316   .tlz short for .tar.lz  (Lzip) or .tar.lzma (LZMA_Alone)
  18317   .tsz short for .tar.sz  (Sunzip)
  18318   .taz short for .tar.Z   (nCompress or possibly some other compressed format)
  18319   .tz  short for .tar.Z   (nCompress or possibly some other compressed format)
  18320   .spm short for .src.rpm (RPM source code package)
  18321 
  18322 CDROM File Compression MacBinary, BinHex, PackIt, StuffIt, Compact Pro
  18323 ----------------------------------------------------------------------
  18324 
  18325 Below are related to MAC filesystems (where the file body consists of separate
  18326 Data and Resource forks), and file type/creator values (resembling filename
  18327 extensions).
  18328 
  18329 MacBinary I,II,III format (v1,v2,v3)
  18330 MacBinary contains a single uncompressed file, used for transferring MAC files
  18331 via network, or storing MAC files on non-MAC filesystems.
  18332 PackIt/StuffIt archives do often have leading MacBinary headers. MacBinary
  18333 doesn't have any unique filename extension (.bin may be used, more often it's
  18334 using the same extension as the enclosed file, eg. .sit if it contains a
  18335 StuffIt archive).
  18336 Also, archives without explicit MAC support may use MacBinary format within
  18337 compressed files (eg. LZH archives created with LHA MAC version).
  18338   000h 1   Old version number, must be kept at zero for compatibility
  18339   001h 1   Length of filename (1..63) (though v3 says 1..31)
  18340   002h 63  Filename (only "length" bytes are significant)
  18341   041h 4   File type    (normally expressed as four characters)
  18342   045h 4   File creator (normally expressed as four characters)
  18343   049h 1   Finder flags, bit8-15 (see [065h] for bit0-7)
  18344   04Ah 1   Zero (must be 00h for compatibility)
  18345   04Bh 2   File Vertical position within its window
  18346   04Dh 2   File Horizontal position within its window
  18347   04Fh 2   File Window or folder ID
  18348   051h 1   Protected flag (bit0=Protected, whatever that is)
  18349   052h 1   Zero (must be 00h for compatibility)
  18350   053h 4   Filesize, Data Fork     (0=None)
  18351   057h 4   Filesize, Resource Fork (0=None)
  18352   05Bh 4   File Timestamp, creation
  18353   05Fh 4   File Timestamp, last modification
  18354   063h 27  v1:    Reserved (zerofilled)
  18355   063h 2   v2/v3: Length of Get Info comment (if any, usually 0000h)
  18356   065h 1   v2/v3: Finder Flags, bit0-7 (see [049h] for bit8-15)
  18357   066h 6   v2:    Reserved (zerofilled)
  18358   066h 4   v3:    ID ("mBIN"=MacBinary III)
  18359   06Ah 1   v3:    Script of file name (from fdScript field of an fxInfo record)
  18360   06Bh 1   v3:    Extended Finder flags (from fdXFlags field of fxInfo record)
  18361   06Ch 8   v2/v3: Reserved (zerofilled)
  18362   074h 4   v2/v3: Length of "total files" when "packed files are unpacked", uh?
  18363   078h 2   v2/v3: Extended Header size (reserved for future, always 0000h)
  18364   07Ah 1   v2/v3: MacBinary II uploader version           (81h=v2, 82h=v3)
  18365   07Bh 1   v2/v3: MacBinary II downloader minimum version (81h=v2)
  18366   07Ch 2   v2/v3: CRC16-XMODEM on [000h..07Bh]
  18367   07Eh 2   Reserved for computer type and OS ID (0000h)
  18368   ...  ..  Extended Header (if any, maybe stored here? when [078h]>0)
  18369   ...  ..  Padding to 80h-byte boundary
  18370   ...  ..  Data Fork (if any)
  18371   ...  ..  Padding to 80h-byte boundary
  18372   ...  ..  Resource Fork (if any)
  18373   ...  ..  Padding to 80h-byte boundary
  18374   ...  ..  Get Info comment (if any, usually none)
  18375 CRC16-XMODEM: http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
  18376 
  18377 BinHex 4.0 (.hqx) (ASCII, RLE90, big-endian)
  18378 Decoding binhex files is done via following steps (in that order):
  18379   1) ASCII to BINARY conversion (similar to BASE64)
  18380   2) RLE90 decompression of whole file (header+data+resource+crc's)
  18381   3) Processing the header+data+resource from the decompressed binary
  18382   4) For Multipart files, repeat above steps for each part
  18383 ASCII to BINARY:
  18384   The file may start with some text message, comments, description. Skip any
  18385   such text lines until reaching a line that contains this 45-byte ID string:
  18386     (This file must be converted with BinHex 4.0)
  18387   That line should be followed by following characters (each char representing
  18388   6bit binary value, MSB first, first char is bit7-2 of first byte):
  18389     !"#$%&'()*+,-    char(21h..2Dh) --> bin(00h..0Ch)
  18390     0123456          char(30h..36h) --> bin(0Dh..13h)
  18391     89               char(38h..39h) --> bin(14h..15h)
  18392     @ABCDEFGHIJKLMN  char(40h..4Eh) --> bin(16h..24h)
  18393     PQRSTUV          char(50h..56h) --> bin(25h..2Bh)
  18394     XYZ[             char(58h..5Bh) --> bin(2Ch..2Fh)
  18395     `abcdef          char(60h..66h) --> bin(30h..36h)
  18396     hijklm           char(68h..6Dh) --> bin(37h..3Ch)
  18397     pqr              char(70h..72h) --> bin(3Dh..3Fh)
  18398     :                char(3Ah)      --> start/end marker
  18399     CR/LF            char(0Dh/0Ah)  --> linebreaks per 64 chars (CR and/or LF)
  18400     SPC/TAB          char(09h/20h)  --> blanks (reportedly in some files)
  18401 RLE90 Decompression:
  18402   RLE90 decompression is same as in ARC files, except, code 90h,00h is handled
  18403   differently: ARC keeps prevbyte=unchanged, BinHex sets prevbyte=90h.
  18404   RLE90 compression is somewhat optional: 90h must be encoded as 90h,00h,
  18405   but many encoders don't bother to compress repeating bytes (eg. many files
  18406   contain "!!!!!!!!" chars aka uncompressed 00h-filled bytes).
  18407   There is no way to know the decompressed size before decompression (either
  18408   decompress the whole file and allocate more memory as needed, or decompress
  18409   only the header (filename+16h bytes) and then compute decompressed size as
  18410   filename+16h+data+2+resource+2 bytes).
  18411 Decompressed Binary (big-endian):
  18412   The decompressed binary contains following data (similar as MacBinary):
  18413     00h   1    Length of Filename (1..63)
  18414     01h   ..   Filename ("FILENAME.EXT")
  18415     01h+N 1    Version (00h)
  18416     02h+N 4    File Type
  18417     06h+N 4    File Creator
  18418     0Ah+N 2    Finder Flags
  18419     0Ch+N 4    Filesize, uncompressed, Data Fork
  18420     10h+N 4    Filesize, uncompressed, Resource Fork
  18421     14h+N 2    Header CRC16-XMODEM on uncompressed 14h+N bytes
  18422     16h+N ..   Data Fork
  18423     ...   2    Data Fork CRC16-XMODEM on uncompressed Data Fork
  18424     ...   ..   Resource Fork
  18425     ...   2    Resource Fork CRC16-XMODEM on uncompressed Resource Fork
  18426     ...   ..   Padding (might reportedly occur in some files)
  18427   Caution: There is a document that does claim that the CRC field should be be
  18428   set to 0000h before CRC calculation, and that the CRC would be computed on
  18429   Size+2 bytes (up to including he CRC field), that appears to be nonsense,
  18430   the CRC is computed on Size+0 bytes, not Size+2.
  18431 Multipart files:
  18432   Emails or other text documents may contain multiple binhex files, if so,
  18433   each part should be reportedly followed by a line containing:
  18434     --- end of part NN ---
  18435   Unknown if there are any .hqx files with such multipart stuff.
  18436   Unknown if the next part starts with "(This file must.." or just with ":".
  18437 Note: Many files with .hqx extension are actually raw .sit or .cpt files (maybe
  18438 because somebody had removed the binhex encoding without altering the filename
  18439 extension).
  18440 
  18441 PackIt (.pit) (Macintosh) (1986) (big-endian)
  18442 MAC File Type,Creator IDs = "PIT ","PIT " <-- normal (=uncompressed?)
  18443 MAC File Type,Creator IDs = "PIT ","UPIT" <-- other (=compressed?)
  18444  Bitstream for Uncompressed File Entries:
  18445   32bits    Uncompressed Header[000h..003h] (Method/Crypto="PMag")
  18446   ..bits    Uncompressed Header[004h..061h] (uncompressed size = 5Eh)
  18447   ..bits    Uncompressed Data+Resource+CRC  (uncompressed size = Data+Rsrc+2)
  18448  Bitstream for Compressed File Entries:
  18449   32bits    Uncompressed Header[000h..003h] (Method/Crypto="PMa4")
  18450   ..bits    Compressed Huffman Tree         (for decoding following bits)
  18451   ..bits    Compressed Header[004h..061h]   (uncompressed size = 5Eh)
  18452   ..bits    Compressed Data+Resource+CRC    (uncompressed size = Data+Rsrc+2)
  18453   ..bits    Padding to 8bit-boundary        (byte align next File Entry)
  18454  Bitstream for Archive End Marker (after last file):
  18455   32bits    Uncompressed Header[000h..003h] (Method/Crypto="PEnd")
  18456  File Entry Format:
  18457   000h 4    Method/Crypto (usually "PMag"=Uncompressed, "PMa4"=Huffman)
  18458   004h 1    Filename length
  18459   005h 63   Filename ("FILENAME", garbage padded)
  18460   044h 4    File Type
  18461   048h 4    File Creator
  18462   04Ch 2    Finder flags
  18463   04Eh 2    Locked?
  18464   050h 4    Filesize, uncompressed, Data fork
  18465   054h 4    Filesize, uncompressed, Resource fork
  18466   058h 4    Timestamp, creation
  18467   05Ch 4    Timestamp, modification
  18468   060h 2    CRC16-XMODEM on [004h..05Fh]
  18469   ...  ..   Data Fork
  18470   ...  ..   Resource Fork
  18471   ...  2    CRC16-XMODEM on uncompressed Data+Resource forks
  18472  Method/Crypto:
  18473   "PEnd" = Archive End marker (4-byte end marker, without filename etc.)
  18474   "PMag" = Uncompressed
  18475   "PMa1" = Uncompressed, Encrypted Simple
  18476   "PMa2" = Uncompressed, Encrypted DES
  18477   "PMa3" = Uncompressed, Encrypted reserved
  18478   "PMa4" = Huffman
  18479   "PMa5" = Huffman, Encrypted Simple
  18480   "PMa6" = Huffman, Encrypted DES
  18481   "PMa7" = Huffman, Encrypted reserved
  18482  Decompression:       ;for PackIt (and also for StuffIt method 03h)
  18483   InitBitstreamMsbFirst(src)             ;-src is after "PMa4" PackIt ID
  18484   tree=GetMem(200h*4)                    ;-alloc tree (probably less needed)
  18485   num_entries=0                          ;\init tree
  18486   root=GetTreeEntry                      ;/
  18487   while dst<dst_end                      ;-decompress, till end...
  18488     index=root                           ;\
  18489     while index<FF00h                    ; huffman decode
  18490       index=[tree+index*4+GetBits(1)*2]  ;/
  18491     [dst]=index AND FFh, dst=dst+1       ;-store data
  18492   return
  18493  ;---
  18494  GetTreeEntry:
  18495   if GetBits(1)=1 then
  18496     return GetBits(8)+FF00h            ;-final data entry
  18497   else
  18498     index=num_entries                  ;-current index
  18499     num_entries=num_entries+1          ;-alloc next index
  18500     [tree+index*4+0*2] = GetTreeEntry  ;-recursive call for node0
  18501     [tree+index*4+1*2] = GetTreeEntry  ;-recursive call for node1
  18502     return index
  18503 http://www.network172.com/early-mac-software/packit-source-code/ - official
  18504 
  18505 StuffIt (.sit) (Macintosh) (old format) (1987) (big-endian)
  18506 MAC File Type,Creator IDs = "SIT!","SIT!" (version=01h).
  18507 MAC File Type,Creator IDs = "SITD","SIT!" (version=02h).
  18508 MAC File Type,Creator IDs = "APPL","STi0" (whatever, with ID="ST65")
  18509  StuffIt Archive Header:
  18510   000h 4    ID ("SIT!", short for StuffIt)
  18511             Reportedly, there are several alternate IDs:
  18512               "SIT!","ST46","ST50","ST60","ST65","STin","STi2","STi3","STi4"
  18513             Unknown why, and if some do differ somehow (ST65 appears to be
  18514             same as SIT!) (for STi, the "i" might be short for it? installer?)
  18515   004h 2    Number of entries in root directory
  18516   006h 4    Total size of archive
  18517   00Ah 4    ID ("rLau", short for Raymond Lau)
  18518   00Eh 1    Version number (01h=v1.x-v1.5.x, 02h=v1.6-v4.5)
  18519   00Fh 7    Reserved (zerofilled)                          ;-when version=01h
  18520   00Fh 1    Unknown (C6h or FFh)                           ;\
  18521   010h 4    Offset to first root entry (16h or elsewhere!) ; when version=02h
  18522   014h 2    Unknown (0001h or FFFFh)                       ;/
  18523  File Entries:
  18524   000h 1    Compression method, Resource fork
  18525   001h 1    Compression method, Data fork
  18526   002h 1    Filename length (1..63 for version=01h, 1..31 for version=02h)
  18527   003h 1Fh  Filename ("FILENAME.EXT", garbage padding)
  18528   022h 20h  Filename further chars                         ;-when version=01h
  18529   022h 2    Filename+size CRC                              ;\
  18530   024h 2    Unknown (always 0000h or 0986h?)               ; when version=02h
  18531   026h 4    Unknown Resource fork related    ;maybe window ;
  18532   02Ah 4    Unknown Data fork related        ;coords ?     ;
  18533   02Eh 1    Unknown Data fork related                      ;
  18534   02Fh 1    Unknown Resource fork related                  ;
  18535   030h 2    Number of child entries (excluding End marker) ;
  18536   032h 4    Offset to previous entry                       ;
  18537   036h 4    Offset to next entry                           ;
  18538   03Ah 4    Offset to parent entry                         ;
  18539   03Eh 4    Offset to first child (or -1 for file entries) ;/
  18540   042h 4    File type     (eg. "APPL")
  18541   046h 4    File creator  (eg. "ACTA")
  18542   04Ah 2    Finder flags  (2100h)
  18543   04Ch 4    Creation date
  18544   050h 4    Modification date
  18545   054h 4    Filesize, uncompressed, Resource fork  (0=None)
  18546   058h 4    Filesize, uncompressed, Data fork      (0=None)
  18547   05Ch 4    Filesize, compressed, Resource fork    (0=None)
  18548   060h 4    Filesize, compressed, Data fork        (0=None)
  18549   064h 2    CRC16 on uncompressed(?) Resource fork (0=None)
  18550   066h 2    CRC16 on uncompressed(?) Data fork     (0=None)
  18551   068h 1    Pad bytes for encrypted Resource? (00h)
  18552   069h 1    Pad bytes for encrypted Data?     (00h)
  18553   06Ah 2    Unknown Data fork related     (0000h, or 0004h=Encrypted?)
  18554   06Ch 2    Unknown Resource fork related (0000h, or 0004h=Encrypted?)
  18555   06Eh 2    CRC16 on Header [000h..06Dh] with initial=0000h
  18556   070h ..   Compressed Data, Resource fork (if any) (size=[05Ch])
  18557   ...  ..   Compressed Data, Data fork     (if any) (size=[060h])
  18558  StuffIt Methods:
  18559   00h Uncompressed
  18560   01h RLE90        (same as... unknown if this is like BinHex, or like ARC)
  18561   02h ClearGap LZW (same as nCompress, 14bit, with Clear(+gap), no Stop code)
  18562   03h Huffman      (same as PackIt "PMa4" method)
  18563   05h LZHUF        (same as LHA "lh1" method)
  18564   06h Fixed Huffman  Segmented. PackBits, then optional Huffman coding.
  18565                        The set of Huffman codes is predefined, but the meaning
  18566                        of a code can be different in each segment
  18567   08h MW (Miller-Wegman, presumably LZMW)
  18568   0Dh LZ+Huffman   (?)                             ;-StuffIt and StuffIt5
  18569   0Eh Installer    (uh?)
  18570   0Fh Arsenic      (BWT and arithmetic coding)     ;-StuffIt5 only?
  18571   1xh Encrypted methods (same as above, plus encryption)
  18572   20h Folder start                                 ;\StuffIt (not StuffIt5)
  18573   21h Folder end                                   ;/
  18574 Common methods are 02h,03h,0Dh (rarely also 00h,01h,05h) (and 0Fh for
  18575 StuffIt5).
  18576 Folders have BOTH methods set to 20h. Uncompressed Data size is WHAT? (maybe
  18577 sum of all decompressed files in that folder?) Compressed Data size is size in
  18578 SIT file including 70h-byte folder end-marker. The Folder END marker has both
  18579 methods set to 21h. The Folder END marker has NONSENSE data size entries?
  18580 When version=01h (eg. blackfor.sit), folder/file entries start at offset 16h,
  18581 and are ordered as so:
  18582   Folder start
  18583     Child entries
  18584     Folder end
  18585   Folder start
  18586     Child entries
  18587     Folder end
  18588 When version=02h (eg. cabletron.sit), folder/file entries start at offset from
  18589 archive header [010h] (which can be anywhere at offset 16h, or near end of
  18590 archive), and are ordered as specified in file header entries [022h..041h].
  18591 
  18592 StuffIt 5 (.sit) (Macintosh, Windows) (1997) (big-endian)
  18593  StuffIt Archive Header:
  18594   000h 82   ID "StuffIt (c)1997",...,"/StuffIt/",0Dh,0Ah,1Ah,00h)
  18595   052h 1    Version (always 05h)
  18596   053h 1    Flags (can be 00h, 10h, 80h) (bit4=what?, bit7=Encrypted)
  18597   054h 4    Total size of archive
  18598   058h 4    Offset to first entry in root directory (64h, plus Extra Data)
  18599   05Ch 2    Number of entries in root directory
  18600   05Eh 4    Same as [058h] (maybe one is 1st entry, and other is Header size)?
  18601   062h 2    Header CRC16 on [000h..[05xh]-1] with [062h]=0000h and initial=0
  18602   064h ..   Extra Data (see below)
  18603   ...  ..   File/Folder entries
  18604  Extra data can be:
  18605   None (when [58h]=64h)                                  ;with Flags=00h
  18606   05h,76h,35h,B9h,87h,11h             ;maybe 05h=Length? ;with Flags=80h=crypto
  18607   0Dh,A5h,A5h,"Reserved",A5h,A5h,00h) ;maybe 0Dh=Length? ;with Flags=10h=what?
  18608  File/Folder entries:
  18609   000h ..   Base Header
  18610   ...  ..   OS Header (depending on OS Type in Base Header)
  18611   ...  ..   Resource fork (if any) (MAC only, not Windows)
  18612   ...  ..   Data fork     (if any)
  18613  Base Header:
  18614   000h 4    ID (A5A5A5A5h) (or B4B4B4B4h=corrupted charset conversion maybe?)
  18615   004h 1    OS Type (1=Mac, 3=Windows)
  18616   005h 1    Unknown (0)
  18617   006h 2    Base Header size (41h)  (30h+IV?+Filename+Comment)
  18618   008h 1    Unknown (0) (maybe Flags MSB?)
  18619   009h 1    Flags (bit3=Comment, bit6=Folder, bit5=Encrypted)
  18620   00Ah 4    Timestamp, Creation     (Mac OS format, seconds since 1904)
  18621   00Eh 4    Timestamp, Modification (Mac OS format, seconds since 1904)
  18622   012h 4    Offset of previous entry          (0=None)
  18623   016h 4    Offset of next entry              (0=None)
  18624   01Ah 4    Offset of parent folder entry     (0=None)
  18625   01Eh 2    Filename size (F)
  18626   020h 2    Base Header CRC-16 on [000h..[006h]-1]
  18627   022h (4)  Offset of first child entry in folder (FFFFFFFFh=End) ;\Folder
  18628   026h (4)  Size of complete directory                            ; (if Flags
  18629   02Ah (4)  Unknown                                               ; bit6=1)
  18630   02Eh (2)  Number of child entries (excluding folder End marker) ;/
  18631   022h (4)  Data fork uncompressed size                           ;\
  18632   026h (4)  Data fork compressed size                             ;
  18633   02Ah (2)  Data fork CRC-16 (0 for method 0Fh)                   ; File
  18634   02Ch (2)  Data fork Unknown (0000h)                             ; (if Flags
  18635   02Eh (1)  Data fork compression method (00h,0Dh,0Fh)            ; bit6=0)
  18636   02Fh (1)  Data fork Encryption IV? size                         ;
  18637   ...  (..) Data fork Encryption IV? data                         ;/
  18638   ...  ..   File/Folder name ("FILENAME.EXT")
  18639   ...  (2)  Comment size (K)                                      ;\Comment
  18640   ...  (2)  Comment Unknown (0)                                   ; (if Flags
  18641   ...  (..) Comment data                                          ;/bit3=1)
  18642  OS Header for Mac (OS=1):
  18643   000h 2       Flags2 (bit0=HasResource, bit4=same as archive header [053h] ?)
  18644   002h 2       CRC16 on OS Header (with [002h]=0000h, initial=0)
  18645   004h 4       Mac OS file type     ;\
  18646   008h 4       Mac OS file creator  ; as so for Files
  18647   00Ch 2       Mac OS Finder flags  ; (seems to contain
  18648   00Eh 2       Mac OS Unknown       ; other stfuff/junk
  18649   010h 4       Mac OS Unknown       ; for Folders)
  18650   014h 4       Mac OS Unknown       ;
  18651   018h 4       Mac OS Unknown       ;
  18652   01Ch 4       Mac OS Unknown       ;
  18653   020h 4       Mac OS Unknown       ;/
  18654   024h (4)     Resource fork uncompressed size               ;\
  18655   028h (4)     Resource fork compressed size                 ; only if
  18656   02Ch (2)     Resource fork CRC-16 (0 for method 0Fh)       ; Flags2
  18657   02Eh (2)     Resource fork Unknown                         ; bit0=1
  18658   030h (1)     Resource fork compression method              ;
  18659   031h (1)     Resource fork Encryption IV? size             ;
  18660   ...  (..)    Resource fork Encryption IV? data             ;/
  18661  OS Header for Windows (OS=3):
  18662   000h 2       Flags 2 (bit4=same as archive header [053h] ?)
  18663   002h 2       CRC16 on OS Header (with [002h]=0000h, initial=0)
  18664   004h 4       Windows File Attribute (20h=Normal, 10h=Folder)
  18665   008h 08h     Windows Zerofilled
  18666   010h 4       Windows Timestamp last accessed?
  18667   014h 4       Windows Unknown (0005xxxxh)
  18668   018h 08h     Windows Zerofilled
  18669 StuffIt 5 seems to only use 00h, 0Dh and 0Fh. See "StuffItSpecs" for
  18670 descriptions of the algorithms.
  18671 
  18672 StuffIt X (.sitx) (Macintosh, Windows) (20xx?)
  18673  StuffIt Archive Header:
  18674   000h 8    ID "StuffIt!" (reportedly "StuffIt?" also exists)
  18675   008h ..   Unknown...
  18676 The StuffIt X headers are somehow compressed/compacted (there are very few 00h
  18677 bytes even when filesize entries should have zeroes in MSBs).
  18678 https://github.com/incbee/Unarchiver/blob/master/XADMaster/XADStuffItXParser.m
  18679 
  18680 Compact Pro aka Compactor (.cpt) (Macintosh) (1990s) (big-endian)
  18681 MAC File Type,Creator IDs = "PACT","CPCT".
  18682 Compact Pro (originally called Compactor) was a MAC archiver competing with
  18683 StuffIt. There's also a DOS tool (ExtractorPC) for extracting .cpt files on PCs
  18684 (albeit released in .EXE.sit.hqx format, making it unlikely that PC users could
  18685 have used it).
  18686  Archive header:
  18687   000h   1   File ID           (always 01h)
  18688   001h   1   Volume number     (01h for single-volume, Other=Unknown)
  18689   002h   2   Random Volume ID? (...must be same in all split volume files?)
  18690   004h   4   Offset to Footer  (from begin of file)
  18691   008h   ..  Compressed files  (resource+data fork pairs)
  18692   ...    ..  Footer            (directory information)
  18693  Footer format:
  18694   000h   4   CRC32 XOR FFFFFFFFh on following bytes
  18695   004h   2   Number of entries in root folder (including all child entries)
  18696   006h   1   Comment length (usually 00h=None)
  18697   007h   N   Comment
  18698   007h+N ..  File/Folder entries
  18699  Folder entries, with [000h].bit=1:
  18700   000h   1   Foldername length (N), plus bit7=Type (1=Folder)
  18701   001h   N   Foldername ("FOLDERNAME")
  18702   001h+N 2   Number of entries in this folder (including all child entries)
  18703  File entries, with [000h].bit=0:
  18704   000h   1   Filename length (N), plus bit7=Type (0=File)
  18705   001h   N   Filename ("FILENAME.EXT")
  18706   001h+N 1   Volume number (01h for single-volume, Other=Unknown)
  18707   002h+N 4   Offset to compressed Resource (followed by compressed Data)
  18708   006h+N 4   File type
  18709   00Ah+N 4   File creator
  18710   00Eh+N 4   Timestamp, creation     (seconds since 1904)
  18711   012h+N 4   Timestamp, modification (seconds since 1904)
  18712   016h+N 2   Finder flags
  18713   018h+N 4   CRC32 XOR FFFFFFFFh on uncompressed Resource + Data forks
  18714   01Ch+N 2   Method/Flags (see below)
  18715   01Eh+N 4   Filesize, uncompressed, Resource fork
  18716   022h+N 4   Filesize, uncompressed, Data fork
  18717   026h+N 4   Filesize, compressed, Resource fork
  18718   02Ah+N 4   Filesize, compressed, Data fork
  18719  Method/Flags:
  18720   0     Encryption               (0=None, 1=Encrypted, unknown how)
  18721   1     Method for Resource fork (0=RLE8182, 1=RLE8182+LZSSHUF)
  18722   2     Method for Data fork     (0=RLE8182, 1=RLE8182+LZSSHUF)
  18723   3-15  Unknown/unused           (0)
  18724  Note: RLE8182 and RLE8182+LZSSHUF are also used by Mac DiskDoubler.
  18725 RLE8182 Compression:
  18726  This is same as RLE90, with two-byte escape code (81h,82h instead of 90h):
  18727   81h,82h,00h       Output 81h,82h
  18728   81h,82h,01h..03h  Output prevbyte 00h..02h times (this is not useful)
  18729   81h,82h,04h       Output prevbyte 03h times (useful if prev=81h, next=82h)
  18730   81h,82h,05h..FFh  Output prevbyte 04h..FEh times (this does save memory)
  18731   81h,xxh           Output 81h, and then process xxh
  18732   81h,padding       Output 81h, at end of file (with padding<>82h)
  18733   xxh               Output xxh (unless it is 81h)
  18734  Note: prevbyte is the previous output byte (ie. that stored at [dst-1]).
  18735  If the uncompressed file ends with 81h, then the compressed file MUST contain
  18736  a dummy padding byte (the RLE decoder in macutils sets a prefix flag upon 81h,
  18737  but doesn't output it to dst until receiving the padding byte, which could be
  18738  81h, or any value other than 82h).
  18739 LZSSHUF Compression:
  18740  This uses LZSS-style flag bits (to distinguish between data and len/disp),
  18741  combined with three Huffman trees (for data, len, disp values). The sliding
  18742  window is 2000h bytes (8Kbytes). The format appears to be a simplified variant
  18743  or LHA compression (but gets complicated by inventing weird corner cases).
  18744 DecompressLzsshuf:
  18745   if uncompressed_size=0 then goto @@all_done   ;-empty (eg. for unused forks)
  18746   [dst+0000h..1FFCh]=uninitialized              ;\
  18747   [dst+1FFDh..1FFFh]=00h,00h,00h                ; prefill sliding window
  18748   dst+dst+2000h                                 ;/
  18749  @@block_lop:
  18750   InitBitstreamMsbFirst(src)
  18751   GetLzsshufTree(data_tree,100h)  ;tree for data=00h..FFh
  18752   GetLzsshufTree(len_tree,40h)    ;tree for len=00h..3Fh (0,1 usually unused)
  18753   GetLzsshufTree(disp_tree,80h)   ;tree for dispUpper7bit=00h..7Fh
  18754   block_org=src, blocksize=0      ;block origin (after above trees)
  18755  @@decompress_lop:
  18756   if src>=src_end then goto @@all_done  ;<-- this may overshoot on padding bits
  18757   if out>=out_end then goto @@all_done  ;<-- more precise; if RleOnTheFly
  18758   if blocksize>=1FFF0h AND type=CompactPro then goto @@block_done
  18759   if blocksize>=0FFF0h AND type=Disc Double then goto @@block_done
  18760   if GetBits(1)=1 then
  18761     [dst]=GetHuffCode(data_tree), dst=dst+1, blocksize=blocksize+2
  18762   else
  18763     len=GetHuffCode(len_tree)+0, blocksize=blocksize+3
  18764     disp=GetHuffCode(disp_tree)*40h+GetBits(6), if disp=0000h then disp=2000h
  18765     for i=1 to len, [dst]=[dst-disp], dst=dst+1, next i
  18766   if RleOnTheFly then forward above byte(s) to RLE (which advances "out" ptr)
  18767   goto @@decompress_lop
  18768  @@block_done:
  18769   ;the decoder does prefetch data in 16bit units, and it does always have
  18770   ;16..31 bits prefetched, these bits are discarded at block end...
  18771   src=src+2+((src-block_org) AND 1) ;discard 16..31 bits (till 16bit-boundary)
  18772   goto @@block_lop                  ;start next block, with new trees
  18773  @@all_done:
  18774   ret
  18775 GetLzsshufTree(tree,max):
  18776   num=GetBits(8)*2, if num>max then goto error ;number of symbols (00h and up)
  18777   for i=0 to num-1, codesizes[i]=GetBits(4)    ;sizes (1..15 bits, or 0=unused)
  18778   lzh_explode_tree(tree,codesizes,num)         ;alike LHA trees
  18779   ret
  18780 Minor Corner cases:
  18781   Disp=0 acts as Disp=2000h (don't care when using ringbuf[index AND 1FFFh])
  18782   Len=0..1 could be definied in the len_tree (but are usually size=0bit=unused)
  18783   Unknown if disp_tree & len_tree can be empty (when using data_tree only)?
  18784   RLE ending with 81h,padding should only output 81h (see RLE8182 description)
  18785 Incomplete Trees
  18786   A few .cpt files (eg. ABC's-1.09.cpt.hqx\..\Colin's ABC's\Message.h) have
  18787   incomplete trees (like only one disp code, "0"=DispUpper7bit=00h, without
  18788   defining any further huffman codes like "1" or "1xxx").
  18789   This isn't much of a problem (except, one may need to remove incomplete tree
  18790   error checking in the "lzh_explode_tree" function).
  18791 End of Last Block
  18792   End of Last Block is usually determined by forwarding the LZSSHUF output
  18793   directly to the RLE8182 decompressor (which does then check if uncompressed
  18794   size is reached) (marked "RleOnTheFly" in above sample code).
  18795   Alternately, one could decompress in separate steps (LZSSHUF to tempbuf, and
  18796   then tempbuf to RLE8182), but that requires to deal with padding bits.
  18797     - padding seems to be 16..31 bits (?) alike at end of blocksize
  18798     - padding bits are (always?) zeroes, which act as flag=0=compressed
  18799     - compressed data occupies at least flg(1),len(1),disp(1),displsbs(6)=9bits
  18800   That can lead to decoding a few extra codes (with lengths up to 3Fh each),
  18801   so the tempbuf must have trailing space for writing that garbage padding.
  18802   And, those padding bits tend to translate to disp=0000h (aka disp=2000h),
  18803   which can cause reads from the whole sliding window, so tempbuf requires
  18804   2000h leading bytes to avoid page faults (not just the 3 initialized bytes).
  18805 See also:
  18806 https://github.com/dgilman/macutils/blob/master/macunpack/cpt.c - source code
  18807 https://github.com/MacPaw/XADMaster/wiki/CompactProSpecs - confused anti-specs
  18808 
  18809 Self-Extracting Archives (SEA)
  18810 The abbreviation SEA (and extension .sea) is used for several self-extracting
  18811 MAC archives. The Resource fork contains an executable (as indicated by
  18812 Type="APPL") which contains the decompressor, and the Data fork contains the
  18813 archive.
  18814   MAC File Type,Creator IDs = "APPL","aust" (StuffIt).
  18815   MAC File Type,Creator IDs = "APPL","EXTR" (CompactPro).
  18816   MAC File Type,Creator IDs = "APPL","DSEA" (DiskDoubler).
  18817 There are some oddities for .sea files found in internet:
  18818   StuffIt .sea files: These are often raw StuffIt archives (apparently
  18819     somebody had removed the MacBinary header and the resource fork with
  18820     the decompressor).
  18821   CompactPro .sea files: These are often stored as MacBinary without 80h-byte
  18822     padding appended to the Data and Resource forks.
  18823     That applies to "Santa.sea" but other such files have OTHER corruptions,
  18824     which may include wrong Size and/or garbage in reserved MacBinary fields?
  18825 Note: Not to be confused with ARC archives from System Enhancement Associates
  18826 (SEA).
  18827 
  18828 Mac OS Data forks
  18829 The Data fork contains the "normal data" part of the file (eg. anything like
  18830 .TXT .DOC .GIF .JPG .WAV .ZIP .LZH .SIT .PIT .CPT etc).
  18831 
  18832 Mac OS Resource forks
  18833 The Resource fork can contain executable code resources (similar to .EXE files;
  18834 with File Type="APPL"), and various other resources (fonts, icons, text strings
  18835 for dialog boxes, etc). Those resources are stored in filesystem-style archive
  18836 and can be accessed with IDs and/or name strings.
  18837  Resource fork Header:
  18838   000h 4    Offset to Resource Data section (from start of file) (100h)
  18839   004h 4    Offset to Resource Map section  (from start of file) (100h+DataSiz)
  18840   008h 4    Size of Resource Data section (can be 0=None)
  18841   00Ch 4    Size of Resource Map section
  18842   010h F0h  Unknown (can contain filename/type.. MAYBE just garbage padding?)
  18843   100h ..   Resource Data section, contains Data Record(s)
  18844   ...  ..   Resource Map section
  18845  Data Record(s) in Resource Data section (usually at offset 100h and up):
  18846   000h 4    Size of Data for this record
  18847   004h ..   Data for this record
  18848  Resource Map section:
  18849   000h 4    Offset to Resource Data section (from start of file) ;\
  18850   004h 4    Offset to Resource Map section  (from start of file) ; same as in
  18851   008h 4    Size of Resource Data section                        ; header
  18852   00Ch 4    Size of Resource Map section                         ;/
  18853   010h 4    Zero (internally used by Resource Manager, nextResourceMap)
  18854   014h 2    Zero (internally used by Resource Manager, fileRef)
  18855   016h 2    Map Attributes
  18856               0-4  Zero (reserved)
  18857               5    Zero (internally used by Resource Manager, changed)
  18858               6    Zero (internally used by Resource Manager, need compression)
  18859               7    Resource map is read-only
  18860               8-15 Zero (reserved)
  18861   018h 2    Offset to Type List (from start of resource map) (usually 1Ch ?)
  18862   01Ah 2    Offset to Name List (from start of resource map)
  18863   ...  ..   Type List
  18864   ...  ..   Resource List (with one or more entry for each entry in Type List)
  18865   ...  ..   Name List (each name consists of 8bit NameLength, plus name string)
  18866  Type List follows the header and contains an array of resource type records.
  18867   000h 2    Number of Type Records, minus one (FFFFh=None, 0000h=One, etc.)
  18868   002h N*8  Type Records
  18869  Type Record format:
  18870   000h 4    Resource Type (four-character constant)
  18871   004h 2    Number of Resource List entries, minus one (0000h=One, etc.)
  18872   006h 2    Offset to first Resource List entry (from start of Type List)
  18873  Resource List entries:
  18874   000h 2    Resource ID (C000h..FFFFh=Special/Owned)
  18875   002h 2    Offset to Resource Name (from start of Name List) (FFFFh=None)
  18876   004h 1    Attributes
  18877               0    Resource data is compressed             (0=No, 1=Compressed)
  18878               1    Zero (internally used by Resource Manager, changed)
  18879               2    Load Resource as soon as file is opened (0=No, 1=Preload)
  18880               3    Resource is read-only                   (0=No, 1=Protected)
  18881               4    Resource may not be moved in memory     (0=No, 1=Locked)
  18882               5    Resource may be paged out of memory     (0=No, 1=Purgeable)
  18883               6    Load Resource to        (0=Application heap, 1=System Heap)
  18884               7    Zero (reserved)
  18885   005h 3    Offset to Resource Data (from start of Resource Data section)
  18886   008h 4    Zero (internally used by Resource Manager, resourcePtr)
  18887  Note: Some (or all?) 16bit offsets are reportedly signed (max 32Kbyte), the
  18888  24bit offsets are reportedly unsigned (max 16Mbyte).
  18889 Compressed Resources (when Attributes.bit0=1)
  18890  Compressed resource have a standarized header, the decompression function(s)
  18891  are supposed to be stored in separate "dmcp" resource (unknown if the OS is
  18892  also providing standard decompression functions).
  18893   000h 4      ID (always A89F6572h for compressed resource)
  18894   004h 2      Always 0012h (maybe compression header size)
  18895   006h 1      Type (0h8=Type8, 0h9=Type9)
  18896   007h 1      Always 01h
  18897   008h 4      Uncompressed resource size
  18898   00Ch 1      For Type8: workingBufferFractionalSize               ;\
  18899   00Dh 1      For Type8: expansionBufferSize                       ; Type8
  18900   00Eh 2      For Type8: dcmpID (ID in "dmcp" decompress resource) ;
  18901   010h 2      For Type8: Zero (reserved?)                          ;/
  18902   00Ch 2      For Type9: dcmpID (ID in "dmcp" decompress resource) ;\Type9
  18903   00Eh 4      For Type9: decompressor_specific_parameters_with_io  ;/
  18904   012h ..     Compressed Resource Data
  18905  http://formats.kaitai.io/compressed_resource/
  18906 Owned Resources (with Resource ID=C000h..FFFFh):
  18907  https://github.com/kreativekorp/ksfl/wiki/Macintosh-Resource-File-Format
  18908 The upper 5bit (mask F800h) indicate the resource type of the owner, the middle
  18909 6bit (mask 07E0h) indicate the resource id of the owner, and the lower 5bit
  18910 (mask 001Fh) indicate the "sub-id" of the owned resource.
  18911   ID MSBs    Owner Type  Notes
  18912   C000h      DRVR        driver or desk accessory
  18913   C800h      WDEF        window definition: code to draw windows
  18914   D000h      MDEF        menu definition: code to draw menus
  18915   D800h      CDEF        control definition: code to draw UI widgets
  18916   E000h      PDEF        printer driver
  18917   E800h      PACK        utility code package/library used by the Mac OS
  18918   F000h      cdev        control panel; owner id is set to 1
  18919   F800h      reserved    reserved for future use
  18920 The Mac OS Resource Manager used this scheme to ensure that certain types of
  18921 programs, themselves stored in resources, could find the other resources they
  18922 needed even if the resources had to be renumbered to avoid conflicts. Utilities
  18923 such as Font/DA Mover that were used to install and remove these programs used
  18924 this scheme to ensure that all associated resources were installed or removed
  18925 as well, and renumber the resources if necessary to avoid conflicts.
  18926 
  18927 CDROM File XYZ and Dummy/Null Files
  18928 -----------------------------------
  18929 
  18930 Dummy/Null Files
  18931 Most PSX discs have huge zerofilled dummy files with about 32Mbytes, using
  18932 filenames like DUMMY, NUL, NULL, or ZNULL, this is probably done to tweak the
  18933 disc to have valid sector numbers at the end of disc (to help the drive head to
  18934 know which sector it is on).
  18935 Of course, Sony could as well pad the discs with longer Lead-Out areas, but the
  18936 dummy files may have been needed during development with CDRs (though burning
  18937 such large files doesn't exactly speed up development).
  18938 There are different ways to make sure that the file is at end of the disc:
  18939 - Some CDROM burning tools may allow to specify which file is where
  18940 - Some games have the file aphabetically sorted as last file in last folder
  18941 - Some games have the file declared as audio track
  18942 - Some games (additionally) have large zeropadding at end of their archive file
  18943 
  18944 XYZ Files
  18945 To reduce seek times, it can make sense to have the boot files & small files at
  18946 the begin of the disc.
  18947 Some games seem to use alphabetically sorted file/folder names to tweak Movies
  18948 and XA-audio to be located at the end of disc (eg. using ZMOVIE as folder
  18949 name).
  18950 
  18951 CDROM Protection - SCEx Strings
  18952 -------------------------------
  18953 
  18954 SCEx String
  18955 The heart of the PSX copy-protection is the four-letter "SCEx" string, encoded
  18956 in the wobble signal of original PSX disks, which cannot reproduced by normal
  18957 CD writers. The last letter varies depending on the region, "SCEI" for Japan,
  18958 "SCEA" for America (and all other NTSC countries except Japan), "SCEE" for
  18959 Europe (and all other PAL countries like Australia). If the string is missing
  18960 (or if it doesn't match up for the local region) then the PSX refuses to boot.
  18961 The verification is done by the Firmware inside of the CDROM Controller (not by
  18962 the PSX BIOS, so there's no way to bypass it by patching the BIOS ROM chip).
  18963 
  18964 Wobble Groove and Absolute Time in Pregroove (ATIP) on CD-R's
  18965 A "blank" CDR contains a pre-formatted spiral on it. The number of windings in
  18966 the spiral varies depending on the number of minutes that can be recorded on
  18967 the disk. The spiral isn't made of a straight line (------), but rather a
  18968 wobbled line (/\/\/\), which is used to adjust the rotation speed during
  18969 recording; at normal drive speed, wobble should produce a 22050Hz sine wave.
  18970 Additionally, the CDR wobble is modulated to provide ATIP information, ATIP is
  18971 used for locating and positioning during recording, and contains information
  18972 about the approximate laser power necessary for recording, the last possible
  18973 time location that lead out can start, and the disc application code.
  18974 Wobble is commonly used only on (recordable) CDRs, ie. usually NOT on
  18975 (readonly) CDROMs and Audio Disks. The copyprotected PSX CDROMs are having a
  18976 short CDR-style wobble period in the first some seconds, which seems to contain
  18977 the "SCEx" string instead of ATIP information.
  18978 
  18979 Other Protections
  18980 Aside from the SCEx string, PSX disks are required to contain region and
  18981 licence strings (in the ISO System Area, and in the .EXE file headers), and the
  18982 "PS" logo (in the System Area, too). This data can be reproduced with normal CD
  18983 writers, although it may be illegal to distribute unlicensed disks with licence
  18984 strings.
  18985 
  18986 CDROM Protection - Bypassing it
  18987 -------------------------------
  18988 
  18989 Modchips
  18990 A modchip is a small microcontroller which injects the "SCEx" signal to the
  18991 mainboard, so the PSX can be booted even from CDRs which don't contain the
  18992 "SCEx" string. Some modchips are additionally patching region checks contained
  18993 in the BIOS ROM.
  18994 Note: Although regular PSX disks are black, the hardware doesn't verify the
  18995 color of the disks, and works also with normal silver disks.
  18996 
  18997 Disk-Swap-Trick
  18998 Once when the PSX has recognized a disk with the "SCEx" signal, it'll be
  18999 satisfied until a new disk is inserted, which is sensed by the SHELL_OPEN
  19000 switch. When having that switch blocked, it is possible to insert a CDR without
  19001 the PSX noticing that the disk was changed.
  19002 Additionally, the trick requires some boot software that stops the drive motor
  19003 (so the new disk can be inserted, despite of the PSX thinking that the drive
  19004 door is still closed), and that does then start the boot executable on the new
  19005 disk.
  19006 The boot software can be stored on a special boot-disk (that do have the "SCEx"
  19007 string on it). Alternately, a regular PSX game disk could be used, with the
  19008 boot software stored somewhere else (eg. on Expansion ROM, or BIOS ROM
  19009 replacement, or Memory Card).
  19010 
  19011 Booting via BIOS ROM or Expansion ROM
  19012 The PSX can be quite easily booted via Expansion ROM, or BIOS ROM replacements,
  19013 allowing to execute code that is stored in the ROM, or that is received via
  19014 whatever serial or parallel cable connection from a PC.
  19015 However, even with a BIOS replacement, the protection in the CDROM controller
  19016 is still active, so the ROM can't read "clean" data from the CDROM Drive
  19017 (unless the Disk-Swap trick is used).
  19018 Whereas, no "clean" data doens't mean no data at all. The CDROM controller does
  19019 still seem to output "raw" data (without removing the sector header, and
  19020 without handling error correction, and with only limited accuracy on the sector
  19021 position). So, eventually, a customized BIOS could convert the "raw" data to
  19022 "clean" data.
  19023 
  19024 Secret Unlock Commands
  19025 There is an "official" backdoor that allows to disable the SCEx protection by
  19026 software via secret commands (for example, sending those commands can be done
  19027 via BIOS patches, nocash BIOS clone, or Expansion ROMs).
  19028 --> CDROM - Secret Unlock Commands
  19029 
  19030 Booting via Memory Card
  19031 Some games that load data from memory cards may get confused if the save data
  19032 isn't formatted as how they expect it - with some fine tuning you can get them
  19033 to "crash" in a manner that they do accidently execute bootcode stored on the
  19034 memory card.
  19035 Requires a tools to write to the memory card (eg. parallel port cable), and the
  19036 memory card data customized for a specific game, and an original CDROM with
  19037 that specific game. Once when the memory card code is booted, the Disk-Swap
  19038 trick can be used.
  19039 
  19040 CDROM Protection - Modchips
  19041 ---------------------------
  19042 
  19043 Modchip Source Code
  19044 The Old Crow mod chip source code works like so:
  19045   entrypoint:                   ;at power_up
  19046     gate=input/highz
  19047     data=input/highz
  19048     wait 50 ms
  19049     data=output/low
  19050     wait 850 ms
  19051     gate=output/low
  19052     wait 314 ms
  19053   loop:
  19054     wait 72 ms                  ;pause (eighteen "1=low" bits)
  19055     sendbyte("S")               ;1st letter
  19056     sendbyte("C")               ;2nd letter
  19057     sendbyte("E")               ;3rd letter
  19058     sendbyte(...)               ;4th letter (A, E, or I, depending on region)
  19059     goto loop
  19060   sendbyte(char):
  19061     sendbit(0)                  ;one start bit (0=highz)
  19062     for i=0 to 7
  19063       sendbit(char AND 1)       ;output data (LSB first)
  19064       char=char/2
  19065     next i
  19066     sendbit(1)                  ;1st stop bit (1=low)
  19067     sendbit(1)                  ;2nd stop bit (1=low)
  19068     return
  19069   sendbit(bit):
  19070     if bit=1 then data=output/low elseif bit=0 then data=input/highz
  19071     wait 4 ms           ;4ms per bit = 250 bits per second
  19072     return
  19073 
  19074 Connection for the data/gate/sync signals:
  19075 For older PSX boards (data/gate):
  19076   Board        data             gate
  19077   PU-xx        unknown?         unknown?        ;older PSX boards
  19078 For newer PSX and PSone boards (data/sync):
  19079   Board        data             sync
  19080   PU-23, PM-41 CXD2938Q.Pin42   CXD2938Q.Pin5   ;newer PSX and older PSone
  19081   PM-41(2)     CXD2941R.Pin36   CXD2941R.Pin76  ;newer PSone boards
  19082 On the mainboard should be a big SMD capacitor (connected to the "data" pin),
  19083 and a big testpoint (connected to the "sync" pin); it's easier to connect the
  19084 signals to that locations than to the tiny CXD-chip pins.
  19085 gate and data must be tristate outputs, or open-collector outputs (or normal
  19086 high/low outputs passed through a diode).
  19087 
  19088 Note on "data" pin (all boards)
  19089 Transfers the "SCEx" data. Note that the signal produced by the modchip is
  19090 looking entirly different than the signal produced by original disks, the real
  19091 signal would be modulated 22050Hz wobble, while the modchip is simply dragging
  19092 the signal permanently LOW throughout "1" bits, and leaves it floating for "0"
  19093 bits. Anyways the "faked" signal seems to be accurate enough to work.
  19094 
  19095 Note on "gate" pin (older PSX boards only)
  19096 The "gate" pin needs to be LOW only for use with original licensed disks
  19097 (reportedly otherwise the SCEx string on that disks would conflict with the
  19098 SCEx string from the modchip).
  19099 At the mainboard side, the "gate" signal is an input, and "data" is an inverted
  19100 output of the gate signal (so dragging gate to low, would cause data to go
  19101 high).
  19102 
  19103 Note on "sync" pin (newer PSX and PSone boards only)
  19104 The "sync" pin is a testpoint on the mainboard, which does (at single speed)
  19105 output a frequency of circa 44.1kHz/6 (of which some clock pulses seem to be
  19106 longer or shorter, probably to indicate adjustments to the rotation speed).
  19107 Some modchips are connected directly to "sync" (so they are apparently
  19108 synchronizing the data output with that signal; which is not implemented in the
  19109 above source code).
  19110 Anyways, other modchips are using a more simplified connection: The modchip
  19111 itself connects only to the "data" pin, and "sync" is required to be wired to
  19112 IC723.Pin17.
  19113 
  19114 Note on Multi-Region chips
  19115 Modchips that are designed to work in different regions are sending a different
  19116 string (SCEA, SCEE, SCEI) in each loop cycle. Due to the slow 250bps transfer
  19117 rate, it may take a while until the PSX has received the correct string, so
  19118 this multi-region technique may cause a noticeable boot-delay.
  19119 
  19120 Stealth (hidden modchip)
  19121 The Stealth connection is required for some newer games with anti-modchip
  19122 protection, ie. games that refuse to run if they detect a modchip. The
  19123 detection relies on the fact that the SCEx signal is normally received only
  19124 when booting the disk, whilst older modchips were sending that signal
  19125 permanently. Stealth modchips are sending the signal only on power-up (and when
  19126 inserting a new disk, which can be sensed via SHELL_OPEN signal).
  19127 Modchip detection reportedly works like so (not too sure if all commands are
  19128 required, some seem to be rather offtopic):
  19129   1.  Com 19h,20h   ;Retrieve CDROM Controller timestamp
  19130   2.  Com 01h       ;CdlNop: Get CD status
  19131   3.  Com 07h       ;CdlMotorOn: Make CD-ROM drive ready (blah?)
  19132   4.  Com 02h,1,1,1 ;CdlSetloc(01:01:01) (sector that does NOT have SCEx data)
  19133   5.  Com 0Eh,1     ;CdlSetmode: Turn on CD-DA read mode
  19134   6.  Short Delay
  19135   7.  Com 16h       ;CdlSeekP: Seek to Setloc's parameters (4426)
  19136   8.  Com 0Bh       ;CdlMute: Turn off sound so CdlPlay is inaudible
  19137   9.  Com 03h       ;CdlPlay: Start playing CD-DA.
  19138   10. Com 19h,04h   ;ResetSCExInfo (reset GetSCExInfo response to 0,0)
  19139   11. Long Delay    ;wait until the modchip (if any) has output SCEx data
  19140   12. Com 19h,05h   ;GetSCExInfo (returns total,success counters)
  19141   13. Com 09h       ;CdlPause: Stop command 19h.
  19142 If GetSCExInfo returns nonzero values, then the console is equipped with a
  19143 modchip, and if so, anti-modchip games would refuse to work (no matter if the
  19144 disk is an illegal copy, or not).
  19145 
  19146 NTSC-Boot BIOS Patch
  19147 Typically connects to two or three BIOS address/data lines, apparently watching
  19148 that signals, and dragging a data line LOW at certain time, to skip software
  19149 based region checks (eg. allowing to play NTSC games on PAL consoles).
  19150 Aside from the modchip connection, that additionally requires to adjust the
  19151 video signal (in 60Hz NTSC mode, the PSX defaults to generate a NTSC video
  19152 signal) (whilst most PAL screens can handle 60Hz refresh, they can't handle
  19153 NTSC colors) (on PSone boards, this can be fixed simply by grounding the /PAL
  19154 pin; IC502.Pin13) (on older PSX boards it seems to be required to install an
  19155 external color clock generator).
  19156 
  19157 MODCHIP Connection Example
  19158 Connection for 8pin "12C508" mod chip from fatcat.co.nz for a PAL PSone with
  19159 PM-41 board (ie. with 208pin SPU CXD2938Q, and 52pin IC304 "C 3060,
  19160 SC430943PB"):
  19161   1 3.5V        (supply)
  19162   2 IC304.Pin44 (unknown?) (XLAT)
  19163   3 BIOS.Pin15  (D2)
  19164   4 BIOS.Pin31  (A18)
  19165   5 SPU.Pin5    ("sync")
  19166   6 SPU.Pin42   ("data")
  19167   7 IC304.Pin19 (SHELL_OPEN)
  19168   8 GND         (supply)
  19169 The chip can be used in a Basic connection (with only pin1,5,6,8 connected), or
  19170 Stealth and NTSC-Boot connection (additionally pin2,3,4,7 connected). Some
  19171 other modchips (such without internal oscillator) are additionally connected to
  19172 a 4MHz or 4.3MHz signal on the mainboard. Some early modchips also connected to
  19173 a bunch of additional pins that were reportedly for power-on timings (whilst
  19174 newer chips use hardcoded power-on delays).
  19175 
  19176 Nocash BIOS "Modchip" Feature
  19177 The nocash PSX bios outputs the "data" signal on the A20 address line, so
  19178 (aside from the BIOS chip) one only needs to install a 1N4148 diode and two
  19179 wires to unlock the CDROM:
  19180   SPU.Pin42 "data" -------|>|------ CPU.Pin149 (A20)
  19181   SPU.Pin5  "sync" ---------------- IC723.Pin17
  19182 With the "sync" connection, the SCEx signal from the disk is disabled (ie. even
  19183 original licensed disks are no longer recognized, unless SCEx is output via A20
  19184 by software). For more variants, see:
  19185 --> CDROM Protection - Chipless Modchips
  19186 
  19187 CDROM Protection - Chipless Modchips
  19188 ------------------------------------
  19189 
  19190 The nocash kernel clone outputs a SCEX signal via A20 and A21 address lines,
  19191 (so one won't need a separate modchip/microprocessor):
  19192   A20 = the normal SCEX signal (inverted ASCII, eg. "A" = BEh)   ;all boards
  19193   A21 = uninverted SCEX signal (uninverted ASCII, eg. "A" = 41h) ;PU-7..PU-20
  19194   A21 = always 1 during SCEX output                              ;PU-22 and up
  19195 When using the clone bios as internal ROM replacement, A20 can be used with
  19196 simple wires/diodes. Doing that with external expansion ROMs would cause the
  19197 console to stop working when unplugging the ROM, hence needing a slightly more
  19198 complex circuit with transistors/logic chips.
  19199 
  19200 External Expansion ROM version, for older boards (PU-7 through PU-20):
  19201               .--------.-.                 .--------.-.
  19202   GATE--------|C  NPN  |  .    DATA--------|C  NPN  |  .
  19203   A20--[10K]--|B  BC   |  |    A21--[10K]--|B  BC   |  |
  19204   GND---------|E  547  |  '    GND---------|E  547  |  '
  19205               '--------'-'                 '--------'-'
  19206 
  19207 External Expansion ROM version, for newer boards (PU-22):
  19208          .-------------------.
  19209   A21----|OE1,OE2            |
  19210   A20----|IN1   74HC126  OUT1|--- DATA
  19211   WFCK---|IN2            OUT2|--- SYNC
  19212          '-------------------'
  19213 
  19214 Internal Kernel ROM version, for older boards (PU-7 through PU-20):
  19215   GATE---------GND
  19216   DATA---------A20
  19217 
  19218 Internal Kernel ROM version, for newer boards (PU-22 through PM-41(2)):
  19219   SYNC--------WFCK
  19220   DATA---|>|---A20
  19221 
  19222 What pin is where...
  19223   GATE is IC703.Pin2  (?) (8pin chip with marking "082B")   ;PU-7? .. PU-16
  19224   GATE is IC706.Pin7/10   (16pin "118" (uPC5023GR-118)      ;PU-18 .. PU-20
  19225   SYNC is IC723.Pin17(TEO)(20pin "SONY CXA2575N")           ;PU-22 .. PM-41(2)
  19226   DATA is IC???.Pin7 (CG) (8pin chip with marking "2903")   ;PU-7? .. PU-16
  19227   DATA is IC706.Pin1 (CG) (16pin "118" (uPC5023GR-118)      ;PU-18 .. PU-20
  19228   DATA is HC05.Pin17 (CG) (52pin "SONY SC4309xxPB")         ;PU-7 .. EARLY-PU-8
  19229   DATA is HC05.Pin32 (CG) (80pin "SONY E35D, 4246xx 185")   ;LATE-PU-8 .. PU-20
  19230   DATA is SPU.Pin42 (CEI) (208pin "SONY CXD2938Q")          ;PU-22 .. PM-41
  19231   DATA is SPU.Pin36?(CEI) (176pin "SONY CXD2941R")          ;PM-41(2)
  19232   WFCK is SPU.Pin5 (WFCK) (208pin "SONY CXD2938Q")          ;PU-22 .. PM-41
  19233   WFCK is SPU.Pin84(WFCK) (176pin "SONY CXD2941R")          ;PM-41(2)
  19234   A20  is CPU.Pin149(A20) (208-pin CPU CXD8530 or CXD8606)  ;PU-7 .. PM-41(2)
  19235   A20  is EXP.Pin28 (A20) (68-pin Expansion Port)           ;PU-7 .. PU-22
  19236   A21  is CPU.Pin150(A21) (208-pin CPU CXD8530 or CXD8606)  ;PU-7 .. PM-41(2)
  19237   A21  is EXP.Pin62 (A21) (68-pin Expansion Port)           ;PU-7 .. PU-22
  19238 GATE on PU-18 is usually IC706.Pin7 (but IC706.Pin10 reportedly works, too).
  19239 GATE on PU-20 is usually IC706.Pin10 (but IC706.Pin7 might work, too).
  19240 
  19241 CDROM Protection - LibCrypt
  19242 ---------------------------
  19243 
  19244 LibCrypt is an additional copy-protection, used by about 100 PSX games. The
  19245 protection uses a 16bit decryption key, which is stored as bad position data in
  19246 Subchannel Q. The 16bit key is then used for a simple XOR-decryption on certain
  19247 800h-byte sectors.
  19248 
  19249 Protected sectors generation schemas
  19250 There are some variants on how the Subchannel Q data is modified:
  19251   1. 2 bits from both MSFs are modified,
  19252      CRC-16 is recalculated and XORed with 0x0080.
  19253      Games: MediEvil (E).
  19254   2. 2 bits from both MSFs are modified,
  19255      original CRC-16 is XORed with 0x8001.
  19256      Games: CTR: Crash Team Racing (E) (No EDC), CTR: Crash Team Racing (E)
  19257      (EDC), Dino Crisis (E), Eagle One: Harrier Attack (E) et al.
  19258   3. Either 2 bits or none from both MSFs are modified,
  19259      CRC-16 is recalculated and XORed with 0x0080.
  19260      Games: Ape Escape (S) et al.
  19261 Anyways, the relevant part is that the modified sectors have wrong CRCs (which
  19262 means that the PSX cdrom controller will ignore them, and the GetlocP command
  19263 will keep returning position data from the previous sector).
  19264 
  19265 LibCrypt sectors
  19266 The modified sectors could be theoretically located anywhere on the disc,
  19267 however, all known protected games are having them located on the same sectors:
  19268   No.    <------- Minute=03/Normal ------->  <------- Minute=09/Backup ------->
  19269   Bit15  14105 (03:08:05)  14110 (03:08:10)  42045 (09:20:45)  42050 (09:20:50)
  19270   Bit14  14231 (03:09:56)  14236 (03:09:61)  42166 (09:22:16)  42171 (09:22:21)
  19271   Bit13  14485 (03:13:10)  14490 (03:13:15)  42432 (09:25:57)  42437 (09:25:62)
  19272   Bit12  14579 (03:14:29)  14584 (03:14:34)  42580 (09:27:55)  42585 (09:27:60)
  19273   Bit11  14649 (03:15:24)  14654 (03:15:29)  42671 (09:28:71)  42676 (09:29:01)
  19274   Bit10  14899 (03:18:49)  14904 (03:18:54)  42813 (09:30:63)  42818 (09:30:68)
  19275   Bit9   15056 (03:20:56)  15061 (03:20:61)  43012 (09:33:37)  43017 (09:33:42)
  19276   Bit8   15130 (03:21:55)  15135 (03:21:60)  43177 (09:35:52)  43182 (09:35:57)
  19277   Bit7   15242 (03:23:17)  15247 (03:23:22)  43289 (09:37:14)  43294 (09:37:19)
  19278   Bit6   15312 (03:24:12)  15317 (03:24:17)  43354 (09:38:04)  43359 (09:38:09)
  19279   Bit5   15378 (03:25:03)  15383 (03:25:08)  43408 (09:38:58)  43413 (09:38:63)
  19280   Bit4   15628 (03:28:28)  15633 (03:28:33)  43634 (09:41:59)  43639 (09:41:64)
  19281   Bit3   15919 (03:32:19)  15924 (03:32:24)  43963 (09:46:13)  43968 (09:46:18)
  19282   Bit2   16031 (03:33:56)  16036 (03:33:61)  44054 (09:47:29)  44059 (09:47:34)
  19283   Bit1   16101 (03:34:51)  16106 (03:34:56)  44159 (09:48:59)  44164 (09:48:64)
  19284   Bit0   16167 (03:35:42)  16172 (03:35:47)  44312 (09:50:62)  44317 (09:50:67)
  19285 Each bit is stored twice on Minute=03 (five sectors apart). For some reason,
  19286 there is also a "backup copy" on Minute=09 (however, the libcrypt software
  19287 doesn't actually support using that backup stuff, and, some discs don't have
  19288 the backup at all (namely, discs with less than 10 minutes on track 1?)).
  19289 A modified sector means a "1" bit, an unmodified means a "0" bit. The 16bit
  19290 keys of the existing games are always having eight "0" bits, and eight "1" bits
  19291 (meaning that there are 16 modified sectors on Minute=03, and, if present,
  19292 another 16 ones one Minute=09).
  19293 
  19294 Example (Legacy of Kain)
  19295 Legacy of Kain (PAL) is reading the LibCrypt data during the title screen, and
  19296 does then display GOT KEY!!! on TTY terminal (this, no matter if the correct
  19297 16bit key was received).
  19298 The actual protection jumps in a bit later (shortly after learning to glide,
  19299 the game will hang when the first enemies appear if the key isn't okay).
  19300 Thereafter, the 16bit key is kept used once and when to decrypt 800h-byte
  19301 sector data via simple XORing.
  19302 The 16bit key (and some other related counters/variables) aren't stored in RAM,
  19303 but rather in COP0 debug registers (which are mis-used as general-purpose
  19304 storage in this case), for example, the 16bit key is stored in LSBs of the
  19305 "cop0r3" register.
  19306 In particuar, the encryption is used for some of the BIGFILE.DAT folder
  19307 headers:
  19308 --> CDROM File Archive BIGFILE.DAT (Soul Reaver)
  19309 
  19310 CDROM Disk Images CCD/IMG/SUB (CloneCD)
  19311 ---------------------------------------
  19312 
  19313 File.IMG - 2352 (930h) bytes per sector
  19314 Contains the sector data, recorded at 930h bytes per sector. Unknown if other
  19315 sizes are also used/supported (like 800h bytes/sector, or even images with
  19316 mixed sizes of 800h and 930h for different tracks).
  19317 
  19318 File.SUB - 96 (60h) bytes per sector (subchannel P..W with 96 bits each)
  19319 Contains subchannel data, recorded at 60h bytes per sector.
  19320   00h..0Bh 12 Subchannel P (Pause-bits, usually all set, or all cleared)
  19321   0Ch..17h 12 Subchannel Q (ADR/Control, custom info, CRC-16-CCITT)
  19322   18h..5Fh .. Subchannel R..W (usually zero) (can be used for CD-TEXT)
  19323 Optionally, the .SUB file can be omitted (it's needed only for discs with
  19324 non-standard subchannel data, such like copy-protected games).
  19325 
  19326 File.CCD - Lead-in info in text format
  19327 Contains Lead-in info in ASCII text format. Lines should be terminated by
  19328 0Dh,0Ah. The overall CCD filestructure is:
  19329   [CloneCD]     ;File ID and version
  19330   [Disc]        ;Overall Disc info
  19331   [CDText]      ;CD-TEXT (included only if present)
  19332   [Session N]   ;Session(s) (numbered 1 and up)
  19333   [Entry N]     ;Lead-in entries (numbered 0..."TocEntries-1")
  19334   [TRACK N]     ;Track info (numbered 1 and up)
  19335 Read on below for details on the separate sections.
  19336 
  19337 [CloneCD]
  19338   Version=3             ;-version (usually 3) (rarely 2)
  19339 
  19340 [Disc]
  19341   TocEntries=4          ;-number of [Entry N] fields (lead-in info blocks)
  19342   Sessions=1            ;-number of sessions (usually 1)
  19343   DataTracksScrambled=0 ;-unknown purpose (usually 0)
  19344   CDTextLength=0        ;-total size of 18-byte CD-TEXT chunks (usually 0)
  19345   CATALOG=NNNNNNNNNNNNN ;-13-digit EAN-13 barcode (included only if present)
  19346 
  19347 [CDText]
  19348   Entries=N       ;number of following entries (CDTextLength/18) (not /16)
  19349   Entry 0=80 00 NN NN NN NN NN NN NN NN NN NN NN NN NN NN   ;entry 0
  19350   Entry 1=80 NN NN NN NN NN NN NN NN NN NN NN NN NN NN NN   ;entry 1
  19351   ...
  19352   Entry XX=8f NN NN NN NN NN NN NN NN NN NN NN NN NN NN NN  ;entry N-1
  19353   Note: Each entry contains 16 bytes (ie. "18-byte CD-TEXT" with CRC excluded)
  19354   "NN NN NN.." consists of 2-digit lowercase HEX numbers (without leading "0x")
  19355 
  19356 [Session 1]
  19357   PreGapMode=2          ;-unknown purpose (usually 1 or 2)
  19358   PreGapSubC=1          ;-unknown purpose (usually 0 or 1)
  19359 
  19360 [Entry 0]
  19361 [Entry 0..2] are usually containing Point A0h..A2h info. [Entry 3..N] are
  19362 usually TOC info for Track 1 and up.
  19363   Session=1             ;-session number that this entry belongs to (usually 1)
  19364   Point=0xa0            ;-point (0..63h=Track, non-BCD!) (A0h..XXh=specials) Q2
  19365   ADR=0x01              ;-lower 4bit of ADR/Control (usually 1)           Q0.lo
  19366   Control=0x04          ;-upper 4bit of ADR/Control (eg. 0=audio, 4=data) Q0.hi
  19367   TrackNo=0             ;-usually/always 0 (as [Entry N]'s are in Lead-in)   Q1
  19368   AMin=0                ;\current MSF address                                Q3
  19369   ASec=0                ; (dummy zero values) (actual content                Q4
  19370   AFrame=0              ; would be current lead-in position)                 Q5
  19371   ALBA=-150             ;/ALBA=((AMin*60+ASec)*75+AFrame)-PreGapSize
  19372   Zero=0                ;-probably reserved byte from Q channel              Q6
  19373   PMin=1                ;\referenced MSF address (non-BCD!), for certain     Q7
  19374   PSec=32               ; Point's, PMin may contain a Track number, and PSec Q8
  19375   PFrame=0              ; the disc type value (that without non-BCD-glitch)  Q9
  19376   PLBA=6750             ;/PLBA=((PMin*60+PSec)*75+PFrame)-PreGapSize
  19377 
  19378 [TRACK 1]             ;-track number (non-BCD) (1..99)
  19379   MODE=2                ;-mode (0=Audio, 1=Mode1, 2=Mode2)
  19380   ISRC=XXXXXNNNNNNN     ;-12-letter/digit ISRC code (included only if present)
  19381   INDEX 0=N             ;-1st sector with index 0, missing EVEN if any?
  19382   INDEX 1=N             ;-1st sector with index 1, usually same as track's PLBA
  19383   INDEX 2=N             ;-1st sector with index 2, if any
  19384   etc.
  19385 
  19386 Missing Sectors & Sector Size
  19387 The .CCD file doesn't define the "PreGapSize" (the number of missing sectors at
  19388 begin of first track). It seems to be simply constant " PreGapSize=150". Unless
  19389 one is supposed to calculate it as
  19390 "PreGapSize=((PMin*60+PSec)*75+PFrame)-PLBA".
  19391 The SectorSize seems to be also constant, "SectorSize=930h".
  19392 
  19393 Non-BCD Caution
  19394 All Min/Sec/Frame/Track/Index values are expressed in non-BCD, ie. they must be
  19395 converted to BCD to get the correct values (as how they are stored on real
  19396 CDs). Exceptions are cases where those bytes have other meanings: For example,
  19397 "PSec=32" does normally mean BcdSecond=32h, but for Point A0h it would mean
  19398 DiscType=20h=CD-ROM-XA).
  19399 The Point value is also special, it is expressed in hex (0xNN), but nonetheless
  19400 it is non-BCD, ie. Point 1..99 are specified as 0x01..0x63, whilst, Point
  19401 A0h..FFh are specified as such (ie. as 0xA0..0xFF).
  19402 
  19403 Versions
  19404 Version=1 doesn't seem to exist (or it is very rare). Version=2 is quite rare,
  19405 and it seems to lack the [TRACK N] entries (meaning that there is no MODE and
  19406 INDEX information, except that the INDEX 1 location can be assumed to be same
  19407 as PLBA). Version=3 is most common, this version includes [TRACK N] entries,
  19408 but often only with INDEX=1 (and up, if more indices), but without INDEX 0 (on
  19409 Track 1 it's probably missing due to pregap, on further Tracks it's missing
  19410 without reason) (so, only ways to reproduce INDEX=0 would be to guess it being
  19411 located 2 seconds before INDEX=1, or, to use the information from the separate
  19412 .SUB file, if that file is present; note: presence of index 0 is absolutely
  19413 required for some games like PSX Tomb Raider 2).
  19414 
  19415 Entry & Points & Sessions
  19416 The [Entry N] fields are usually containing Point A0h,A1h,A2h, followed by
  19417 Point 1..N (for N tracks). For multiple sessions: The session is terminated by
  19418 Point B0h,C0h. The next session does then contain Point A0h,A1h,A2h, and Point
  19419 N+1..X (for further tracks). The INDEX values in the [TRACK N] entries are
  19420 originated at the begin of the corresponding session, whilst PLBA values in
  19421 [Entry N] entries are always originated at the begin of the disk.
  19422 
  19423 CDROM Disk Images CDI (DiscJuggler)
  19424 -----------------------------------
  19425 
  19426 Overall Format
  19427   Sector Data (sector 00:00:00 and up)          ;-body
  19428   Number of Sessions (1 byte)     <--- located at "Filesize-Footersize"
  19429   Session Block for 1st session (15 bytes)      ;\
  19430   nnn-byte info for 1st track                   ; 1st session
  19431   nnn-byte info for 2nd track (if any)          ;
  19432   etc.                                          ;/
  19433   Session Block for 2nd session (15 bytes)      ;\
  19434   nnn-byte info for 1st track                   ; 2nd session (if any)
  19435   nnn-byte info for 2nd track (if any)          ;
  19436   etc.                                          ;/
  19437   etc.                                          ;-further sessions (if any)
  19438   Session Block for no-more-sessions (15 bytes) ;-end marker
  19439   nnn-byte Disc Info Block                      ;-general disc info
  19440   Entrypoint (4 bytes)            <--- located at "Filesize-4"
  19441 
  19442 Sector Data
  19443 Contains Sector Data for sector 00:00:00 and up (ie. all sectors are stored in
  19444 the file, there are no missing "pregap" sectors).
  19445 Sector Size can be 800h..990h bytes/sector (sector size may vary per track).
  19446 
  19447 Number of Sessions (1 byte)
  19448   00h   1   Number of Sessions (usually 1)
  19449 
  19450 Session Block (15-bytes)
  19451   00h   1   Unknown (00h)
  19452   01h   1   Number of Tracks in session (01h..63h) (or 00h=No More Sessions)
  19453   02h   7   Unknown (00h-filled)
  19454   09h   1   Unknown (01h)
  19455   0Ah   3   Unknown (00h-filled)
  19456   0Dh   2   Unknown (FFh,FFh)
  19457 
  19458 Track/Disc Header (30h+F bytes) (used in Track Blocks and Disc Info Block)
  19459   00h   12  Unknown (FFh,FFh,00h,00h,01h,00h,00h,00h,FFh,FFh,FFh,FFh)
  19460   0Ch   3   Unknown (DAh,0Ah,D5h or 64h,05h,2Ah) (random/id/chksum?)
  19461   0Fh   1   Total Number of Tracks on Disc (00h..63h) (non-BCD)
  19462   10h   1   Length of below Path/Filename (F)
  19463   11h   (F) Full Path/Filename (eg. "C:\folder\file.cdi")
  19464   11h+F 11  Unknown (00h-filled)
  19465   1Ch+F 1   Unknown (02h)
  19466   1Dh+F 10  Unknown (00h-filled)
  19467   27h+F 1   Unknown (80h)
  19468   28h+F 4   Unknown (00057E40h) (=360000 decimal) (disc capacity 80 minutes?)
  19469   2Ch+F 2   Unknown (00h,00h)
  19470   2Eh+F 2   Medium Type (0098h=CD-ROM, 0038h=DVD-ROM)
  19471 
  19472 Track Block (E4h+F+I+T bytes)
  19473   00h     30h+F Track/Disc Header (see above)
  19474   30h+F   02h   Number of Indices (usually 0002h) (I=Num*4)
  19475   32h+F   (I)   32bit Lengths (per index) (eg. 00000096h,00007044h)
  19476   32h+FI  04h   Number of CD-Text blocks (usually 0) (T=Num*18+VariableLen's)
  19477   36h+FI  (T)   CD-Text (if any) (see "mirage_parser_cdi_parse_cdtext")
  19478   36h+FIT 02h   Unknown (00h,00h)
  19479   38h+FIT 01h   Track Mode (0=Audio, 1=Mode1, 2=Mode2/Mixed)
  19480   39h+FIT 07h   Unknown (00h,00h,00h,00h,00h,00h,00h)
  19481   40h+FIT 04h   Session Number (starting at 0) (usually 00h)
  19482   44h+FIT 04h   Track Number   (non-BCD, starting at 0) (00h..62h)
  19483   48h+FIT 04h   Track Start Address (eg. 00000000h)
  19484   4Ch+FIT 04h   Track Length        (eg. 000070DAh)
  19485   50h+FIT 0Ch   Unknown (00h-filled)
  19486   5Ch+FIT 04h   Unknown (00000000h or 00000001h)
  19487   60h+FIT 04h   read_mode (0..4)
  19488                   0: Mode1,        800h, 2048
  19489                   1: Mode2,        920h, 2336
  19490                   2: Audio,        930h, 2352
  19491                   3: Raw+PQ,       940h, 2352+16 non-interleaved (P=only 1bit)
  19492                   4: Raw+PQRSTUVW, 990h, 2352+96 interleaved
  19493   64h+FIT 4     Control (Upper 4bit of ADR/Control, eg. 00000004h=Data)
  19494   68h+FIT 1     Unknown (00h)
  19495   69h+FIT 4     Track Length        (eg. 000070DAh) (same as above)
  19496   6Dh+FIT 4     Unknown (00h,00h,00h,00h)
  19497   71h+FIT 12    ISRC Code 12-letter/digit (ASCII?) string (00h-filled if none)
  19498   7Dh+FIT 4     ISRC Valid Flag (0=None, Other?=Yes?)
  19499   81h+FIT 1     Unknown (00h)
  19500   82h+FIT 8     Unknown (FFh,FFh,FFh,FFh,FFh,FFh,FFh,FFh)
  19501   8Ah+FIT 4     Unknown (00000001h)
  19502   8Eh+FIT 4     Unknown (00000080h)
  19503   92h+FIT 4     Unknown (00000002h)     (guess: maybe audio num channels??)
  19504   96h+FIT 4     Unknown (00000010h)      (guess: maybe audio bits/sample??)
  19505   9Ah+FIT 4     Unknown (0000AC44h) (44100 decimal, ie. audio sample rate?)
  19506   9Eh+FIT 2Ah   Unknown (00h-filled)
  19507   C8h+FIT 4     Unknown (FFh,FFh,FFh,FFh)
  19508   CCh+FIT 12    Unknown (00h-filled)
  19509   D8h+FIT 1       session_type  ONLY if last track of a session (else 0)
  19510                    (0=Audio/CD-DA, 1=Mode1/CD-ROM, 2=Mode2/CD-XA)
  19511   D9h+FIT 5     Unknown (00h-filled)
  19512   DEh+FIT 1     Not Last Track of Session Flag (0=Last Track, 1=Not Last)
  19513   DFh+FIT 1     Unknown (00h)
  19514   E0h+FIT 4        address for last track of a session? (otherwise 00,00,FF,FF)
  19515 
  19516 Disc Info Block (5Fh+F+V+T bytes)
  19517   00h     30h+F Track/Disc Header (see above)
  19518   30h+F   4     Disc Size (total number of sectors)
  19519   34h+F   1     Volume ID Length (V) ;\from Primary Volume Descriptor[28h..47h]
  19520   35h+F   (V)   Volume ID String     ;/(ISO Data discs) (unknown for Audio)
  19521   35h+FV  1     Unknown (00h)
  19522   36h+FV  4     Unknown (01h,00h,00h,00h)
  19523   3Ah+FV  4     Unknown (01h,00h,00h,00h)
  19524   3Eh+FV  13    EAN-13 Code 13-digit (ASCII?) string (00h-filled if none)
  19525   4Bh+FV  4     EAN-13 Valid Flag (0=None, Other?=Yes?)
  19526   4Fh+FV  4     CD-Text Length in bytes (T=Num*1)
  19527   53h+FV  (T)   CD-Text (for Lead-in) (probably 18-byte units?)
  19528   53h+FVT 8     Unknown (00h-filled)
  19529   5Bh+FVT 4     Unknown (06h,00h,00h,80h)
  19530 
  19531 Entrypoint (4 bytes) (located at "Filesize-4")
  19532   00h     4     Footer Size in bytes
  19533 
  19534 CDROM Disk Images CUE/BIN/CDT (Cdrwin)
  19535 --------------------------------------
  19536 
  19537 .CUE/.BIN (CDRWIN)
  19538 CDRWIN stores disk images in two separate files. The .BIN file contains the raw
  19539 disk image, starting at sector 00:02:00, with 930h bytes per sector, but
  19540 without any TOC or subchannel information. The .CUE file contains additional
  19541 information about the separate track(s) on the disk, in ASCII format, for
  19542 example:
  19543  FILE "PATH\FILENAME.BIN" BINARY
  19544    TRACK 01 MODE2/2352
  19545      INDEX 01 00:00:00           ;real address = 00:02:00  (+2 seconds)
  19546    TRACK 02 AUDIO
  19547      PREGAP 00:02:00             ;two missing seconds      (NOT stored in .BIN)
  19548      INDEX 01 08:09:29           ;real address = 08:13:29  (+2 seconds +pregap)
  19549    TRACK 03 AUDIO
  19550      INDEX 00 14:00:29           ;real address = 14:04:29  (+2 seconds +pregap)
  19551      INDEX 01 14:02:29           ;real address = 14:06:29  (+2 seconds +pregap)
  19552    TRACK 04 AUDIO
  19553      INDEX 00 18:30:20           ;real address = 18:34:20  (+2 seconds +pregap)
  19554      INDEX 01 18:32:20           ;real address = 18:36:20  (+2 seconds +pregap)
  19555 The .BIN file does not contain ALL sectors, as said above, the first 2 seconds
  19556 are not stored in the .BIN file. Moreover, there may be missing sectors
  19557 somewhere in the middle of the file (indicated as PREGAP in the .CUE file;
  19558 PREGAPs are usually found between Data and Audio Tracks).
  19559 The MM:SS:FF values in the .CUE file are logical addresses in the .BIN file,
  19560 rather than physical addresses on real CDROMs. To convert the .CUE values back
  19561 to real addresses, add 2 seconds to all MM:SS:FF addresses (to compensate the
  19562 missing first 2 seconds), and, if the .CUE contains a PREGAP, then the pregap
  19563 value must be additionally added to all following MM:SS:FF addresses.
  19564 The end address of the last track is not stored in the .CUE, instead, it can be
  19565 only calculated by converting the .BIN filesize to MM:SS:FF format and adding 2
  19566 seconds (plus any PREGAP values) to it.
  19567 
  19568 FILE <filename> BINARY|MOTOTOLA..or..MOTOROLA?|AIFF|WAVE|MP3
  19569   (must appear before any other commands, except CATALOG)
  19570   (uh, may also appear before further tracks)
  19571 
  19572 FLAGS DCP 4CH PRE SCMS
  19573 
  19574 INDEX NN MM:SS:FF
  19575 
  19576 TRACK NN datatype
  19577   AUDIO          ;930h  ;bytes 000h..92Fh
  19578   CDG            ;?     ;?
  19579   MODE1/2048     ;800h  ;bytes 010h..80Fh
  19580   MODE1/2352     ;930h  ;bytes 000h..92Fh
  19581   MODE2/2336     ;920h  ;bytes 010h..92Fh
  19582   MODE2/2352     ;930h  ;bytes 000h..92Fh
  19583   CDI/2336       ;920h  ;?
  19584   CDI/2352       ;930h  ;bytes 000h..92Fh
  19585 
  19586 PREGAP MM:SS:FF
  19587 POSTGAP MM:SS:FF
  19588 Duration of silence at the begin (PREGAP) or end (POSTGAP) of a track. Even if
  19589 it isn't specified, the first track will always have a 2-second pregap.
  19590 The gaps are NOT stored in the BIN file.
  19591 
  19592 REM comment
  19593 Allows to insert comments/remarks (which are usually ignored). Some third-party
  19594 tools are mis-using REM to define additional information.
  19595 
  19596 CATALOG 1234567890123
  19597 ISRC ABCDE1234567
  19598   (ISRC must be after TRACK, and before INDEX)
  19599 
  19600 PERFORMER "The Band"
  19601 SONGWRITER "The Writer"
  19602 TITLE "The Title"
  19603 These entries allow to define basic CD-Text info directly in the .CUE file.
  19604 Some third-party utilites allow to define additional CD-Text info via REM
  19605 lines, eg. "REM GENRE Rock".
  19606 Alternately, more complex CD-Text data can be stored in a separate .CDT file.
  19607 
  19608 CDTEXTFILE "C:\LONG FILENAME.CDT"
  19609 Specifies an optional file which may contain CD-TEXT. The .CDT file consists of
  19610 raw 18-byte CD-TEXT fragments (which may include any type of information,
  19611 including exotic one's like a "Message" from the producer). For whatever
  19612 reason, there's a 00h-byte appended at the end of the file. Alternately to the
  19613 .CDT file, the less exotic types of CD-TEXT can be defined by PERFORMER, TITLE,
  19614 and SONGWRITER commands in the .CUE file.
  19615 
  19616 Missing
  19617 Unknown if newer CUE/BIN versions do also support subchannel data.
  19618 
  19619 Malformed .CUE files
  19620 Some .CCD files are bundled with uncommon/corrupted .CUE files, with entries as
  19621 so:
  19622    TRACK 1 MODE2/2352   ;three spaces indent, and 1-digit track
  19623    INDEX 1 00:00:00     ;three spaces indent, and 1-digit index
  19624 Normally, that should look as so:
  19625   TRACK 01 MODE2/2352   ;two spaces indent, and 2-digit track
  19626     INDEX 01 00:00:00   ;four spaces indent, and 2-digit index
  19627 The purpose of the malformed .CUE might be unsuccessful compatibility, or
  19628 tricking people into thinking that .CCD works better than .CUE.
  19629 
  19630 CDROM Disk Images MDS/MDF (Alcohol 120%)
  19631 ----------------------------------------
  19632 
  19633 File.MDF - Contains sector data (optionally with sub-channel data)
  19634 Contains the sector data, recorded at 800h..930h bytes per sector, optionally
  19635 followed by 60h bytes subchannel data (appended at the end of each sector). The
  19636 stuff seems to be start on 00:02:00 (ie. the first 150 sectors are missing; at
  19637 least it is like so when "Session Start Sector" is -150).
  19638 The subchannel data (if present) consists of 8 subchannels, stored in 96 bytes
  19639 (each byte containing one bit per subchannel).
  19640   Bit7..0 = Subchannel P..W (in that order, eg. Bit6=Subchannel Q)
  19641 The 96 bits (per subchannel) can be translated to bytes, as so:
  19642   1st..8th bit  = Bit7..Bit0 of 1st byte (in that order, ie. MSB/Bit7 first)
  19643   9st..16th bit = Bit7..Bit0 of 2nd byte ("")
  19644   17th..        = etc.
  19645 
  19646 File.MDS - Contains disc/lead-in info (in binary format)
  19647 An MDS file's structure consists of the following stuff ...
  19648   Header              (58h bytes)
  19649   Session block(s)    (usually one 18h byte entry)
  19650   Data blocks         (N*50h bytes)
  19651   Index blocks        (usually N*8 bytes)
  19652   Filename blocks(s)  (usually one 10h byte entry)
  19653   Filename string(s)  (usually one 6 byte string)
  19654 
  19655 Header (58h bytes)
  19656   00h 16  File ID ("MEDIA DESCRIPTOR")
  19657   10h 2   Unknown (01h,03h or 01h,04h or 01h,05h) (Fileformat version?)
  19658   12h 2   Media Type (0=CD-ROM, 1=CD-R, 2=CD-RW, 10h=DVD-ROM, 12h=DCD-R)
  19659   14h 2   Number of sessions (usually 1)
  19660   16h 4   Unknown (02h,00h,00h,00h)
  19661   1Ah 2   Zero (for DVD: Length of BCA data)
  19662   1Ch 8   Zero
  19663   24h 4   Zero (for DVD: Offset to BCA data)
  19664   28h 18h Zero
  19665   40h 4   Zero (for DVD: Offset to Disc Structures)   (from begin of .MDS file)
  19666   44h 0Ch Zero
  19667   50h 4   Offset to First Session-Block (usually 58h) (from begin of .MDS file)
  19668   54h 4   Zero (for DVD?: Offset to DPM data blocks)  (from begin of .MDS file)
  19669 
  19670 Session-Blocks (18h bytes)
  19671   00h 4   Session Start Sector (starting at FFFFFF6Ah=-150 in first session)
  19672   04h 4   Session End Sector     (XXX plus 150 ?)
  19673   08h 2   Session number (starting at 1) (non-BCD)
  19674   0Ah 1   Number of Data Blocks with any Point value (Total Data Blocks)
  19675   0Bh 1   Number of Data Blocks with Point>=A0h      (Special Lead-In info)
  19676   0Ch 2   First Track Number in Session (01h..63h, non-BCD!)
  19677   0Eh 2   Last Track Number in Session  (01h..63h, non-BCD!)
  19678   10h 4   Zero
  19679   14h 4   Offset to First Data-Block (usually 70h) (from begin of .MDS file)
  19680 
  19681 Data-Blocks (50h bytes)
  19682 Block 0..2 are usually containing Point A0h..A2h info. Block 3..N are usually
  19683 TOC info for Track 1 and up.
  19684   00h 1   Track mode (see below for details)
  19685   01h 1   Number of subchannels in .MDF file (0=None, 8=Sector has +60h bytes)
  19686   02h 1   ADR/Control (but with upper/lower 4bit swapped, ie. MSBs=ADR!)    Q0
  19687   03h 1   TrackNo (usually/always 00h; as this info is in Lead-in area)     Q1
  19688   04h 1   Point (Track 01h..63h, non-BCD!) (or A0h and up=Lead-in info)     Q2
  19689   05h 4   Zero (probably dummy MSF and reserved byte from Q channel)   Q3..Q6?
  19690   09h 1   Minute (Non-BCD!) (if track >= 0xA0 -> info about track ###)      Q7
  19691                             (if track = 0xA2 -> min. @ lead-out)
  19692   0Ah 1   Second (Non-BCD!) (if track = 0xA2 -> sec. @ lead-out)            Q8
  19693   0Bh 1   Frame  (Non-BCD!) (if track = 0xA2 -> frame @ lead-out)           Q9
  19694 For Point>=A0h, below 44h bytes at [0Ch..4Fh] are zero-filled
  19695   0Ch 4   Offset to Index-block for this track    (from begin of .MDS file)
  19696   10h 2   Sector size (800h..930h) (or 860h..990h if with subchannels)
  19697   12h 1   Unknown (02h) (maybe number of indices?)
  19698   13h 11h Zero
  19699   24h 4   Track start sector, PLBA (00000000h=00:02:00)
  19700   28h 8   Track start offset                      (from begin of .MDF file)
  19701   30h 4   Number of Filenames for this track (usually 1)
  19702   34h 4   Offset to Filename Block for this track (from begin of .MDS file)
  19703   38h 18h Zero
  19704 Trackmode:
  19705   (upper 4bit seem to be meaningless?)
  19706   00h=None (used for entries with Point=A0h..FF)
  19707   A9h=AUDIO       ;sector size = 2352    930h  ;bytes 000h..92Fh
  19708   AAh=MODE1       ;sector size = 2048    800h  ;bytes 010h..80Fh
  19709   ABh=MODE2       ;sector size = 2336    920h  ;bytes 010h..92Fh
  19710   ACh=MODE2_FORM1 ;sector size = 2048    800h  ;bytes 018h..817h (incomplete!)
  19711   ADh=MODE2_FORM2 ;sector size = 2324+0? 914h  ;bytes 018h..91Bh (incomplete!)
  19712   ADh=MODE2_FORM2 ;sector size = 2324+4? 918h  ;bytes ??..?? (contains what?)
  19713   ECh=MODE2       ;sector size = 2448    990h  ;(930h+60h) (with subchannels)
  19714 
  19715 Index Blocks (usually 8 bytes per track)
  19716   00h 4  Number of sectors with Index 0 (usually 96h or zero)
  19717   04h 4  Number of sectors with Index 1 (usually size of main-track area)
  19718 Index blocks are usually 8 bytes in size (two indices per track). Maybe this
  19719 block is/was intended to allow to contain more indices (although the Alcohol
  19720 120% does always store only 2 indices, even when recording a CD with more than
  19721 2 indices per track).
  19722 The MDS file does usually contain Index blocks for <all> Data Blocks (ie.
  19723 including unused dummy Index Blocks for Data Blocks with Point>=A0h).
  19724 
  19725 Filename Blocks (10h bytes)
  19726   00h 4  Offset to Filename (from begin of .MDS file)
  19727   04h 1  Filename format (0=8bit, 1=16bit characters)
  19728   05h 11 Zero
  19729 Normally all tracks are sharing the same filename block (although theoretically
  19730 the tracks could use separate filename blocks; with different filenames).
  19731 
  19732 Filename Strings (usually 6 bytes)
  19733   00h 6  Filename, terminated by zero (usually "*.mdf",00h)
  19734 Contains the filename of the of the sector data (usually "*.mdf", indicating to
  19735 use the same name as for the .mds file, but with .mdf extension).
  19736 
  19737 Missing
  19738 Unknown if/how this format supports EAN-13, ISRC, CD-TEXT.
  19739 Unknown if Track/Point/Index are BCD or non-BCD.
  19740 
  19741 CDROM Disk Images NRG (Nero)
  19742 ----------------------------
  19743 
  19744 .NRG (NERO)
  19745 Nero is probably the most bloated and most popular CD recording software. The
  19746 first part of the file contains the disk image, starting at sector 00:00:00,
  19747 with 800h..930h bytes per sector. Additional chunk-based information is
  19748 appended at the end of the file, usually consisting of only four chunks:
  19749 CUES,DAOI,END!,NERO (in that order).
  19750 
  19751 Chunk Entrypoint (in last 8/12 bytes of file)
  19752   4   File ID "NERO"/"NER5"
  19753   4/8 Fileoffset of first chunk
  19754 
  19755 Cue Sheet (summary of the Table of Contents, TOC)
  19756   4   Chunk ID "CUES"/"CUEX"
  19757   4   Chunk size (bytes)
  19758 below EIGHT bytes repeated for each track/index,
  19759 of which, first FOUR bytes are same for both CUES and CUEX,
  19760   1   ADR/Control from TOC (usually LSBs=ADR=1=fixed, MSBs=Control=Variable)
  19761   1   Track  (BCD) (00h=Lead-in, 01h..99h=Track N, AAh=Lead-out)
  19762   1   Index  (BCD) (usually 00h=pregap, 01h=actual track)
  19763   1   Zero
  19764 next FOUR bytes for CUES,
  19765   1   Zero
  19766   1   Minute (BCD) ;starting at 00:00:00 = 2 seconds before ISO vol. descr.
  19767   1   Second (BCD)
  19768   1   Sector (BCD)
  19769 or, next FOUR four bytes for CUEX,
  19770   4   Logical Sector Number (HEX) ;starting at FFFFFF6Ah (=00:00:00)
  19771 Caution: Above may contain two position 00:00:00 entries: one nonsense entry
  19772 for Track 00 (lead-in), followed by a reasonable entry for Track 01, Index 00.
  19773 
  19774 Disc at Once Information
  19775   4   Chunk ID "DAOI"/"DAOX"
  19776   4   Chunk size (bytes)
  19777   4   Garbage (usually same as above Chunk size)
  19778   13  EAN-13 Catalog Number (13-digit ASCII) (or 00h-filled if none/unknown)
  19779   1   Zero
  19780   1   Disk type (00h=Mode1 or Audio, 20h=XA/Mode2) (and probably 10h=CD-I?)
  19781   1   Unknown (01h)
  19782   1   First track (Non-BCD) (01h..63h)
  19783   1   Last track  (Non-BCD) (01h..63h)
  19784 below repeated for each track,
  19785   12  ISRC in ASCII (eg. "USXYZ9912345") (or 00h-filled if none/unknown)
  19786   2   Sector size (usually 800h, 920h, or 930h) (see Mode entry for more info)
  19787   1   Mode:
  19788         0=Mode1/800h ;raw mode1 data (excluding sync+header+edc+errorinfo)
  19789         3=Mode2/920h ;almost full sector (exluding first 16 bytes; sync+header)
  19790         6=Mode2/930h ;full sector (including first 16 bytes; sync+header)
  19791         7=Audio/930h ;full sector (plain audio data)
  19792       Mode values from wikipedia:
  19793         00h for data                                     Mode1/800h
  19794         02h
  19795         03h for Mode 2 Form 1 data   eh? FORM1???        Mode2/920h
  19796         05h for raw data                                 Mode1?/930h
  19797         06h for raw Mode 2/form 1 data                   Mode2/930h
  19798         07h for audio                                    Audio/930h
  19799         0Fh for raw data with sub-channel                Mode1?/930h+WHAT?
  19800         10h for audio with sub-channel                   Audio/930h+WHAT?
  19801         11h for raw Mode 2/form 1 data with sub-channel  Mode2/WHAT?+WHAT?
  19802        Note: Some newer files do actually use different sector sizes for each
  19803        track (eg. 920h for the data track, and 930h for any following audio
  19804        tracks), older files were using the same sector size for all tracks
  19805        (eg. if the disk contained 930-byte Audio tracks, then Data tracks
  19806        were stored at the same size, rather than at 800h or 920h bytes).
  19807   3   Unknown (always 00h,00h,01h)
  19808   4/8 Fileoffset 1 (Start of Track's Pregap) (with Index=00h)
  19809   4/8 Fileoffset 2 (Start of actual Track) (with Index=01h and up)
  19810   4/8 Fileoffset 3 (End of Track+1) (aka begin of next track's pregap)
  19811 
  19812 End of chain
  19813   4   Chunk ID "END!"
  19814   4   Chunk size (always zero)
  19815 
  19816 Track Information (contained only in Track at Once images)
  19817   4     Chunk ID "TINF"/"ETNF"/"ETN2"
  19818   4     Chunk size (bytes)
  19819 below repeated for each track,
  19820   4/4/8 Track fileoffset        ;\32bit in TINF/ETNF chunks,
  19821   4/4/8 Track length (bytes)    ;/64bit in ETN2 chunks
  19822   4     Mode (should be same as in DAO chunks, see there) (implies sector size)
  19823   0/4/4 Start lba on disc       ;\only in ETNF/ETN2 chunks,
  19824   0/4/4 Unknown?                ;/not in TINF chunks
  19825 
  19826 Unknown 1 (contained only in Track at Once images)
  19827   4   Chunk ID "RELO"
  19828   4   Chunk size (bytes)
  19829   4   Zero
  19830 
  19831 Unknown 2 (contained only in Track at Once images)
  19832   4   Chunk ID "TOCT"
  19833   4   Chunk size (bytes)
  19834   1   Disk type (00h=Mode1 or Audio, 20h=XA/Mode2) (and probably 10h=CD-I?)
  19835   1   Zero (00h)
  19836 
  19837 Session Info (begin of a session) (contained only in multi-session images)
  19838   4   Chunk ID "SINF"
  19839   4   Chunk size (bytes)
  19840   4   Number of tracks in session
  19841 
  19842 CD-Text (contained only in whatever images)
  19843   4   Chunk ID None/"CDTX"
  19844   4   Chunk size (bytes) (must be a multiple of 18 bytes)
  19845 below repeated for each fragment,
  19846   18  Raw 18-byte CD-text data fragments
  19847 
  19848 Media Type? (contained only in whatever images)
  19849   4   Chunk ID "MTYP"
  19850   4   Chunk size (bytes)
  19851   4   Unknown? (00000001h for CDROM) (maybe other value for DVD)
  19852 
  19853 Notes
  19854 Newer/older .NRG files may contain 32bit/64bit values (and use "OLD"/"NEW"
  19855 chunk names) (as indicated by the "/" slashes).
  19856 CAUTION: All 16bit/32bit/64bit values are in big endian byte-order.
  19857 
  19858 Missing
  19859 Unknown if newer NRG versions do also support subchannel data.
  19860 
  19861 CDROM Disk Image/Containers CDZ
  19862 -------------------------------
  19863 
  19864 .CDZ is a compressed disk image container format (developed by pSX Author, and
  19865 used only by the pSX emulator). The disk is split into 64kbyte blocks, which
  19866 allows fast random access (without needing to decompress all preceeding
  19867 sectors).
  19868 However, the compression ratio is surprisingly bad (despite of being
  19869 specifically designed for cdrom compression, the format doesn't remove
  19870 redundant sector headers, error correction information, and EDC checksums).
  19871 
  19872 .CDZ File Structure
  19873   FileID ("CDZ",00h for cdztool v0/v1, or "CDZ",01h for cdztool v2 and up)
  19874   One or two Chunk(s)
  19875 
  19876 .CDZ Chunk Format
  19877 Chunk Header in v0 (unreleased prototype):
  19878   4    32bit Decompressed Size (of all blocks) (must be other than "ZLIB")
  19879 Chunk Header in v1 (first released version):
  19880   4    ZLIB ID ("ZLIB")
  19881   8    64bit Decompressed Size (of all blocks)
  19882 Chunk Header in v2 and up (later versions):
  19883   4    Chunk ID (eg. "CUE",00h)
  19884   8    Chunk Size in bytes (starting at "ZLIB" up to including Footer, if any)
  19885   4    ZLIB ID ("ZLIB")
  19886   8    64bit Decompressed Size (of all blocks)
  19887 Chunk Body (same in all versions):
  19888   4    Number of Blocks (N)
  19889   4    Block 1 Compressed Size (CS.1)
  19890   4    Block 1 Decompressed Size (always 00010000h, except last block)
  19891   CS.1 Block 1 Compressed ZLIB Data (starting with 78h,9Ch)
  19892   ...  ...                                     ;\
  19893   4    Block N Compressed Size (CS.N)          ; further block(s)
  19894   4    Block N Decompressed Size               ; (if any)
  19895   CS.N Block N Compressed ZLIB Data            ;/
  19896 Chunk Footer in v0 (when above header didn't have the "ZLIB" ID):
  19897   4*N       Directory Entries for N blocks     ;-this ONLY for BIN chunk
  19898 Chunk Footer in v1 and up:
  19899   BPD*(N-1) Directory Entries for N-1 blocks   ;\this ONLY for BIN chunk
  19900   1         Bytes per Directory Entry (BPD)    ;/(not for CUE/CCD/MDS)
  19901 The "Compressed ZLIB Data" parts contain Deflate'd data (starting with 2-byte
  19902 ZLIB header, and ending with 4-byte ZLIB/ADLER checksum), for details see:
  19903 --> CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  19904 
  19905 .CDZ Chunks / Content
  19906 The chunk(s) have following content:
  19907   noname+noname       --> .CUE+.BIN (cdztool v1 and below)
  19908   "BIN",0             --> .ISO      (cdztool v2? and up)
  19909   "CUE",0+"BIN",0     --> .CUE+.BIN (cdztool v2 and up)
  19910   "CCD",0+"BIN",0     --> .CCD+.IMG (cdztool v2 and up)
  19911   "CCD",0+"BIN",01h   --> .CCD+.IMG+.SUB (930h sectors, plus 60h subchannels)
  19912   "MDS",0+"BIN",0     --> .MDS+.MDF (cdztool v5 only)
  19913 Note: cdztool doesn't actually recognize files with .ISO extension (however,
  19914 one can rename them to .BIN, and then compress them as CUE-less .BIN file).
  19915 
  19916 Cdztool.exe Versions
  19917   cdztool.exe v0, unrelased prototype
  19918   cdztool.exe v1, 22 May 2005, CRC32=620dbb08, 102400 bytes, pSX v1.0-5
  19919   cdztool.exe v2, 02 Jul 2006, CRC32=bcb29c1e, 110592 bytes, pSX v1.6
  19920   cdztool.exe v3, 22 Jul 2006, CRC32=4062ba82, 110592 bytes, pSX v1.7
  19921   cdztool.exe v4, 13 Aug 2006, CRC32=7388dd3d, 118784 bytes, pSX v1.8-11
  19922   cdztool.exe v5, 22 Jul 2007, CRC32=f25c1659, 155648 bytes, pSX v1.12-13
  19923 Note: v0 wasn't ever released (it's only noteworthy because later versions do
  19924 have backwards compatibility for decompressing old v0 files). v1 didn't work
  19925 with all operating systems (on Win98 it just says "Error: Couldn't create
  19926 <output>" no matter what one is doing, however, v1 does work on later windows
  19927 versions like WinXP or so?).
  19928 
  19929 CDROM Disk Image/Containers ECM
  19930 -------------------------------
  19931 
  19932 ECM (Error Code Modeler by Neill Corlett) is a utility that removes
  19933 unneccessary ECC error correction and EDC error detection values from
  19934 CDROM-images. This is making the images a bit smaller, but the real size
  19935 reduction isn't gained until subsequently compressing the images via tools like
  19936 ZIP. Accordingly, these files are extremly uncomfortable to use: One most first
  19937 UNZIP them, and then UNECM them.
  19938 
  19939 .EXT.ECM - Double extension
  19940 ECM can be applied to various CDROM-image formats (like .BIN, .CDI, .IMG, .ISO,
  19941 .MDF, .NRG), as indicated by the double-extension. Most commonly it's applied
  19942 to .BIN files (hence using extension .BIN.ECM).
  19943 
  19944 Example / File Structure
  19945   45 43 4D 00                                      ;FileID "ECM",00h
  19946   3C                                               ;Type 0, Len=10h (aka 0Fh+1)
  19947   00 FF FF FF FF FF FF FF FF FF FF 00 00 02 00 02  ;16 data bytes
  19948   02                                               ;Type 2, Len=1 (aka 00h+1)
  19949   00 00 08 00 00 00 00 00 00 00 00 ..... 00 00 00  ;804h data bytes
  19950   3C                                               ;Type 0, Len=10h (aka 0Fh+1)
  19951   00 FF FF FF FF FF FF FF FF FF FF 00 00 02 01 02  ;16 data bytes
  19952   02                                               ;Type 2, Len=1 (aka 00h+1)
  19953   00 00 08 00 00 00 00 00 00 00 00 ..... 00 00 00  ;804h data bytes
  19954   ...
  19955   FC FF FF FF 3F                                   ;End Code (Len=FFFFFFFFh+1)
  19956   NN NN NN NN                                      ;EDC (on decompressed data)
  19957 
  19958 Type/Length Byte(s)
  19959 Type/Length is encoded in 1..5 byte(s), with "More=1" indicating that further
  19960 length byte(s) follow:
  19961   1st Byte: Bit7=More, Bit6-2=LengthBit4-0, Bit1-0=Type(0..3)
  19962   2nd Byte: Bit7=More, Bit6-0=LengthBit5-11
  19963   3rd Byte: Bit7=More, Bit6-0=LengthBit12-18
  19964   4th Byte: Bit7=More, Bit6-0=LengthBit19-25
  19965   5th Byte: Bit7-6=Reserved/Zero, Bit5-0=LengthBit26-31
  19966 Length=FFFFFFFFh=End Indicator
  19967 The actual decompression LEN is: "LEN=Length+1"
  19968 
  19969 ECM Decompression
  19970 Below is repeated LEN times (with LEN being the Length value plus 1):
  19971   Type 0: load 1 byte, save 1 byte
  19972   Type 1: load 803h bytes [0Ch..0Eh,10h..80Fh], save 930h bytes [0..92Fh]
  19973   Type 2: load 804h bytes [14h..817h], save 920h bytes [10h..92Fh]
  19974   Type 3: load 918h bytes [14h..91Bh], save 920h bytes [10h..92Fh]
  19975 Type 1-3 are reconstructing the missing bytes before saving. Type 2-3 are
  19976 saving only 920h bytes, so (if the original image contained full 930h byte
  19977 sectors) the missing 10h bytes must be inserted via Type 0. Type 0 can be also
  19978 used for copying whole sectors as-is (eg. Audio sectors, or Data sectors with
  19979 invalid Sync/Header/ECC/EDC values). And, Type 0 can be used to store
  19980 non-sector data (such like the chunks at the end of .NRG or .CDI files).
  19981 
  19982 Central Mistakes
  19983 There's a lot of wrong with the ECM format. The two central problems are that
  19984 it doesn't support data-compression (and needs external compression tools like
  19985 zip/rar), and, that it doesn't contain a sector look-up table (meaning that
  19986 random access isn't possible unless when scanning the whole file until reaching
  19987 the desired sector).
  19988 
  19989 Worst-case Scenario
  19990 As if ECM as such wouldn't be uncomfortable enough, you may expect typical ECM
  19991 users to get more things messed up. For example:
  19992   A RAR file containing a 7Z file containing a ECM file containing a BIN file.
  19993   The BIN containing only Track 1, other tracks stored in APE files.
  19994   And, of course, the whole mess without including the required CUE file.
  19995 
  19996 CDROM Subchannel Images
  19997 -----------------------
  19998 
  19999 SBI (redump.org)
  20000 SBI Files start with a 4-byte FileID:
  20001   4 bytes FileID ("SBI",00h)
  20002 The followed by entries as so:
  20003   3 bytes real absolute MM:SS:FF address where the sub q data was bad
  20004   1 byte Format: the format can be 1, 2 or 3:
  20005   Format 1: complete 10 bytes sub q data            (Q0..Q9)
  20006   Format 2: 3 bytes wrong relative MM:SS:FF address (Q3..Q5)
  20007   Format 3: 3 bytes wrong absolute MM:SS:FF address (Q7..Q9)
  20008 Note: The PSX libcrypt protection relies on bad checksums (Q10..Q11), which
  20009 will cause the PSX cdrom controller to ignore Q0..Q9 (and to keep returning
  20010 position data from most recent sector with intact checksum).
  20011 Ironically, the SBI format cannot store the required Q10..Q11 checksum. The
  20012 trick for using SBI files with libcrypted PSX discs is to ignore the useless
  20013 Q0..Q9 data, and to assume that all sectors in the SBI file have wrong Q10..Q11
  20014 checksums.
  20015 
  20016 M3S (Subchannel Q Data for Minute 3) (ePSXe)
  20017 M3S files are containing Subchannel Q data for all sectors on Minute=03 (the
  20018 region where PSX libcrypt data is located) (there is no support for storing the
  20019 (unused) libcrypt backup copy on Minute=09). The .M3S filesize is 72000 bytes
  20020 (60 seconds * 75 sectors * 16 bytes). The 16 bytes per sector are:
  20021   Q0..Q9   Subchannel Q data (normally position data)
  20022   Q10..Q11 Subchannel Q checksum
  20023   Q12..Q15 Dummy/garbage/padding (usually 00000000h or FFFFFFFFh)
  20024 Unfortunately, there are at least 3 variants of the format:
  20025   1. With CRC (Q0..Q11 intact) (and Q12..Q15 randomly 00000000h or FFFFFFFFh)
  20026   2. Without CRC (only Q0..Q9 intact, but Q10..Q15 zerofilled)
  20027   3. Without anything (only Q0 intact, but Q1..Q15 zerofilled)
  20028 The third variant is definetly corrupt (and one should ignore such zerofilled
  20029 entries). The second variant is corrupt, too (but one might attempt to repair
  20030 them by guessing the missing checksum: if it contains normal position values
  20031 assume correct crc, if it contains uncommon values assume a libcrypted sector
  20032 with bad crc).
  20033 The M3S format is intended for libcrypted PSX games, but, people seem to have
  20034 also recorded (corrupted) M3S files for unprotected PSX games (in so far, more
  20035 than often, the M3S files might cause problems, instead of solving them).
  20036 Note: The odd 16-byte format with 4-byte padding does somehow resemble the "P
  20037 and Q Sub-Channel" format 'defined' in MMC-drafts; if the .M3S format was based
  20038 on the MMC stuff: then the 16th byte might contain a Subchannel P "pause" flag
  20039 in bit7.
  20040 
  20041 CDROM Images with Subchannel Data
  20042 Most CDROM-Image formats can (optionally) contain subchannel recordings. The
  20043 downsides are: Storing all 8 subchannels for a full CDROM takes up about
  20044 20MBytes. And, some entries may contain 'wrong' data (read errors caused by
  20045 scratches cannot be automatically repaired since subchannels do not contain
  20046 error correction info).
  20047 If present, the subchannel data is usually appended at the end of each sector
  20048 in the main binary file (one exception is CloneCD, which stores it in a
  20049 separate .SUB file instead of in the .IMG file).
  20050   CCD/IMG/SUB (CloneCD)  P-W  60h-bytes Non-interleaved (in separate .SUB file)
  20051   CDI (DiscJuggler)      P-Q  10h-bytes Non-interleaved (in .CDI file)
  20052   ""                     P-W  60h-bytes Interleaved (in .CDI file)
  20053   CUE/BIN/CDT (Cdrwin)        N/A
  20054   ISO (single-track)          N/A
  20055   MDS/MDF (Alcohol 120%) P-W  60h-bytes Interleaved (in .MDF file)
  20056   NRG (Nero)             P-W  60h-bytes Interleaved (in .NRG file)
  20057 Interleaved Subchannel format (eg. Alcohol .MDF files):
  20058   00h-07h   80 C0 80 80 80 80 80 C0   ;P=FFh, Q=41h=ADR/Control, R..W=00h
  20059   08h-0Fh   80 80 80 80 80 80 80 C0   ;P=FFh, Q=01h=Track,       R..W=00h
  20060   10h-17h   80 80 80 80 80 80 80 C0   ;P=FFh, Q=01h=Index,       R..W=00h
  20061   18h-1Fh   80 80 80 80 80 80 80 80   ;P=FFh, Q=00h=RelMinute,   R..W=00h
  20062   20h-27h   80 80 80 80 80 80 80 80   ;P=FFh, Q=00h=RelSecond,   R..W=00h
  20063   28h-2Fh   80 80 80 80 80 80 80 80   ;P=FFh, Q=00h=RelSector,   R..W=00h
  20064   30h-37h   80 80 80 80 80 80 80 80   ;P=FFh, Q=00h=Reserved,    R..W=00h
  20065   38h-3Fh   80 80 80 80 80 80 80 80   ;P=FFh, Q=00h=AbsMinute,   R..W=00h
  20066   40h-47h   80 80 80 80 80 80 C0 80   ;P=FFh, Q=02h=AbsSecond,   R..W=00h
  20067   48h-4Fh   80 80 80 80 80 80 80 80   ;P=FFh, Q=00h=AbsSector,   R..W=00h
  20068   50h-57h   80 80 C0 80 C0 80 80 80   ;P=FFh, Q=28h=ChecksumMsb, R..W=00h
  20069   58h-5Fh   80 80 C0 C0 80 80 C0 80   ;P=FFh, Q=32h=ChecksumLsb, R..W=00h
  20070 Non-Interleaved Subchannel format (eg. CloneCD .SUB files):
  20071   00h-0Bh   FF FF FF FF FF FF FF FF FF FF FF FF  ;Subchannel P (Pause)
  20072   0Ch-17h   41 01 01 00 00 00 00 00 02 00 28 32  ;Subchannel Q (Position)
  20073   18h-23h   00 00 00 00 00 00 00 00 00 00 00 00  ;Subchannel R
  20074   24h-2Fh   00 00 00 00 00 00 00 00 00 00 00 00  ;Subchannel S
  20075   30h-3Bh   00 00 00 00 00 00 00 00 00 00 00 00  ;Subchannel T
  20076   3Ch-47h   00 00 00 00 00 00 00 00 00 00 00 00  ;Subchannel U
  20077   48h-53h   00 00 00 00 00 00 00 00 00 00 00 00  ;Subchannel V
  20078   54h-5Fh   00 00 00 00 00 00 00 00 00 00 00 00  ;Subchannel W
  20079 Non-Interleaved P-Q 10h-byte Subchannel format:
  20080   This is probably based on MMC protocol, which would be as crude as this:
  20081   The 96 pause bits are summarized in 1 bit. Pause/Checksum are optional.
  20082   00h-09h   41 01 01 00 00 00 00 00 02 00        ;Subchannel Q (Position)
  20083   0Ah-0Bh   28 32    ;<-- OPTIONAL, can be zero! ;Subchannel Q (Checksum)
  20084   0Ch-0Eh   00 00 00                             ;Unused padding (zero)
  20085   0F        80       ;<-- OPTIONAL, can be zero! ;Subchannel P (Bit7=Pause)
  20086 
  20087 CDROM Disk Images Other Formats
  20088 -------------------------------
  20089 
  20090 .ISO - A raw ISO9660 image (can contain a single data track only)
  20091 Contains raw sectors without any sub-channel information (and thus it's
  20092 restricted to the ISO filesystem region only, and cannot contain extras like
  20093 additional audio tracks or additional sessions). The image should start at
  20094 00:02:00 (although I wouldn't be surprised if some <might> start at 00:00:00 or
  20095 so). Obviously, all sectors must have the same size, either 800h or 930h bytes
  20096 (if the image contains only Mode1 or Mode2/Form1 sectors then 800h bytes would
  20097 usually enough; if it contains one or more Mode2/Form2 sectors then all sectors
  20098 should be 930h bytes).
  20099 Handling .ISO files does thus require to detect the image's sector size, and to
  20100 search the sector that contains the first ISO Volume Descriptor. In case of
  20101 800h byte sectors it may be additionally required to detect if it is a Mode1 or
  20102 Mode2/Form1 image; for PSX images (and any CD-XA images) it'd be Mode2.
  20103 
  20104 .CHD
  20105 Something used by MAME/MESS. Originally intended for compressed ROM-images, but
  20106 does also support compressed CDROM-images. Fileformat and compression ratio are
  20107 unknown. Also unknown if it allows random-access.
  20108 Some info can be found in MAME source code (looking at the source code for the
  20109 CHDMAN tool might be a good starting point... although the actual file
  20110 structure might be hidden in other source files).
  20111 
  20112 .C2D
  20113 Something. Can contain compressed or uncompressed CDROM-images. Fileformat and
  20114 compression ratio are unknown. Also unknown if it allows random-access.
  20115 Some info on (uncompressed) .C2D files can be found in libmirage source code.
  20116 
  20117 .ISZ
  20118 This is reportedly a "zipped" .ISO file, using some unknown compression format
  20119 (unrelated to pkzip .zip file format).
  20120 
  20121 .MDX
  20122 Reportedly a compressed MDS/MDF file, supported by Daemon Tools. Fileformat and
  20123 compression ratio are unknown. Also unknown if it allows random-access.
  20124 
  20125 .CU2/.BIN
  20126 Custom format used by PSIO (an SD-card based CDROM-drive emulator connected to
  20127 PSX expansion port). The .CU2 file is somewhat intended to be smaller and
  20128 easier to parse than normal .CUE files, the drawback is that it's kinda
  20129 non-standard, and doesn't support INDEX and ADSR information. A sample .CUE
  20130 file looks as so:
  20131   ntracks 3
  20132   size      39:33:17
  20133   data1     00:02:00
  20134   track02   31:36:46
  20135   track03   36:03:17
  20136   ;(insert 2 blanks lines here, and insert 1 leading space in next line)
  20137   trk end 39:37:17
  20138 All track numbers and MM:SS:FF values are decimal. The ASCII strings should be
  20139 as shown above, but they are simple ignored by the PSIO firmware (eg. using
  20140 "popcorn666" instead of "size" or "track02" should also work). The first track
  20141 should be marked "data1", but PSIO ignores that string, too (it does always
  20142 treat track 1 as data, and track 2-99 as audio; thus not supporting PSX games
  20143 with multiple data tracks). The "trk end" value should be equal to the "size"
  20144 value plus 4 seconds (purpose is unknown, PSIO does just ignore the "trk end"
  20145 value).
  20146 CU2 creation seems to require CDROM images in "CUE/BIN redump.org format" (with
  20147 separate BIN files for each track), the CUE is then converted to a CU3 file
  20148 (which is used only temporarily), until the whole stuff is finally converted to
  20149 a CU2 file (and with all tracks in a single BIN file). Tools like RD2PSIO (aka
  20150 redump2psio) or PSIO's own SYSCON.ZIP might help on doing some of those steps
  20151 automatically.
  20152 Alongsides, PSIO uses a "multidisc.lst" file... for games that require more
  20153 than one CDROM disc?
  20154 
  20155 CD Image File Format (Xe - Multi System Emulator)
  20156 This is a rather crude file format, used only by the Xe Emulator. The files are
  20157 meant to be generated by a utility called CDR (CD Image Ripper), which, in
  20158 practice merely displays an "Unable to read TOC." error message.
  20159 The overall file structure is, according to "Xe User's Manual":
  20160   header: 200h bytes header (see below)
  20161   data:   990h bytes per sector (2352 Main, 96 Sub), 00:00:00->Lead Out
  20162 The header "definition" from the "Xe User's Manual" is as unclear as this:
  20163   000h   00
  20164   001h   00
  20165   002h   First Track
  20166   003h   Last Track
  20167   004h   Track 1 (ADR << 4) | CTRL              ;\
  20168   005h   Track 1 Start Minutes                  ; Track 1
  20169   006h   Track 1 Start Seconds                  ;
  20170   007h   Track 1 Start Frames                   ;/
  20171   ...     ...                                   ;-Probably Further Tracks (?)
  20172   n+0    Last Track Start Minutes               ;\
  20173   n+1    Last Track Start Seconds               ; Last Track
  20174   n+2    Last Track Start Frames                ;
  20175   n+3    Last Track (ADR << 4) | CTRL           ;/
  20176   n+4    Lead-Out Track Start Minutes           ;\
  20177   n+5    Lead-Out Track Start Seconds           ; Lead-Out
  20178   n+6    Lead-Out Track Start Frames            ;
  20179   n+7    Lead-Out Track (ADR << 4) | CTRL       ;/
  20180   ...    00
  20181   1FFh   00
  20182 Unknown if MM:SS:FF values and/or First+Last Track numbers are BCD or non-BCD.
  20183 Unknown if Last track is separately defined even if there is only ONE track.
  20184 Unknown if Track 2 and up include ADR/Control (and if yes: where?).
  20185 Unknown if ADR/Control is really meant to be <before> MM:SS:FF on Track 1.
  20186 Unknown if ADR/Control is really meant to be <after> MM:SS:FF on Last+Lead-Out.
  20187 Unknown if this format does have a file extension (if yes: which?).
  20188 Unknown if subchannel data is meant to be interleaved or not.
  20189 The format supports only around max 62 tracks (in case each track is 4 bytes).
  20190 There is no support for "special" features like multi-sessions, cd-text.
  20191 
  20192 CDROM Internal Info on PSX CDROM Controller
  20193 -------------------------------------------
  20194 
  20195 PSX software can access the CDROM via Port 1F801800h..1F801803h (as described
  20196 in the previous chapters). The following chapters describe the inner workings
  20197 of the PSX CDROM controller - this information is here for curiosity only -
  20198 normally PSX software cannot gain control of those lower-level stuff (although
  20199 some low level registers can be manipulated via Test commands, but that will
  20200 usually conflict with normal operation).
  20201 
  20202 Motorola MC68HC05 (8bit single-chip CPU)
  20203 The Playstation CDROM drive is controlled by a MC68HC05 8bit CPU with on-chip
  20204 I/O ports and on-chip BIOS ROM. There is no way to reprogram that BIOS, nor to
  20205 tweak it to execute custom code in RAM.
  20206 --> CDROM Internal HC05 Instruction Set
  20207 --> CDROM Internal HC05 On-Chip I/O Ports
  20208 --> CDROM Internal HC05 I/O Port Usage in PSX
  20209 --> CDROM Internal HC05 Motorola Selftest Mode
  20210 The PSX can read HC05 I/O Ports and RAM via Test Commands:
  20211 --> CDROM - Test Commands - Read HC05 SUB-CPU RAM and I/O Ports
  20212 
  20213 Decoder/FIFO (CXD1199BQ or CXD1815Q)
  20214 This chip handles error correction and ADPCM decoding, and acts as some sort of
  20215 FIFO interface between main/sub CPUs and incoming cdrom sector data. On the
  20216 MIPS Main CPU it is controlled via Port 1F801800h..1F801803h.
  20217 --> CDROM Controller I/O Ports
  20218 On the HC05 Sub CPU it is controlled via Port A (data in/out), Port E
  20219 (address/index), and Port D (read/write/select signals); the HC05 doesn't have
  20220 external address/data bus, so one must manually access the CXD1815Q via those
  20221 ports.
  20222 --> CDROM Internal CXD1815Q Sub-CPU Configuration Registers
  20223 --> CDROM Internal CXD1815Q Sub-CPU Sector Status Registers
  20224 --> CDROM Internal CXD1815Q Sub-CPU Address Registers
  20225 --> CDROM Internal CXD1815Q Sub-CPU Misc Registers
  20226 The PSX can read/write the Decoder I/O Ports and SRAM via Test commands:
  20227 --> CDROM - Test Commands - Read/Write Decoder RAM and I/O Ports
  20228 The sector buffer used in the PSX is 32Kx8 SRAM. Old PU-7 boards are using
  20229 CXD1199BQ chips, later boards are using CXD1815Q, and even later boards have
  20230 the stuff intergrated in the SPU. Note: The CXD1199BQ/CXD1815Q are about 99%
  20231 same as described in CXD1199AQ datasheet.
  20232 
  20233 Signal Processor and Servo Amplifier
  20234 Older PSX mainboards are using two separate chips:
  20235 --> CDROM Internal Commands CX(0x..3x) - CXA1782BR Servo Amplifier
  20236 --> CDROM Internal Commands CX(4x..Ex) - CXD2510Q Signal Processor
  20237 Later PSX mainboards have the above intergrated in a single chip, with some
  20238 extended features:
  20239 --> CDROM Internal Commands CX(0x..Ex) - CXD2545Q Servo/Signal Combo
  20240 Later version is CXD1817R (Servo/Signal/Decoder Combo).
  20241 Even later PSX mainboards have it integrated in the Sound Chip: CXD2938Q
  20242 (SPU+CDROM) with some changed bits and New SCEx transfer:
  20243 --> CDROM Internal Commands CX(0x..Ex) - CXD2938Q Servo/Signal/SPU Combo
  20244 Finally, PM-41(2) boards are using a CXD2941R chip (SPU+CDROM+SPU_RAM), unknown
  20245 if/how far the CDROM part of that chip differs from CXD2938Q.
  20246 Some general notes:
  20247 --> CDROM Internal Commands CX(xx) - Notes
  20248 --> CDROM Internal Commands CX(xx) - Summary of Used CX(xx) Commands
  20249 The PSX can manipulate the CX(..) registers via some test commands:
  20250 --> CDROM - Test Commands - Test Drive Mechanics
  20251 Note: Datasheets for CXD2510Q/CXA1782BR/CXD2545Q do exist.
  20252 
  20253 CDROM Pinouts
  20254 --> Pinouts - DRV Pinouts
  20255 --> Pinouts - HC05 Pinouts
  20256 
  20257 CDROM Internal HC05 Instruction Set
  20258 -----------------------------------
  20259 
  20260 ALU, Load/Store, Jump/Call
  20261   Opcode      Clk HINZC Name Syntax
  20262   x6 ...      2-5 --NZ- LDA  MOV  A,<op>      ;A=op
  20263   xE ...      2-5 --NZ- LDX  MOV  X,<op>      ;X=op
  20264   x7 ...      4-6 --NZ- STA  MOV  <op>,A      ;op=A
  20265   xF ...      4-6 --NZ- STX  MOV  <op>,X      ;op=X
  20266   xC ...      2-4 ----- JMP  JMP  <op>        ;PC=op
  20267   xD ...      5-7 ----- JSR  CALL <op>        ;[SP]=PC, PC=op
  20268   xB ...      2-5 H-NZC ADD  ADD  A,<op>      ;A=A+op
  20269   x9 ...      2-5 H-NZC ADC  ADC  A,<op>      ;A=A+op+C
  20270   x0 ...      2-5 --NZC SUB  SUB  A,<op>      ;A=A-op
  20271   x2 ...      2-5 --NZC SBC  SBC  A,<op>      ;A=A-op-C
  20272   x4 ...      2-5 --NZ- AND  AND  A,<op>      ;A=A AND op
  20273   xA ...      2-5 --NZ- ORA  OR   A,<op>      ;A=A OR op
  20274   x8 ...      2-5 --NZ- EOR  XOR  A,<op>      ;A=A XOR op
  20275   x1 ...      2-5 --NZC CMP  CMP  A,<op>      ;A-op
  20276   x3 ...      2-5 --NZC CPX  CMP  X,<op>      ;X-op
  20277   x5 ...      2-5 --NZ- BIT  TEST A,<op>      ;A AND op
  20278   A7,AF,AC = Reserved (no STA/STX/JMP with immediate operand)
  20279 Operands can be...
  20280   Opcode      Clk ALU/LDA/LDX      Clk STA/STX          Clk JMP/CALL
  20281   Ax nn         2 cmd r,nn           - N/A              -/6 call relative (BSR)
  20282   Bx nn         3 cmd r,[nn]         4 mov [nn],r       2/5 cmd nn
  20283   Cx nn mm      4 cmd r,[nnmm]       5 mov [nnmm],r     3/6 cmd nnmm
  20284   Dx nn mm      5 cmd r,[X+nnmm]     6 mov [X+nnmm],r   4/7 cmd X+nnmm
  20285   Ex nn         4 cmd r,[X+nn]       5 mov [X+nn],r     3/6 cmd X+nn
  20286   Fx            3 cmd r,[X]          4 mov [X],r        2/5 cmd X
  20287 
  20288 Read-Modify-Write
  20289   Opcode      Clk HINZC Name Syntax
  20290   xC ...      3-6 --NZ- INC  INC op      ;increment   ;op=op+1
  20291   xA ...      3-6 --NZ- DEC  DEC op      ;decrement   ;op=op-1
  20292   xF ...      3-6 --01- CLR  ??  op,00h  ;clear       ;op=op AND 00h
  20293   x3 ...      3-6 --NZ1 COM  NOT op      ;complement  ;op=op XOR FFh
  20294   x0 ...      3-6 --NZC NEG  NEG op      ;negate      ;op=00h-op
  20295   x9 ...      3-6 --NZC ROL  RCL op      ;rotate left through carry
  20296   x6 ...      3-6 --NZC ROR  RCR op      ;rotate right through carry
  20297   x8 ...      3-6 --NZC LSL  SHL op      ;shift left logical
  20298   x4 ...      3-6 --0ZC LSR  SHR op      ;shift right logical
  20299   x7 ...      3-6 --NZC ASR  SAR op      ;shift right arithmetic
  20300   xD ...      3-5 --NZ- TST  TEST op,FFh ;test for negative or zero (AND FFh?)
  20301   x1,x2,x5,xB,xE = Reserved (except for: 42 = MUL)
  20302 Operands can be...
  20303   Opcode      Clk RMW          Clk CLR                Clk TST
  20304   3x nn         5 cmd [nn]       5 MOV [nn],00h         4 TEST [nn],0FFh
  20305   4x            3 cmd A          3 MOV A,00h,slow       3 TEST A,0FFh,slow
  20306   5x            3 cmd X          3 MOV X,00h,slow       3 TEST X,0FFh
  20307   6x nn         6 cmd [X+nn]     6 MOV [X+nn],00h       5 TEST [X+nn],0FFh
  20308   7x            5 cmd [X]        5 MOV [X],00h          4 TEST [X],0FFh
  20309 CLR includes a dummy-read-cycle, whilst TST does omit the dummy-write cycle.
  20310 The ",slow" RMW opcodes are smaller, but slower than equivalent ALU opcodes.
  20311 
  20312 Bit Manipulation and Bit Test with Relative Jump (to $+3+/-dd)
  20313   Opcode      Clk HINZC Name  Syntax
  20314   00h+i*2 nn dd 5 ----C BRSET JNZ [nn].i,dest  ;C=[nn].i, branch if set
  20315   01h+i*2 nn dd 5 ----C BRCLR JZ  [nn].i,dest  ;C=[nn].i, branch if clear
  20316   10h+i*2 nn    5 ----- BSET  SET [nn].i       ;set [nn].i
  20317   11h+i*2 nn    5 ----- BCLR  RES [nn].i       ;clear [nn].i
  20318 
  20319 Branch (Relative jump to $+2+/-nn)
  20320   Opcode      Clk HINZC Name    Syntax
  20321   20 nn         3 ----- BRA     JR  nn      ;branch always
  20322   21 nn         3 ----- BRN     NUL nn      ;branch never
  20323   22 nn         3 ----- BHI     JA  nn      ;if C=0 and Z=0, higher        ?
  20324   23 nn         3 ----- BLS     JBE nn      ;if C=1 or Z=1, lower or same  ?
  20325   24 nn         3 ----- BCC/BHS JNC/JAE nn  ;if C=0, carry clear, higher.same
  20326   25 nn         3 ----- BCS/BLO JC/JB nn    ;if C=1, carry set, lower
  20327   26 nn         3 ----- BNE     JNZ/JNE nn  ;if Z=0, not equal / not zero
  20328   27 nn         3 ----- BEQ     JZ/JE nn    ;if Z=1, equal / zero
  20329   28 nn         3 ----- BHCC    JNH nn      ;if H=0, half-carry clear
  20330   29 nn         3 ----- BHCS    JH  nn      ;if H=1, half-carry set
  20331   2A nn         3 ----- BPL     JNS nn      ;if S=0, plus / not signed
  20332   2B nn         3 ----- BMI     JS  nn      ;if S=1, minus / signed
  20333   2C nn         3 ----- BMC     JEI nn      ;if I=0, interrupt mask clear
  20334   2D nn         3 ----- BMS     JDI nn      ;if I=1, interrupt mask set
  20335   2E nn         3 ----- BIL     JIL nn      ;if XX=LO, interrupt line low
  20336   2F nn         3 ----- BIH     JIH nn      ;if XX=HI, interrupt line high
  20337   AD nn         6 ----- BSR     CALL relative nn  ;branch to subroutine always
  20338 
  20339 Control/Misc
  20340   Opcode      Clk HINZC Name Syntax
  20341   9D            2 ----- NOP  NOP            ;no operation
  20342   97            2 ----- TAX  MOV X,A        ;transfer A to X
  20343   9F            2 ----- TXA  MOV A,X        ;transfer X to A
  20344   9C            2 ----- RSP  MOV SP,00FFh   ;reset stack pointer (SP=00FFh)
  20345   42           11 0---0 MUL  MUL X,A        ;X:A=X*A (unsigned multiply)
  20346   81            6 ----- RTS  RET            ;return from subroutine
  20347   80            9 xxxxx RTI  RETI           ;return from interrupt
  20348   99            2 ----1 SEC  STC            ;set carry flag
  20349   98            2 ----0 CLC  CLC            ;clear carry flag
  20350   9B            2 -1--- SEI  DI             ;set interrupt mask (disable ints)
  20351   9A            2 -0--- CLI  EI             ;clear interrupt mask (enable ints)
  20352   8E          ..2 -0--- STOP STOP           ;?
  20353   8F          ..2 -0--- WAIT WAIT           ;?
  20354   83           10 -1--- SWI  SWI            ;software interrupt ...? PC=[FFFCh]
  20355   <IRQ>         ? ????? Interrupt           ;?                       PC=[FFFxh]
  20356   <RESET>       ? ????? Reset               ;?                       PC=[FFFEh]
  20357   82,84..8D,90..96,9E = Reserved
  20358 MUL isn't supported in original "M146805 CMOS" family (MUL is used/supported in
  20359 PSX cdrom controller).
  20360 
  20361 Registers
  20362   A   8bit  accumulator
  20363   X   8bit  index register
  20364   SP  6bit  stack pointer (range 00C0h..00FFh)
  20365   PC  16bit program pointer (range 0000h..FFFFh)
  20366   CCR 5bit  condition code register (flags) (111HINZC)
  20367 
  20368 Pushed on IRQ are:
  20369   SP.highest PC.lo
  20370              PC.hi
  20371              X
  20372              A
  20373   SP.lowest  Flags (CCR, 5bit condition code register) (111HINZC)
  20374 
  20375 Addressing Modes
  20376   nn       immediate             ;00h..FFh
  20377   [nn]     direct address        ;[0000h..00FFh]
  20378   [nnmm]   extended address      ;[0000h..FFFFh]
  20379   [X]      indexed, no offset    ;[0000h..00FFh]
  20380   [X+nn]   indexed, 8bit offset  ;[0000h..01FEh]
  20381   [X+nnmm] indexed, 16bit offset ;[0000h..FFFFh]
  20382   [nn].i   bit                   ;[0000h..00FFh].bit0..7
  20383   dd       relative              ;$+2..3+(-80h..+7Fh)
  20384 Notes:
  20385   operand "X+nn" performs an unsigned addition, and can address 0000h..01FEh.
  20386   16bit operands (nnmm) are encoded in BIG-ENDIAN format (same for pushed PC).
  20387 
  20388 Exception Vectors
  20389 Exception vectors are 16bit BIG-ENDIAN values at FFF0h-FFFFh (or at FFE0h-FFEFh
  20390 when running in Motorola Bootstrap mode).
  20391   Vector Prio Usage
  20392   FFF0h  7=lo TBI Vector (Timebase)
  20393   FFF2h  6    SSPI Vector (SPI bus)     (SPI1 and SPI2)
  20394   FFF4h  5    Timer 2 Interrupt Vector  (Timer 2 Input/Compare)
  20395   FFF6h  4    Timer 1 Interrupt Vector  (Timer 1 Input/Compare/Overflow)
  20396   FFF8h  3    KWI Vector (Key Wakeup)   (KWI0..7 pins)
  20397   FFFAh  2    External Interrupt Vector (/IRQ1 and /IRQ2 pins)
  20398   FFFCh  none Software Interrupt Vector (SWI opcode)            ;\regardless of
  20399   FFFEh  1=hi Reset Vector              (/RESET signal and COP) ;/CPU's "I"
  20400 
  20401 Directives/Pseudos (used by a22i assembler; in no$psx utility menu)
  20402   .hc05         select HC05 instruction set (default would be .mips)
  20403   .nocash       select nocash syntax (default would be .native opcode names)
  20404   db ...        define 8bit byte(s), or quoted ascii strings
  20405   dw ...        define 16bit word(s) in BIG ENDIAN (for HC05 exception vectors)
  20406   org nnnn      change origin for following opcodes
  20407   end           end of file
  20408   mov c,[nn].i  alias for "jnz [nn].i,$+3" (dummy jump & set carry=[nn].i)
  20409 
  20410 CDROM Internal HC05 On-Chip I/O Ports
  20411 -------------------------------------
  20412 
  20413 HC05 Port 3Eh - MISC - Miscellaneous Register (R/W)
  20414   0    OPTM  Option Map Select (bank-switching for Port 00h..0Fh)
  20415   1    FOSCE Fast (Main) Oscillator Enable (0=Disable OSC, 1=Normal)
  20416   2-3  SYS   System Clock Select (0=OSC/2, 1=OSC/4, 2=OSC/64, 3=XOSC/2)
  20417   4-5  -     Not used (0)
  20418   6    STUP  XOSC Time Up Flag   (R)
  20419   7    FTUP  OSC Time Up Flag    (R)   (0=Busy, 1=Ready/Good/Stable)
  20420 Note: For PSX, OSC is 4.0000MHz (PU-7/PU-8), 4.2336MHz (PU-18 and up). SysClk
  20421 is usually set to OSC/2, ie. around 2MHz.
  20422 
  20423 HC05 Port OPTM=0:00h - PORTA - Port A Data Register (R/W)
  20424 HC05 Port OPTM=0:01h - PORTB - Port B Data Register (R)
  20425 HC05 Port OPTM=0:02h - PORTC - Port C Data Register (R/W)
  20426 HC05 Port OPTM=0:03h - PORTD - Port D Data Register (R/W)
  20427 HC05 Port OPTM=0:04h - PORTE - Port E Data Register (R/W)
  20428 HC05 Port OPTM=0:05h - PORTF - Port F Data Register (R) (undoc: R/W)
  20429 These are general purpose I/O ports (controlling external pins). Some ports are
  20430 Input-only, and some can be optionally used for special things (like IRQs,
  20431 SPI-bus, or as Timer input/output).
  20432   PA.0-7  PAn   Port A Bit0..7 Input/Output            (0=Low, 1=High) (R/W)
  20433   PB.0-7  PBn   Port B Bit0..7 Input        /KWI0..7   (0=Low, 1=High) (R)
  20434   PC.0    PC0   Port C Bit0    Input/Output /SDI1 (SPI)(0=Low, 1=High) (R/W)
  20435   PC.1    PC1   Port C Bit1    Input/Output /SDO1 (SPI)(0=Low, 1=High) (R/W)
  20436   PC.2    PC2   Port C Bit2    Input/Output /SCK1 (SPI)(0=Low, 1=High) (R/W)
  20437   PC.3    PC3   Port C Bit3    Input/Output /TCAP (T1) (0=Low, 1=High) (R/W)
  20438   PC.4    PC4   Port C Bit4    Input/Output /EVI  (T2) (0=Low, 1=High) (R/W)
  20439   PC.5    PC5   Port C Bit5    Input/Output /EVO  (T2) (0=Low, 1=High) (R/W)
  20440   PC.6    PC6   Port C Bit6    Input/Output /IRQ2      (0=Low, 1=High) (R/W)
  20441   PC.7    PC7   Port C Bit7    Input/Output /IRQ1      (0=Low, 1=High) (R/W)
  20442   PD.0-7  PDn   Port D Bit0..7 Input/Output            (0=Low, 1=High) (R/W)
  20443   PE.0-7  PEn   Port E Bit0..7 Input/Output            (0=Low, 1=High) (R/W)
  20444   PF.0-7  PFn   Port F Bit0..7 Input/Undoc  A/D-input  (0=Low, 1=High) (R)(R/W)
  20445 
  20446 HC05 Port OPTM=1:00h - DDRA - Port A Data Direction Register (R/W)
  20447 HC05 Port OPTM=1:02h - DDRC - Port C Data Direction Register (R/W)
  20448 HC05 Port OPTM=1:03h - DDRD - Port D Data Direction Register (R/W)
  20449 HC05 Port OPTM=1:04h - DDRE - Port E Data Direction Register (R/W)
  20450 HC05 Port OPTM=1:05h - DDRF - Port F Data Direction Register (undoc)
  20451   DDRX.0-7  DDRXn Port X Data Direction Bit0..7 (0=Input, 1=Output) (R/W)
  20452 Officially, there are no DDRB and DDRF registers (Port B and F are always
  20453 Inputs). Although, actually, Motorola's Bootstrap RAM <does> manipulate DDRF.
  20454 
  20455 HC05 Port OPTM=1:08h - RCR1 - Resistor Control Register 1 (R/W)
  20456 HC05 Port OPTM=1:09h - RCR2 - Resistor Control Register 2 (R/W)
  20457   RCR1.0    RAL   Port A.Bit0-3 Pullup Resistors (0=Off, 1=On)
  20458   RCR1.1    RAH   Port A.Bit4-7 Pullup Resistors (0=Off, 1=On)
  20459   RCR1.2    RBL   Port B.Bit0-3 Pullup Resistors (0=Off, 1=On)
  20460   RCR1.3    RBH   Port B.Bit4-7 Pullup Resistors (0=Off, 1=On)
  20461   RCR1.4    RGL   Port G.Bit0-3 Pullup Resistors (0=Off, 1=On) ;\
  20462   RCR1.5    RGH   Port G.Bit4-7 Pullup Resistors (0=Off, 1=On) ; on chips
  20463   RCR1.6    RHL   Port H.Bit0-3 Pullup Resistors (0=Off, 1=On) ; with Port G,H
  20464   RCR1.7    RHH   Port H.Bit4-7 Pullup Resistors (0=Off, 1=On) ;/
  20465   RCR2.0-7  RCn   Port C.Bit0-7 Pullup Resistors (0=Off, 1=On)
  20466 
  20467 HC05 Port OPTM=1:0Ah - WOM1 - Open Drain Output Control Register 1 (R/W)
  20468 HC05 Port OPTM=1:0Bh - WOM2 - Open Drain Output Control Register 2 (R/W)
  20469   WOM1.0   AWOML Port A.Bit0-3 Open Drain Mode when DDR=1 (0=No, 1=Open Drain)
  20470   WOM1.1   AWOMH Port A.Bit4-5 Open Drain Mode when DDR=1 (0=No, 1=Open Drain)
  20471   WOM1.2   GWOML Port G.Bit0-3 Open Drain Mode when DDR=1 (0=No, 1=Open Drain)
  20472   WOM1.3   GWOMH Port G.Bit4-5 Open Drain Mode when DDR=1 (0=No, 1=Open Drain)
  20473   WOM1.4   HWOML Port H.Bit0-3 Open Drain Mode when DDR=1 (0=No, 1=Open Drain)
  20474   WOM1.5   HWOMH Port H.Bit4-5 Open Drain Mode when DDR=1 (0=No, 1=Open Drain)
  20475   WOM1.6-7 -     Not used (0)
  20476   WOM2.0-5 CWOMn Port C.Bit0..5 Open Drain Mode when DDR=1 (0=No, 1=Open Drain)
  20477   WOM2.6-7 -     Not used (always both bits set)
  20478 
  20479 ==== Interrupts =====
  20480 
  20481 HC05 Port OPTM=0:08h - INTCR - Interrupt Control Register (R/W)
  20482   0-1  -     Not used (0)
  20483   2    IRQ2S IRQ2 Select Edge-Sensitive Only (0=LowLevelAndNegEdge, 1=NegEdge)
  20484   3    IRQ1S IRQ1 Select Edge-Sensitive Only (0=LowLevelAndNegEdge, 1=NegEdge)
  20485   4    KWIE  Key Wakeup Interrupt Enable (0=Disable, 1=Enable)
  20486   5    -     Not used (0)
  20487   6    IRQ2E IRQ2 Interrupt Enable (0=Disable, 1=Enable)
  20488   7    IRQ1E IRQ1 Interrupt Enable (0=Disable, 1=Enable)
  20489 
  20490 HC05 Port OPTM=0:09h - INTSR - Interrupt Status Register (R and W)
  20491   0    RKWIF Reset Key Wakeup Interrupt Flag (0=No Change, 1=Reset) (W)
  20492   1    -     Not used (0)
  20493   2    RIRQ2 Reset IRQ2 Interrupt Flag       (0=No Change, 1=Reset) (W)
  20494   3    RIRQ1 Reset IRQ1 Interrupt Flag       (0=No Change, 1=Reset) (W)
  20495   4    KWIF  Key Wakeup Interrupt Flag (PB/KWI)       (0=No, 1=IRQ) (R)
  20496   5    -     Not used (0)
  20497   6    IRQ2F IRQ2 Interrupt Flag (PC6)                (0=No, 1=IRQ) (R)
  20498   7    IRQ1F IRQ1 Interrupt Flag (PC7)                (0=No, 1=IRQ) (R)
  20499 
  20500 HC05 Port OPTM=1:0Eh - KWIE - Key Wakeup Interrupt Enable Register (R/W)
  20501   0-7  KWIEn Port B.Bit0..7 Key Wakeup Interrupt Enable (0=Disable, 1=Enable)
  20502 
  20503 ==== SPI Bus ====
  20504 
  20505 HC05 Port OPTM=0:0Ah - SPCR1 - Serial Peripheral Control Register 1 (R/W)
  20506   0    SPRn  SPI Clock Rate (0=ProcessorClock/2, 1=ProcessorClock/16)
  20507   1-3  -     Not used (0)
  20508   4    MSTRn SPI Master Mode Select      (0=Slave/SCK.In, 1=Master/SCK.Out)
  20509   5    DORDn SPI Data Transmission Order         (0=MSB First, 1=LSB First)
  20510   6    SPEn  SPI Enable (SPI1:PortC, SPI2:PortG) (0=Disable, 1=Enable)
  20511   7    SPIEn SPI Interrupt Enable (... ack HOW?) (0=Disable, 1=Enable)
  20512 
  20513 HC05 Port OPTM=0:0Bh - SPSR1 - Serial Peripheral Status Register 1 (R)
  20514   0-5  -     Not used (0)
  20515   6    DCOLn SPI Data Collision Occurred         (0=No, 1=Collision)
  20516   7    SPIFn SPI Transfer Complete Flag          (0=Busy, 1=Complete) (R)
  20517 Note: SPSR1.7 appears to be reset after reading SPSR1 (probably same for
  20518 SPSR1.6, and maybe also same for whatever SPI IRQ signal).
  20519 
  20520 HC05 Port OPTM=0:0Ch - SPDR1 - Serial Peripheral Data Register 1 (R/W)
  20521   0-7  BITn  Data to be sent / being received
  20522 
  20523 ==== Time Base / Config ====
  20524 
  20525 HC05 Port 10h - TBCR1 - Time Base Control Register 1 (R/W)
  20526   0-1  T2R   Timer2 Prescaler (0=SysClk, 1=SysClk/4, 2=SysClk/32, 3=SysClk/256)
  20527   2-3  T3R   PWM Prescaler    (0=CLK3, 1=CLK3/2, 2=CLK3/8, 3=Timer2compare)
  20528   4-6  -     Not used (0)
  20529   7    TBCLK Time Base Clock (0=XOSC, 1=OSC/128) ;<-- write-able only ONCE
  20530 
  20531 HC05 Port 11h - TBCR2 - Time Base Control Register 2 (R/W, some bits R or W)
  20532   0    COPC  COP Clear 2bit COP timeout divider (0=No Change, 1=Clear) (W)
  20533   1    COPE  COP Enable                          ;<-- write-able only ONCE
  20534   2    -     Not used (0)
  20535   3    RTBIF Reset Time Base Interrupt Flag (0=No Change, 1=Clear TBIF) (W)
  20536   4-5  TBR   Time Base Interrupt Rate (0=TBCLK/128, 1=/4096, 2=/8192, 3=/16384)
  20537   6    TBIE  Time Base Interrupt Enable (0=Disable, 1=Enable)
  20538   7    TBIF  Time Base Interrupt Flag   (0=No, 1=IRQ)        (R)
  20539 
  20540 HC05 Port OPTM=1:0Fh - MOSR - Mask Option Status Register (R)
  20541   0-4  -     Not used (0)
  20542   5    XOSCR XOSC Feedback Resistor (0=None, 1=Implemented)
  20543   6    OSCR  OSC Feedback Resistor  (0=None, 1=Implemented)
  20544   7    RSTR  /RESET Pullup Resistor (0=None, 1=Implemented)
  20545 Reading this register returns A0h (on PSX/PSone with 52pin chips).
  20546 
  20547 ==== Timer 1 ====
  20548 
  20549 HC05 Port 12h - TCR - Timer 1 Control Register (R/W)
  20550   0    OLVL  Output Level on TCMP pin on Compare Match? (0=Low, 1=High)
  20551   1    IEDG  Input Edge on TCAP pin (0=NegativeEdge, 1=PositiveEdge)
  20552   2-4  -     Not used (0)
  20553   5    TOIE  Timer Overflow Interrupt Enable (0=Disable, 1=Enable)
  20554   6    OC1IE Output Compare Interrupt Enable (0=Disable, 1=Enable)
  20555   7    ICIE  Input Capture Interrupt Enable  (0=Disable, 1=Enable)
  20556 
  20557 HC05 Port 13h - TSR - Timer 1 Status Register (R)
  20558   0-4  -     Not used (0)
  20559   5    TOF   Timer Overflow Flag (0=No, 1=Yes) (R) ;clear by Port 19h access
  20560   6    OC1F  Output Compare Flag (0=No, 1=Yes) (R) ;clear by Port 17h access
  20561   7    ICF   Input Capture Flag  (0=No, 1=Yes) (R) ;clear by Port 15h access
  20562 
  20563 HC05 Port 14h - ICH - Timer 1 Input Capture High (undoc)
  20564 HC05 Port 15h - ICL - Timer 1 Input Capture Low (undoc)
  20565   0-15 Capture Value
  20566 
  20567 HC05 Port 16h - OC1H - Timer 1 Output Compare 1 High (undoc)
  20568 HC05 Port 17h - OC1H - Timer 1 Output Compare 1 Low (undoc)
  20569   0-15 Compare Value
  20570 
  20571 HC05 Port 18h - TCNTH - Timer 1 Counter 1 High (undoc)
  20572 HC05 Port 19h - TCNTL - Timer 1 Counter 1 Low (undoc)
  20573   0-15 Counter
  20574 
  20575 HC05 Port 1Ah - ACNTH - Alternate Counter High (undoc)
  20576 HC05 Port 1Bh - ACNTL - Alternate Counter Low (undoc)
  20577   0-15 Alternate Counter (uh, what?)
  20578 
  20579 ==== Timer 2 ====
  20580 
  20581 HC05 Port 1Ch - TCR2 - Timer 2 Control Register (R/W)
  20582   0    OL2   Timer Output 2 Edge (0=Falling, 1=Rising)
  20583   1    OE2   Timer Output 2 Enable (EVO) (0=Disable, 1=Enable)
  20584   2    IL2   Timer Input 2 Edge/Level (0=Low/Falling, 1=High/Rising)
  20585   3    IM2   Timer Input 2 Mode Select for EVI (0=EventMode, 1=GatedByCLK2)
  20586   4    T2CLK Timer 2 Clock Select (0=CLK2 from Prescaler, 1=EXCLK from EVI)
  20587   5    -     Not used (0)
  20588   6    OC2IE Output Compare 2 Interrupt Enable    (0=Disable, 1=Enable)
  20589   7    TI2IE Timer Input 2 Interrupt Enable (EVI) (0=Disable, 1=Enable)
  20590 
  20591 HC05 Port 1Dh - TSR2 - Timer 2 Status Register (R/W)
  20592   0-1  -     Not used (0)
  20593   2    ROC2F Reset Output Compare 2 Interrupt Flag (0=No Change, 1=Clear) (W)
  20594   3    RTI2F Reset Timer Input 2 Interrupt Flag    (0=No Change, 1=Clear) (W)
  20595   4-5  -     Not used (0)
  20596   6    OC2F  Output Compare 2 Interrupt Flag    (0=No, 1=Yes) (R)
  20597   7    TI2F  Timer Input 2 Interrupt Flag (EVI) (0=No, 1=Yes) (R)
  20598 
  20599 HC05 Port 1Eh - OC2 - Timer 2 Output Compare Register (R/W)
  20600   0-7  Compare Value ("Transferred to buffer on certain events?")
  20601 
  20602 HC05 Port 1Fh - TCNT2 - Timer 2 Counter Register (R) (W=Set Counter to 01h)
  20603   0-7  Counter Value, incremented at T2R (set to 01h on Compare Matches)
  20604 
  20605 ==== Reserved ====
  20606 
  20607 HC05 Port 3Fh - Unknown/Unused
  20608 Reading this port via Sony's test command returns 20h (same as openbus), but
  20609 reading it via Motorola's selftest function returns 00h (unlike openbus), so it
  20610 seems to have some unknown/undocumented function; bit5 might indicate selftest
  20611 mode, or it might reflect initialization of whatever other ports.
  20612 
  20613 HC05 Port OPTM=0:06h..07h,0Dh..0Fh - Reserved
  20614 HC05 Port OPTM=1:01h,06h..07h,0Ch..0Dh - Reserved
  20615 HC05 Port 20h..3Dh - Reserved
  20616 These ports are unused/reserved. Trying to read them on a PSone does return 20h
  20617 (possibly the prefetched next opcode value from the RAM test command). Other
  20618 HC05 variants contain some extra features in these ports:
  20619 --> CDROM Internal HC05 On-Chip I/O Ports - Extras
  20620 The PSX CDROM BIOS doesn't use any of these ports - execpt, it is writing
  20621 [20h]=2Eh (possibly to disable unused LCD hardware; which might be actually
  20622 present in the huge 80pin HC05 chips on old PU-7 mainboards).
  20623 
  20624 HC05 Openbus
  20625 Openbus values can be read from invalid memory locations, on PSX with 52pin
  20626 chips:
  20627   I/O bank 0:    0:06h..07h, 0:0Dh..0Fh
  20628   I/O bank 1:    1:01h, 1:06h..07h, 1:0Ch..0Dh, and upper 4bit of 1:05h
  20629   Unbanked I/O:  20h..3Dh
  20630   Unused Memory: 0240h..0FFFh, 5000h..FDFFh
  20631 The returned openbus value depends on the opcode's memory operand:
  20632   [nn],[mmnn],[nn+x],[mmnn+x] --> returns LAST byte of current opcode (=nn)
  20633   [x]                         --> returns FIRST byte of following opcode
  20634 
  20635 CDROM Internal HC05 On-Chip I/O Ports - Extras
  20636 ----------------------------------------------
  20637 
  20638 HC05 Port OPTM=0:0Dh - SPCR2 - Serial Peripheral Control Register 2 (R/W)
  20639 HC05 Port OPTM=0:0Eh - SPSR2 - Serial Peripheral Status Register 2 (R)
  20640 HC05 Port OPTM=0:0Fh - SPDR2 - Serial Peripheral Data Register 2 (R/W)
  20641 This is a second SPI channel, works same as first SPI channel, but using the
  20642 lower 3bits of Port G (instead of Port C) for the SPI signals.
  20643 
  20644 HC05 Port OPTM=0:06h - PORTG - Port G Data Register (R/W)
  20645 HC05 Port OPTM=0:07h - PORTH - Port H Data Register (R/W)
  20646 HC05 Port 3Ch - PORTJ - Port J Data Register (R/W)
  20647   PG.0    PG0   Port G Bit0    Input/Output /SDI2      (0=Low, 1=High) (R/W)
  20648   PG.1    PG1   Port G Bit1    Input/Output /SDO2      (0=Low, 1=High) (R/W)
  20649   PG.2    PG2   Port G Bit2    Input/Output /SCK2      (0=Low, 1=High) (R/W)
  20650   PG.3    PG3   Port G Bit3    Input/Output /TCMP      (0=Low, 1=High) (R/W)
  20651   PG.4    PG4   Port G Bit4    Input/Output /PWM0      (0=Low, 1=High) (R/W)
  20652   PG.5    PG5   Port G Bit5    Input/Output /PWM1      (0=Low, 1=High) (R/W)
  20653   PG.6    PG6   Port G Bit6    Input/Output /PWM2      (0=Low, 1=High) (R/W)
  20654   PG.7    PG7   Port G Bit7    Input/Output /PWM3      (0=Low, 1=High) (R/W)
  20655   PH.0-7  PHn   Port H Bit0..7 Input/Output            (0=Low, 1=High) (R/W)
  20656   PJ.0-3  PJn   Port J Bit0..3 Output                  (0=Low, 1=High) (R/W)
  20657   PJ.4-7  -     Not used (0)
  20658 
  20659 HC05 Port OPTM=1:06h - DDRG - Port G Data Direction Register (R/W)
  20660 HC05 Port OPTM=1:07h - DDRH - Port H Data Direction Register (R/W)
  20661   0-7  DDRXn Port X Data Direction Bit0..7 (0=Input, 1=Output) (R/W)
  20662 
  20663 HC05 Port 20h - LCDCR - LCD Control Register (R/W)
  20664   0    -     Not used (0)
  20665   1    PDH   Select Port D (H) (0=FP35-FP38 pins, 1=PD7-PD4 pins)
  20666   2    PEL   Select Port E (L) (0=FP31-FP34 pins, 1=PE3-PE0 pins)
  20667   3    PEH   Select Port E (H) (0=FP27-FP30 pins, 1=PE7-PE4 pins)
  20668   4    -     Not used (0)
  20669   5-6  DUTY  LCD Duty Select (...)
  20670   7    LCDE  LCD Output Enable BP and FP pins (0=Disable, 1=Enable)
  20671 
  20672 HC05 Port 21h..34h - LCDDR1..20 - LCD Data Register 1..20 (R/W)
  20673   0-3  First Data Unit  ;\Fourty 4bit LCD values (in the twenty registers)
  20674   4-7  Second Data Unit ;/(some duties use only the LSBs of that 4bit values)
  20675 
  20676 HC05 Port 34h - PWMCR - PWM Pulse Width Modulation Control Register (R/W)
  20677   0-3  CH0-3 PWM Channel 0..3 on Port G.Bit4-7 Enable (0=Disable, 1=Enable)
  20678   4-7  -     Not used (0)
  20679 
  20680 HC05 Port 35h - PWMCNT - PWM Counter Register (R) (W=Set Counter to FFh)
  20681   0-7  PWM Counter, incremented at PHI2 (range 01h..FFh)
  20682 
  20683 HC05 Port 36h - PWMDR0 - PWM Duty Register 0 (R/W)
  20684 HC05 Port 37h - PWMDR1 - PWM Duty Register 1 (R/W)
  20685 HC05 Port 38h - PWMDR2 - PWM Duty Register 2 (R/W)
  20686 HC05 Port 39h - PWMDR3 - PWM Duty Register 3 (R/W)
  20687   0-7  Duty (N cycles High, 255-N cycles Low)
  20688 
  20689 HC05 Port 3Ah - ADR - A/D Data Register (R)
  20690   0-3  A/D Conversion result (probably unsigned, 00h=Lowest, FFh=Max voltage?)
  20691 
  20692 HC05 Port 3Bh - ADSCR - A/D Status and Control Register (R/W)
  20693   0-3  CH0-3 A/D Channel (0..7=PortF.Bit0-7, 8..0Fh=Reserved/Vref/FactorTest)
  20694   4    -     Not used (0)
  20695   5    ADON  A/D Charge Pump enable (0=Disable, 1=Enable)
  20696   6    ADRC  A/D RC Oscillator On (0=Normal/Use CPU Clock, 1=Use RC Clock)
  20697   7    COCO  A/D Conversion Complete (0=Busy, 1=Complete) (R)
  20698 
  20699 HC05 Port 3Dh - PCR - Program Control Register (R/W) (for EPROM version)
  20700   0    PGM   EPROM Program Command (0=Normal, 1=Apply Programming Power)
  20701   1    ELAT  EPROM Latch Control (0=Normal/Read, 1=Latch/Write)
  20702   2-7  RES   Reserved for Factory Testing (always 0 in user mode)
  20703 
  20704 CDROM Internal HC05 I/O Port Usage in PSX
  20705 -----------------------------------------
  20706 
  20707 Port A - Data (indexed via Port E)
  20708   porta.0-7 i/o  CXD1815Q.Data (indexed via Port E)
  20709   porta.0   in   debug.dta.serial.in  ;\normally unused (exists in early bios)
  20710   porta.1   out  debug.dta.serial.out ; (prototype/debug_status stuff)
  20711   porta.2   out  debug.clk.serial.out ;/(with portc.5 = debug.select)
  20712 
  20713 Port B - Inputs
  20714   portb.0   in   F-BIAS  ;unused
  20715   portb.1   in   SCEx input (serial 250 baud, received via 1000Hz timer2 irq)
  20716   portb.2   in   LMTSW  aka /POS0        ;\pos0 and door switches
  20717   portb.3   in   DOOR   aka SHELL_OPEN   ;/
  20718   portb.4   in   TEST2
  20719   portb.5   in   TEST1 (CL316) enter test mode (instead of mainloop)
  20720   portb.6   in   COUT   ;<-- unused, extra pin, not "SENSE=COUT"
  20721   portb.7   in   CXD2510Q.SENSE ;-from CXD2510Q (and forwarded from CXA1782BR)
  20722 
  20723 Port C - Inputs/Outputs
  20724   portc.0   in   CXD2510Q.SUBQ  ;\
  20725   portc.1   in?  NC (SPI.OUT)   ; used via SPDR1 to receive SPI bus SUBQ data
  20726   portc.2   out  CXD2510Q.SQCK  ;/
  20727   portc.3   out  SPEED
  20728   portc.4   out    ="SPEED XOR 1"  ... AL/TE ... or CG ... or MIRR ?
  20729   portc.5   out  ROMSEL: debug.select   (or "SCLK" on later boards???)
  20730   portc.6   in   CXD1815Q.XINT/IRQ2 ;unused (instead INTSTS bits are polled)
  20731   portc.7   in   CXD2510Q.SCOR/IRQ1 ;used via polling INTSR.7 (not as irq)
  20732 
  20733 Port D - Outputs
  20734   portd.0   out  NC             ;-unused (always 1)
  20735   portd.1   out  CXD2510Q.DATA  ;\serial bus for CXD2510Q
  20736   portd.2   out  CXD2510Q.XLAT  ; (and also forwarded to CXA1782BR)
  20737   portd.3   out  CXD2510Q.CLOK  ;/
  20738   portd.4   out  CXD1815Q.DECCS ;\
  20739   portd.5   out  CXD1815Q.DECWR ; control for data/index on Port A/E
  20740   portd.6   out  CXD1815Q.DECRD ;/
  20741   portd.7   out  LDON  ... IC723.Pin11 ... maybe "laser on" ?
  20742 
  20743 Port E - Index (for data on Port A)
  20744   porte.0-4 out  CXD1815Q.Index (for data on Port A)
  20745   porte.5   out  NC, not used
  20746   porte.6   out  NC, see "idx_4xh" maybe test signal ???
  20747   porte.7   out? NC, TEST? configured as OUTPUT... but used as INPUT?
  20748 
  20749 Port F - Motorola Bootstrap Serial I/O (not used in cdrom bios)
  20750   portf.0   out  NC, TX         ;\
  20751   portf.1   in   NC, RX         ; not used by sony's cdrom bios
  20752   portf.2   out  NC, RTS        ; (but used by motorola's bootstrap rom)
  20753   portf.3   out  NC, DTR        ;/
  20754   portf.0   in   Serial Data In  (from daughterboard)  ;\
  20755   portf.1   out  Serial Data Out   (to daughterboard)  ; usage in SCPH-5903
  20756   portf.2   out  Serial Clock Out  (to daughterboard)  ; (PSX with Video CD)
  20757   portf.3   out  Audio/Video Select (0=Normal, 1=VCD)  ;/
  20758   portf.4-7 -    NC, not used (probably pins don't even exist)
  20759 
  20760 Other HC05 I/O Ports
  20761   SPI 1   - used for receiving SUBQ (via Port C)
  20762   IRQ 1   - used for latching/polling SUBQ's "SCOR" (not used as interrupt)
  20763   IRQ 2   - connects to CXD1815Q.XINT, but isn't actually used at all
  20764   Timer 1 - unused
  20765   Timer 2 - generates 1000Hz interrupts (for 250 baud "SCEx" string transfers)
  20766   DDRx    - data directions for Port A-F (as listed above)
  20767 Note: The PSX has the HC05 clocked via 4.00MHz oscillator (older boards), or
  20768 via 4.3MHz signal from SPU (newer boards); internally, the HC05 is clocked at
  20769 half of those frequencies (ie. around 2 MHz).
  20770 
  20771 CDROM Internal HC05 Motorola Selftest Mode
  20772 ------------------------------------------
  20773 
  20774 52-pin HC05 chips (newer psx cdrom controllers)
  20775 52-pin chips are used on LATE-PU-8 boards, and on later boards ranging from
  20776 PU-18 up to PM-41(2).
  20777 --> CDROM Internal HC05 Motorola Selftest Mode (52pin chips)
  20778 
  20779 80-pin HC05 chips (older psx cdrom controllers)
  20780 80-pin chips are used PU-7, EARLY-PU-8, and PU-9 boards.
  20781 --> CDROM Internal HC05 Motorola Selftest Mode (80pin chips)
  20782 
  20783 32-pin HC05 chips (joypad/mouse)
  20784 Sony's Digital Joypad and Mouse are using 32pin chips (with TQFP-32 package),
  20785 which are probably containing Motorola HC05 CPUs, too. Unknown if/how those
  20786 chips can be switched into bootstrap/dumping modes.
  20787 
  20788 Pinouts
  20789 --> Pinouts - HC05 Pinouts
  20790 
  20791 CDROM Internal HC05 Motorola Selftest Mode (52pin chips)
  20792 --------------------------------------------------------
  20793 
  20794 Motorola Bootstrap ROM
  20795 The Motorola MC68HC05 chips are including a small bootstrap ROM which gets
  20796 activated upon /RESET when having two pins strapped to following levels:
  20797   Pin30 PortC.6 (/IRQ2) (/XINT) ----> wire to 3.5V (VCC)
  20798   Pin31 PortC.7 (/IRQ1) (SCOR)  ----> wire to 7V (2xVCC)
  20799 Moreover, two pins are needed on /RESET for selecting a specific test mode:
  20800   Pin16 PortB.0 ----> ModeSelectBit0 (0=GND, 1=3.5V)
  20801   Pin17 PortB.1 ----> ModeSelectBit1 (0=GND, 1=3.5V)
  20802 The selectable four modes are:
  20803   Mode0: Jump to RAM Address 0040h (useless when RAM is empty)
  20804   Mode1: Semifunctional Selftest (useless)
  20805   Mode2: Upload 200h bytes to RAM & jump to 0040h (allows fast/custom dumping)
  20806   Mode3: Download ROM as ASCII hexdump (nice, but very slow)
  20807 The upload/download functions are using following additional pins:
  20808   Pin50 PortF.0 ----> TX output (11bytes: 0Dh,0Ah," AAAA DD ")
  20809   Pin51 PortF.1 <---- RX input  (1byte: "!" to request next 11 bytes)
  20810   Pin52 PortF.2 ----> RTS output or so (not needed)
  20811   Pin1  PortF.3 ----> DTR output or so (not needed)
  20812   Ground ------------ GND for RX/TX
  20813 RX/TX are RS232-like serial signals (but using other voltages, 0=0V and
  20814 1=3.5V). Transfer format is 8-N-1, ie. one startbit(0), 8 databits LSB first,
  20815 no parity, one stopbit(1). Baudrate is OSC/2/208 (ie. 9616 bps for 4.000MHz, or
  20816 10176 bps for 4.2336MHz clock derived from CXD2545Q/CXD2938Q).
  20817 Note: Above pins may vary on some chips (namely on chips that don't have
  20818 PortF). The pins for entering bootstrap mode (PortC in this case) should be
  20819 described in datasheets; but transfer protocol and mode selection (PortB) and
  20820 transmission (PortF) aren't officially documented.
  20821 
  20822 Mode2: Upload 200h bytes to RAM & jump to 0040h
  20823 This mode is very simple and powerful: After /RESET, you send 200h bytes to the
  20824 RX input (without any response on TX output), the bytes are stored at
  20825 0040h..023Fh in RAM, and the chip jumps to 0040h after transferring the last
  20826 byte. The uploaded program can contain a custum highspeed dumping function, or
  20827 perform hardware tests, etc. A custom dumping function for PSX/PSone can be
  20828 found at:
  20829   http://www.psxdev.net/forum/viewtopic.php?f=70&t=557
  20830 After uploading the 200h-byte dumping function it will respond by send 4540h
  20831 bytes (containing some ASCII string, the 16.5Kbyte ROM image, plus dumps for
  20832 RAM and (banked) I/O port region, plus openbus tests for unused memory and I/O
  20833 regions.
  20834 
  20835 Wiring for Mode2 on PSX/PSone consoles with 52-pin HC05 chips
  20836                             .------------ pin31, PC7, SCOR, cut the connection
  20837                    39       |   27               to Signal Processor,
  20838                  .-----------------.             then wire Pin31 to 7.5V
  20839               40 |                 | 26
  20840                  |  C nnnn         |
  20841                  |  SC4309nnPB     |
  20842                  |  G63C 185       |
  20843   pin50, TX <--- |                 | ---- pin17, PB1, SCEX, wire to 3.5V,
  20844   pin51, RX ---> |                 |                  for Mode2 Selection
  20845               52 | O               | 14
  20846                  '-----------------'
  20847                    1            13
  20848 Good places to pick 3.5V and 7.5V from nice solder pads are:
  20849   CN602.Pin1  = 7.5V     ;\on PSX boards (with either 5pin or
  20850   CN602.Pin3  = 3.5V     ;/               7pin CN602 connectors)
  20851   IC601.Pin1  = 7.5V     ;-on PSone boards (3pin 78M05 voltage regulator)
  20852   IC102.Pin32 = 3.5V     ;-on PSone boards (32pin Main BIOS ROM chip)
  20853 The SCOR trace on Pin31, connects to Signal Processor...
  20854   CXD2510Q.Pin63  (eg. on PU-8 boards)   ;\
  20855   CXD2545Q.Pin74  (eg. on PU-18 boards)  ; either one of these, depending
  20856   CXD1817R.Pin49  (eg. on PU-20 boards)  ; on which chipset you have
  20857   CXD2938Q.Pin77  (eg. on PM-41 boards)  ;
  20858   CXD2941R.Pin85  (eg. PM-41(2) boards)  ;/
  20859 cut that trace (preferably on the PCB between two vias or test points, so you
  20860 can later repair it easily) (better don't try to lift Pin31, it breaks off
  20861 easily)
  20862 Note: Mode2 also requires Pin16=Low, and Pin30=High (but PSX/PSone boards
  20863 should have those pins at that voltages anyways).
  20864 
  20865 Mode3: Download ROM as ASCII hexdump
  20866 This mode is very slow and not too powerful. But it may useful if you can't get
  20867 Mode2 working for whatever reason. Wiring for Mode3 is same as above, plus
  20868 PortB.0=3.5V. In this mode, the chip will send one 0Dh,0Ah," AAAA DD " string
  20869 immediately after /RESET (with 16bit address "AAAA" (initially 1000h), and 8bit
  20870 data "DD"). Thereafter the chip will wait for incoming commands:
  20871   4-digit ASCII HEX address --> change address, and return 0Dh,0Ah," AAAA DD "
  20872   chr(00h) --> increment address, and return 0Dh,0Ah," AAAA DD "
  20873   chr(07h) --> jump to current address (not so useful)
  20874   other characters --> same as chr(00h)
  20875   All digits/characters sent to RX input will produce an echo on TX output.
  20876 Basic setup would be wiring RX to GND (the chip will treat that as infinite
  20877 stream of start bits with chr(00h), so it will respond by sending data from
  20878 increasing addresses automatically; the increment wraps from 4FFFh to FE00h
  20879 (skipping the gap between Main ROM and Bootstrap ROM), and also wraps from
  20880 FFFFh to 0000h; transfer is ultraslow: 13 characters needed per dumped byte:
  20881 chr(00h) to chip, chr(00h) echo from chip, and 0Dh,0Ah," AAAA DD " from chip.
  20882 
  20883 CDROM Internal HC05 Motorola Selftest Mode (80pin chips)
  20884 --------------------------------------------------------
  20885 
  20886 80pin Sony 4246xx chips
  20887 And for anyone else planning to try this, these are the connections:
  20888   Pin PortC
  20889   46  PC7/IRQ1 (SCOR) disconnect from PCB, then wire the pin to Vtst (7.6V)
  20890   45  PC6/IRQ2 (/XINT) wire to Vdd (3.5V) (you have to solder to the pin)
  20891 In bootstrap mode, Port A is used as follows:
  20892   Pin PortA DDRA Usage
  20893   23  PA0   in   RXD
  20894   24  PA1   out  TXD
  20895   25  PA2   in   -
  20896   26  PA3   in   Testmode.bit0 (GND=0, 3.5V=1)
  20897   27  PA4   in   Testmode.bit1 (GND=0, 3.5V=1)
  20898   28  PA5   in   Testmode.bit2 (GND=0, 3.5V=1)
  20899   29  PA6   out  RTS (don't care)
  20900   30  PA7   out  -
  20901 The selectable testmodes are:
  20902   PA5 PA4 PA3  Effect
  20903   0   x   x    Jump to 0040h      ;\
  20904   1   0   0    Test (complex)     ; not so useful
  20905   1   0   1    Test (simple loop) ;/
  20906   1   1   0    ROM Dump 4200h bytes (plain binary, non-ASCII)
  20907   1   1   1    RAM Upload 100h bytes to 0040h..013Fh, then jump to 0040h
  20908 RX/TX are plain binary (non-ASCII), baudrate is 9600 (when using 4.000MHz
  20909 oscillator), transfer format is 8,N,2 (aka 8,N,1 with an extra pause bit).
  20910 
  20911 Wiring for Upload/Download on PSX consoles with 80-pin HC05 chips
  20912                   .------------ pin46, PC7/IRQ1, SCOR, cut & wire to 7.5V
  20913                   |.----------- pin45, PC6/IRQ2, wire to 3.5V
  20914          60       ||  41
  20915        .-----------------.
  20916     61 |               o | 40
  20917        |  Sony Computer  |           ,----- pin28, PA5, wire to 3.5V
  20918        |  Entertainment  | _________/  ,--- pin27, PA4, wire to 3.5V
  20919        |  Inc. (C) E35D  | ==========='---- pin26, PA3, mode select
  20920        |     4246xx 185  | ----> pin24, PA1, TXD (for ROM dump)
  20921        |                 | <---- pin23, PA0, RXD (for RAM upload)
  20922     80 | O               | 21
  20923        '-----------------'
  20924          1            20
  20925 Good places to pick 3.5V and 7.5V from nice solder pads are:
  20926   CN602.Pin1  = 7.5V     ;\on PSX boards (with 7pin CN602 connectors)
  20927   CN602.Pin3  = 3.5V     ;/
  20928 Credits to TriMesh for finding the 80pin chip's bootstrap signals.
  20929 
  20930 Other 80pin chips
  20931 DTL-H100x uses 80pin chip with onchip PROM (chip text "(M) MC68HC705L15",
  20932 instead of "Sony [...] 4246xx"), wiring for serial dumping on that is unknown
  20933 (the bootstrap ROM may be a little different because it should contain PROM
  20934 burning functions). PU-9 boards boards seem to use a similar PROM (with some
  20935 sticker on it).
  20936 DTL-H2000 uses 80pin CXP82300 chip with socketed piggyback 32pin EPROM - that
  20937 chip is a Sony SPC700 CPU, not a Motorola HC05 CPU. Accordingly there's no
  20938 Motorola Bootstrap mode in it, but of course one could simply dump the EPROM
  20939 with standard eprom utilities, but nobody did do so yet).
  20940 
  20941 CDROM Internal CXD1815Q Sub-CPU Configuration Registers
  20942 -------------------------------------------------------
  20943 
  20944 00h - DRVIF - Drive Interface (W)
  20945   0-1 "L"     Reserved (should be 0)
  20946   2   LSB 1st CD DSP DATA order               (0=MSB first, 1=LSB first)
  20947   3-4 BCK MD  CD DSP Number of BCLKs per WCLK (0=16, 1=24, 2=32, 3=Reserved)
  20948   5   BCK RED Strobe DATA on BLCK Edge        (0=Falling Edge, 1=Rising Edge)
  20949   6   LCH LOW Channel on LRCK=Low             (0=Right, 1=Left)
  20950   7   C2PL1st      ... C2PO lower byte 1st
  20951 
  20952 01h - CONFIG 1 - Configuration 1 (W)
  20953   0   HCLKDIS  HCLK Pin Output (0=8.4672MHz, 1=Disable; Fixed Low)
  20954   1   CLKDIS   CLK Pin Output (0=16.9344MHz, 1=Disable; Fixed Low)
  20955   2   9BITRAM  SRAM Databus width (0=8bit/normal, 1=9bit)
  20956   3-4 RAM SZ   SRMA Address bus (0=32K, 1=64K, 2=128K, 3=Reserved)
  20957   5   PRTYCTL      ... Priority Control
  20958   6   XSLOW    Number of clock cycles per DMA cycle (0=12, 1=4) (for SRAM)
  20959   7   "L"      Reserved (should be 0)
  20960 
  20961 02h - CONFIG 2 - Configuration 2 (W)
  20962   0   "L"      Reserved (should be 0)
  20963   1   DACODIS        .... DAC Out Disable
  20964   2   DAMIXEN  Digital Audio Mixer Enable (0=Attentuator/Mixer for CD-DA, 1=No)
  20965   3   SMBF2    Number of Sound Map Buffer Surfaces (0=Three, 1=Two)
  20966   4   SPMCTL   Sound Parameter Majority Control (0=?)  ;\for ADPCM params
  20967   5   SPECTL   Sound Parameter Error Control    (0=?)  ;/
  20968   6-7 "L"      Reserved (should be 0)
  20969 
  20970 03h - DECCTL - Decoder Control (W)
  20971   0-2 DECMD    Decoder Mode (0-7)
  20972                  0 or 1  Decoder Disable            ;-disable sector reading
  20973                  2 or 3  Monitor-only Mode          ;\no error correction
  20974                  4       Write-only Mode            ;/
  20975                  5       Real-time Correction Mode  ;\with error correction
  20976                  6       Repeat Correction Mode     ;/
  20977                  7       CD-DA Mode                 ;-audio
  20978   3   AUTODIST Auto Distinction (0=Use MODESEL/FORMSEL bits, 1=Use Sector Hdr)
  20979                (Error Correction is done according to above MODE/FORM values)
  20980   4   FORMSEL  Form Select (0=FORM1, 1=FORM2) (must be 0 for MODE1)
  20981   5   MODESEL  Mode Select (0=MODE1, 1=MODE2)
  20982   6   ECCSTR   ECC Strategy (0=Normal, 1=Use Error Flags; requires 9bit SRAM)
  20983   7   ENDLADR  Enable Drive Last Address    ...
  20984 
  20985 07h - CHPCTL - Chip Control (W)
  20986   0   "L"      Reserved (should be 0)
  20987   1   DBLSPD   Double Speed Mode (0=Normal, 1=Double) (init CD DSP first)
  20988   2   RPSTART  Repeat Correction Start (0=No, 1=Start) (automatically cleared)
  20989   3   SWOPEN   Sync Window Open (0=SyncControlledByIC, 1=OpenDetectionWindow)
  20990   4   CD-DA    CD-DA Play     (0=No, 1=Playback CD-DA as audio)
  20991   5   CDDAMUTE CD-DA Mute     (0=Normal, 1=Mute CD-DA Audio)
  20992   6   RTMUTE   Real-time Mute (0=Normal, 1=Mute CDROM ADPCM)
  20993   7   SMMUTE   Sound Map Mute (0=Normal, 1=Mute Sound Map ADPCM)
  20994 
  20995 CDROM Internal CXD1815Q Sub-CPU Sector Status Registers
  20996 -------------------------------------------------------
  20997 
  20998 00h - ECCSTS - ECC Status (R)
  20999   0 CFORM   FORM assumed by Error Correction (0=FORM1, 1=FORM2)
  21000   1 CMODE   MODE assumed by Error Correction (0=MODE1, 1=MODE2)
  21001   2 ECCOK   ECC Okay (0=Bad, 1=Okay)
  21002   3 EDCOK   EDC Okay (0=Bad, 1=Okay)
  21003   4 CORDONE Correction Done (0=None, 1=Error occurred and was corrected)
  21004   5 CORINH  Correction Inhibit (0=Okay,1=AUTODIST couldn't determine MODE/FORM)
  21005   6 ERINBLK Erasure in Block (0=Okay, 1=At least 1 byte is wrong & uncorrected)
  21006   7 EDCALL0 EDC all-zero  (0=No/EDC Exists, 1=Yes/All four EDC bytes are 00h)
  21007 
  21008 01h - DECSTS - Decoder Status (R)
  21009   0   NOSYNC   No Sync       (0=Okay, 1=Sector Sync Mark Missing)
  21010   1   SHRTSCT  Short Sector  (0=Okay, 1=Sector Sync Mark within Sector Data)
  21011   2-4 -        Reserved (undefined)
  21012   5   RTADPBSY Real-time ADPCM Busy (0=No, 1=Busy/playback)
  21013   6-7 -        Reserved (undefined)
  21014 
  21015 02h - HDRFLG - Header/Subheader Error Flags for HDR/SHDR registers (R)
  21016   0 CI      Error in 4th Subheader byte (Coding Info) (0=Okay, 1=Error)
  21017   1 SUBMODE Error in 3rd Subheader byte (Submode)     (0=Okay, 1=Error)
  21018   2 CHANNEL Error in 2nd Subheader byte (Channel)     (0=Okay, 1=Error)
  21019   3 FILE    Error in 1st Subheader byte (File)        (0=Okay, 1=Error)
  21020   4 MODE    Error in 4th Header byte (MODE)           (0=Okay, 1=Error)
  21021   5 BLOCK   Error in 3rd Header byte (FF)             (0=Okay, 1=Error)
  21022   6 SEC     Error in 2nd Header byte (SS)             (0=Okay, 1=Error)
  21023   7 MIN     Error in 1st Header byte (MM)             (0=Okay, 1=Error)
  21024 Error flags for current sector are probably stored straight in this register
  21025 (ie. these flags are probably available even without using 9bit SRAM).
  21026 Or maybe not... if the chip supports receiving newer sectors during
  21027 time-consuming error corrections... then those newer would need to be stored in
  21028 SRAM, and would thus require 9bit SRAM for the error flags?
  21029 
  21030 03h - HDR - Header Bytes (R)
  21031   1st read: 1st Header byte (MM)
  21032   2nd read: 2nd Header byte (SS)
  21033   3rd read: 3rd Header byte (FF)
  21034   4th read: 4th Header byte (MODE)
  21035 
  21036 04h - SHDR - Subheader Bytes (R)
  21037   1st read: 1st Subheader byte (File)
  21038   2nd read: 2nd Subheader byte (Channel)
  21039   3rd read: 3rd Subheader byte (Submode) (SM)
  21040   4th read: 4th Subheader byte (Coding Info) (CI)
  21041 The contents of the HDRFLG, HDR, SHDR registers indicate:
  21042       (1) The corrected value in the real-time correction or
  21043           repeat correction mode
  21044       (2) Value of the raw data from the drive in the monitor-only
  21045           or write-only mode
  21046     The CMOME? and CMODE bits (bits 1, 0) of ECCSTS indicate the FORM and MODE
  21047     of the sector the decoder has discriminated by the raw data from the drive.
  21048     Due to erroneous correction, the values of these bits may be at variance
  21049     with those of the HDR register MODE byte and SHDR register submode byte
  21050     bit5.
  21051 
  21052 Unknown when 1st..4th read indices are reset for HDR and SHDR (maybe on access
  21053 to certain I/O ports, or maybe anytime when receiving a new sector), also
  21054 unknown what happens on 5th read and up.
  21055 
  21056 CDROM Internal CXD1815Q Sub-CPU Address Registers
  21057 -------------------------------------------------
  21058 
  21059 Drive Address -- used for storing incoming CDROM sectors in Buffer RAM
  21060 Host Address -- used for transferring Buffer RAM to (or from) Main CPU
  21061 ADPCM Address -- used for Real-time ADPCM audio output from Buffer RAM
  21062 
  21063 05h - CMADR - Drive Current Minute Address (R)
  21064   0-6   CMADR    Address bit10-16 (in 1Kbyte steps)
  21065   7     -        Reserved (undefined)
  21066 Indicates the start address of the most recently decoded sector (called "Minute
  21067 Address" because it points to the MM byte of the MM:SS:FF:MODE sector header).
  21068 Normally, CMADR should be forwarded to Host:
  21069   HADR = (CMADR AND 7Fh)*400h+offset
  21070   HXFR = length OR 4000h
  21071 Whereas, offset would be usually 00h, 04h, or 0Ch (to start reading from the
  21072 begin of the sector, or to skip 4-byte MODE1 header, or 12-byte MODE2 header).
  21073 And length would be usually 800h (normal data sector), or 924h (entire sector,
  21074 excluding the leading 12 sync-bytes). Length bit14 is undocumented/reserved,
  21075 but the PSX CDROM BIOS does set that bit for whatever reason.
  21076 Alternately, the sector can be forwarded to the Real-time ADPCM decoder:
  21077   ADPMNT = (CMADR AND 7Fh) OR 80h
  21078 
  21079 19h - ADPMNT - ADPCM "MNT" Address (W)
  21080   0-6   ADPxxx  ADPCM source Address bit10-16 (in 1Kbyte-steps)
  21081   7     RTADPEN Real-time ADPCM Enable (0=Disable, 1=Enable Real-time ADPCM)
  21082 
  21083 04h - DLADR-L, Drive Last Address, bit0-7 (W)
  21084 05h - DLADR-M, Drive Last Address, bit8-15 (W)
  21085 06h - DLADR-H, Drive Last Address, bit16 (W)
  21086   0-16  DLADR  Addr. bit0-16     ...
  21087   17-23 "L"    Reserved (should be 0)
  21088 
  21089 10h - DADRC-L - Drive Address Counter, bit0-7 (W)
  21090 11h - DADRC-M - Drive Address Counter, bit8-15 (W)
  21091 12h - DADRC-H - Drive Address Counter, bit16 (W)
  21092   0-16  DADRC    Incrementing Drive-to-Buffer Write Address, bit0-16
  21093   17-23 "L"      Reserved (should be 0)
  21094 
  21095 0Eh - DADRC-L - Drive Address Counter, Bit0-7 (R)
  21096 0Fh - DADRC-M - Drive Address Counter, Bit8-15 (R)
  21097   0-15  DADRC Address bit0-15  ;bit16 is in Port 0Bh            ...
  21098 
  21099 0Ch - HXFR-L - Host Transfer Length, bit0-7 (W)
  21100 0Dh - HXFR-H - Host Transfer Length, bit8-11 and stuff (W)
  21101   0-11  HXFR     number of data bytes, bit0-11 (0..FFFh)       ...
  21102   12    HADR.16  HADR  bit16
  21103   13    "L"      Reserved (should be 0)
  21104   14    "L" ??   Reserved (should be 0)   ;<-- XXX but on PSX: Always 1 !?!
  21105                                           ;    seems to Disable INT8 ?!!!
  21106   15    DISHXFRC Disable HXFRC (0=Use HXFRC, 1=Disable, Infinite-or-Zero Len?)
  21107 
  21108 0Eh - HADR-L - Host Transfer Address, bit0-7 (W)
  21109 0Fh - HADR-M - Host Transfer Address, bit8-15 (W)
  21110   0-15  HADR     Addr. bit0-15  ;bit16 in Port 0Dh    ...
  21111 
  21112 0Ah - HXFRC-L - Host Transfer Remain Counter, bit0-7 (R)
  21113 0Bh - HXFRC-H - Host Transfer Remain Counter, bit8-11, and other bits (R)
  21114   0-11  HXFRC Host Transfer Counter bit0-11 (number of remaining bytes)
  21115   12    HADRC bit16  ;MSB of Port 0Ch/0Dh
  21116   13    DADRC bit16  ;MSB of Port 0Eh/0Fh
  21117   14-15 -     Reserved (undefined) (usually both bits set)
  21118 
  21119 0Ch - HADRC-L - Host Transfer Address Counter, bit0-7 (R)
  21120 0Dh - HADRC-M - Host Transfer Address Counter, bit8-15 (R)
  21121   0-15  HADRC Address bit0-15  ;bit16 is in Port 0Bh
  21122 "This counter keeps the addresses which write or read the data with host
  21123 into/from the buffer.
  21124 When data from the host is written into the buffer or data to the host is read
  21125 from the buffer, the HADRC value is output from MA0 to 16. HADRC is incremented
  21126 each time one byte of data from the drive is read from the buffer (BFRD is
  21127 high) or written into the buffer (BFWR is high)."
  21128 
  21129 Note
  21130 When reading from SRAM, data seems to go through a 8-byte data fifo, the HXFRC
  21131 (remain) and HADRC (addr) values aren't aware of that FIFO (ie. if there's data
  21132 in the fifo, then addr will be 8 bigger and remain 8 smaller than what has
  21133 arrived at the host).
  21134 
  21135 Unclear Notes
  21136 "If sound map data is to be transferred before the data is transferred
  21137 (immediately after the host has set the BFRD and BFWR bits (bits 7 and 6) of
  21138 the HCHPCTL register high)":
  21139   900h is loaded into HXFRC
  21140   and 600Ch, 6A0Ch, or 740Ch is loaded into HADRC
  21141   (at least, supposedly, above addresses , for cases when using 32K SRAM)
  21142 "At any other time":
  21143   HADR and HXFR are loaded into HADRC and HXFRC
  21144 Unknown what the above crap is trying to say exactly.
  21145 "At any other time" does apparently refer to cases when transfers get started
  21146 (whilst during transfer, the address/remain values are obviously
  21147 increasing/decreasing).
  21148 For sound map, theoretically, the SMEN bit should be set, but above does
  21149 somewhat suggest that BFRD or BFWR (or actually: both BFRD and BFWR) need to be
  21150 set...?
  21151 
  21152 Sector Buffer Memory Map (32Kx8 SRAM)
  21153   0000h 1st Sector (at 0000h..0923h) (unused gap at 0924h..0BFFh)
  21154   0C00h 2nd Sector (at 0C00h..1523h) (unused gap at 1524h..17FFh)
  21155   1800h 3rd Sector (at 1800h..2123h) (unused gap at 2124h..23FFh)
  21156   2400h 4th Sector (at 2400h..2D23h) (unused gap at 2D24h..2FFFh)
  21157   3000h 5th Sector (at 3000h..3923h) (unused gap at 3924h..3BFFh)
  21158   3C00h 6th Sector (at 3C00h..4523h) (unused gap at 4524h..47FFh)
  21159   4800h 7th Sector (at 4800h..5123h) (unused gap at 5124h..53FFh)
  21160   5400h 8th Sector (at 5400h..5D23h) (unused gap at 5D24h..5FFFh)
  21161   6000h Soundmap ADPCM Buffer (at 600Ch..690Bh) (gaps at 6000h and 690Ch)
  21162   6A00h Soundmap ADPCM Buffer (at 6A0Ch..730Bh) (gaps at 6A00h and 730Ch)
  21163   7400h Soundmap ADPCM Buffer (at 740Ch..7D0Bh) (gaps at 7400h and 7D0Ch)
  21164   7E00h Unknown/Unused
  21165 
  21166 CDROM Internal CXD1815Q Sub-CPU Misc Registers
  21167 ----------------------------------------------
  21168 
  21169 16h - HIFCTL - Host Interface Control (W)
  21170   0-2  HINT    Request Host Interrupt (INT1..INT7, or 0=None/No change)
  21171   3-7  "L"     Reserved (should be 0)
  21172 
  21173 11h - HIFSTS - Host Interface Status (R)
  21174   0-2 HINTSTS  Pending Host Interrupt (INT1..INT7, or 0=None/All acknowledged)
  21175   3   DMABUSY  DMA Busy (0=Data FIFO Empty and HXFRC=0, 1=Data Transfer Busy)
  21176   4   PRMRRDY  Paramter Read Ready (0=Parameter FIFO Empty, 1=Ready/Not Empty)
  21177   5   RSLEMPT  Result Empty        (0=Response FIFO Not Empty, 1=Empty)
  21178   6   RSLWRDY  Result Write Ready  (0=Response FIFO Full, 1=Ready/Not Full)
  21179   7   BUSYSTS  Command Busy Status (0=Command Not Empty, 1=Ack'ed by CLRBUSY)
  21180 
  21181 0Ah - CLRCTL - Clear Control (W)
  21182   0   RESYNC   Sync with CD DSP (0=No change, 1=Resync, eg. after speed change)
  21183   1-3 "L"      Reserved (should be 0)
  21184   4   RTADPCLR Abort Real-time ADPCM (0=No Change, 1=Abort; when ADPMNT.7=0)
  21185   5   CLRRSLT  Clear Reply FIFO    (0=No change, 1=Acknowledge; clear FIFO)
  21186   6   CLRBUSY  Acknowledge Command (0=No change, 1=Acknowledge; clear BUSYSTS)
  21187   7   CHPRST   Chip Reset          (0=No change, 1=Do Chip Initialization)
  21188 
  21189 07h - INTSTS - Interrupt Status (R) - (0=No, 1=IRQ)
  21190 09h - INTMSK - Interrupt Mask (W) - (0=Disable, 1=Enable)
  21191 0Bh - CLRINT - Clear Interrupt Status (W) - (0=No change, 1=Clear/Ack)
  21192   0   HCRISD   Host Chip Reset Issued
  21193   1   HSTCMND  Host Command                ...
  21194   2   DECINT   Decoder Interrupt           ..
  21195   3   HDMACMP  Host DMA Complete           .   <-- PSX: used for retry ?!?!!!
  21196   4   RTADPEND Real-time ADPCM end
  21197   5   RSLTEMPT Result Empty
  21198   6   DECTOUT  Decoder Time Out
  21199   7   DRVOVRN  Drive Overrun
  21200 
  21201 12h - HSTPRM - Host Parameter (R)
  21202   0-7  Param FIFO (check HIFSTS.4 to see if the FIFO is empty)
  21203 HIFSTS.4 goes off when all bytes read.
  21204 Said to have 8-byte FIFO in CXD1199AQ datasheet.
  21205 But, PSX has 16-byte Parameter FIFO...!?!
  21206 
  21207 13h - HSTCMD - Host Command (R)
  21208   0-7  Command (check INTSTS.1 or HIFSTS.7 to see if a command was sent)
  21209 Command should be ack'ed via CLRINT.1 and CLRCTL.6.
  21210 
  21211 17h - RESULT - Response FIFO (W)
  21212   0-7  Data (has 8-byte FIFO)
  21213 Said to have 8-byte FIFO in CXD1199AQ datasheet.
  21214 But, PSX has 16-byte Response FIFO...!?!
  21215 
  21216 08h - ADPCI - ADPCM Coding Information (R)
  21217   0   S/M      ADPCM Stereo/Mono        (0=Mono, 1=Stereo)
  21218   1   -        Reserved (undefined)
  21219   2   FS       ADPCM Sampling Frequency (0=37.8kHz, 1=18.9kHz)
  21220   3   -        Reserved (undefined)
  21221   4   BITLNGTH ADPCM Sample Bit Length  (0=Normal/4bit, 1=8bit)
  21222   5   ADPBUSY  ADPCM Decoding           (0=No, 1=Yes/Busy)
  21223   6   EMPHASIS ADPCM Emphasis           (0=Normal/Off, 1=On)
  21224   7   MUTE     DA Data is Muted (uh?)   (0=No, 1=Yes/Muted)
  21225 Unknown if ADPCI is affected by configurations by Main-CPU's Sound Map ADPCM or
  21226 by Sub-CPU's Real-time ADPCM (or by both)?
  21227 Note: Bit5,7 are semi-undocumented in the datasheet (mentioned in the ADPCI
  21228 description, but missing in overall register summary).
  21229 
  21230 1Bh - RTCI - Real-time ADPCM Coding Information (W)
  21231   0    S/M      ADPCM Stereo/Mono        (0=Mono, 1=Stereo)
  21232   1    "L"      Reserved (should be 0)
  21233   2    FS       ADPCM Sampling Frequency (0=37.8kHz, 1=18.9kHz)
  21234   3    "L"      Reserved (should be 0)
  21235   4    BITLNGTH ADPCM Sample Bit Length  (0=Normal/4bit, 1=8bit)
  21236   5    "L"      Reserved (should be 0)
  21237   6    EMPHASIS ADPCM Emphasis           (0=Normal/Off, 1=On)
  21238   7    "L"      Reserved (should be 0)
  21239 
  21240 06h,09h,10h,14h..1Fh - Reserved (R)
  21241   0-7  Reserved (undefined)
  21242 Of these, 09h and 10h are officially unused/reserved. And addresses 06h and
  21243 14h..1Fh aren't officially mentioned to exist at all.
  21244 Trying to read these registers on a PSone returns Data=C0h for 06h, 09h, 10h,
  21245 15h-16h, 18h-1Fh, and Data=FFh for 14h, and Data=DEh for 17h.
  21246 
  21247 08h,13h-15h,18h,1Ah,1Ch-1Fh - Reserved (W)
  21248   0-7  Reserved (should be 00h) (or don't write at all)
  21249 Of these, 09h,13h-15h,18h,1Ah are officially unused/reserved. And addresses
  21250 1Ch-1Fh aren't officially mentioned to exist at all.
  21251 
  21252 CDROM Internal Commands CX(0x..3x) - CXA1782BR Servo Amplifier
  21253 --------------------------------------------------------------
  21254 
  21255 CXA1782BR - CX(0x) - Focus Servo Control - "FZC" FocusZeroCross at SENS pin
  21256   23-20 4bit  Command (00h)
  21257   19    1bit  FS4 Focus Servo (0=Off, 1=On)
  21258   18    1bit  FS3 DEFECT
  21259   17    1bit  FS2 Enable Focus Search Voltage (0=Off, 1=On)
  21260   16    1bit  FS1 Select Focus Search Voltage (0=Falling, 1=Rising)
  21261   15-0  16bit Unused (don't care)
  21262 For Focus Search: Keep FS1=on, and toggle FS2 on and off (this will generate a
  21263 waveform, and SENS will indicate when reaching a good focus voltage).
  21264 
  21265 CXA1782BR - CX(1x) - Tracking/Brake/Sled - "DEFECT" at SENS pin
  21266   23-20 4bit  Command (01h)
  21267   19    1bit  TG1,TG2 ON/OFF Tracking Servo Gain Up/Normal (hmmm?)
  21268   18    1bit  Brake Circuit ON/OFF
  21269   17-16 2bit  PS Sled Kick Height (0=+/-1, 1=+/-2, 2=Undoc, 3="Don't use"?)
  21270   15-0  16bit Unused (don't care)
  21271 Note: The PSX CDROM BIOS does use the "Undoc" setting (ie. bit17=1), but the
  21272 effect is undoc/unknown?
  21273 Note: CX(1x) works different on CXD2545Q (some bits are moved around, and the
  21274 "SledKickHeight" bits are renamed to "SledKickLevel" and moved to different/new
  21275 CX(3X) commands.
  21276 
  21277 CXA1782BR - CX(2x) - Tracking and Sled Servo Control - "TZC" at SENS pin
  21278   23-20 4bit  Command (02h)
  21279   19-18 2bit  Tracking Control (0=Off, 1=Servo On, 2=F-Jump, 3=R-Jump) ;TM1,3,4
  21280   17-16 2bit  Sled Control     (0=Off, 1=Servo On, 2=F-Fast, 3=R-Fast) ;TM2,5,6
  21281   15-0  16bit Unused (don't care)
  21282 
  21283 CXA1782BR - CX(3x) - "Automatic Adjustment Comparator Output" at SENS pin
  21284   23-20 4bit  Command (03h)
  21285   19    1bit  Value to be adjusted (0=Balance, 1=Gain)
  21286   18-16 3bit  New Balance or Gain value (depending on above bit)
  21287   15-0  16bit Unused (don't care)
  21288 Note: CX(3x) is extended and works very different on CXD2545Q.
  21289 
  21290 CXA1782BR Command 4x..7x - "HIGH-Z" at SENS pin
  21291   N-N   4bit  Command (04h..07h)
  21292 
  21293 CXA1782BR Command 8x..Fx - "UNSPECIFIED???" at SENS pin
  21294   N-N   4bit  Command (08h..0Fh)
  21295 
  21296 Note
  21297 The Servo Amplifier isn't directly connected to the CPU. Instead, it's
  21298 connected as a slave device to the Signal Processor. There are two ways to
  21299 access the Servo Amplifier:
  21300 1) The CPU can send CX(0X..3X) commands to the Signal Processor (which will
  21301 then forward them to the Servo Amplifier).
  21302 2) The Signal Processor can send CX(0X..3X) commands to the Servo Amplifier
  21303 (this happens during CX(4xxx) Auto Sequence command).
  21304 
  21305 CDROM Internal Commands CX(4x..Ex) - CXD2510Q Signal Processor
  21306 --------------------------------------------------------------
  21307 
  21308 CXD2510Q - CX(4xxx) - Auto Sequence
  21309   23-20 4bit  Command (4)
  21310   19-16 4bit  AS3-0 Auto Sequence Command (see below)
  21311   15-12 4bit  MT3-0 Max Timer Value (N timer units, or 0=Invalidate Timer)
  21312   11    1bit  LSSL  Timer Units     (0=2.9ms, 1=186ms) (for above MT value)
  21313   10-8  3bit  Unused (zero)
  21314   7-0   8bit  Unused (don't care)
  21315 Values for AS (Auto Sequence Command):
  21316   00h     Cancel
  21317   04h/05h Forward/Reverse Fine Search   ;<--sends CX(25h) ;\these do internally
  21318   07h     Focus-On                      ;<--sends CX(02h) ; send commands to
  21319   08h/09h Forward/Reverse 1 Track Jump  ;\                ; CXA1782BR
  21320   0Ah/0Bh Forward/Reverse 10 Track Jump ;   sends CX(25h) ; and, auto sequence
  21321   0Ch/0Dh Forward/Reverse 2N Track Jump ;/                ;/is interrupted?
  21322   0Eh/0Fh Forward/Reverse 1N Track Move ;<--CXD2545Q only(Reserved on CXD2510Q)
  21323   01h..03h,06h = Reserved
  21324 
  21325 CXD2510Q - CX(5x) - Blind,Brake,Overflow Timer
  21326   23-20 4bit  Command (5)
  21327   19-16 4bit  TR3-0 Timer (N*0.022ms for Blind/Overflow, N*0.045ms for Brake)
  21328   15-8  8bit  Unused (don't care on CXD2510Q, zero on CXD2545Q)
  21329   7-0   8bit  Unused (don't care)
  21330 
  21331 CXD2510Q - CX(6xx) - SledKick,Brake,Kick Timer
  21332   23-20 4bit  Command (6)
  21333   19-16 4bit  SD3-0 Timer KICK.D (N*2.9ms for Fine Search? else N*1.45ms?)
  21334   15-12 4bit  KF3-0 Timer KICK.F (N*0.09ms)
  21335   11-8  4bit  Unused (don't care on CXD2510Q, zero on CXD2545Q)
  21336   7-0   8bit  Unused (don't care)
  21337 
  21338 CXD2510Q - CX(7xxxx) - Track jump count setting (for Auto Sequence Command)
  21339   23-20 4bit  Command (7)
  21340   19-4  16bit Track Jump Count Setting (0..65535) for Command 4x
  21341   3-0   4bit  Unused (don't care)
  21342 
  21343 CXD2510Q - CX(8xx) - MODE Specification
  21344   23-20 4bit  Command (8)
  21345   19    1bit  CDROM        (0=Audio, 1=CDROM; no average and pre-value stuff)
  21346   18    1bit  DOUT Mute    (0=Not muted, 1=Mute DOUT)
  21347   17    1bit  D.out Mute-F (0=Not muted, 1=Mute DA)
  21348   16    1bit  WSEL         (0=Enhanced Sync Window, 1=Enhanced Anti-Rolling)
  21349   15    1bit  VCO SEL      (0=Double Correction, 1=Quadruple Correction)
  21350   14    1bit  ASHS         (0=Double Correction, 1=Quadruple Correction)
  21351   13    1bit  SOCT         (0=Output SubQ to SQSO, 1=Output Each? to SQSO)
  21352   12    1bit  Unused (zero)
  21353   11-8  4bit  Unused (don't care on CXD2510Q, zero on CXD2545Q)
  21354   7-0   8bit  Unused (don't care)
  21355 
  21356 CXD2510Q - CX(9xx) - Function Specification
  21357   23-20 4bit  Command (9)
  21358   19    1bit  DCLV ON-OFF (complex stuff, related to gain and frequencies)
  21359   18    1bit  DSPB ON-OFF (0=Normal Speed, 1=Double Speed; fixed pitch)
  21360   17    1bit  ASEQ ON-OFF (select output on SENS pin)
  21361   16    1bit  DPLL ON-OFF (0=Analog RFPLL, 1=Digital RFPLL)
  21362   15-14 1bit  Bilingual Audio (0=Stereo, 1=RightOnly, 2=LeftOnly, 3=Mute)
  21363   13    1bit  FLFC (normally 0)
  21364   12    1bit  Unused (zero)
  21365   11-8  4bit  Unused (don't care on CXD2510Q, zero on CXD2545Q)
  21366   7-0   8bit  Unused (don't care)
  21367 
  21368 CXD2510Q - CX(Axx) - Audio Control
  21369   23-20 4bit  Command (0Ah)
  21370   19    1bit  Vari Up   (write 1-then-0 to increase pitch by +0.1%)
  21371   18    1bit  Vari Down (write 1-then-0 to decrease pitch by -0.1%)
  21372   17    1bit  Mute (0=Not muted; unless muted elsewhere, 1=Mute & Peak=0)
  21373   16    1bit  ATT  (0=Attentuation off, 1=Minus 12 dB)
  21374   15-14 2bit  PCT  (0=Normal, 1=LevelMeter, 2=PeakMeter, 3=Normal) (0-1=QuadC2)
  21375   13-12 2bit  Unused (zero)
  21376   11-8  4bit  Unused (don't care on CXD2510Q, zero on CXD2545Q)
  21377   7-0   8bit  Unused (don't care)
  21378 Normal: SQSO outputs... WHAT?
  21379 PeakMeter: SQSO outputs highest peak ever on any channel (bit15: usually 0)
  21380 LevelMeter: SQSO outputs recent peak (with bit15 toggled: 0=Right, 1=Left)
  21381 
  21382 CXD2510Q - CX(Bxxxx) - Traverse Monitor Counter Setting
  21383   23-20 4bit  Command (0Bh)
  21384   19-4  16bit Traverse Monitor Count (used when monitored by COMP and COUT) (?)
  21385   3-0   4bit  Unused (don't care)
  21386 
  21387 CXD2510Q - CX(Cxx) - Spindle Servo Coefficient Setting
  21388   23-20 4bit  Command (0Ch)
  21389   19-18 2bit  Gain MDP for CLVP mode (0=-6db, 1=0dB, 1=+6dB, 3=Reserved)
  21390   17-16 2bit  Gain MDS for CLVS/CLVP (0=-12dB, 1=-6dB, 2=0dB, 3=Reserved)
  21391   15    1bit  Zero (zero)
  21392   14    1bit  Gain DCLV0 overall gain (0=0dB, 1=+6dB
  21393   13-12 2bit  Unused (zero)
  21394   11-8  4bit  Unused (don't care on CXD2510Q, zero on CXD2545Q)
  21395   7-0   8bit  Unused (don't care)
  21396 
  21397 CXD2510Q - CX(Dx) - CLV Control
  21398   23-20 4bit  Command (0Dh)
  21399   19    1bit  DCLV PWM MD Digital CLV PWM mode  (0=Use MDS+MDP, 1=Ternary MDP)
  21400   18    1bit  TB Bottom Hold in CLVS/CLVH modes (0=At cycle RFCK/32, 1=RFCK/16)
  21401   17    1bit  TP Peak Hold in CLVS mode         (0=At cycle RFCK/4, 1=RFCK/2)
  21402   16    1bit  Gain CLVS for CLVS mode (0=0dB, 1=+6dB)(always +6dB in CLVP mode)
  21403   15-8  8bit  Unused (don't care on CXD2510Q, zero on CXD2545Q)
  21404   7-0   8bit  Unused (don't care)
  21405 
  21406 CXD2510Q - CX(Ex) - CLV Mode
  21407   23-20 4bit  Command (0Eh)
  21408   19-16 4bit  CM3-0
  21409   15-8  8bit  Unused (don't care on CXD2510Q, zero on CXD2545Q)
  21410   7-0   8bit  Unused (don't care)
  21411 Values for CM (CLV Mode):
  21412   00h Stop  Spindle Motor Stop mode
  21413   06h CLVA  Automatic CLVS/CLVP switching mode, normally used for playback
  21414   08h Kick  Spindle Motor Forward rotation mode
  21415   0Ah Brake Spindle Motor Reverse rotation mode
  21416   0Ch CLVH  Peak hold at 34kHz
  21417   0Eh CLVS  Rough Servo Mode, RF-PLL related
  21418   0Fh CLVP  PLL Servo mode
  21419 
  21420 N/A - CX(F) - Reserved
  21421   23-0  N/A  Don't use
  21422 
  21423 SUBQ Output
  21424  80bit subq
  21425  15bit peak level (lsb first) (absolute/unsigned value)
  21426  1bit  peak l/r flag (aka appears as "MSB" of peak level)
  21427 L/R is toggled after each SUBQ reading, however the PSX Report mode does
  21428 usually forward SUBQ only every 10 frames, so it stays stuck in one setting
  21429 (but may toggle after one second; ie. every 75 frames). And, peak is reset
  21430 after each read, so 9 of the 10 frames are lost.
  21431 
  21432 CXD2510Q - SENS output
  21433   Index         ASEQ=0  ASEQ=1   ;<-- ASEQ can be set via CX(9xx)
  21434   0X            HighZ   SEIN (FZC)                     ;\aka SENS output
  21435   1X            HighZ   SEIN (A.S)    ... aka DEFECT   ; from CXA1782BR
  21436   2X            HighZ   SEIN (T.Z.C)  ... aka TZC      ; forwarded through
  21437   3X            HighZ   SEIN (SSTOP)  ... aka Gain/Bal ;/CXD2510Q
  21438   4X            HighZ   XBUSY
  21439   5X            HighZ   FOK
  21440   6X            HighZ   SEIN (HighZ)
  21441   AX            GFS     GFS
  21442   BX            COMP    COMP
  21443   CX            COUT    COUT
  21444   EX            /OV64   /OV64
  21445   7X-9X,DX,FX   HighZ   0
  21446 Whereas,
  21447  FZC    Focus Zero Cross
  21448  DEFECT Defect?
  21449  TZC    Tracking Zero Cross
  21450  SSTOP  Gain or Balance adjust reached wanted level
  21451  XBUSY  Low while the auto sequencer operation is busy
  21452  FOK    High for "focus OK" (same as FOK pin)
  21453  GFS    High when the played back frame sync is obtained with correct timing
  21454  COMP   Measures the number of tracks set with Reg B. High when Reg B is
  21455           latched, low when the initial Reg B number is input by CNIN
  21456  COUT   Measures the number of tracks set with Reg B. High when Reg B is
  21457           latched, toggles each time the Reg B number is input by CNIN. While
  21458           $44 and $45 are being executed, toggles with each CNIN 8-count
  21459           instead of the Reg B number
  21460  OV64   Low when filtered EFM signal is lengthened by 64 channel clock
  21461           pulses or more
  21462 
  21463 CDROM Internal Commands CX(0x..Ex) - CXD2545Q Servo/Signal Combo
  21464 ----------------------------------------------------------------
  21465 
  21466 CXD2545Q - CX(0x) and CX(2x) - same as CXA1782BR Servo Amplifier
  21467 --> CDROM Internal Commands CX(0x..3x) - CXA1782BR Servo Amplifier
  21468 
  21469 CXD2545Q - CX(4x..Ex) - same as CXD2510Q Signal Processor
  21470 --> CDROM Internal Commands CX(4x..Ex) - CXD2510Q Signal Processor
  21471 One small difference is that the CXD2545Q supports a new "M Track Move"
  21472 function as part of the CX(4xxx) command. And, some "don't care" bits are now
  21473 reserved (ie. some commands need to be padded with additional leading "0"
  21474 bits).
  21475 
  21476 CXD2545Q - CX(1x) - Anti Shock/Brake/Tracking Gain/Filter
  21477   23-20 4bit  Command (01h)
  21478   19    1bit  Anti Shock (0=Off, 1=On)
  21479   18    1bit  Brake      (0=Off, 1=On)
  21480   17    1bit  Tracking Gain (0=Normal, 1=Up)
  21481   16    1bit  Tracking Gain Filter (0=Select 1, 1=Select 2)
  21482   15-0  16bit Unused (don't care)
  21483 
  21484 CXD2545Q - CX(30..33) - Sled Kick Level
  21485   23-20 4bit  Command (03h)
  21486   19-18 2bit  Subcommand (0)
  21487   17-16 2bit  Sled Kick Level (0=+/-1, 1=+/-2, 2=+/-3, 3=+/-4)
  21488   15-0  16bit Unused (don't care)
  21489 
  21490 CXD2545Q - CX(34xxxx) - Write to Coefficient RAM
  21491   23-16 8bit  Command (34h)
  21492   15    1bit  Zero (0)
  21493   14-8  7bit  Address (00h..4Fh = Select Coefficient K00..K4F)
  21494   7-0   8bit  Data    (00h..FFh = New value)
  21495   PLUS  8bit  Eight more bits on PSone (!)
  21496 Allows to change the default preset coefficient values,
  21497 --> CDROM Internal Coefficients (for CXD2545Q)
  21498 
  21499 CXD2545Q - CX(34Fxxx) - Write to Special Register
  21500   23-12 12bit Command (34Fh)
  21501   11-10 2bit  Index (0=TRVSC, 1=FBIAS, 2=?, 3=?)
  21502   9-0   10bit Data (for FBIAS: bit0=don't care)
  21503 
  21504 CXD2545Q - CX(35xxxx) - FOCUS SEARCH SPEED/VOLTAGE/AUTO GAIN
  21505   23-16 8bit  Command (35h)
  21506   15-14 2bit  FT  Focus Search-up speed 1
  21507   13-8  6bit  FS  Focus Search limit voltage (default 011000b) (+/-1.875V)
  21508   7     1bit  FTZ Focus Search-up speed 2
  21509   6-0   7bit  FG  AGF Convergence Gain Setting (default 0101101b)
  21510 
  21511 CXD2545Q - CX(36xxxx) - DTZC/TRACK JUMP VOLTAGE/AUTO GAIN
  21512   23-16 8bit  Command (36h)
  21513   15    1bit  Zero (0)
  21514   14    1bit  DTZC DTZC Delay (0=4.25us/Default, 1=8.5us)
  21515   13-8  6bit  TJ   Track Jump voltage (default 001110b) (+/-1.09V)
  21516   7     1bit  Zero (0)
  21517   6-0   7bit  TG   AGT Convergence Gain Setting (default 0101110b)
  21518 
  21519 CXD2545Q - CX(37xxxx) - FZSL/SLED MOVE/Voltage/AUTO GAIN
  21520   23-16 8bit  Command (37h)
  21521   15-14 2bit  FZS              XXX pg. 84
  21522   13-8  6bit  SM    Sled Move Voltage
  21523   7     1bit  AGS
  21524   6     1bit  AGJ
  21525   5     1bit  AGGF
  21526   4     1bit  AGGT
  21527   3     1bit  AGV1
  21528   2     1bit  AGV2
  21529   1     1bit  AGHS
  21530   0     1bit  AGHT
  21531 
  21532 CXD2545Q - CX(38xxxx) - Level/Auto Gain/DFSW (Initialize)
  21533   23-16 8bit  Command (38h)
  21534   15    1bit  VCLM VC level measurement on/off
  21535   14    1bit  VCLC VC level compensation for FCS_In Register on/off
  21536   13    1bit  FLM  Focus zero level measurement on/off
  21537   12    1bit  FLC0 Focus zero level compensation for FZC Register on/off
  21538   11    1bit  RFLM RF zero level measurement on/off
  21539   10    1bit  RFLC RF zero level compensation on/off
  21540   9     1bit  AGF  Focus automatic gain adjustment on/off
  21541   8     1bit  AGT  Tracking automatic gain adjustment on/off
  21542   7     1bit  DFSW Defect switch disable (1=disable defect measurement)
  21543   6     1bit  LKSW Lock switch (1=disable sled free-running prevention)
  21544   5     1bit  TBLM Traverse center measurement on/off
  21545   4     1bit  TCLM Tracking zero level measurement on/off
  21546   3     1bit  FLC1 Focus zero level compensation for FCS_In Register on/off
  21547   2     1bit  TLC2 Traverse center compensation on/off
  21548   1     1bit  TLC1 Tracking zero level compensation on/off
  21549   0     1bit  TLC0 VC level compensation for TRK/SLD_In register on/off
  21550 VCLM,FLM,RFLM,TCLM are accepted every 2.9ms.
  21551 
  21552 CXD2545Q - CX(39xx) - Select internal RAM/Registers for serial readout
  21553   23-16 8bit  Command (39h)
  21554   15    1bit  DAC Serial data readout DAC mode on/off
  21555   14-8  7bit  SD  Serial readout data select (see below)
  21556   7-0   8bit  Unused (don't care)
  21557 Serial Readout Addresses:
  21558   Addr    Data  Content
  21559   00h     8bit  VC input signal
  21560   01h     8bit  SE input signal
  21561   02h     8bit  TE input signal
  21562   03h     8bit  FE input signal
  21563   04h-07h 9bit  TE AVRG register (mirrored to 04h-07h)
  21564   08h-0Bh 9bit  FE AVRG register (mirrored to 08h-0Bh)
  21565   0Ch-0Fh 9bit  VC AVRG register (mirrored to 0Ch-0Fh)
  21566   12h     8bit  RFDC envelope (peak)
  21567   13h     8bit  RFDC envelope (bottom)
  21568   1Ch     9bit  TRVSC register
  21569   1Dh     9bit  FBIAS register
  21570   1Eh     8bit  RFDC input signal
  21571   1Fh     8bit  RF AVRG register
  21572   20h-3Fh 16bit Data RAM        (M00-M1F)
  21573   40h-7Fh 8bit  Coefficient RAM (K00-K3F) (note: K40-K4F cannot be read out)
  21574 
  21575 CXD2545Q - CX(3Ax000) - Focus BIAS addition enable
  21576   23-16 8bit  Command (3Ah)
  21577   15    1bit  Zero (0)
  21578   14    1bit  FBON: FBIAS register addition (0=off, 1=Add FBIAS to FCS)
  21579   13-0  14bit Zero (0)
  21580 
  21581 CXD2545Q - CX(3Bxxxx) - Operation for MIRR/DFCT/FOK
  21582   23-16 8bit  Command (3Bh)
  21583   15-14 2bit  SFO  FOK Slice Level (...depends on SFOX)
  21584   13-12 2bit  SDF  DFCT Slice Level (0=89mV, 1=134mV, 2=179mV, 3=224mV)
  21585   11-10 2bit  MAX  DFCT Maximum Time (0=No Limit, 1=2ms, 2=2.36ms, 3=2.72ms)
  21586   9     1bit  SFOX FOK Slice Level (...depends on SFO)
  21587   8     1bit  BTF  Bottom Hold Double-Speed Count-Up mode for MIRR (0=off)
  21588   7-6   2bit  D2V  Peak Hold 2 for DFCT (0=22.05kHz, 1=44.1, 2=88.2, 3=176.4)
  21589   5-4   2bit  D1V  Peak Hold 1 for DFCT (0=176.4kHz, 1=352.8, 2=705.6, 3=1411)
  21590   3-0   4bit  Zero (0)
  21591 
  21592 CXD2545Q - CX(3Cxxxx) - TZC for COUT SLCT HPTZC (Default)
  21593   23-16 8bit  Command (3Ch)
  21594   15-0  16bit Unused (don't care)
  21595 
  21596 CXD2545Q - CX(3Dxxxx) - TZC for COUT SLCT DTZC
  21597   23-16 8bit  Command (3Dh)
  21598   15-0  16bit Unused (don't care)
  21599 
  21600 CXD2545Q - CX(3Exxxx) - Filter
  21601   23-16 8bit  Command (3Eh)
  21602   15-14 2bit  F1NDM FCS servo filter 1st stage (1=normal, 2=down)
  21603   13-12 2bit  F3NUM FCS servo filter 3rd stage (1=normal, 2=up)
  21604   11-10 2bit  T1NDM TRK servo filter 1st stage (1=normal, 2=down)
  21605   9-8   2bit  T3NUM TRK servo filter 3rd stage (1=normal, 2=up)
  21606   7     1bit  DFIS  FCS hold filter input extraction node (0=M05, 1=M04)
  21607   6     1bit  TLCD  Mask TLC2 set by D2 of CX(38) only when FOK low
  21608   5     1bit  RFLP  Pass signal from RFDC pin through low-pass-filter
  21609   4-0   5bit  Zero (0)
  21610 
  21611 CXD2545Q - CX(3Fxxxx) - Others
  21612   23-16 8bit  Command (3Fh)          ... XXX pg. 89
  21613   15-14 2bit  Unused (0)
  21614   13-12 2bit  XTD
  21615   11    1bit  Unused (0)
  21616   10-8  3bit  DRR
  21617   7     1bit  Unused (0)
  21618   6     1bit  ASFG
  21619   5     1bit  Unused (0)
  21620   4     1bit  LPAS
  21621   3-2   2bit  SRO
  21622   1-0   2bit  Unused (0)
  21623 
  21624 CXD2545Q feedback on 39xx: see pg. 77 (eg. 390C = VC AVRG)
  21625 XXX
  21626 
  21627 CXD2545Q - SENS output
  21628   Index          ASEQ=0  ASEQ=1           Length
  21629   $0X            Z       FZC              -
  21630   $1X            Z       AS               -
  21631   $2X            Z       TZC              -
  21632   $38            Z       AGOK*1           -
  21633   $38            Z       XAVEBSY*1        -
  21634   $30-37,$3A-3F  Z       SSTP             -
  21635   $3904          Z       TE Avrg Reg.     9 bit
  21636   $3908          Z       FE Avrg Reg.     9 bit
  21637   $390C          Z       VC Avrg Reg.     9 bit
  21638   $391C          Z       TRVSC Reg.       9 bit
  21639   $391D          Z       FB Reg.          9 bit
  21640   $391F          Z       RFDC Avrg Reg.   8 bit
  21641   $4X            Z       XBUSY            -
  21642   $5X            Z       FOK              -
  21643   $6X            Z       0                -
  21644   $AX            GFS     GFS              -
  21645   $BX            COMP    COMP             -
  21646   $CX            COUT    COUT             -
  21647   $EX            OV64    OV64             -
  21648   $7X-9X,DX,FX   Z       0                -
  21649 *1 $38 outputs AGOK during AGT and AGF command settings, and XAVEBSY during
  21650 AVRG measurement.
  21651 SSTP is output in all other cases.
  21652 
  21653 CDROM Internal Commands CX(0x..Ex) - CXD2938Q Servo/Signal/SPU Combo
  21654 --------------------------------------------------------------------
  21655 
  21656 Most commands are same as on CXD2545Q. New/changed commands are:
  21657 
  21658 CXD2938Q - CX(349xxxxx) - New SCEx
  21659 Older PSX consoles have received the "SCEx" string at 250 baud via HC05
  21660 PortB.bit1, which allowed modchips to injected faked "SCEx" signals to that
  21661 pin. To prevent that, the CXD2938Q contains some new 32bit commands that allow
  21662 to receive somewhat encrypted "SCEx" strings via SPI bus. The used commands
  21663 are:
  21664   CX(34910000) NewScexStopReading
  21665   CX(3491xy80) NewScexRandomKey(xy)
  21666   CX(34920000) NewScexFlushResyncOrSo
  21667   CX(34944A00) NewScexInitValue1
  21668   CX(3498C000) NewScexInitValue2
  21669   CX(349C1000) NewScexThis   ;\inverse  ;\use CX(3C2080) for COUT selection
  21670   CX(349D1000) NewScexThat   ;/of COUT  ;/
  21671 The relevant command is NewScexRandomKey(xy) which does send a random value
  21672 (x=01h..0Fh, and y=01h), and does then receive a 12-byte response via SPI bus
  21673 (which is normally used to receive SUB-Q data).
  21674   1st byte: Unknown/unused (normally ADR/Control) ;\these should be probably
  21675   2nd byte: Unknown/unused (normally Track)       ; set to some invalid values
  21676   3rd byte: Unknown/unused (normally Index/Point) ;/to avoid SUB-Q confusion
  21677   4th..10th byte: SCEx data or Dummy bytes (depending on xy.bit7..1)
  21678   11th..12th byte: Unknown/unused (normally Audio Peak level)
  21679 The 12-byte packet does contain one SCEx character encoded in 4th..10th byte
  21680 corresponding to Flags in "xy" bit 7..1 (in that order):
  21681 All bytes with Flag=1 are ORed together to compute a Character byte (those
  21682 bytes could be all set to 53h for "S", or if more than one flag is set, it
  21683 could be theoretically split to something like 41h and 12h).
  21684 All bytes with Flag=0 are ORed together to compute a Dummy byte. If the
  21685 Character byte is same as the Dummy byte, then it gets destroyed by setting
  21686 Character=00h (to avoid that, one could set all dummies to 00h, or set one or
  21687 more dummies to FFh, for example).
  21688 Finally, "xy" bit0=0 indicates that the resulting character byte is inverted
  21689 (XORed by FFh), however, the CDROM BIOS does always use bit0=1, so the
  21690 inversion feature is never used.
  21691 For the whole SCEx string, there must be at least one 00h byte inserted between
  21692 each character (or some Char=Dummy mismatch, which results in Char=00h either),
  21693 and there should be a few more 00h bytes preceeding the first character ("S").
  21694 Note: Modchips didn't bother to reproduce that new SCEx transfers, instead they
  21695 have simply bypassed it by injecting the 250 baud SCEx string to some analog
  21696 lower level signal.
  21697 
  21698 CXD2938Q - CX(3Bxxxx) - Some Changed Bits
  21699 Same as in older version, but initialized slightly differently: CXD2545Q used
  21700 CX(3B2250) whilst CXD2938Q is using CX(3B7250).
  21701 
  21702 CXD2938Q - CX(3Cxxxx) - TzcCoutSelect with New/Changed Extra Bits
  21703 The CXD2545Q used two 8bit commands, CX(3C) and CX(3D), for TzcOut selection,
  21704 which are now replaced by a single 24bit command, CX(3Cxxxx), and which do
  21705 include a new mode related to New SCEx.
  21706   CXD2545Q   CXD2938Q
  21707   CX(3C)     CX(3C0080) TzcCoutSelectHPTZC;\ <--formerly CX(3C)
  21708   -          CX(3C2080) TzcCoutSelectSCEX ;  <--special NewScex mode
  21709   CX(3D)     CX(3C4080) TzcCoutSelectDTZC ;/ <--formerly CX(3D)
  21710 
  21711 CXD2938Q - CX(8xxxxx) - Disc Mode with New/Changed Extra Bits
  21712 Command CX(8xx) has been 12bit wide on CXD2545Q, and is now expanded 24bit
  21713 width (with some changed/unknown bits).
  21714   CXD2545Q   CXD2938Q
  21715   CX(8180)   CX(810408) MODE = Audio (CD-DA)
  21716   CX(8120)   CX(812400) MODE = Audio (CD-DA) (manual SPI bus access)
  21717   CX(8980)   CX(890408) MODE = CDROM (Data)
  21718   -          CX(898000) MODE = CDROM (Data) (used on RESET)
  21719 
  21720 CXD2938Q - CX(9xx000) - Normal/Double Speed with New Extra Bits
  21721 Command CX(9xx) has been 12bit wide on CXD2545Q (with bit12=reserved/zero), and
  21722 is now expanded 24bit width (with bit12=unknown/one and bit11-0=unknown/zero).
  21723 
  21724 CXD2938Q - CX(Dx0000) and CX(Ex0000) - New Zero Padding
  21725 Commands CX(Dx) and CX(Ex) have been 8bit wide on CXD2545Q, and are now
  21726 zeropadded to 24bit width, ie. CX(Dx0000) and CX(Ex0000). Unknown if the extra
  21727 bits are hiding any extra features. In practice, the CDROM BIOS is always
  21728 setting them zero (except in some test commands which are accidently still
  21729 using the old 8bit form, resulting in garbage in lower 16bits).
  21730 
  21731 CDROM Internal Commands CX(xx) - Notes
  21732 --------------------------------------
  21733 
  21734 Serial Command Transmission (for Signal Processor and Servo Amplifier)
  21735 Commands are sent serially LSB first via DATA,CLOK,XLAT pins: DATA+CLOK are
  21736 used to send commands to the chip, command execution is then applied by
  21737 dragging XLAT low for a moment.
  21738 Commands can be up to 24bits in length, but unused LSBs (the "don't care" bits)
  21739 can be omitted; the PSX BIOS clips the length to 8bit/16bit where possible (due
  21740 to the LSB-first transfer order, the chip does treat the most recently
  21741 transferred bit as MSB=bit23, and there's no need to transfer the LSBs if they
  21742 aren't used).
  21743 Aside from being used as command number, the four most recently transferred
  21744 bits are also used to select SENS status feedback (for the SENS selection it
  21745 doesn't matter if the four bits were terminated by XLAT or not).
  21746 
  21747 Sled Motor / Track Jumps / Tracking
  21748 The Sled motor moves the drive head to the current read position. On a Compact
  21749 Disc, the term "Track" does normally refer to Audio tracks (songs). But the
  21750 drive hardware uses the terms "Track" and "Tracking" for different purposes:
  21751 Tracking appears to refer to moving the Optics via magnets (ie. moving only the
  21752 laser/lens, without actually moving the whole sled) (this is done for fine
  21753 adjustments, and it seems to happen more or less automatically; emulators can
  21754 just return increasing sectors without needing to handle special tracking
  21755 commands).
  21756 Track jumps refer to moving the entire Sled, one "track" is equal to one spiral
  21757 winding (1.6 micrometers). One winding contains between 9 sectors on innermost
  21758 windings, and 22.5 sectors on outermost windings (the PSX cdrom bios is
  21759 translating the sector-distance to non-linear track-distance, and emulators
  21760 must undo that translation; otherwise the sled doesn't arrive at the intended
  21761 location; the cdrom bios will retry seeking a couple of times and eventually
  21762 settle down at the desired location - but it will timeout if the sled emulation
  21763 is too inaccurate).
  21764 The PSX hardware uses two mechanisms for moving the Sled:
  21765 Command CX(4xxx) Forward/Reverse Track Jump: allows to move the sled by
  21766 1..131070 tracks (ie. max 210 millimeters), and the hardware does stop
  21767 automatically after reaching the desired distance.
  21768 Command CX(2x) Forward/Reverse Fast Sled: moves the sled continously until it
  21769 gets stopped by another command (in this mode, software can watch the COUT
  21770 signal, which gets toggled each "N" tracks; whereas "N" can be selected via
  21771 Command CX(Bxxxx), which is configured to N=100h in PSX).
  21772 The PSX cdrom bios is issuing another Fast Sled command (in opposite direction)
  21773 after Fast Sled commands, emulators must somehow interprete this as "sled
  21774 slowdown" (rather than as actually moving the sled in opposite direction, which
  21775 could move the sled miles away from the target). For some reason vC1 BIOS is
  21776 using a relative short slowdown period, whilst vC2/vC3 are using much longer
  21777 slowdown periods (probably related to different SledKickHeight aka
  21778 SledKickLevel settings and/or to different Sled Move Voltage settings).
  21779 
  21780 Focus / Gain / Balance
  21781 The hardware includes commands for adjusting & measuring focus/gain/balance.
  21782 Emulators can just omit that stuff, and can always signalize good operation
  21783 (except that one should emulate failures for Disc Missing; and eventually also
  21784 for cases like Laser=Off, or Spindle=Stopped).
  21785 Focus does obviously refer to moving the lens up/down. Gain does probably refer
  21786 to reflection level/laser intensity. Balance might refer to tracking
  21787 adjustments or so.
  21788 
  21789 CDROM Internal Commands CX(xx) - Summary of Used CX(xx) Commands
  21790 ----------------------------------------------------------------
  21791 
  21792 The PSX CDROM BIOS versions vC1, vC2, and vC3 are using following CX()
  21793 commands:
  21794   <--vC1-->  <--vC2-->  <--vC3-->
  21795   CXD2510Q   CXD2545Q   CXD2938Q
  21796   CX(00)     CX(00)     CX(00)     AllFocusSwitchesOff
  21797   CX(02)     CX(02)     CX(02)     FocusSearchVoltageFalling
  21798   CX(03)     CX(03)     CX(03)     FocusSearchVoltageRising ;ForTestOnly
  21799   CX(08)     CX(08)     CX(08)     FocusServoOn
  21800   CX(0C)     CX(0C)     CX(0C)     FocusServoOnAndDefectOn ;diff.usage vC# ?
  21801   -----
  21802   CX(11)     -          -          SledKickHeight2
  21803   CX(12)     -          -          SledKickHeightInvalid
  21804   CX(19)     -          -          TrackingGainAndSledKickHeight2
  21805   CX(1D)     -          -          TrackingGainBrakeAndSledKickHeight2
  21806   CX(1E)     -          -          TrackingGainBrakeAndSledKickHeightInvalid
  21807   -----
  21808   -          CX(11)     CX(11)     AntiShockOff            ;\
  21809   -          CX(13)     CX(13)     AntiShockOffGainUp      ;
  21810   -          CX(17)     CX(17)     AntiShockOffGainUpBrake ;/
  21811   -----
  21812   CX(20)     CX(20)     CX(20)     SledAndTrackingOff
  21813   CX(21)     CX(21)     CX(21)     SledServoOn          ;ForTestOnly
  21814   CX(22)     CX(22)     CX(22)     SledFastForward
  21815   CX(23)     CX(23)     CX(23)     SledFastReverse
  21816   CX(24)     -          -          TrackingServoOn
  21817   CX(25)     CX(25)     CX(25)     SledAndTrackingServoOn
  21818   -          CX(26)     CX(26)     SledFastForwardAndTrackingServoOn
  21819   CX(28)     CX(28)     CX(28)     TrackingForwardJump  ;ForTestOnly
  21820   CX(2C)     CX(2C)     CX(2C)     TrackingReverseJump  ;ForTestOnly
  21821   -----
  21822   CX(30+n)   -          -          BalanceAdjust(0..7)
  21823   CX(38+n)   -          -          GainAdjust(0..7)
  21824   -----
  21825   -          CX(30)     CX(30)     SetSledKickLevel1       ;\
  21826   -          CX(31)     CX(31)     SetSledKickLevel2       ;
  21827   -          CX(32)     CX(32)     SetSledKickLevel3       ;/
  21828   -----
  21829   -          CX(3400E6) CX(3400E6) SetK00toE6hSledInputGain            ;def=E0h
  21830   -          CX(340730) CX(340730) SetK07to30hSledAutoGain       ;blah ;def=30h
  21831   -          CX(34114A) CX(34114A) SetK11to4AhFocusOutputGain          ;def=32h
  21832   -          CX(341330) CX(341330) SetK13to30hFocusAutoGain      ;blah ;def=30h
  21833   -          CX(341D6F) CX(341D6F) SetK1Dto6FhTrackingLowBoostFilterAL ;def=44h
  21834   -          CX(341F64) CX(341F64) SetK1Fto64hTrackingLowBoostFilterBL ;def=5Eh
  21835   -          CX(342220) CX(342220) SetK22to20hTrackingOutputGain       ;def=18h
  21836   -          CX(342330) CX(342330) SetK23to30hTrackingAutoGain   ;blah ;def=30h
  21837   -          CX(342D28) CX(342D28) SetK2Dto28hFocusGainDownOutputGain  ;def=1Bh
  21838   -          CX(343E70) CX(343E70) SetK3Eto70hTrackingGainUpOutputGain ;def=57h
  21839   -          -          CX(34910000) NewScexStopReading      ;\
  21840   -          -          CX(3491x180) NewScexRandomKey(x)     ;
  21841   -          -          CX(34920000) NewScexFlushResyncOrSo  ; SCEX SPECIAL
  21842   -          -          CX(34944A00) NewScexInitValue1       ; see also:
  21843   -          -          CX(3498C000) NewScexInitValue2       ; CX(3C2080)
  21844   -          -          CX(349C1000) NewScexThis   ;\inverse ;
  21845   -          -          CX(349D1000) NewScexThat   ;/of COUT ;/
  21846   -          CX(34F000) CX(34F000) SetTRVSCto000h
  21847   -          CX(34Fxxx) CX(34Fxxx) SetFBIAStoNNNh
  21848   -----
  21849   -          CX(3740AA) CX(3740AA) SetSMto00h      ;\set SM to 0,6,7,9
  21850   -          CX(3746AA) CX(3746AA) SetSMto06h      ; (sled move voltage)
  21851   -          CX(3747AA) CX(3747AA) SetSMto07h      ; (and init several
  21852   -          CX(3749AA) CX(3749AA) SetSMto09h      ;/fixed settings)
  21853   -----
  21854   -          CX(380010) CX(380010) ModeMeasureTrackingZeroLevel ;\Measure modes
  21855   -          CX(380800) CX(380800) ModeMeasureRfZeroLevel       ; (accepted
  21856   -          CX(382000) CX(382000) ModeMeasureFocusZeroLevel    ; every 2.9ms)
  21857   -          CX(388000) CX(388000) ModeMeasureVcLevel           ;/
  21858   -          CX(38140A) CX(38140A) ModeCompensate
  21859   -          CX(38140E) CX(38140E) ModeCompensateAndTraverseCenter
  21860   -          CX(38148A) CX(38148A) ModeCompensateAndDefectOff
  21861   -          CX(38148E) CX(38148E) ModeCompensateAndDefectOffTraverseCenter
  21862   -          CX(3814AA) CX(3814AA) ModeCompensateAndStuffAndMeasureTraverse ;!
  21863   -          CX(38150A) CX(38150A) ModeCompensateAndTrackingAutoGain
  21864   -          CX(38150E) CX(38150E) ModeCompensateAndTrackingAutoGain
  21865   -          CX(38160A) CX(38160A) ModeCompensateAndFocusAutoGain
  21866   -----
  21867   -          CX(391E)   -          SenseRFDCinputSignalWithoutDAC  ;\rather
  21868   -          CX(3983)   -          SenseFEinputSignalWithDAC       ;/unused
  21869   -          CX(399C)   -          SenseTRVSCregisterWithDAC       ;\only if
  21870   -          CX(399D)   -          SenseFBIASregisterWithDAC       ;/TEST1=LOW
  21871   -----
  21872   -          CX(3A0000) CX(3A0000) FocusBiasAdditionOff            ;\
  21873   -          CX(3A4000) CX(3A4000) FocusBiasAdditionOn             ;/
  21874   -          CX(3B2250)!CX(3B7250)!InitOperationForMirrDfctFok <-- vC2/vC3 DIFF
  21875   -          CX(3C)  !!!CX(3C0080) TzcCoutSelectHPTZC;\ <--formerly CX(3C)
  21876   -          -       !!!CX(3C2080) TzcCoutSelectSCEX ;  <--special NewScex mode
  21877   -          CX(3D)  !!!CX(3C4080) TzcCoutSelectDTZC ;/ <--formerly CX(3D)
  21878   -          CX(3E0000) CX(3E0000) InitFilterBits                  ;\
  21879   -          CX(3E0008) CX(3E0008) InitFilterBitsInvalid           ;/
  21880   -          CX(3F0008) CX(3F0008) InitOtherStuff                  ;-
  21881   -----
  21882   CX(4000)   CX(4000)   CX(4000)   AutoSeqCancel
  21883   CX(4700)   CX(4700)   CX(4700)   AutoSeqFocusOn
  21884   CX(4800)   CX(4800)   CX(4800)   Forward1track
  21885   CX(4900)   CX(4900)   CX(4900)   Reverse1track
  21886   CX(4C00)   CX(4C00)   CX(4C00)   Forward2Ntrack
  21887   CX(4D00)   CX(4D00)   CX(4D00)   Reverse2Ntrack
  21888   -----
  21889   CX(54)     CX(54)     CX(54)     BlindBrakeOverflowTimer=4
  21890   CX(5A)     CX(5A)     CX(5A)     BlindBrakeOverflowTimer=A
  21891   CX(6100)   CX(6100)   CX(6100)   SledKickBrakeKickTimer
  21892   CX(70xxx0) CX(70xxx0) CX(70xxx0) TrackJumpCountSetting
  21893   CX(8180)   CX(8180)!!!CX(810408) MODE = Audio (CD-DA)
  21894   -          CX(8120)!!!CX(812400) MODE = Audio (CD-DA) (manual SPI bus access)
  21895   -          -          CX(810000/UNUSED)
  21896   -          -          CX(812000/UNUSED)
  21897   CX(8980)   CX(8980)   CX(890408) MODE = CDROM (Data)
  21898   -          -          CX(898000) MODE = CDROM (Data) (used on RESET)
  21899   CX(9B00)   CX(9B00)!!!CX(9B1000) NormalSpeed
  21900   CX(9F00)   CX(9F00)!!!CX(9F1000) DoubleSpeed
  21901   CX(A040)   CX(A040)   CX(A040)   Attentuation Off
  21902   CX(A140)   CX(A140)   CX(A140)   Attentuation -12 dB
  21903   CX(B01000) CX(B01000) CX(B01000) TraverseMonitorCounterSetting
  21904   CX(C600)   CX(C600)   CX(C600)   SpindleServoCoefficientSetting
  21905   CX(D7)     CX(D7)     CX(D70000) ClvControl (fixed)
  21906   CX(E0)     CX(E0)     CX(E00000) SpindleMotorStop
  21907   -          -          CX(E02000) <-- aka bugged CX(E0) with CRAP=2000h
  21908   CX(E6)     CX(E6)     CX(E60000) AutomaticNormal
  21909   CX(E8)     CX(E8)     CX(E80000) SpindleMotorForward
  21910   -          -          CX(E8crap) <-- aka bugged CX(E8) with CRAP=xxxxh
  21911   CX(EA)     CX(EA)     CX(EA0000) SpindleMotorReverse
  21912   -          -          CX(EAcrap) <-- aka bugged CX(EA) with CRAP=xxxxh
  21913   CX(EE)     CX(EE)     CX(EE0000) RoughServo
  21914   -----
  21915   CX(F)      CX(F)      CX(F)      Unused (N/A)
  21916   -----
  21917   CX(Xx)     CX(Xx)     CX(Xx)       ;\
  21918   CX(Xxxx)   CX(Xxxx)   CX(Xxxx)     ; TestCommand (cmd_19h_50h)
  21919   CX(Xxxxxx) CX(Xxxxxx) CX(Xxxxxx)   ;
  21920   -          -          CX(Xxxxxxxx) ;/
  21921   -          CX(Xxxxxx) CX(Xxxxxx) SerialSense, CX(Xxxx) with extra 8bit junk
  21922 Note: for vC2, some CX(38xxxx) values may differ depending on
  21923 "set_mid_lsb_to_140Eh".
  21924 For vC2, CX(Dx) and CX(Ex) should be officially zero-padded to CX(Dx00) and
  21925 CX(Ex00), but the vC2 BIOS doesn't do that, it still uses short 8bit form.
  21926 For vC2, CX(Dx) and CX(Ex) should be apparently zero-padded to CX(Dx0000) and
  21927 CX(Ex0000), at least, the vC3 BIOS is doing so (except on some test comannds
  21928 that do still use the CX(Ex) short form).
  21929 
  21930 Used Sense Values
  21931   sense(30)  SEIN.BAL       ;vC2: SSTP
  21932   sense(38)  SEIN.GAIN      ;vC2: AGOK(AGT/AGF) or XAVEBSY(AVRG) or SSTP(else?)
  21933   sense(40)  XBUSY (low=AutoSeqBusy)
  21934   sense(50)  FOK   (high=FokusOkay)
  21935   sense(A0)  GFS   (high=GoodFrameSync, ie. CorrectPlaybackSpeed)
  21936   sense(C5)  COUT  (toggles each 100h 'tracks') (100h=selected via CX(B01000))
  21937   sense(EA)  /OV64 (low=EFM too long?)
  21938 
  21939 CDROM Internal Coefficients (for CXD2545Q)
  21940 ------------------------------------------
  21941 
  21942 The CXD2545Q contains Preset Coefficients in internal ROM, which are copied to
  21943 internal Coefficient RAM shortly after Reset. CX(34xxxx) allows to change those
  21944 RAM settings, and CX(39xxxx) allows to readout some of those values serially.
  21945 
  21946 CXD2545Q - Coefficient Preset Values
  21947   Addr Val Expl.
  21948   K00  E0  Sled input gain
  21949   K01  81  Sled low boost filter A-H
  21950   K02  23  Sled low boost filter A-L
  21951   K03  7F  Sled low boost filter B-H
  21952   K04  6A  Sled low boost filter B-L
  21953   K05  10  Sled output gain
  21954   K06  14  Focus input gain
  21955   K07  30  Sled auto gain
  21956   K08  7F  Focus high cut filter A
  21957   K09  46  Focus high cut filter B
  21958   K0A  81  Focus low boost filter A-H
  21959   K0B  1C  Focus low boost filter A-L
  21960   K0C  7F  Focus low boost filter B-H
  21961   K0D  58  Focus low boost filter B-L
  21962   K0E  82  Focus phase compensate filter A
  21963   K0F  7F  Focus defect hold gain
  21964   K10  4E  Focus phase compensate filter B
  21965   K11  32  Focus output gain
  21966   K12  20  Anti shock input gain
  21967   K13  30  Focus auto gain
  21968   K14  80  HPTZC / Auto Gain High pass filter A
  21969   K15  77  HPTZC / Auto Gain High pass filter B
  21970   K16  80  Anti shock high pass filter A
  21971   K17  77  HPTZC / Auto Gain low pass filter B
  21972   K18  00  Fix (should not change this preset value)
  21973   K19  F1  Tracking input gain
  21974   K1A  7F  Tracking high cut filter A
  21975   K1B  3B  Tracking high cut filter B
  21976   K1C  81  Tracking low boost filter A-H
  21977   K1D  44  Tracking low boost filter A-L
  21978   K1E  7F  Tracking low boost filter B-H
  21979   K1F  5E  Tracking low boost filter B-L
  21980   K20  82  Tracking phase compensate filter A
  21981   K21  44  Tracking phase compensate filter B
  21982   K22  18  Tracking output gain
  21983   K23  30  Tracking auto gain
  21984   K24  7F  Focus gain down high cut filter A
  21985   K25  46  Focus gain down high cut filter B
  21986   K26  81  Focus gain down low boost filter A-H
  21987   K27  3A  Focus gain down low boost filter A-L
  21988   K28  7F  Focus gain down low boost filter B-H
  21989   K29  66  Focus gain down low boost filter B-L
  21990   K2A  82  Focus gain down phase compensate filter A
  21991   K2B  44  Focus gain down defect hold gain
  21992   K2C  4E  Focus gain down phase compensate filter B
  21993   K2D  1B  Focus gain down output gain
  21994   K2E  00  Not used
  21995   K2F  00  Not used
  21996   K30  80  Fix (should not change this preset value)
  21997   K31  66  Anti shock low pass filter B
  21998   K32  00  Not used
  21999   K33  7F  Anti shock high pass filter B-H
  22000   K34  6E  Anti shock high pass filter B-L
  22001   K35  20  Anti shock filter comparate gain
  22002   K36  7F  Tracking gain up2 high cut filter A
  22003   K37  3B  Tracking gain up2 high cut filter B
  22004   K38  80  Tracking gain up2 low boost filter A-H
  22005   K39  44  Tracking gain up2 low boost filter A-L
  22006   K3A  7F  Tracking gain up2 low boost filter B-H
  22007   K3B  77  Tracking gain up2 low boost filter B-L
  22008   K3C  86  Tracking gain up phase compensate filter A
  22009   K3D  0D  Tracking gain up phase compensate filter B
  22010   K3E  57  Tracking gain up output gain
  22011   K3F  00  Not used
  22012   K40  04  Tracking hold filter input gain
  22013   K41  7F  Tracking hold filter A-H
  22014   K42  7F  Tracking hold filter A-L
  22015   K43  79  Tracking hold filter B-H
  22016   K44  17  Tracking hold filter B-L
  22017   K45  6D  Tracking hold filter output gain
  22018   K46  00  Not used
  22019   K47  00  Not used
  22020   K48  02  Focus hold filter input gain
  22021   K49  7F  Focus hold filter A-H
  22022   K4A  7F  Focus hold filter A-L
  22023   K4B  79  Focus hold filter B-H
  22024   K4C  17  Focus hold filter B-L
  22025   K4D  54  Focus hold filter output gain
  22026   K4E  00  Not used
  22027   K4F  00  Not used
  22028 
  22029 CDROM Video CDs (VCD)
  22030 ---------------------
  22031 
  22032 VCDs are Video CDs with MPEG compression, yielding a playtime of 72 minutes per
  22033 disc (whole movies usually being stored on two CDs). VCDs are popular in asia
  22034 (as opposed to VHS tapes used in western world).
  22035 
  22036 VCDs on Playstation
  22037 For the Playstation, the asian SCPH-5903 model includes a special daughterboard
  22038 with MPEG decoding hardware for playing VCDs.
  22039 --> CDROM - Video CD Commands
  22040 --> Pinouts - VCD Pinouts
  22041 Without that hardware it has been widely believed to be impossible to play VCDs
  22042 on Playstations, although, as of 2017, it turned out that the Playstation's CPU
  22043 and MDEC decoder are fast enough for that purpose (when skipping B-frames,
  22044 rendering the movie in monochrome without colors, and reducing audio output to
  22045 11kHz/mono).
  22046 
  22047 ISO Filesystem (Track 1)
  22048 --> VCD ISO Basic Files (INFO, ENTRIES, AVSEQnn, ISO Filesystem)
  22049 --> VCD ISO Playback Control PBC Files (PSD, LOT, ITEMnnnn)
  22050 --> VCD ISO Search Files (SCANDATA, SEARCH, TRACKS, SPICONTX)
  22051 --> VCD ISO Misc files (CAPTnn, AUDIOnn, KARINFO, PICTURES, CDI)
  22052 
  22053 MPEG Streams (Track 2 and up)
  22054 --> VCD MPEG-1 Multiplex Stream
  22055 --> VCD MPEG-1 Video Stream
  22056 XXX MPEG-1 Macroblocks
  22057 --> VCD MP2 Audio Stream
  22058 
  22059 VCD Versions & Variants
  22060 XXX
  22061 
  22062 VCD ISO Basic Files (INFO, ENTRIES, AVSEQnn, ISO Filesystem)
  22063 ------------------------------------------------------------
  22064 
  22065 Primary Volume Descriptor (00:02:16)
  22066 VCDs are having a standard ISO Primary Volume Descriptor, with some VCD
  22067 specific entries:
  22068   008h 32  System Identifier (always "CD-RTOS CD-BRIDGE" for VCDs)
  22069   028h 32  Volume Identifier (often nonsense, eg. "" or "__" or "VolumeLabel")
  22070   23Eh 128 Application Identifier ("CDI/CDI_APPL.VCD;1" or "CDI/CDI_VCD.APP;1")
  22071   400h 8   CD-XA Identifying Signature ("CD-XA001" for PSX and VCD)
  22072 There are some more differences to normal CDROMs:
  22073   VCDs are using MODE2 (with 800h-byte and 914h-byte sectors)
  22074   MPEG videos are on extra data tracks (outside of the ISO area on Track 1)
  22075   Files in VCD or SVCD folders use fixed sectors numbers (00:04:00 and up)
  22076   All 16bit/32bit values in files in VCD,SVCD,EXT,etc are BIG-ENDIAN
  22077 Due to the fixed sector numbers, VCDs players can completely ignore the ISO
  22078 filesystem with filenames and folders, and just address everything via sector
  22079 numbers (though accessing files in EXT and CDI folders seem to require using
  22080 the filesystem).
  22081 
  22082 VCD\INFO.VCD or SVCD\INFO.SVD (00:04:00) (800h bytes, one sector)
  22083   000h 8    ID "VIDEO_CD" for VCD (or "SUPERVCD"/"HQ-VCD  " for SVCD)
  22084   008h 1    Version             ;Version Major (01h) (or 02h for VCD 2.0)
  22085   009h 1    System Profile Tag  ;Version Minor (00h) (or 01h for VCD 1.1 or HQ)
  22086   00Ah 16   Album ID/Desc (name in ASCII, padded with SPC) (usually empty)
  22087   01Ah 2    Total Number of CDs in Album (1..N) ;\usually always 1,1 (even
  22088   01Ch 2    Number of this CD in Album   (1..N) ;/for movies with 2 discs)
  22089   01Eh 13   PAL Flags, 98x1bit, for each Track? (0=NTSC, 1=PAL)
  22090   02Bh 1    InfoStatusFlags (see below)
  22091  Below is usually zero-filled when not using PBC
  22092   02Ch 4    Size of PSD.VCD file (or PSD.SVD?) (0=None)
  22093   030h 3    First segment addr MM:SS:00 in BCD    (00:02:00 ???)
  22094   033h 1    Offset Multiplier for "PsdOffset" values in PSD.VCD (must be 8)
  22095   034h 2    Number of ListIDs in LOT.VCD file (1..7FFFh, plus 1 in some discs)
  22096   036h 2    Number of ITEMnnnn.DAT files (plus nonsense in some discs?)
  22097  Below is usually zero-filled (maybe exists on SVCD only?)
  22098   038h 1980 SegmentContent[1..1980] (b0-1=Audio, b2-4=Video, b5=Cont, b6-7=OGT)
  22099   7F4h 5*2  volume start time[0]: 5x16bit  ;aka playing_time[5] in seconds (?)
  22100   7FEh 2    Reserved (0)
  22101 InfoStatusFlags at [02Bh] describes certain characteristics of the disc:
  22102   bit0   Reserved, must be zero
  22103   bit1-2 Restriction (0=No, 1..3=Restricted category 1..3) (eg. "not for kids")
  22104   bit3   Special Information is encoded in the pictures, uh?
  22105   bit4   MPEG User Data is used for Closed Caption (user_data_cc) (0=No, 1=Yes)
  22106   bit5   Next Disc with PBC     (0=Start at ListID#1, 1=Start at ListID#2)
  22107   bit6   Next Disc without PBC  (0=Start at Track #2, 1=Start at Track #3)
  22108   bit7   Extended PBC available (0=No, 1=Yes... aka EXT\PSD_X exists?)
  22109 Note: Bit5/6 are used only if the next disc has the same Album ID (eg. the
  22110 feature allows to skip copyright messages if the same message was already shown
  22111 on another disc).
  22112 First_segment_addr: The location of the first sector of the Segment Play Item
  22113 Area [that is... the first ITEMnnnn.DAT file?], in the form mm:ss:00. Must be
  22114 00:00:00 if PSD size is zero. If PSD size is nonzero, but no segments used:
  22115 Usually set to 00:02:00.
  22116 
  22117 VCD\ENTRIES.VCD or SVCD\ENTRIES.SVD (00:04:01) (800h bytes, one sector)
  22118   000h 8     ID "ENTRYVCD" for VCD and SVCD (or "ENTRYSVD" for VCD30)
  22119   008h 1     Version               ;\same as in INFO.VCD/SVD
  22120   009h 1     System Profile Tag    ;/
  22121   00Ah 2     Number of Entries/Chapters (1..500)
  22122   00Ch 4*500 Entry[N] (Track 02h..99h, and MM:SS:FF) (all 4 bytes in BCD)
  22123   7DCh 36    Reserved (0)
  22124 Version;
  22125   0x02 --- VCD2.0
  22126   0x01 --- SVCD, should be same as version in INFO.SVD
  22127 Sys_prof_tag;
  22128   0x01 if VCD1.1
  22129   0x00 else
  22130 
  22131 MPEGAV\AVSEQnn.DAT (pointers to max 98 MPEG-1 Tracks, nn=01..98) (for VCDs)
  22132 MPEG2\AVSEQnn.MPG (pointers to max 98 MPEG-2 Tracks, nn=01..98) (for SVCDs)
  22133 MPEGAV\AVSEQnn.MPG (pointers to WHATEVER) (as so on some SVCDs or VCD30?)
  22134 These filesystem entries contain pointers to the video tracks (that is, outside
  22135 of the ISO area on Track 1).
  22136 Commercially made SVCDs can reportedly contain 7 folders: Autorun, Data, Ext,
  22137 Mpegav, Segment, Svcd and Vmp (ie. there's no MPEG2 folder on all SVCDs? though
  22138 that MPEGAV folder is said to contain a .MPG file instead of .DAT file).
  22139 
  22140 VCD ISO Playback Control PBC Files (PSD, LOT, ITEMnnnn)
  22141 -------------------------------------------------------
  22142 
  22143 Playback Control (PBC) is an optional feature that allows to define menues,
  22144 pictures or text pages (whereas all those is internally just consisting of MPEG
  22145 compressed bitmaps; rather than of text characters).
  22146 Presence of the PBC feature is indicated by PSD.VCD filesize entry (in
  22147 INFO.VCD) being nonzero. PBC seems to be supported by most VCDs (except older
  22148 discs from around 1997), however, many VCDs are merely including a single
  22149 PlayList entry for the movie track, without any further menues/extras.
  22150 
  22151 VCD\PSD.VCD or SVCD\PSD.SVD (00:04:34 and up) (max 256 sectors)
  22152 The Descriptors in this file can be considered as being "program code". The
  22153 program is usually stuck on "executing" the current descriptor (eg. playing a
  22154 movie, or showing a selection menu) without automatically increasing the
  22155 program counter. Actual program flow occurs only if the user presses a button
  22156 (or upon selection timeouts), causing the program to "goto" to a new PsdOffset.
  22157 And, something does probably happen upon end-of-track/item... maybe that does
  22158 automatically trigger the Next button handler?
  22159  PsdPlayListDescriptor (14+2*N bytes):
  22160   00h 1   Type (10h=PlayList)
  22161   01h 1   Number of Items (noi)     ;for Start-of-Movie and Numeric-Input?
  22162   02h 2   ListID for this Descriptor (1..7FFFh)
  22163   04h 2   PsdOffset for Prev button                 (FFFFh=Disable)
  22164   06h 2   PsdOffset for Next button                 (FFFFh=Disable)
  22165   08h 2   PsdOffset for Return/back button          (FFFFh=Disable)
  22166   0Ah 2   Play time in 1/15s (=max 72.8 minutes) (or 0000h=full item)
  22167   0Ch 1   Delay time in "1s/10s" units after ;<-- uh, after? after what?
  22168   0Dh 1   Auto pause time in "1s/10s" units (used for each item in list if
  22169           the auto pause flag in a sector is true) [WHAT is that? Trigger bit?]
  22170   0Eh 2*N ItemID[N]  ;item number (0..599 or 1000..2979)
  22171           Entry 0 is for "start of movie" (usually 0002h=Track 2)
  22172           Entry 1..N-1 is for numeric input ?
  22173  PsdSelectionListDescriptor (20+2*N bytes, or 36+6*N bytes):
  22174   00h      1   Type (18h=SELECTION_LIST, or 1Ah=EXT_SELECTION_LIST)
  22175   01h      1   Flags (bit0=SelectionArea, bit1=CommandList, bit2-7=Reserved)
  22176   02h      1   nos     <-- aka Number of Numeric-input selections ?
  22177   03h      1   bsn     <-- ?
  22178   04h      2   ListID for this Descriptor (1..7FFFh)
  22179   06h      2   PsdOffset for Prev button
  22180   08h      2   PsdOffset for Next button
  22181   0Ah      2   PsdOffset for Return/back button
  22182   0Ch      2   PsdOffset for Default button (uh, what is that?)
  22183   0Eh      2   PsdOffset for Timeout
  22184   10h      1   totime  <-- aka Timeout Time maybe? in WHAT units?
  22185   11h      1   loop    <-- aka ?
  22186   12h      2   itemid  <-- aka Item to be displayed during the selection?
  22187   14h      2*N PsdOffset[N] for Numeric-input ?
  22188  Below only for SVCDs (with Type=18h), or for Extended VCDs (with Type=1Ah):
  22189  (14h+2*N) 4   Area for Prev    (x1,y1,x2,y2)  ;\these extra entries exist for
  22190  (18h+2*N) 4   Area for Next    (x1,y1,x2,y2)  ; SVCDs with Type=18h, and
  22191  (1Ch+2*N) 4   Area for Return  (x1,y1,x2,y2)  ; Extended VCDs with Type=1Ah
  22192  (20h+2*N) 4   Area for Default (x1,y1,x2,y2)  ; (but do NOT exist for
  22193  (24h+2*N) 4*N Area[N]          (x1,y1,x2,y2)  ;/older VCDs with Type=18h)
  22194  PsdEndListDescriptor (8 bytes)
  22195   00h 1     Type (1Fh=EndList)
  22196   01h 1     Next_disc   ;00h to stop PBC or NNh to switch to disc no NN (BCD!?)
  22197   02h 2     Item (0 or 1000..2979, should be still image, eg. Change Disc pic)
  22198   04h 4     Reserved (0)
  22199   N/A -     This descriptor doesn't have a ListID (unlike as other descriptors)
  22200  PsdCommandListDescriptor (5+2*N bytes)
  22201   00h 1     Type (20h=CommandList)
  22202   01h 2     Command_count
  22203   03h 2     ListID for this Descriptor (1..7FFFh)
  22204   05h 2*N   command[EMPTY_ARRAY_SIZE]  ;uh, WHAT is a command?
  22205  PsdAlignmentPadding (after each list entry)
  22206   00h 0..7  Padding to next 8-byte PsdOffset boundary (00h-filled)
  22207 Delay values in "1s/10s" units (for PlayList[0Ch,0Dh]):
  22208   1..60   --> wait "N" seconds
  22209   61..254 --> wait "(N-60)*10+60" seconds
  22210   255     --> wait infinite
  22211 Item numbers (0..599 or 1000..2979) can be:
  22212   0..1        - Play nothing
  22213   2..99       - Play Track 2..99 (TOC tracks, for AVSEQnn.DAT and AUDIOnn.DAT?)
  22214   100..599    - Play Entry 1..500 from table in ENTRIES file up to end of track
  22215   600..999    - Reserved
  22216   1000..2979  - Play SPI Segment Play Item 1..1980 (ITEMnnnn.DAT file)
  22217   2980..65535 - Reserved
  22218 PsdOffset values can be:
  22219   0..N   Offset within PSD.VCD file, in 8-byte units
  22220   FFFDh  PSD_OFS_MULTI_DEF_NO_NUM ;\uh, what is that?
  22221   FFFEh  PSD_OFS_MULTI_DEF        ;/
  22222   FFFFh  PSD_OFS_DISABLED         ;-no function assigned to the button
  22223 For whatever reason, some PsdOffsets are specified as ListID (lid), these
  22224 ListID values must be translated to actual PsdOffset via the ListID Offset
  22225 Table (aka LOT.VCD/LOT.SVD file).
  22226 
  22227 VCD\LOT.VCD or SVCD\LOT.SVD (00:04:02..33) (64Kbyte, 32 sectors)
  22228 The ListID Offset Table (LOT) allows to translate ListIDs to PsdOffsets. The
  22229 file is always 64Kbyte in size (unused entries should be set to FFFFh).
  22230 The PSD.VCD file does also assign ListIDs to each descriptor (ie. instead of
  22231 using the LOT.VCD file, one could also scan all descriptors in PSD.VCD when
  22232 searching a specific ListID).
  22233   0000h 2       Reserved (0)
  22234   0002h 2*7FFFh PsdOffset[1..7FFFh]  ;for ListID 1..7FFFh
  22235 Note: ListID#1 is used as entrypoint to PSD.VCD when inserting a new disc (or
  22236 when inserting another disc of the SAME movie, the entrypoint can be ListID#2,
  22237 depending on the Next Disc flag in INFO.VCD).
  22238 
  22239 SEGMENT\ITEMnnnn.DAT (Pictures, Menu screens) (nnnn=0001..1980)
  22240 These files contain Pictures/Menu screens referenced from PSD.VCD. The files
  22241 seem to be stored in FORM2 sectors (not FORM1). Unknown if the files are
  22242 located on Track 1.
  22243 The content of the files seems to resemble short MPEG video clips (with only
  22244 one picture frame, or eventually with a few frames for short animations,
  22245 including audio in some cases). Still images are said to be allowed to use
  22246 twice the resolution of MPEG videos.
  22247 
  22248 EXT\PSD_X.VCD or EXT\PSD_X.SVD (extended version of PSD.VCD)
  22249 EXT\LOT_X.VCD or EXT\LOT_X.SVD (extended version of LOT.VCD)
  22250 The "extended" files are often identical to the normal PSD/LOT files. The
  22251 difference is that, if disc uses SelectionLists, then PSD should use the normal
  22252 descriptor (18h), and PSD_X should use the extended descriptor (1Ah), the
  22253 latter one seems to be intended to allow to highlight the current menu
  22254 selection (particulary useful when using +/- buttons instead of Numeric Keypad
  22255 input). Note: Nethertheless, Muppets from Space uses descriptor 18h in PSD_X.
  22256 Unknown if SVCDs do really have "extended" files, too (theoretically the VCD
  22257 extension should be a default feature for SVCDs).
  22258 
  22259 Playback Control Issues
  22260 Although PBC was intended as "nice extra feature", many VCDs are containing
  22261 faulty PSD files. In general, VCD players should either leave PBC unsupported
  22262 (or at the very least, provide an option for disabling it).
  22263 Red Dragon from 2003 uses extended selection lists, but crops PSD_X.VCD to the
  22264 same filesize as PSD.VCD.
  22265 Muppets from Space from 1999 assigns weird functions to Prev/Next buttons (Next
  22266 wraps from Last Track to First Track, but Prev doesn't wrap from First to Last;
  22267 default Non-PBC Prev/Next functions are more user friendly).
  22268 Sony's SCPH-5903 console refuses to display the HH:MM:SS playback time when
  22269 using PBC (instead it does only display a "PBC" logo).
  22270 
  22271 VCD ISO Search Files (SCANDATA, SEARCH, TRACKS, SPICONTX)
  22272 ---------------------------------------------------------
  22273 
  22274 Below files can help searching I-frames, and provide some info about the
  22275 content of Tracks and Segments.
  22276 Essentially, searching I-frames is possible without these files - however, if
  22277 present, then the files may be useful in two cases: For discs with variable
  22278 bitrates (which isn't allowed on VCDs though), and, for CDROM firmwares that
  22279 don't support "inaccurate" seeking (like telling it to start reading anywhere
  22280 NEAR some MM:SS:FF value, so one could skip sectors till reaching an I-frame)
  22281 (ie. if the firmware insists on a "accurate" seek position, then it's best to
  22282 give it a known I-frame address).
  22283 
  22284 Caution: Overlapping Sectors (!?!)
  22285 Reportedly the new SVCD files TRACKS.SVD and SEARCH.DAT are on these sectors:
  22286   TRACKS_SVD_SECTOR = (PSD_VCD_SECTOR+1)    ;aka 2nd sector in PSD.SVD?
  22287   SEARCH_DAT_SECTOR = (TRACKS_SVD_SECTOR+1) ;aka 3rd..Nth sector in PSD.SVD?
  22288 If that's correct, then the files would overlap with PSD.SVD (when PSD.SVD is
  22289 bigger than one sector), that would be weird, but possible (ie. the "PsdOffset"
  22290 in PSD.SVD would need to "skip" the region used by those two files).
  22291 
  22292 EXT\SCANDATA.DAT (12+3*N bytes for VCD 2.0) (or 16+3*N+2*X+3*Y+3*Z for SVCD)
  22293 This file fulfills much the same purpose of the SEARCH.DAT file except that
  22294 this file is mandatory only if the System Profile Tag of the INFO.SVD file is
  22295 0x01 (HQ-VCD) and also that it contains sector addresses also for each video
  22296 Segment Play Items in addition to the regular MPEG tracks.
  22297  SCANDATA.DAT Format for VCD 2.0 (12+3*N bytes):
  22298   000h 8    ID "SCAN_VCD"
  22299   008h 1    Version (02h for VCD 2.0)
  22300   009h 1    Reserved (0)
  22301   00Ah 2    Number of scan points (in 0.5s units) (max FFFFh = ca. 9.1 hours)
  22302   00Ch 3*N  Scan Point[0..N-1]  ;MM:SS:FF of closest I-frame
  22303  SCANDATA.DAT Format for SVCD (16+3*N+2*X+3*Y+3*Z bytes):
  22304   000h 8    ID "SCAN_VCD"
  22305   008h 1    Version (01h for SVCD)
  22306   009h 1    Reserved (0)
  22307   00Ah 2    scandata_count ;number of 3-byte entries in the table
  22308   00Ch 2    track_count    ;number of MPEG tracks on disc
  22309   00Eh 2    spi_count      ;number of consecutively recorded play item segments
  22310                            ; (as opposed to the number of segment play items).
  22311   010h 3*N  msf_t cum_playtimes[N]  ;cumulative playing time up to track N.
  22312                                     ; (track time just wraps at 99:59:74)
  22313   xxxh 2*X  spi_indexes[X]          ;Indexes into the following scandata table
  22314   xxxh 2    mpegtrack_start_index   ;Index into the following scandata table
  22315                                     ; (where the MPEG track scan points start)
  22316   xxxh 3*Y  The scandata table... [Y]  ;8bit Track Number and 16bit Index
  22317                 uint8_t  track_num;      /* Track number as in TOC
  22318                 uint16_t table_offset;   /* Index into scandata table
  22319   xxxh 3*Z  msf_t scandata_table[Z]  ;MM:SS:FF
  22320 
  22321 SVCD\SEARCH.DAT (13+3*N bytes)
  22322 This file defines where the scan points are. It covers all mpeg tracks
  22323 together. A scan point at time T is the nearest I-picture in the MPEG stream to
  22324 the given time T. Scan points are given at every half-second for the entire
  22325 duration of the disc.
  22326   000h 8    ID "SEARCHSV"
  22327   008h 1    Version (01h)
  22328   009h 1    Reserved (0)
  22329   00Ah 2    Number of scan points
  22330   00Ch 1    Time_interval (in units of 0.5 seconds) (must be 01h)
  22331   00Dh 3*N  Scan Point[0..N-1]  ;MM:SS:FF of closest I-frame
  22332 Note: This SVCD file is about same as the old EXT\SCANDATA.DAT file on VCDs
  22333 (with one extra entry for Time Interval). Whilst, SVCDs are storing some
  22334 different stuff in EXT\SCANDATA.DAT (despite of the identical filename).
  22335 
  22336 SVCD\TRACKS.SVD (11+4*N bytes) (or rarely:11+5*N bytes)
  22337 The TRACKS.SVD file contains a series of structures, one for each track, which
  22338 indicates the track's playing time (in sectors, not actually real time) and
  22339 contents.
  22340 SVCD\TRACKS.SVD is a mandatory file which describes the numbers and types of
  22341 MPEG tracks on the disc.
  22342  SVCD\TRACKS.SVD Format for SVCD (11+4*N bytes):
  22343   000h 8   ID "TRACKSVD"
  22344   008h 1   Version (01h)
  22345   009h 1   Reserved (0)
  22346   00Ah 1   Number of MPEG tracks (N)
  22347   00Bh 3*N Track playing_time[N]  (MM:SS:FF, in BCD)(in sectors, not real time)
  22348   0xxh 1*N TrackContent[N]  ;bit0-1=Audio,bit2-4=Video,bit5=Reserved,bit6-7=OGT
  22349  SVCD\TRACKS.SVD Format for VCD30 (11+5*N bytes) (some sort of SVCD-prototype):
  22350   000h 8   ID "TRACKSVD"
  22351   008h 1   Version (01h)
  22352   009h 1   Reserved (0)
  22353   00Ah 1   Number of MPEG tracks (N)
  22354   00Bh 5*N Cum_Playing_time and Content (MM:SS:FF in BCD, and OGT, Audio)
  22355 
  22356 SVCD\SPICONTX.SVD (1000h bytes, two sectors)
  22357 Unknown if/when/where/why this file exists, possibly only on VCD30?
  22358 Note: The same info can be stored in INFO.SVD at offsets [038h..7F3h].
  22359   0000h 8       ID "SPICONSV"
  22360   0008h 1       Version (01h)
  22361   0009h 1       Reserved (0)
  22362   000Ah 2*1980  Segment Content[1..1980] (1st byte=OGT, 2nd byte=Audio)
  22363   0F82h 126     Reserved (0)
  22364 
  22365 Content Flags for Segments and Tracks
  22366 For SVCD\INFO.SVD and SVCD\TRACKS.SVD (on SVCD) these are encoded in 1 byte:
  22367   bit0-1  Audio characteristics:
  22368             0 = No MPEG audio stream
  22369             1 = One MPEG1 or MPEG2 audio stream without extension
  22370             2 = Two MPEG1 or MPEG2 audio streams without extension
  22371             3 = One MPEG2 multi-channel audio stream with extension
  22372   bit2-4  Video characteristics:
  22373             In TRACKS.SVD this must be 0,3,7 (no still pictures)
  22374             0 = No MPEG video data
  22375             1 = NTSC still picture
  22376             2 = NTSC Reserved (NTSC still pic hires?)
  22377             3 = NTSC motion picture
  22378             4 = Reserved
  22379             5 = PAL still picture
  22380             6 = PAL Reserved (PAL still pic hires?)
  22381             7 = PAL motion picture
  22382   bit5    Indicates segment is continuation of an item
  22383             In TRACKS.SVD this must be 0 (reserved)
  22384             0 = First or only segment of item
  22385             1 = Second or later segment of item
  22386   bit6-7  Overlay Graphics/Text (OGT):
  22387             0 = No OGT substream
  22388             1 = Sub-stream 0 available
  22389             2 = Sub-stream 0 & 1 available
  22390             3 = All OGT sub-substreams available
  22391 For SPICONTX.SVD and SVCD\TRACKS.SVD (on VCD30) these are encoded in 2 bytes:
  22392   1st byte = Audio characteristics        ;\probably same values as
  22393   2nd byte = Overlay Graphics/Text (OGT)  ;/in above bitfields?
  22394 
  22395 VCD ISO Misc files (CAPTnn, AUDIOnn, KARINFO, PICTURES, CDI)
  22396 ------------------------------------------------------------
  22397 
  22398 EXT\CAPTnn.DAT (Closed Caption data, aka subtitles) (SVCD only?)
  22399 VCDs with subtitles are usually/always having the subtitles encoded directly in
  22400 the picture frames (ie. in the MPEG macroblocks, rather than using the Closed
  22401 Caption feature).
  22402 These CAPTnn.DAT files are intended for Closed Captions (eg. subtitles in
  22403 different languages and/or for deaf people).
  22404 Alternately, the "user_data_cc" flag in INFO.VCD?/INFO.SVD can indicate to
  22405 store Closed Captions in MPEG User Data (with START_CODE=000001B2h=User Data)
  22406 instead of in EXT\CAPTnn.DAT. Either way, the format of those Closed Captions
  22407 is unknown.
  22408 Moreover, Content can be flagged to have Overlay Graphics/Text (OGT), whatever
  22409 that is: it might be related to Closed Captions.
  22410 Note: Reportedly CAPTnn.DAT can exist on VCDs and SVCDs (although the same
  22411 person reported that VCDs do not support subtitles, so that info sounds wrong).
  22412 
  22413 CDDA\AUDIOnn.DAT (pointers to uncompressed CD Audio Tracks)
  22414 These filesystem entries contain pointers to uncompressed audio tracks tracks
  22415 (that is, outside of the ISO area on Track 1).
  22416 Most VCDs don't have audio tracks (though some VCDs do contain empty CDDA
  22417 folders).
  22418 Maybe the feature is occassionally used the other way around: Music discs
  22419 containing VCD clips as bonus feature?
  22420 
  22421 KARAOKE\KARINFO.xxx (whatever)
  22422 The KARAOKE folder exists on many VCDs (about 50%), but it's usually/always
  22423 empty on all discs.
  22424 Reportedly the folder can contain "KARINFO.xxx" files, but the purpose/format
  22425 of that files is unknown.
  22426 Reportedly there are Midi VCDs (MVCDs) for karaoke, maybe those discs have
  22427 "KARINFO.xxx" files(?)
  22428 
  22429 PICTURES\*.* (whatever)
  22430 Unknown purpose. The PICTURES folder has been spotted on one VCD (Wallace and
  22431 Gromit), but the folder was just empty.
  22432 
  22433 CDI\*.* (some kind of GUI/driver for Philips CDI Players)
  22434 The CDI folder is some relict for Philips CDI Players, it isn't used by normal
  22435 VCD players, however, the CDI folder & files are included on most or all VCDs.
  22436 The path/name for the CDI executable is stored at offset 23Eh in the ISO
  22437 Primary Volume Descriptor (usually "CDI/CDI_APPL.VCD;1" or "CDI/CDI_VCD.APP;1")
  22438 (or accidentally "CDI_CDI_VCD.APP;1" on homebrew Nero discs).
  22439 The files in the CDI folder are usually just some standard files (without any
  22440 customizations), however, there are some different revisions of these files:
  22441  Revision A (spotted on two discs from 1997 and 1999):
  22442   CDI_APPL.VCD   80702 bytes, 04-Mar-1996, CRC32=AE8FC5D0h  ;executable
  22443   VCD_BACK.DYV   92572 bytes, 18-Jul-1995, CRC32=00693E5Eh  ;whatever?
  22444   VCD_BTN.C8     93719 bytes, 18-Jul-1995, CRC32=FF0A636Ah  ;whatever?
  22445  Revision B (spotted on a disc from 2003):
  22446   CDI_VCD.APP    20648 bytes, 00-Nul-0000  CRC32=DC885F70h  ;executable
  22447   CDI_FONT.FNT  145388 bytes, 00-Nul-0000  CRC32=FB4D63F4h  ;font?
  22448   CDI_ALL.RTF        ? bytes,              CRC32=?          ;realtimefile?
  22449   CDI_BUM.RTF        ? bytes,              CRC32=?          ;realtimefile?
  22450  Revision C (spotted on a disc from 2006, and homebrews from 2001 and 2017):
  22451   CDI_VCD.APP   102400 bytes, 00-Nul-0000  CRC32=E91E128Dh  ;executable
  22452   CDI_VCD.CFG      193 bytes, 00-Nul-0000  CRC32=D1C6F7ADh  ;config/ascii
  22453   CDI_TEXT.FNT   13616 bytes, 00-Nul-0000  CRC32=BDC55E86h  ;font?
  22454   CDI_IMAG.RTF 1510028 bytes, 00-Nul-0000  CRC32=(RIFF)     ;realtimefile?
  22455 CDI_VCD.CFG is some ASCII text file (with uncommon 0Dh,0Dh,0Ah line breaks),
  22456 the file could be customized to change things like GUI colors, but most or all
  22457 discs seem to contain the same file with CRC32=D1C6F7ADh. Note: The CFG file is
  22458 missing on the homebrew DemoVCD.
  22459 CDI_IMAG.RTF is seen as 1510028 byte file under windows (that is, with a
  22460 windows RIFF header, and with data area containing the whole 930h bytes from
  22461 each sector; this includes the MM:SS:FF values from the sector header, so the
  22462 RTF file may look slightly different depending on which sectors it has been
  22463 stored on, although the files are usually exactly same apart from those
  22464 MM:SS:FF values). Note: The RTF file is cropped to 1324220 bytes (instead of
  22465 1510028) on the homebrew DemoVCD (apart from that, the file is same as normal).
  22466 CDI_ALL.RTF and CDI_BUM.RTF cannot be read/copied under Windows 7 (which is
  22467 weirdly reporting them to use an "invalid MS-DOS function"; some people also
  22468 reported having CDI_IMAG.RTF files with similar problems). The reason is
  22469 unknown, maybe windows doesn't fully support the CD filesystem, or some VCDs
  22470 are violating the filesystem specs, or whatever... maybe windows is
  22471 mis-identifying certain RTF files as Rich Text Format files and tries to
  22472 prevent virus-infections by throwing a faked "MS-DOS" error message.
  22473 
  22474 VCD MPEG-1 Multiplex Stream
  22475 ---------------------------
  22476 
  22477 Multiplex Stream & Sector Boundaries
  22478 The Multiplex stream is some higher level stream, intended to help to
  22479 distinguish between Audio- and Video-streams (which are enclosed in the
  22480 Multiplex stream). MPEG's are somewhat organized in "sectors", with sector size
  22481 varying for normal .mpg files and VCDs:
  22482   VCD discs   --> Sector Size = 914h bytes (the discs MODE2/FORM2 sector size)
  22483   .mpg files  --> Sector Size = 800h bytes (regardless of physical sector size)
  22484 Sectors are always beginning with a Multiplex Packet (and Multiplex Packets are
  22485 never crossing sector boundaries). If the amount of video data exceeds the
  22486 sector size, then it's split into several Multiplex packets, whereas, that may
  22487 happen anywhere in the video stream (ie. there can be Multiplex Headers
  22488 occurring even in the middle of Video packet).
  22489 
  22490 MPEG-1 Multiplex Pack (sector header) (12 bytes)
  22491 The Pack Header is found at the begin of the stream (on VCDs, it's also found
  22492 at the begin of each sector). The SCR values might help on identifying the
  22493 current playback position, and, with the bitrate value, this could be also used
  22494 to compute the distance to another position (though there are other ways to
  22495 determine the position/bitrate, so the Pack is kinda useless).
  22496  32bit PACK_START_CODE (000001BAh)                                      ;-4byte
  22497   2bit Fixed (00b for MPEG-1) (would be 01b for MPEG-2)                 ;\
  22498   2bit Fixed (10b)                                                      ;
  22499   3bit System Clock Reference, bit32-30  ;\                             ;
  22500   1bit Marker (1)                        ; System Clock Reference (SCR) ;
  22501  15bit System Clock Reference, bit29-15  ; (intended Time,              ; 5byte
  22502   1bit Marker (1)                        ; in 90kHz clock cycles)       ;
  22503  15bit System Clock Reference, bit14-0   ;/                             ;
  22504   1bit Marker (1)                                                       ;/
  22505   1bit Marker (1)                                                       ;\
  22506  22bit Multiplex Rate (total bitrate of the stream, in 400bit/s units)  ; 3byte
  22507   1bit Marker (1)                                                       ;/
  22508 
  22509 MPEG-1 Multiplex System Header (12+N*3 bytes)(optionally)(at start of stream)
  22510 The System Header is usally found after the first Pack at the begin of the
  22511 stream.
  22512  32bit SYSTEM_HEADER_START_CODE (000001BBh)                             ;\6byte
  22513  16bit Header Length minus 6 (in bytes) (0006h+N*3)                     ;/
  22514   1bit Marker (1)                                                       ;\
  22515  22bit Rate bound (max multiplex rate of all packs in the stream,       ; 3byte
  22516   1bit Marker (1)                              in 400bit/s units)       ;/
  22517   6bit Audio Bound (max number of audio streams in this ISO stream)     ;\
  22518   1bit Fixed Flag (1=Fixed bitrate)                                     ; 1byte
  22519   1bit CSPS Flag  (1=Constrained)                                       ;/
  22520   1bit System Audio Lock Flag  XXX                                      ;\
  22521   1bit System Video Lock Flag  XXX                                      ; 1byte
  22522   1bit Marker (1)                                                       ;
  22523   5bit Video Bound (max number of video streams in this ISO stream)     ;/
  22524   8bit Reserved (FFh)                                                   ;-1byte
  22525 Followed by N*3 bytes for the streams (each with first bit=set):
  22526   8bit Stream ID (C0h..DFh=Audio, E0h..EFh=Video)                       ;\
  22527   2bit Fixed (11b)                                                      ; 3byte
  22528   1bit STD buffer scale (0=Mul128/audio, 1=Mul1024/video)               ;
  22529  13bit STD buffer size  (largest required buffer over all packets)      ;/
  22530 Terminated by a value with first bit=cleared (eg. next 000001xxh value).
  22531 
  22532 MPEG-1 Multiplex Video/Audio/Special Packets (7..24 bytes, plus data)
  22533 These packets are encapsulating the lower-level Video/Audio streams.
  22534   32bit  START (000001xxh BDh-BFh=Special, C0h-DFh=Audio, E0h-EFh=Video);\6byte
  22535   16bit  Packet Length minus 6 (in bytes) (1..18, plus data)            ;/
  22536 If (and while) next two bits are 11b (0..16 padding bytes):
  22537   (2bit) Fixed (11b, indicates presence of stuffing)       ;\optional 0..16byte
  22538   (6bit) Fixed (111111b)                                   ;/
  22539 If next two bits are 01b (buffer size info):
  22540   (2bit) Fixed (01b, indicates presence of buffer size)        ;\
  22541   (1bit) STD Buffer Scale (0=Mul128/audio, 1=Mul1024/video)    ; optional 2byte
  22542  (13bit) STD Buffer Size (for decoding, in above scale units)  ;/
  22543 Always:
  22544    2bit  Fixed (00b, indicates no further stuffing/buffer info);\
  22545    1bit  PTS Flag (Presentation Time Stamp)                    ; 0.5 bytes
  22546    1bit  DTS Flag (Decoding Time Stamp)                        ;/
  22547 If PTS Flag set:
  22548   (3bit) Presentation Time Stamp, bit32-30       ;\
  22549   (1bit) Marker (1)                              ; optional 4.5 bytes
  22550  (15bit) Presentation Time Stamp, bit29-15       ; (time when to output the
  22551   (1bit) Marker (1)                              ; the packet to audio/video
  22552  (15bit) Presentation Time Stamp, bit14-0        ; hardware, in 90kHz cycles)
  22553   (1bit) Marker (1)                              ;/
  22554 If DTS Flag set (in this case PTS Flag must be also set):
  22555   (4bit) Fixed (0001b)                           ;\
  22556   (3bit) Decoding Time Stamp, bit32-30           ; optional 5 bytes
  22557   (1bit) Marker (1)                              ; (recommended time when
  22558  (15bit) Decoding Time Stamp, bit29-15           ; to decode the block,
  22559   (1bit) Marker (1)                              ; in 90kHz cycles)
  22560  (15bit) Decoding Time Stamp, bit14-0            ;
  22561   (1bit) Marker (1)                              ;/
  22562 If PTS and DTS Flags are both zero:
  22563   (4bit) Fixed (1111b)                           ;-optional 0.5 bytes
  22564 Always:
  22565   ...  packet data bytes                         ;-data...(not crossing sector)
  22566 Note: The first Multiplex Video Packet would usually start with a Sequence
  22567 Header Code (000001B3h), and the first Multiplex Audio Packet should always
  22568 start with an Audio Sync Word (FFFh).
  22569 However, the size of the Multiplex packets does usually differ from the size of
  22570 the packets in the audio/video stream, so new Multiplex Packets may occur
  22571 anywhere in the middle of those streams (eg. in the middle of a video slice,
  22572 the next Multiplex Video packet would then begin with the remaining slice
  22573 bytes, rather than with a 000001xxh code; it's also possible that a Multiplex
  22574 Audio packet gets inserted in the middle of the video slice).
  22575 The best (or easiest) way to get continous data for the lower level streams
  22576 might be to memcopy the data from Multiplex packets to separate Audio & Video
  22577 buffers.
  22578 
  22579 MPEG-1 Multiplex End Code (4 bytes)
  22580  32bit END_CODE (000001B9h)                                             ;-4byte
  22581 This should occur at the end of the video. On a VCD it does also occur at the
  22582 end of each video track.
  22583 
  22584 VCD MPEG-1 Video Stream
  22585 -----------------------
  22586 
  22587 The Video stream is part of the Multiplex stream, meaning that the Video
  22588 packets preceeded (and interrupted) by Multiplex headers. Ie. before processing
  22589 the Video packets, one must first extract the video snippets from the Multiplex
  22590 stream (see previous chapter).
  22591 
  22592 MPEG-1 Video Sequence Header (12, 76, or 140 bytes, ie. 12+N*64)
  22593   32bit SEQUENCE_HEADER_CODE (000001B3h)                        ;-4byte
  22594   12bit Width in pixels  (1..4095)                              ;\3byte
  22595   12bit Height in pixels (1..2800, for max AFh slices)          ;/
  22596    4bit Aspect Ratio (01h..0Eh, see below)                      ;\1byte
  22597    4bit Framerate    (01h..08h, see below)                      ;/
  22598   18bit Bitrate (in 400bit/s units, 3FFFFh=variable rate)       ;\
  22599    1bit Marker (1)                                              ; 3byte
  22600   10bit VBV (required decoding memory size, in "16 kB" units)   ; +6bit
  22601    1bit Constrained Parameter Flag                              ;/
  22602    1bit Load Intra Q Matrix      (0=No, use Standard Matrix, 1=Yes, Custom)
  22603 Next 64byte only when above bit was set:
  22604  (64byte) Intra Quantizer Matrix (64 x 8bit, unsigned) (in zigzag order)
  22605    1bit Load Non-Intra Q Matrix  (0=No, use Standard Matrix, 1=Yes, Custom)
  22606 Next 64byte only when above bit was set:
  22607  (64byte) Non-Intra Quantizer Matrix (64 x 8bit, unsigned) (in zigzag order)
  22608 Aspect Ratio values:
  22609   0     -       ;forbidden
  22610   1     1.0     ;square pixels
  22611   2     0.6735  ;0.6735
  22612   3     0.7031  ;16:9, 625 line, PAL
  22613   4     0.7615  ;0.7615
  22614   5     0.8055  ;0.8055
  22615   6     0.8437  ;16:9, 525 line, NTSC
  22616   7     0.8935  ;0.8935
  22617   8     0.9157  ;4:3, 625 line, PAL, CCIR601
  22618   9     0.9815  ;0.9815
  22619   10    1.0255  ;1.0255
  22620   11    1.0695  ;1.0695
  22621   12    1.0950  ;4:3, 525 line, NTSC, CCIR601
  22622   13    1.1575  ;1.1575
  22623   14    1.2015  ;1.2015
  22624   15    -       ;reserved
  22625 Frame Rate values:
  22626   0     -                     ;forbidden
  22627   1     23.976 (24000/1001)   ;NTSC encapsulated film rate
  22628   2     24.0                  ;Standard international cinema film rate
  22629   3     25.0                  ;PAL  video frame rate (625/50)
  22630   4     29.97  (30000/1001)   ;NTSC video frame rate
  22631   5     30.0                  ;NTSC video frame rate drop-frame (525/60)
  22632   6     50.0                  ;PAL  double frame rate/progressive
  22633   7     59.94  (60000/1001)   ;NTSC double frame rate
  22634   8     60.0                  ;NTSC double frame rate drop-frame
  22635   9-15  -                     ;reserved
  22636 
  22637 MPEG-1 Video Group of Pictures (GOP) (8 bytes) XXX...
  22638  32bit GROUP_START_CODE (000001B8h)
  22639   1bit Drop Frame (1=drop this frame; for reducing 30 fps to 29.97 fps)
  22640   5bit Time Code Hours   (0..23)
  22641   6bit Time Code Minutes (0..59)
  22642   1bit Marker (1)
  22643   6bit Time Code Seconds (0..59)
  22644   6bit Time Code Picture (0..59)
  22645   1bit Closed GOP
  22646   1bit Broken Link
  22647 
  22648 MPEG-1 Video Picture Header XXX...
  22649   32bit  PICTURE_START_CODE (00000100h)                           ;\
  22650   10bit  Temporal Reference (display order, 0..3FFh)              ; 61bit
  22651    3bit  Coding Type (0=Invalid, 1=I, 2=P, 3=B, 4=D, 5-7=Reserved);
  22652   16bit  VBV Delay (in 90kHz cycles, FFFFh=variable bitrate)      ;/
  22653 If Coding Type is 2 or 3 (P-Frame or B-Frame):
  22654   (1bit) full fel forward vector   (0=half pix, 1=full pix)     ;\optional 4bit
  22655   (3bit) forward f code            (0=invalid, 1..7=0..6bits)   ;/
  22656 If Coding Type is 3 (B-Frame):
  22657   (1bit) full backward vector                                   ;\optional 4bit
  22658   (3bit) backward f code                                        ;/
  22659 If (and while) next bit is set:
  22660   (1bit) Fixed (1, indicates presence of Extra Info)            ;\opt. N*9bit
  22661   (8bit) Extra Information                                      ;/
  22662 End of Extra:
  22663    1bit  Fixed (0, indicates no further Extra Info)             ;-1bit
  22664  0-7bit  Padding to byte boundary (0)                           ;-0..7bit
  22665 Coding Type values:
  22666   0  Forbidden
  22667   1  I - Intra Coded                      (full image)
  22668   2  P - Predictive Coded                 (based on prev I or P frame)
  22669   3  B - Bidirectionally Predictive Coded (based on prev+next I or P frame)
  22670   4  D - DC Intra Coded                   (don't care, lowres thumbnail)
  22671   5  Reserved
  22672   6  Reserved
  22673   7  Reserved
  22674 
  22675 Frame Order
  22676   DISPLAY ORDER:
  22677   I B B B P B B B P B B B P B B B I B B B P B B B P B B B P B B B ...
  22678   |       |_______|_______|       |       |_______|_______|
  22679   |               |               |               |
  22680   I-Frame         P-frames        I-Frame         P-frames
  22681 The B-fames require to know the next P- (or I-) frame in advance, for that
  22682 reason, the frames are stored as "PBBB" (although being played as "BBBP"):
  22683   STORAGE ORDER:
  22684   I P B B B P B B B P B B B I B B B P B B B P B B B P B B B ...
  22685   | |_______|_______|       |       |_______|_______|
  22686   |         |               |               |
  22687   I-Frame   P-frames        I-Frame         P-frames
  22688 
  22689 MPEG-1 Video Slice
  22690 Slices are containing the actual 16x16 pixel Macro Blocks. Usually a Slice
  22691 contains one horizontal line - although, theoretically, it could be longer or
  22692 shorter, ie. a slice could wrap to next line, or a line could be split into
  22693 several slices (with the leading "MBA Increment" value greater than 1 to define
  22694 the horizontal start offset).
  22695   32bit  PACK_START_CODE (000001xxh; xx=01h..AFh; vertical index) ;-4byte
  22696    5bit  Quantizer Scale (1..31) (may be later changed by blocks) ;-5bit
  22697 If (and while) next bit is set:
  22698   (1bit) Fixed (1, indicates presence of Extra Info)              ;\opt. N*9bit
  22699   (8bit) Extra Information                                        ;/
  22700 End of Extra:
  22701    1bit  Fixed (0, indicates no further Extra Info)               ;-1bit
  22702 If (and while) next 23bit are nonzero (ie. until next 000001xxh):
  22703    ...   Macroblock (within horizontal line)                      ;...
  22704 Final padding:
  22705  0-7bit  Padding to byte boundary (0)                             ;-0..7bit
  22706 
  22707 MPEG-1 Video Group/Sequence Extension Data (reserved)
  22708 MPEG-1 Video User Data (optional)
  22709  32bit START_CODE (000001B2h=User Data, 000001B5h=Extension Data)       ;-4byte
  22710    ... data (end is signaled by presence of next 000001xxh code)        ;-data
  22711 User Data can contain Closed Captions (see flag in VCD\INFO.VCD or
  22712 SVCD\INFO.SVD).
  22713 User Data contains 11h-byte "Created with Nero" in some homebrew discs.
  22714 
  22715 MPEG-1 Video Sequence End Code (4 bytes)
  22716   32bit SEQUENCE_END_CODE (000001B7h)                                   ;-4byte
  22717 
  22718 
  22719 
  22720 
  22721 MPEG-1 Video 4:2:0 Macroblock
  22722          N*11bit  Macroblock_address_increase escape/stuffing codes (if any)
  22723          1..11bit Macroblock_address_increase
  22724          1-6bit   Macroblock_type
  22725          5bit     Quantizer_scale
  22726          ...      Motion_vector
  22727          3-9bit   Coded_block_pattern
  22728          ...      Block(i)
  22729 Aka...
  22730   Addr Incr
  22731   Type
  22732   Motion Vector
  22733   QScale
  22734   CBP
  22735   Block b0 (Y1)
  22736   Block b1 (Y2)
  22737   Block b2 (Y3)
  22738   Block b3 (Y4)
  22739   Block b4 (Cb)
  22740   Block b5 (Cr)
  22741 
  22742 
  22743 VCD MP2 Audio Stream
  22744 --------------------
  22745 
  22746 VCD video discs and .mpg movie files are having the MP2 Audio Stream enclosed
  22747 in the Multiplex stream (whilst .mp2 audio files may contain raw MP2 data
  22748 without Multiplex stream).
  22749 
  22750 Each MP2 frame is starting with a FFFh syncword (which is always located on a
  22751 byte boundary). Unfortunately, the value FFFh can also occur anywhere in the
  22752 audio data (eg. a 16bit sample with value 3FFCh).
  22753 So, when starting mid-stream, one will need some guessing when searching a
  22754 valid syncword. The best method is to compute the frame size (based on the
  22755 supposed frame header), and then to check if supposed frame begins AND ends
  22756 with a sync word. Moreover, one could check for invalid sample rate values in
  22757 the frame header, or invalid "groupings" in the frame's data part.
  22758 VCDs are conventionally having three audio frames encoded in one CDROM sector,
  22759 so the first syncword can be simply found right after the multiplex packet
  22760 header (though that might differ in some cases: VCD2.0 allows different audio
  22761 bitrates, and a CDROM sector could be theoretically shared for Audio and Video
  22762 data).
  22763 
  22764 Overall MP2 Frame Format
  22765   Header (32bit)
  22766   Optional CRC (16bit) (or 0bit if none)
  22767   Allocation Information
  22768   Scale Factor Selector Information
  22769   Scale Factors
  22770   Data
  22771 
  22772 MP2 Header
  22773   12bit Syncword (FFFh)                                         ;\
  22774   1bit  Revision (0=MPEG-2, 1=MPEG-1)                           ; 2 bytes
  22775   2bit  Layer (2=Audio LayerII)                   ;for VCDs     ;
  22776               (3=LayerI, 1=LayerIII, 0=reserved)  ;not on VCDs  ;
  22777   1bit  Protection_bit (1=no crc)                               ;/
  22778   4bit  Bitrate_index (1..14)                                   ;\
  22779           (0=free format, 15=reserved)                          ;
  22780   2bit  Sampling_frequency                                      ; 1 byte
  22781   1bit  Padding_bit                                             ;
  22782   1bit  Private_bit                                             ;/
  22783   2bit  Mode                                                    ;\
  22784   2bit  Mode_extension (aka bound)                              ;
  22785   1bit  Copyright                                               ; 1 byte
  22786   1bit  Original/home                                           ;
  22787   2bit  Emphasis                                                ;/
  22788 
  22789 MP2 Checksum (optional)
  22790   16bit CRC
  22791 
  22792 Allocation Information
  22793 Scale Factor Selector Information
  22794 Scale Factors
  22795 Data
  22796   XXX...
  22797 
  22798 Controllers and Memory Cards
  22799 ----------------------------
  22800 
  22801 Controllers/Memory Cards
  22802 --> Controller and Memory Card I/O Ports
  22803 --> Controller and Memory Card Misc
  22804 --> Controller and Memory Card Signals
  22805 --> Controller and Memory Card Multitap Adaptor
  22806 
  22807 Controllers
  22808 --> Controllers - Communication Sequence
  22809 --> Controllers - Standard Digital/Analog Controllers
  22810 --> Controllers - Mouse
  22811 --> Controllers - Racing Controllers
  22812 --> Controllers - Lightguns
  22813 --> Controllers - Configuration Commands
  22814 --> Controllers - Vibration/Rumble Control
  22815 --> Controllers - Analog Buttons (Dualshock2)
  22816 --> Controllers - Dance Mats
  22817 --> Controllers - Fishing Controllers
  22818 --> Controllers - I-Mode Adaptor (Mobile Internet)
  22819 --> Controllers - Keyboards
  22820 --> Controllers - Additional Inputs
  22821 --> Controllers - Misc
  22822 
  22823 Memory Cards
  22824 --> Memory Card Read/Write Commands
  22825 --> Memory Card Data Format
  22826 --> Memory Card Images
  22827 --> Memory Card Notes
  22828 
  22829 Pocketstation (Memory Card with built-in LCD screen and buttons)
  22830 --> Pocketstation
  22831 
  22832 Pinouts
  22833 --> Pinouts - Controller Ports and Memory-Card Ports
  22834 
  22835 Controller and Memory Card I/O Ports
  22836 ------------------------------------
  22837 
  22838 1F801040h JOY_TX_DATA (W)
  22839   0-7   Data to be sent
  22840   8-31  Not used
  22841 Writing to this register starts the transfer (if, or as soon as TXEN=1 and
  22842 JOY_STAT.2=Ready), the written value is sent to the controller or memory card,
  22843 and, simultaneously, a byte is received (and stored in RX FIFO if JOY_CTRL.1 or
  22844 JOY_CTRL.2 is set).
  22845 The "TXEN=1" condition is a bit more complex: Writing to SIO_TX_DATA latches
  22846 the current TXEN value, and the transfer DOES start if the current TXEN value
  22847 OR the latched TXEN value is set (ie. if TXEN gets cleared after writing to
  22848 SIO_TX_DATA, then the transfer may STILL start if the old latched TXEN value
  22849 was set).
  22850 
  22851 1F801040h JOY_RX_DATA (R)
  22852   0-7   Received Data      (1st RX FIFO entry) (oldest entry)
  22853   8-15  Preview            (2nd RX FIFO entry)
  22854   16-23 Preview            (3rd RX FIFO entry)
  22855   24-31 Preview            (4th RX FIFO entry) (5th..8th cannot be previewed)
  22856 A data byte can be read when JOY_STAT.1=1. Data should be read only via 8bit
  22857 memory access (the 16bit/32bit "preview" feature is rather unusable, and
  22858 usually there shouldn't be more than 1 byte in the FIFO anyways).
  22859 
  22860 1F801044h JOY_STAT (R)
  22861   0     TX Ready Flag 1   (1=Ready/Started)
  22862   1     RX FIFO Not Empty (0=Empty, 1=Not Empty)
  22863   2     TX Ready Flag 2   (1=Ready/Finished)
  22864   3     RX Parity Error   (0=No, 1=Error; Wrong Parity, when enabled)  (sticky)
  22865   4     Unknown (zero)    (unlike SIO, this isn't RX FIFO Overrun flag)
  22866   5     Unknown (zero)    (for SIO this would be RX Bad Stop Bit)
  22867   6     Unknown (zero)    (for SIO this would be RX Input Level AFTER Stop bit)
  22868   7     /ACK Input Level  (0=High, 1=Low)
  22869   8     Unknown (zero)    (for SIO this would be CTS Input Level)
  22870   9     Interrupt Request (0=None, 1=IRQ7) (See JOY_CTRL.Bit4,10-12)   (sticky)
  22871   10    Unknown (always zero)
  22872   11-31 Baudrate Timer    (21bit timer, decrementing at 33MHz)
  22873 
  22874 1F801048h JOY_MODE (R/W) (usually 000Dh, ie. 8bit, no parity, MUL1)
  22875   0-1   Baudrate Reload Factor (1=MUL1, 2=MUL16, 3=MUL64) (or 0=MUL1, too)
  22876   2-3   Character Length       (0=5bits, 1=6bits, 2=7bits, 3=8bits)
  22877   4     Parity Enable          (0=No, 1=Enable)
  22878   5     Parity Type            (0=Even, 1=Odd) (seems to be vice-versa...?)
  22879   6-7   Unknown (always zero)
  22880   8     CLK Output Polarity    (0=Normal:High=Idle, 1=Inverse:Low=Idle)
  22881   9-15  Unknown (always zero)
  22882 
  22883 1F80104Ah JOY_CTRL (R/W) (usually 1003h,3003h,0000h)
  22884   0     TX Enable (TXEN)  (0=Disable, 1=Enable)
  22885   1     /JOYn Output      (0=High, 1=Low/Select) (/JOYn as defined in Bit13)
  22886   2     RX Enable (RXEN)  (0=Normal, when /JOYn=Low, 1=Force Enable Once)
  22887   3     Unknown? (read/write-able) (for SIO, this would be TX Output Level)
  22888   4     Acknowledge       (0=No change, 1=Reset JOY_STAT.Bits 3,9)          (W)
  22889   5     Unknown? (read/write-able) (for SIO, this would be RTS Output Level)
  22890   6     Reset             (0=No change, 1=Reset most JOY_registers to zero) (W)
  22891   7     Not used             (always zero) (unlike SIO, no matter of FACTOR)
  22892   8-9   RX Interrupt Mode    (0..3 = IRQ when RX FIFO contains 1,2,4,8 bytes)
  22893   10    TX Interrupt Enable  (0=Disable, 1=Enable) ;when JOY_STAT.0-or-2 ;Ready
  22894   11    RX Interrupt Enable  (0=Disable, 1=Enable) ;when N bytes in RX FIFO
  22895   12    ACK Interrupt Enable (0=Disable, 1=Enable) ;when JOY_STAT.7  ;/ACK=LOW
  22896   13    Desired Slot Number  (0=/JOY1, 1=/JOY2) (set to LOW when Bit1=1)
  22897   14-15 Not used             (always zero)
  22898 Caution: After slot selection (via Bits 1,13), one should issue a delay before
  22899 sending the first data byte: Digital Joypads may work without delay, Dualshock
  22900 and Mouse require at least some small delay, and older Analog Joypads require a
  22901 huge delay (around 500 clock cycles for SCPH-1150), official kernel waits more
  22902 than 2000 cycles (which is much more than needed).
  22903 
  22904 1F80104Eh JOY_BAUD (R/W) (usually 0088h, ie. circa 250kHz, when Factor=MUL1)
  22905   0-15  Baudrate Reload value for decrementing Baudrate Timer
  22906 Timer reload occurs when writing to this register, and, automatically when the
  22907 Baudrate Timer reaches zero. Upon reload, the 16bit Reload value is multiplied
  22908 by the Baudrate Factor (see 1F801048h.Bit0-1), divided by 2, and then copied to
  22909 the 21bit Baudrate Timer (1F801044h.Bit11-31). The 21bit timer decreases at
  22910 33MHz, and, it ellapses twice per bit (once for CLK=LOW and once for CLK=HIGH).
  22911   BitsPerSecond = (44100Hz*300h) / MIN(((Reload*Factor) AND NOT 1),1)
  22912 The default BAUD value is 0088h (equivalent to 44h cpu cycles), and default
  22913 factor is MUL1, so CLK pulses are 44h cpu cycles LOW, and 44h cpu cycles HIGH,
  22914 giving it a transfer rate of circa 250kHz per bit (33MHz divided by 88h
  22915 cycles).
  22916 Note: The Baudrate Timer is always running; even if there's no transfer in
  22917 progress.
  22918 
  22919 /IRQ7 (/ACK) Controller and Memory Card - Byte Received Interrupt
  22920 Gets set after receiving a data byte - that only if an /ACK has been received
  22921 from the peripheral (ie. there will be no IRQ if the peripheral fails to send
  22922 an /ACK, or if there's no peripheral connected at all).
  22923   Actually, /IRQ7 means "more-data-request",
  22924   accordingly, it does NOT get triggered after receiving the LAST byte.
  22925 I_STAT.7 is edge triggered (that means it can be acknowledge before or after
  22926 acknowledging JOY_STAT.9). However, JOY_STAT.9 is NOT edge triggered (that
  22927 means it CANNOT be acknowledged while the external /IRQ input is still low; ie.
  22928 one must first wait until JOY_STAT.7=0, and then set JOY_CTRL.4=1) (this is
  22929 apparently a hardware glitch; note: the LOW duration is circa 100 clock
  22930 cycles).
  22931 
  22932 /IRQ10 (/IRQ) Controller - Lightpen Interrupt
  22933 Pin8 on Controller Port. Routed directly to the Interrupt Controller (at
  22934 1F80107xh). There are no status/enable bits in the JOY_registers (at
  22935 1F80104xh).
  22936 
  22937 RX FIFO / TX FIFO Notes
  22938 The JOY registers can hold up to 8 bytes in RX direction, and almost 2 bytes in
  22939 TX direction (just like the SIO registers, see there for details), however,
  22940 normally only 1 byte should be in the RX/TX registers (one shouldn't send a 2nd
  22941 byte until /ACK is sensed, and, since the transfer CLK is dictated by the CPU,
  22942 the amount of incoming data cannot exceed 1 byte; provided that one reads
  22943 received response byte after each transfer).
  22944 Unlike SIO, the JOY status register doesn't have a RX FIFO Overrun flag.
  22945 
  22946 General Notes
  22947 RXEN should be usually zero (the hardware automatically enables receive when
  22948 /JOYn is low). When RXEN is set, the next transfer causes data to be stored in
  22949 RX FIFO even when /JOYn is high; the hardware automatically clears RXEN after
  22950 the transfer.
  22951 For existing joypads and memory cards, data should be always transferred as
  22952 8bit no parity (although the JOY registers do support parity just like SIO
  22953 registers).
  22954 
  22955 Plugging and Unplugging Cautions
  22956 During plugging and unplugging, the Serial Data line may be dragged LOW for a
  22957 moment; this may also affect other connected devices because the same Data line
  22958 is shared for all controllers and memory cards (for example, connecting a
  22959 joypad in slot 1 may corrupt memory card accesses in slot 2).
  22960 Moreover, the Sony Mouse does power-up with /ACK=LOW, and stays stuck in that
  22961 state until it is accessed at least once (by at least sending one 01h byte to
  22962 its controller port); this will also affect other devices (as a workaround one
  22963 should always access BOTH controller ports; even if a game uses only one
  22964 controller, and, code that waits for /ACK=HIGH should use timeouts).
  22965 
  22966 Emulation Note
  22967 After sending a byte, the Kernel waits 100 cycles or so, and does THEN
  22968 acknowledge any old IRQ7, and does then wait for the new IRQ7. Due to that
  22969 bizarre coding, emulators can't trigger IRQ7 immediately within 0 cycles after
  22970 sending the byte.
  22971 
  22972 Controller and Memory Card Misc
  22973 -------------------------------
  22974 
  22975 BIOS Functions
  22976 Controllers can be probably accessed via InitPad and StartPad functions,
  22977 --> BIOS Joypad Functions
  22978 Memory cards can be accessed by the filesystem (with device names "bu00:"
  22979 (slot1) and "bu10:" (slot2) or so). Before using that device names, it seems to
  22980 be required to call InitCard, StartCard, and _bu_init (?).
  22981 
  22982 Connectors
  22983 The PlayStation has four connectors (two controllers, two memory cards),
  22984   Memory Card 1         Memory Card 2
  22985   Controller 1          Controller 2
  22986 The controller ports have 9 pins, the memory cards only 8 pins. However, there
  22987 are only 10 different pins in total.
  22988   JOYDAT,JOYCMD,JOYCLK  Data in/out/clock
  22989   +7.5V,+3.5V,GND       Supply
  22990   /JOY1,/JOY2  Selects controller/memorycard 1, or controller/memorycard 2
  22991   /ACK         Indicates that the device is ready to send more data (IRQ7)
  22992   /IRQ10       Lightgun (controllers only, not memory card) (IRQ10)
  22993 Most of these pins are shared for all 4 connectors (eg. a CLK signal meant to
  22994 be sent to one device will also arrive at the other 3 devices).
  22995 The /JOYn signals are selecting BOTH the corresponding controller, and the
  22996 corresponding memory card (whether it is a controller access or memory card
  22997 access depends on the first byte transferred via the CMD line; this byte should
  22998 be 01h=Controller, or 81h=Memory Card; or, a special case would be 21h=Yaroze
  22999 Access Card).
  23000 
  23001 Data In/Out
  23002 The data is transferred in units of bytes, via separate input and output lines.
  23003 So, when sending byte, the hardware does simultaneously receive a response
  23004 byte.
  23005 One exception is the first command byte (which selects either the controller,
  23006 or the memory card) until that byte has been sent, neither the controller nor
  23007 memory card are selected (and so the first "response" byte should be ignored;
  23008 probably containing more or less stable high-z levels).
  23009 The other exception is, when you have send all command bytes, and still want to
  23010 receive further data, then you'll need to send dummy command bytes (should be
  23011 usually 00h) to receive the response bytes.
  23012 
  23013 Controller and Memory Card Signals
  23014 ----------------------------------
  23015 
  23016 Overview
  23017        ____                                                              _____
  23018   /SEL     |____________________________________________________________|
  23019        ______        ____        ____        ____        ____        _________
  23020   CLK        ||||||||    ||||||||    ||||||||    ||||||||    ||||||||
  23021        _______________________________________________________________________
  23022   CMD       X  01h   XXXX  42h   XXXX  00h   XXXX  00h   XXXX  00h   XXXX
  23023             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  23024             _____________________________________________________________
  23025   DAT  -----XXXXXXXXXXXXX   ID   XXXX  5Ah   XXXX  key1  XXXX  key2  XXXX-----
  23026             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  23027   /ACK ---------------|_|---------|_|---------|_|---------|_|-----------------
  23028 
  23029 Top command. First comminucation(device check)
  23030        ____
  23031   /SEL     |__________________________________________________________________
  23032        ______   _   _   _   _   _   _   _   __________________   _   _   _   _
  23033   CLK        |_| |_| |_| |_| |_| |_| |_| |_|                  |_| |_| |_| |_|
  23034        __________                                                  ___
  23035   CMD            |________________________________________________|   |_______
  23036                                                               ____
  23037   DAT  -----XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX    |___________
  23038   /ACK ----------------------------------------------|___|--------------------
  23039 
  23040 X = none, - = Hi-Z
  23041 
  23042 * 0x81 is memory-card, 0x01 is standard-pad at top command.
  23043 * serial data transfer is LSB-First format.
  23044 * data is down edged output, PSX is read at up edge in shift clock.
  23045 * PSX expects No-connection if not returned Acknowledge less than 100 usec.
  23046 * clock pulse is 250KHz.
  23047 * no need Acknowledge at last data.
  23048 * Acknowledge signal width is more than 2 usec.
  23049 * time is 16msec between SEL from previous SEL.
  23050 * SEL- for memory card in PAD access.
  23051 
  23052 Controller and Memory Card Multitap Adaptor
  23053 -------------------------------------------
  23054 
  23055 SCPH-1070 (Multitap)
  23056 The Multitap is an external adaptor that allows to connect 4 controllers, and 4
  23057 memory cards to one controller port. When using two adaptors (one on each
  23058 slot), up to 8 controllers and 8 memory cards can be used.
  23059 
  23060 Multitap Controller Access
  23061 Normally joypad reading is done by sending this bytes to the pad:
  23062   01 42 00 00 ..   ;normal read
  23063 And with the multitap, there are even two different ways how to access extra
  23064 pads:
  23065   01 42 01 00 ..   ;method 1: receive special ID and data from ALL four pads
  23066   0n 42 00 00 ..   ;method 2: receive data from pad number "n" (1..4)
  23067 The first method seems to be the more commonly used one (and its special ID is
  23068 also good for detecting the multitap); see below for details.
  23069 The second method works more like "normal" reads, among other it's allowing to
  23070 transfer more than 4 halfwords per slot (unknown if any existing games are
  23071 using that feature).
  23072 The IRQ10 signal (for Konami Lightguns) is simply wired to all four slots via
  23073 small resistors (without special logic for activating/deactivating the IRQ on
  23074 certain slots).
  23075 
  23076 Multitap Controller Access, Method 1 Details
  23077 Below LONG response is activated by sending "01h" as third command byte;
  23078 observe that sending that byte does NOT affect the current response. Instead,
  23079 it does request that the NEXT command shall return special data, as so:
  23080   Halfword 0      --> Controller ID for MultiTap (5A80h=Multitap)
  23081   Halfword 1..4   --> Player A (Controller ID, Buttons, Analog Inputs, if any)
  23082   Halfword 5..8   --> Player B (Controller ID, Buttons, Analog Inputs, if any)
  23083   Halfword 9..12  --> Player C (Controller ID, Buttons, Analog Inputs, if any)
  23084   Halfword 13..16 --> Player D (Controller ID, Buttons, Analog Inputs, if any)
  23085 With this method, the Multitap is always sending 4 halfwords per slot (padded
  23086 with FFFFh values for devices like Digital Joypads and Mice; which do use less
  23087 than 4 halfwords); for empty slots it's padding all 4 halfwords with FFFFh.
  23088 Sending the request is possible ONLY if there is a controller in Slot A (if
  23089 controller Slot A is empty then the Slot A access aborts after the FIRST byte,
  23090 and it's thus impossible to send the request in the THIRD byte).
  23091 Sending the request works on access to Slot A, trying to send another request
  23092 during the LONG response is glitchy (for whatever strange reason); one must
  23093 thus REPEATEDLY do TWO accesses: one dummy Slot A access (with the request),
  23094 followed by the long Slot A+B+C+D access.
  23095   Previous access had REQ=0 and returned Slot A data ---> returns Slot A data
  23096   Previous access had REQ=0 and returned Slot A-D data -> returns Slot A data
  23097   Previous access had REQ=1 and returned Slot A data ---> returns Slot A-D data
  23098   Previous access had REQ=1 and returned Slot A-D data -> returns garbage
  23099   Previous access had REQ=1 and returned garbage -------> returns Slot A-D data
  23100 In practice:
  23101 Toggling REQ on/off after each command: Returns responses toggling between
  23102 normal Slot A data and long Slot A+B+C+D data.
  23103 Sending REQ=1 in ALL commands: Returns responses toggling between Garbage and
  23104 long Slot A+B+C+D data.
  23105 Both of the above is working (one needs only the Slot A+B+C+D part, and it
  23106 doesn't matter if the other part is Slot A, or Garbage; as long as the software
  23107 is able/aware of ignoring the Garbage). Garbage response means that the
  23108 multitap returns ONLY four bytes, like so: Hiz,80h,5Ah,LSB (ie. the leading
  23109 HighZ byte, the 5A80h Multitap ID, and the LSB of the Slot A controller ID),
  23110 and aborts transfer after that four bytes.
  23111 
  23112 Multitap Memory Card Access
  23113 Normally memory card access is done by sending this bytes to the card:
  23114   80 xx .. ..      ;normal access
  23115 And with the multitap, memory cards can be accessed as so:
  23116   8n xx .. ..      ;access memory card in slot "n" (1..4)
  23117 That's the way how its done in Silent Hill. Although for the best of confusion,
  23118 it doesn't actually work in that game (probably the developer has just linked
  23119 in the multitap library, without actually supporting the multitap at higher
  23120 program levels).
  23121 
  23122 Multitap Games
  23123   Bomberman World
  23124   Breakout: Off the Wall Fun
  23125   Circuit Breakers
  23126   Crash Team Racing
  23127   FIFA series soccer games
  23128   Frogger
  23129   Gauntlet: Dark Legacy
  23130   Hot Shots Golf 2 & 3
  23131   NBA Live (any year) (up to 8 players with two multitaps)
  23132   Need For Speed 3
  23133   Need For Speed 5
  23134   Poy Poy (4 players hitting each other with rocks and trees)
  23135   Running Wild
  23136 
  23137 Multitap Versions
  23138                    .------.
  23139    SCPH-1070       |      |        SCPH-111
  23140    (gray case)     |      |        (white case)
  23141    (for PSX)       |    D |        (for PSone)
  23142                    |      |                   .----------------.
  23143         cable      |      |        cable     .'   D        C   '.
  23144             ''--.. |    C |         '''--..__|                  |
  23145                   \|      |                  |                  |
  23146   .----------------'      |                  '.   A        B   .'
  23147   |                       |                   '----------------'
  23148   |                       |
  23149   |    A        B        /
  23150   '---------------------'
  23151 The cable connects to one of the PSX controller ports (which also carries the
  23152 memory card signals). The PSX memory card port is left unused (and is blocked
  23153 by a small edge on the Multitap's plug).
  23154 
  23155 MultiTap Parsed Controller IDs
  23156 Halfword 0 is parsed (by the BIOS) as usually, ie. the LSB is moved to MSB, and
  23157 LSB is replaced by status byte (so ID 5A80h becomes 8000h=Multitap/okay, or
  23158 xxFFh=bad). Halfwords 1,5,9,13 are NOT parsed (neither by the BIOS nor by the
  23159 Multitap hardware), however, some info in the internet is hinting that Sony's
  23160 libraries might be parsing these IDs too (so for example 5A41h would become
  23161 4100h=DigitalPad/okay, or xxFFh=bad).
  23162 
  23163 Power Supply
  23164 The Multitap is powered by the PSX controller port. Unknown if there are any
  23165 power supply restrictions (up to eight controllers and eight cards may scratch
  23166 some limits, especially when doing things like activating rumble on all
  23167 joypads). However, the Multitap hardware itself doesn't do much on supply
  23168 restrictions (+3.5V is passed through something; maybe some fuse, loop, or 1
  23169 ohm resistor or so) (and +7.5V is passed without any restrictions).
  23170 
  23171 See also
  23172 --> Pinouts - Component List and Chipset Pin-Outs for Multitap, SCPH-1070
  23173 
  23174 Controllers - Communication Sequence
  23175 ------------------------------------
  23176 
  23177 Controller Communication Sequence
  23178   Send Reply Comment
  23179   01h  Hi-Z  Controller Access (unlike 81h=Memory Card access), dummy response
  23180   42h  idlo  Receive ID bit0..7 (variable) and Send Read Command (ASCII "B")
  23181   TAP  idhi  Receive ID bit8..15 (usually/always 5Ah)
  23182   MOT  swlo  Receive Digital Switches bit0..7
  23183   MOT  swhi  Receive Digital Switches bit8..15
  23184   --- transfer stops here for digital pad (or analog pad in digital mode) ---
  23185   00h  adc0  Receive Analog Input 0 (if any) (eg. analog joypad or mouse)
  23186   00h  adc1  Receive Analog Input 1 (if any) (eg. analog joypad or mouse)
  23187   --- transfer stops here for analog mouse ----------------------------------
  23188   00h  adc2  Receive Analog Input 2 (if any) (eg. analog joypad)
  23189   00h  adc3  Receive Analog Input 3 (if any) (eg. analog joypad)
  23190   --- transfer stops here for analog pad (in analog mode) -------------------
  23191   --- transfer stops here for nonstandard devices (steering/twist/paddle) ---
  23192 The TAP byte should be usually zero, unless one wants to activate Multitap
  23193 (multi-player mode), for details, see
  23194 --> Controller and Memory Card Multitap Adaptor
  23195 The two MOT bytes are meant to control the rumble motors (for normal non-rumble
  23196 controllers, that bytes should be 00h), however, the MOT bytes have no effect
  23197 unless rumble is enabled via config commands, for details, see
  23198 --> Controllers - Configuration Commands
  23199 --> Controllers - Vibration/Rumble Control
  23200 
  23201 Controller ID (Halfword Number 0)
  23202   0-3  Number of following halfwords (01h..0Fh=1..15, or 00h=16 halfwords)
  23203   4-7  Controller Type (or currently selected Controller Mode)
  23204   8-15 Fixed (5Ah)
  23205 Known 16bit ID values are:
  23206   xx00h=N/A                 (initial buffer value from InitPad BIOS function)
  23207   5A12h=Mouse               (two button mouse)
  23208   5A23h=NegCon              (steering twist/wheel/paddle)
  23209   5A31h=Konami Lightgun     (IRQ10-type)
  23210   5A41h=Digital Pad         (or analog pad/stick in digital mode; LED=Off)
  23211   5A53h=Analog Stick        (or analog pad in "flight mode"; LED=Green)
  23212   5A63h=Namco Lightgun      (Cinch-type)
  23213   5A73h=Analog Pad          (in normal analog mode; LED=Red)
  23214   5A7xh=Dualshock2          (with variable number of inputs enabled)
  23215   5A79h=Dualshock2          (with all analog/digital inputs enabled)
  23216   5A80h=Multitap            (multiplayer adaptor) (when activated)
  23217   5A96h=Keyboard            (rare lightspan keyboard)
  23218   5AE3h=Jogcon              (steering dial)
  23219   5AE8h=Keyboard/Sticks     (rare homebrew keyboard/segasticks adaptor)
  23220   5AF3h=Config Mode         (when in config mode; see rumble command 43h)
  23221   FFFFh=High-Z              (no controller connected, pins floating High-Z)
  23222 
  23223 Controllers - Standard Digital/Analog Controllers
  23224 -------------------------------------------------
  23225        ___                      ___           ___                      ___
  23226     __/_L_\__   Analog Pad   __/_R_\__     __/_L_\__  Digital Pad   __/_R_\__
  23227    /    _    \--------------/         \   /    _    \--------------/         \
  23228   |   _| |_   |            |     /\    | |   _| |_   |            |     /\    |
  23229   |  |_ X _|  |SEL      STA|  []    () | |  |_ X _|  |            |  []    () |
  23230   |    |_|  ___   ANALOG   ___   ><    | |    |_|    |  SEL  STA  |     ><    |
  23231   |\______ / L \   LED    / R \ ______/| |\_________/--------------\_________/|
  23232   |       | Joy |--------| Joy |       | |       |                    |       |
  23233   |      / \___/          \___/ \      | |      /                      \      |
  23234    \____/                        \____/   \____/                        \____/
  23235 
  23236 Standard Controllers
  23237   __Halfword 0 (Controller Info)_______________________________________________
  23238   0-15  Controller Info  (5A41h=digital, 5A73h=analog/pad, 5A53h=analog/stick)
  23239   __Halfword 1 (Digital Switches)______________________________________________
  23240   0   Select Button    (0=Pressed, 1=Released)
  23241   1   L3/Joy-button    (0=Pressed, 1=Released/None/Disabled) ;analog mode only
  23242   2   R3/Joy-button    (0=Pressed, 1=Released/None/Disabled) ;analog mode only
  23243   3   Start Button     (0=Pressed, 1=Released)
  23244   4   Joypad Up        (0=Pressed, 1=Released)
  23245   5   Joypad Right     (0=Pressed, 1=Released)
  23246   6   Joypad Down      (0=Pressed, 1=Released)
  23247   7   Joypad Left      (0=Pressed, 1=Released)
  23248   8   L2 Button        (0=Pressed, 1=Released) (Lower-left shoulder)
  23249   9   R2 Button        (0=Pressed, 1=Released) (Lower-right shoulder)
  23250   10  L1 Button        (0=Pressed, 1=Released) (Upper-left shoulder)
  23251   11  R1 Button        (0=Pressed, 1=Released) (Upper-right shoulder)
  23252   12  /\ Button        (0=Pressed, 1=Released) (Triangle, upper button)
  23253   13  () Button        (0=Pressed, 1=Released) (Circle, right button)
  23254   14  >< Button        (0=Pressed, 1=Released) (Cross, lower button)
  23255   15  [] Button        (0=Pressed, 1=Released) (Square, left button)
  23256   __Halfword 2 (Right joystick) (analog pad/stick in analog mode only)_________
  23257   0-7   adc0 RightJoyX (00h=Left, 80h=Center, FFh=Right)
  23258   8-15  adc1 RightJoyY (00h=Up,   80h=Center, FFh=Down)
  23259   __Halfword 3 (Left joystick) (analog pad/stick in analog mode only)__________
  23260   0-7   adc2 LeftJoyX  (00h=Left, 80h=Center, FFh=Right)
  23261   8-15  adc3 LeftJoyY  (00h=Up,   80h=Center, FFh=Down)
  23262   __Further Halfword(s) (Dualshock2 only, and only if enabled)_________________
  23263   0-7   ..   Analog Button (if enabled) (00h=Released, FFh=Max Pressure)
  23264   8-15  ..   Analog Button (if enabled) (00h=Released, FFh=Max Pressure)
  23265   ..    ..   ..
  23266 
  23267 Analog Mode Note
  23268 On power-up, the controllers are in digital mode (with analog inputs disabled).
  23269 Analog mode can be (de-)activated manually by pushing the Analog button.
  23270 Alternately, analog mode can be (de-)activated by software via rumble
  23271 configuration commands (though that's supported only on newer pads; those with
  23272 two rumble motors).
  23273 The analog sticks are mechanically restricted to a "circular field of motion"
  23274 (most joypads can reach "min/max" values only in "straight" horizontal or
  23275 vertical directions, but not in "diagonal" directions).
  23276 
  23277 Analog Joypad Range
  23278                ...''''''''''...
  23279        ____ .''________________''._____       ___ 00h
  23280       |  .''                      ''.  |
  23281       |.'                            '.|      ___ 10h
  23282       .'                              '.
  23283      :|                                |:
  23284     : |                                | :    ___ 60h
  23285    .' |            .''''''.            | '.
  23286    :  |          .'        '.          |  :
  23287    :  |          :          :          |  :   ___ 80h
  23288    :  |          :          :          |  :
  23289    :  |          '.        .'          |  :
  23290    '. |            '......'            | .'   ___ A0h
  23291     : |                                | :
  23292      :|                                |:
  23293       '.                              .'      ___ F0h
  23294       |'.                            .'|
  23295       |__'..______________________..'__|      ___ FFh
  23296       .     '..                ..'     .
  23297      00h       '''..........'''       FFh
  23298 
  23299    Big Circle   --> Mechanically possible field of motion
  23300    Square Area  --> Digitally visible 8bit field of motion
  23301    Small Circle --> Resting position when releasing the joystick
  23302 Example min/center/max values for three different pads:
  23303   SCPH-1150          Min=(00,00), Mid: (72..90,79..AC), Max=(FF,FF) at 25'C
  23304   SCPH-1200          Min=(0E,0E), Mid: (6C..8A,75..79), Max=(ED,ED) at 16'C
  23305   SCPH-110           Min=(11,11), Mid: (8A..9F,70..96), Max=(FD,FD) at 16'C
  23306 Values may vary for other pads and/or different temperatures.
  23307 
  23308 Dual Analog Pad in LED=Green Mode
  23309 Basically same as normal analog LED=Red mode, with following differences:
  23310   ID is 5A53h (identifying itself as analog stick) (rather than analog pad)
  23311   Left/right joy-buttons disabled (as for real analog stick, bits are always 1)
  23312   Some buttons are re-arranged: bit9=L1 bit10=[] bit11=/\ bit12=R1 bit15=R2
  23313 Concerning the button names, the real analog-stick does NOT have re-arranged
  23314 buttons (eg. it's L1 button is in bit10), however, concerning the button
  23315 locations, the analog stick's buttons are arranged completely differently as on
  23316 analog pads (so it might be rather uncomfortable to play analog stick games on
  23317 analog pads in LED=Red mode; the LED=Green mode is intended to solve that
  23318 problem).
  23319 Might be useful for a few analog-stick games like MechWarrior 2, Ace Combat 2,
  23320 Descent Maximum, and Colony Wars. In most other cases the feature is rather
  23321 confusing (that's probably why the LED=Green mode wasn't implemented on the
  23322 Dual Shock).
  23323 
  23324 See also
  23325 --> Pinouts - Component List and Chipset Pin-Outs for Digital Joypad, SCPH-1080
  23326 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-1150
  23327 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-1200
  23328 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-110
  23329 --> Pinouts - Component List and Chipset Pin-Outs for Dualshock2, SCPH-10010
  23330 
  23331 Controllers - Mouse
  23332 -------------------
  23333 
  23334 Sony Mouse Controller
  23335   __Halfword 0 (Controller Info)________________
  23336   0-15  Controller Info  (5A12h=Mouse)
  23337   __Halfword 1 (Mouse Buttons)__________________
  23338   0-7   Not used         (All bits always 1)
  23339   8-9   Unknown          (Seems to be always 0) (maybe SNES-style sensitivity?)
  23340   10    Right Button     (0=Pressed, 1=Released)
  23341   11    Left Button      (0=Pressed, 1=Released)
  23342   12-15 Not used         (All bits always 1)
  23343   __Halfword 2 (Mouse Motion Sensors)___________
  23344   0-7   Horizontal Motion (-80h..+7Fh = Left..Right) (00h=No motion)
  23345   8-15  Vertical Motion   (-80h..+7Fh = Up..Down)    (00h=No motion)
  23346 
  23347 Sony Mouse Hardware Bug on Power-On
  23348 On Power-on (or when newly connecting it), the Sony mouse does draw /ACK to LOW
  23349 on power-on, and does then hold /ACK stuck in the LOW position.
  23350 For reference: Normal controllers and memory cards set /ACK=LOW only for around
  23351 100 clk cycles, and only after having received a byte from the console.
  23352 The /ACK pin is shared for both controllers and both memory cards, so the stuck
  23353 /ACK is also "blocking" all other connected controllers/cards. To release the
  23354 stuck /ACK signal: Send a command (at least one 01h byte) to both controller
  23355 slots.
  23356 
  23357 Sony Mouse Compatible Games
  23358   3D Lemmings
  23359   Alien Resurrection
  23360   Area 51
  23361   Ark of Time
  23362   Atari Anniversary Edition
  23363   Atlantis: The Lost Tales
  23364   Breakout: Off the Wall Fun
  23365   Broken Sword: The Shadow of the Templars
  23366   Broken Sword II: The Smoking Mirror
  23367   Clock Tower: The First Fear
  23368   Clock Tower II: The Struggle Within
  23369   Command & Conquer: Red Alert
  23370   Command & Conquer: Red Alert - Retaliation
  23371   Constructor (Europe)
  23372   Die Hard Trilogy
  23373   Die Hard Trilogy 2: Viva Las Vegas
  23374   Discworld
  23375   Discworld II: Missing Presumed...!?
  23376   Discworld Noir
  23377   Dune 2000
  23378   Final Doom
  23379   Galaxian 3
  23380   Ghoul Panic
  23381   Klaymen Klaymen: Neverhood no Nazon (Japan)
  23382   Lemmings and Oh No! More Lemmings
  23383   Monopoly
  23384   Music 2000
  23385   Myst
  23386   Neorude (Japan)
  23387   Perfect Assassin
  23388   Policenauts (Japan)
  23389   Puchi Carat
  23390   Quake II
  23391   Railroad Tycoon II
  23392   Rescue Shot
  23393   Risk
  23394   Riven: The Sequel to Myst
  23395   RPG Maker
  23396   Sentinel Returns
  23397   SimCity 2000
  23398   Syndicate Wars
  23399   Tempest 2000 (Tempest X3)
  23400   Theme Aquarium (Japan)
  23401   Transport Tycoon
  23402   Warhammer: Dark Omen
  23403   Warzone 2100
  23404   X-COM: Enemy Unknown
  23405   X-COM: Terror from the Deep
  23406   Z
  23407 Note: There are probably many more mouse compatible games.
  23408 Plus: Dracula - The Resurrection
  23409 
  23410 Sony Mouse Component List
  23411 PCB "TD-T41V/\, MITSUMI"
  23412 Component Side:
  23413   1x 3pin   4.00MHz "[M]4000A, 85 2"
  23414   2x 2pin   button (left/right)
  23415   1x 8pin   connector (to cable with shield and 7 wires)
  23416   1x 3pin   "811, T994I"
  23417   2x 3pin   photo transistor (black)  ;\or so, no idea which one is
  23418   2x 2pin   photo diode (transparent) ;/sender and which is sensor
  23419   1x 2pin   electrolyt capacitor 16V, 10uF
  23420 Solder/SMD Side:
  23421   1x 32pin  "(M), SC442116, FB G22K, JSAA815B"
  23422   1x 14pin  "BA10339F, 817 L67" (Quad Comparator)
  23423   2x 3pin   "LC" (amplifier for photo diodes)
  23424   1x 3pin   "24-" (looks like a dual-diode or so)
  23425   plus many SMD resistors/capacitors
  23426 Cable:
  23427   PSX.Controller.Pin1 JOYDAT ---- brown  -- Mouse.Pin4
  23428   PSX.Controller.Pin2 JOYCMD ---- red    -- Mouse.Pin3
  23429   PSX.Controller.Pin3 +7.5V  ---- N/A
  23430   PSX.Controller.Pin4 GND    ---- orange -- Mouse.Pin7 GND (G)
  23431   PSX.Controller.Pin5 +3.5V  ---- yellow -- Mouse.Pin1
  23432   PSX.Controller.Pin6 /JOYn  ---- green  -- Mouse.Pin5
  23433   PSX.Controller.Pin7 JOYCLK ---- blue   -- Mouse.Pin2
  23434   PSX.Controller.Pin8 /IRQ10 ---- N/A
  23435   PSX.Controller.Pin9 /ACK   ---- purple -- Mouse.Pin6
  23436   PSX.Controller.Shield --------- shield -- Mouse.Pin8 GND (SHIELD)
  23437 
  23438 PS/2 and USB Mouse Adaptors
  23439 Some keyboard adaptors are also including a mouse adpator feature (either by
  23440 simulating normal Sony Mouse controller data, or via more uncommon ways like
  23441 using the PSX expansion port).
  23442 --> Controllers - Keyboards
  23443 
  23444 RS232 Mice
  23445 Below is some info on RS232 serial mice. That info isn't directly PSX related
  23446 as the PSX normally doesn't support those mice.
  23447 With some efforts, one can upgrade the PSX SIO port to support RS232 voltages,
  23448 and with such a modded console one could use RS232 mice (in case one wants to
  23449 do that).
  23450 The nocash PSX bios can map a RS232 mouse to a spare controller slot (thereby
  23451 simulating a Sony mouse), that trick may work with various PSX games.
  23452 
  23453 Standard Serial Mouse
  23454 A serial mouse should be read at 1200 bauds, 7 data bits, no parity, 1 stop bit
  23455 (7N1) with DTR and RTS on. For best compatibility, the mouse should output 2
  23456 stop bits (so it could be alternately also read as 7N2 or 8N1). When the mouse
  23457 gets moved, or when a button gets pressed/released, the mouse sends 3 or 4
  23458 characters:
  23459   __First Character____________________
  23460   6    First Character Flag (1)
  23461   5    Left Button  (1=Pressed)
  23462   4    Right Button (1=Pressed)
  23463   2-3  Upper 2bit of Vertical Motion
  23464   0-1  Upper 2bit of Horizontal Motion
  23465   __Second Character___________________
  23466   6    Non-first Character Flag (0)
  23467   5-0  Lower 6bit of Horizontal Motion
  23468   __Third Character____________________
  23469   6    Non-first Character Flag (0)
  23470   5-0  Lower 6bit of Vertical Motion
  23471   __Fourth Character (if any)__________
  23472   6    Non-first Character Flag (0)
  23473   5    Middle Button (1=Pressed)
  23474   4    Unused ???
  23475   3-0  Wheel  ???
  23476 Additionally, the mouse outputs a detection character (when switching RTS (or
  23477 DTR?) off and on:
  23478   "M" = Two-Button Mouse (aka "Microsoft" mouse)
  23479   "3" = Three-Button Mouse (aka "Logitech" mouse)
  23480   "Z" = Mouse-Wheel
  23481 Normally, the detection response consist of a single character (usually "M"),
  23482 though some mice have the "M" followed by 11 additional characters of garbage
  23483 or version information (these extra characters have bit6=0, so after detection,
  23484 one should ignore all characters until receiving the first data character with
  23485 bit6=1).
  23486 
  23487 Mouse Systems Serial Mouse (rarely used)
  23488 Accessed at 1200 bauds, just like standard serial mouse, but with 8N1 instead
  23489 7N1, and with different data bytes.
  23490   __First Byte_________________________
  23491   7-3  First Byte Code (10000b)
  23492   2    Left? Button   (0=Pressed)
  23493   1    Middle? Button (0=Pressed)
  23494   0    Right? Button  (0=Pressed)
  23495   __Second Byte________________________
  23496   7-0  Horizontal Motion (X1)
  23497   __Third Byte_________________________
  23498   7-0  Vertical Motion   (Y1)
  23499   __Fourth Byte________________________
  23500   7-0  Horizontal Motion (X2)
  23501   __Fifth Byte_________________________
  23502   7-0  Vertical Motion   (Y2)
  23503 The strange duplicated 8bit motion values are usually simply added together,
  23504 ie. X=X1+X2 and Y=Y1+Y2, producing 9bit motion values.
  23505 
  23506 Notes
  23507 The Sony Mouse connects directly to the PSX controller port. Alternately serial
  23508 RS232 mice can be connected to the SIO port (with voltage conversion adaptor)
  23509 (most or all commercial games don't support SIO mice, nor does the original
  23510 BIOS do so, however, the nocash BIOS maps SIO mice to unused controller slots,
  23511 so they can be used even with commercial games; if the game uses BIOS functions
  23512 to read controller data).
  23513 Serial Mice (and maybe also the Sony mouse) do return raw mickeys, so effects
  23514 like double speed threshold must (should) be implemented by software. Mice are
  23515 rather rarely used by PSX games. The game "Perfect Assassin" includes
  23516 ultra-crude mouse support, apparently without threshold, and without properly
  23517 matching the cursor range to the screen resolution.
  23518 
  23519 Controllers - Racing Controllers
  23520 --------------------------------
  23521 
  23522 neGcon Racing Controller (Twist) (NPC-101/SLPH-00001/SLEH-0003)
  23523   __Halfword 0 (Controller Info)_______________________________________________
  23524   0-15  Controller Info  (5A23h=neGcon)
  23525   __Halfword 1 (Digital Switches)______________________________________________
  23526   0-2   Not used       (always 1)       (would be Select, L3, R3 on other pads)
  23527   3     Start Button   (0=Pressed, 1=Released)
  23528   4     Joypad Up      (0=Pressed, 1=Released)
  23529   5     Joypad Right   (0=Pressed, 1=Released)
  23530   6     Joypad Down    (0=Pressed, 1=Released)
  23531   7     Joypad Left    (0=Pressed, 1=Released)
  23532   8-10  Not used       (always 1)       (would be L2, R2, L1 on other pads)
  23533   11    R Button       (0=Pressed, 1=Released) (would be R1 on other pads)
  23534   12    B Button       (0=Pressed, 1=Released) (would be /\ on other pads)
  23535   13    A Button       (0=Pressed, 1=Released) (would be () on other pads)
  23536   14-15 Not used       (always 1)              (would be ><, [] on other pads)
  23537   __Halfword 2 (Right joystick) (analog pad/stick in analog mode only)_________
  23538   0-7   Steering Axis    (00h=Left, 80h=Center, FFh=Right) (or vice-versa?)
  23539   8-15  Analog I button  (00h=Out ... FFh=In)  (Out=released, in=pressed?)
  23540   __Halfword 3 (Left joystick) (analog pad/stick in analog mode only)__________
  23541   0-7   Analog II button (00h=Out ... FFh=In)  (Out=released, in=pressed?)
  23542   8-15  Analog L button  (00h=Out ... FFh=In)  (Out=released, in=pressed?)
  23543 The Twist controller works like a paddle or steering wheel, but doesn't have a
  23544 wheel or knob, instead, it can be twisted: To move into one direction (=maybe
  23545 right?), turn its right end away from you (or its left end towards you). For
  23546 the opposite direction (=maybe left?), do it vice-versa.
  23547      _____         _  _         _____                              ____
  23548     |__L__\_______/ || \_______/__R__|                            /    \
  23549    /    _   namco   ||   neGcon       \                          /      \
  23550   |   _| |_         ||            B    |                        |       |
  23551   |  |_ X _|    ....||....     II   A  | .... Rotation Axis ... | ...  \|/
  23552   |    |_|          ||            I    |                        |
  23553   |        START    ||                 |                         \
  23554   |       ________  ||  ________       |                          \__\
  23555   |      /        \_||_/        \      |                             /
  23556    \____/                        \____/
  23557 
  23558 Namco Volume Controller (a paddle with two buttons) (SLPH-00015)
  23559 This is a cut-down variant of the neGcon, just a featureless small box. It does
  23560 have the same ID value as neGcon (ID=5A23h), but, it excludes most digital, and
  23561 all analog buttons.
  23562    _______
  23563   | namco |      Halfword 1 (digital buttons):
  23564   |       |      Bit3  Button A (0=Pressed) (aka neGcon Start button)
  23565   | A   B |      Bit13 Button B (0=Pressed) (aka neGcon A button aka () button)
  23566   |       |      Other bits     (not used, always 1)
  23567   |   _   |      Halfword 2 and 3 (analog inputs):
  23568   |  (_)  |      Steering Axis  (00h..FFh)  (as for neGcon)
  23569   |_______|      Analog I,II,L button values (not used, always 00h)
  23570 
  23571 SANKYO N.ASUKA aka Nasca Pachinco Handle (SLPH-00007)
  23572 Another cut-down variant of the neGcon (with ID=5A23h, too). But, this one
  23573 seems to have only one button. Unlike Namco's volume controller it doesn't look
  23574 featureless. It looks pretty much as shown in the ascii-arts image below. Seems
  23575 to be supported by several irem titles. No idea what exactly it is used for,
  23576 it's probably not a sewing machine controller, nor an electronic amboss.
  23577    ____ ____     Halfword 1 (digital buttons):
  23578   |   /   _ \    Bit12 Button   (0=Pressed) (aka neGcon B button aka /\ button)
  23579   |_ /   (_) )   Other bits     (not used, always 1)
  23580   |_|___    /\   Halfword 2 and 3 (analog inputs):
  23581    ____|   |_    Steering Axis  (00h..FFh)  (as for neGcon)
  23582   |__________|   Analog I,II,L button values (not used, always 00h)
  23583 
  23584 Mad Catz Steering Wheel (SLEH-0006)
  23585 A neGcon compatible controller. The Twist-feature has been replaced by a
  23586 steering wheel (can be turned by 270 degrees), and the analog I and II buttons
  23587 by foot pedals. The analog L button has been replaced by a digital button (ie.
  23588 in neGcon mode, the last byte of the controller data can be only either 00h or
  23589 FFh). When not using the pedals, the I/II buttons on the wheel can be used
  23590 (like L button, they aren't analog though).
  23591         __________________________
  23592        /   ____________________   \    Stick
  23593       /   /                    \   \    ___        Brakes  Gas
  23594      /   (                      )   \  (   )         II     I
  23595     /  I  \                    /  A  \  \ /          ___   ___
  23596    / /\ II \____________MODE__/  B /\ \  |          |   | |   |
  23597   | |  \ L  _                   R /  | | |          |!!!|_|!!!|___
  23598   | |   ) _| |_   MadCatz        (   | |_|_        /|!!!| |!!!|  /
  23599   | |  | |_ X _|                  |  | | | |      / |___| |___| /
  23600   | |  |   |_|                    |  | |  /      / =========== /
  23601   | |   \         SEL STA        /   | | /      / =========== /
  23602    \ \__/ ______________________ \__/ / /      /_____________/
  23603     \____/                      \____/_/
  23604        |___________________________|
  23605 
  23606 Unlike the neGon, the controller has Select, >< and [] buttons, and a second
  23607 set of L/R buttons (at the rear-side of the wheel) (no idea if L1/R1 or L2/R2
  23608 are at front?). Aside from the neGcon mode, the controller can be also switched
  23609 to Digital mode (see below for button chart).
  23610 
  23611 MadCatz Dual Force Racing Wheel
  23612 Same as above, but with a new Analog mode (additionally to Digital and neGcon
  23613 modes). The new mode is for racing games that support only Analog Joypads
  23614 (instead of neGcon). Additionally it supports vibration feedback.
  23615 
  23616 MadCatz MC2 Vibration compatible Racing Wheel and Pedals
  23617 Same as above, but with a redesigned wheel with rearranged buttons, the digital
  23618 pad moved to the center of the wheel, the L/R buttons at the rear-side of the
  23619 wheel have been replaced by 2-way butterfly buttons ("pull towards user" acts
  23620 as normal, the new "push away from user" function acts as L3/R3).
  23621             ____________________
  23622            /  ________________  \   ___ Stick      Brakes  Gas
  23623           /  /       MC2      \  \ (   )             ___   ___
  23624          /  /__________________\  \ \ /             |   | |   |
  23625         |    A ()    _|_    I ><   | |              |!!!|_|!!!|___
  23626         |   B /\ _    |    _ II [] | |             /|!!!| |!!!|  /
  23627      ___|  L2   / \  STA  / \ R2   |_|_           / |___| |___| /
  23628     /    \     /   | SEL |   \    /    \         / =========== /
  23629    /  ____\    |___|     |___|   /____  \       / =========== /
  23630   /__/     \____________________/     \__\     /_____________/
  23631 
  23632 MadCatz Button Chart
  23633   Mode     Buttons...................... Gas Brake Stick Wheel
  23634   Digital  >< [] () /\ L1 R1 L2 R2 L1 R1 ><  ()    L1/R1 lt/rt
  23635   Analog   >< [] () /\ L1 R1 L2 R2 L3 R3 UP  DN    L1/R1 LT/RT
  23636   Negcon   I  II A  B  L  R  L  R  L  R  I   II    up/dn Twist
  23637 Whereas, lt/rt/up/dn=Digital Pad, UP/DN=Left Analog Pad Up/Down, LT/RT=Right
  23638 Analog Pad Left/Right. Analog mode is supported only by the Dual Force and MC2
  23639 versions, L3/R3 only by the MC2 version.
  23640 
  23641 Namco Jogcon (NPC-105/SLEH-0020/SLPH-00126/SLUH-00059)
  23642   __Halfword 0 (Controller Info)___________________
  23643   0-15  Controller Info  (5AE3h=Jogcon in Jogcon mode) (ie. not Digital mode)
  23644  halfword1: buttons: same as digital pad
  23645  halfword2:
  23646    0    unknown (uh, this isn't LSB of rotation?)
  23647    1-15 dial rotation (signed offset since last read?) (or absolute position?)
  23648  halfword3:
  23649    0    flag: dial was turned left  (0=no, 1=yes)
  23650    1    flag: dial was turned right (0=no, 1=yes)
  23651    2-15 unknown
  23652 Rotations of the dial are recognized by an optical sensor (so, unlike
  23653 potentiometers, the dial can be freely rotated; by more than 360 degrees). The
  23654 dial is also connected to a small motor, giving it a real force-feedback effect
  23655 (unlike all other PSX controllers which merely have vibration feedback).
  23656 Although that's great, the mechanics are reportedly rather cheap and using the
  23657 controller doesn't feel too comfortable. The Jogcon is used only by Ridge Racer
  23658 4 for PS1 (and Ridge Racer 5 for PS2), and Breakout - Off the Wall Fun.
  23659 The Mode button probably allows to switch between Jogcon mode and Digital Pad
  23660 mode (similar to the Analog button on other pads), not sure if the mode can be
  23661 also changed by software via configuration commands...? Unknown how the motor
  23662 is controlled; probably somewhat similar to vibration motors, ie. by the M1
  23663 and/or M2 bytes, but there must be also a way to select clockwise and
  23664 anticlockwise direction)...? The controller does reportedly support config
  23665 command 4Dh (same as analog rumble).
  23666        ___       ________       ___
  23667     __/_L_\__   /        \   __/_R_\__
  23668    /    _    \ / LED MODE \-/         \
  23669   |   _| |_   | SEL    STA |     /\    |
  23670   |  |_ X _|  |  ________  |  []    () |
  23671   |    |_|    | /        \ |     ><    |
  23672   |\_________/\/          \/\__ ______/|
  23673   |       |   |   JOGCON   |   |       |
  23674   |       |   |    DIAL    |   |       |
  23675   |       |    \          /    |       |
  23676   |       |     \________/     |       |
  23677   |       |                    |       |
  23678   |       |                    |       |
  23679    \_____/                      \_____/
  23680 
  23681 Controllers - Lightguns
  23682 -----------------------
  23683 
  23684 There are two different types of PSX lightguns (which are incompatible with
  23685 each other).
  23686 
  23687 Namco Lightgun (GunCon)
  23688 Namco's Cinch-based lightguns are extracting Vsync/Hsync timings from the video
  23689 signal (via a cinch adaptor) (so they are working completely independed of
  23690 software timings).
  23691 --> Controllers - Lightguns - Namco (GunCon)
  23692 
  23693 Konami Lightgun (IRQ10)
  23694 Konami's IRQ10-based lightguns are using the lightgun input on the controller
  23695 slot (which requires IRQ10/timings being properly handled at software side).
  23696 --> Controllers - Lightguns - Konami Justifier/Hyperblaster (IRQ10)
  23697 The IRQ10-method is reportedly less accurate (although that may be just due to
  23698 bugs at software side).
  23699 
  23700 Third-Party Lightguns
  23701 There are also a lot of unlicensed lightguns which are either IRQ10-based, or
  23702 Cinch-based, or do support both.
  23703 For example, the Blaze Scorpion supports both IRQ10 and Cinch, and it does
  23704 additionally have a rumble/vibration function; though unknown how that rumble
  23705 feature is accessed, and which games are supporting it).
  23706 
  23707 Lightgun Games
  23708 --> Controllers - Lightguns - PSX Lightgun Games
  23709 
  23710 Compatibilty Notes (IRQ10 vs Cinch, PAL vs NTSC, Calibration)
  23711 Some lightguns are reportedly working only with PAL or only with NTSC games
  23712 (unknown which guns, and unknown what is causing problems; the IRQ10 method
  23713 should be quite hardware independed, the GunCon variant, too, although
  23714 theoretically, some GunCon guns might have problems to extract Vsync/Hsync from
  23715 either PAL or NTSC composite signals).
  23716 Lightguns from different manufacturers are reportedly returning slightly
  23717 different values, so it would be recommended to include a calibration function
  23718 in the game, using at least one calibration point (that would also resolve
  23719 different X/Y offsets caused by modifying GP1 display control registers).
  23720 Lightguns are needing to sense light from the cathode ray beam; as such they
  23721 won't work on regions of the screen that contain too dark/black graphics.
  23722 
  23723 Controllers - Lightguns - Namco (GunCon)
  23724 ----------------------------------------
  23725 
  23726 GunCon Cinch-based Lightguns (Namco)
  23727   __Halfword 0 (Controller Info)___________________
  23728   0-15  Controller Info  (5A63h=Namco Lightgun; GunCon/Cinch Type)
  23729   __Halfword 1 (Buttons)___________________________
  23730   0-2   Not used              (All bits always 1)
  23731   3     Button A (Left Side)  (0=Pressed, 1=Released) ;aka Joypad Start
  23732   4-12  Not used              (All bits always 1)
  23733   13    Trigger Button        (0=Pressed, 1=Released) ;aka Joypad O-Button
  23734   14    Button B (Right Side) (0=Pressed, 1=Released) ;aka Joypad X-Button
  23735   15    Not used              (All bits always 1)
  23736   __Halfword 2 (X)_________________________________
  23737   0-15  8MHz clks since HSYNC (01h=Error, or 04Dh..1CDh)
  23738   __Halfword 3 (Y)_________________________________
  23739   0-15  Scanlines since VSYNC (05h/0Ah=Error, PAL=20h..127h, NTSC=19h..F8h)
  23740 Caution: The gun should be read only shortly after begin of VBLANK.
  23741 
  23742 Error/Busy Codes
  23743 Coordinates X=0001h, Y=0005h indicates "unexpected light":
  23744   ERROR: Sensed light during VSYNC (eg. from a Bulb or Sunlight).
  23745 Coordinates X=0001h, Y=000Ah indicates "no light", this can mean either:
  23746   ERROR: no light sensed at all (not aimed at screen, or screen too dark).
  23747   BUSY: no light sensed yet (when trying to read gun during rendering).
  23748 To avoid the BUSY error, one should read the gun shortly after begin of VBLANK
  23749 (ie. AFTER rendering, but still BEFORE vsync). Doing that isn't as simple as
  23750 one might think:
  23751 On a NTSC console, time between VBLANK and VSYNC is around 30000 cpu clks,
  23752 reading the lightgun (or analog joypads) takes around 15000 cpu clks. So,
  23753 reading two controllers within that timeframe may be problematic (and reading
  23754 up to eight controllers via multitaps would be absolutely impossible). As a
  23755 workaround, one may arrange the read-order to read lightguns at VBLANK (and
  23756 joypads at later time). If more than one lightgun is connected, then one may
  23757 need to restrict reading to only one (or maybe: max two) guns per frame.
  23758 
  23759 Minimum Brightness
  23760 Below are some average minimum brightness values, the gun may be unable to
  23761 return position data near/below that limits (especially coordinates close to
  23762 left screen border are most fragile). The exact limits may vary from gun to
  23763 gun, and will also depend on the TV Set's brightness setting.
  23764   666666h Minimum Gray
  23765   770000h Minimum Blue
  23766   007700h Minimum Green
  23767   000099h Minimum Red
  23768 The gun does also work with mixed colors (eg. white bold text on black
  23769 background works without errors, but the returned coordinates are a bit "jumpy"
  23770 in that case; returning the position of the closest white pixels).
  23771 BUG: On a plain RED screen, aiming at Y>=00F0h, the gun is randomly returning
  23772 either Y, or Y-80h (that error occurs in about every 2nd frame, ie. at 50%
  23773 chance). It's strange... no idea what is causing that effect.
  23774 
  23775 Coordinates
  23776 The coordinates are updated in all frames (as opposed to some lightguns which
  23777 do update them only when pulling the trigger).
  23778 The absolute min/max coordinates may vary from TV set to TV set (some may show
  23779 a few more pixels than others). The relation of the gun's Screen Coodinates to
  23780 VRAM Coordinates does (obviously) depend on where the VRAM is located on the
  23781 screen; ie. on the game's GP1(06h) and GP1(07h) settings.
  23782 Vertical coordinates are counted in scanlines (ie. equal to pixels). Horizontal
  23783 coordinates are counted in 8MHz units (which would equal a resolution of 385
  23784 pixels; which can be, for example, converted to 320 pixel resolution as
  23785 X=X*320/385).
  23786 
  23787 Misinformation (from bugged homebrew source code)
  23788   __Halfword 2 (X)_________________________________
  23789   0-7   X-Coordinate  (actual: see X-Offset)             ;\with unspecified
  23790   8-15  X-Offset      (00h: X=X-80, Nonzero: X=X-80+220) ;/dotclock?
  23791   __Halfword 3 (Y)_________________________________
  23792   0-7   Y-Coordinate  (actual: Y=Y-25) (but then, max is only 230, not 263 ?)
  23793   8-15  Pad ID        (uh, what id?) (reportedly too dark/bright error flag?)
  23794 
  23795 Namco Lightgun Drawing
  23796            _-_______________________--_
  23797   ----->  |    namco            \\\\   \    Namco G-Con 45 (light gray) (cinch)
  23798   sensor   |............ .. .....\\\\...|_
  23799           |_ :          :..   _____      _\
  23800             |  O        :__../  )))|    (
  23801              \__________/  |_\____/|     \
  23802                :               :   |      |
  23803                :               :   |      |  NPC-103
  23804          A-Button (Left)   Trigger |      |  SLPH-00034/SLEH-0007/SLUH-00035
  23805          B-Button (Right)          |______|
  23806 
  23807 See also
  23808 --> Pinouts - Component List and Chipset Pin-Outs for Namco Lightgun, NPC-103
  23809 
  23810 Controllers - Lightguns - Konami Justifier/Hyperblaster (IRQ10)
  23811 ---------------------------------------------------------------
  23812 
  23813 Overall IRQ10-Based Lightgun Access
  23814   Send  01h 42h 00h x0h 00h
  23815   Reply HiZ 31h 5Ah buttons
  23816 The purpose of the "x0h" byte is probably to enable IRQ10 (00h=off, 10h=on),
  23817 this would allow to access more than one lightgun (with only one per frame
  23818 having the IRQ enabled).
  23819 
  23820 Standard IRQ10-based Lightguns (Konami)
  23821 The Controller Data simply consists of the ID and buttons states:
  23822   __Halfword 0 (Controller Info)___________________
  23823   0-15  Controller Info  (5A31h=Konami Lightgun; Timer/IRQ10 type)
  23824   __Halfword 1 (Buttons)
  23825   0-2   Not used                 (All bits always 1)
  23826   3     Start Button (Left Side) (0=Pressed, 1=Released)  ;aka Joypad Start
  23827   4-13  Not used                 (All bits always 1)
  23828   14    Back Button  (Rear End)  (0=Pressed, 1=Released)  ;aka Joypad X-Button
  23829   15    Trigger Button           (0=Pressed, 1=Released)  ;aka Joypad []-Button
  23830 The coordinates aren't part of the controller data, instead they must be read
  23831 from Timer 0 and 1 upon receiving IRQ10 (see IRQ10 Notes below).
  23832 
  23833 Konami Lightgun Drawing
  23834      __                 ______ _
  23835    _|__\_______________/  ___ \ \   Konami Justifier/Hyperblaster (light green)
  23836   |   _______________ __ /   \ \ \
  23837   |__|   _ _ _ _     |==|    O| \O\ .... Back Button (Rear End)
  23838      |__:_:_:_:_:__  |___\__ /  ( (
  23839                    |_|  ) \  :   \ \
  23840       Trigger ......  \___/| :...|.|.... Start Button (Left Side)
  23841                            |     | |
  23842                            |     | | SLPH-00013/SLPH-00014/SLEH-0005/SLUH-00017
  23843                           /     _|_|
  23844                           \___--
  23845 
  23846 Konami IRQ10 Notes
  23847 The PSX does have a lightgun input (Pin 8 of the controller), but, Sony did
  23848 apparently "forget" to latch the current cathode ray beam coordinates by
  23849 hardware when sensing the lightgun signal (quite strange, since that'd be a
  23850 simple, inexpensive, and very obvious feature for a gaming console).
  23851 Instead, the lightgun signal triggers IRQ10, and the interrupt handler is
  23852 intended to "latch" the coordinates by software (by reading Timer 0 and 1
  23853 values, which must configured to be synchronized with the GPU).
  23854 That method requires IRQ handling to be properly implemented in software
  23855 (basically, IRQs should not be disabled for longer periods, and DMA transfers
  23856 should not block the bus for longer periods). In practice, most programmers
  23857 probably don't realize how to do that, to the worst, Sony seems to have
  23858 delivered a slightly bugged library (libgun) to developers.
  23859 For details on Timers, see:
  23860 --> Timers
  23861 In some consoles, IRQ10 seems to be routed through a Secondary IRQ Controller,
  23862 see:
  23863 --> EXP2 DTL-H2000 I/O Ports
  23864 
  23865 IRQ10 Priority
  23866 For processing IRQ10 as soon as possible, it should be assigned higher priority
  23867 than all other IRQs (ie. when using the SysEnqIntRP BIOS function, it should be
  23868 the first/newest element in priority chain 0). The libgun stuff assigns an even
  23869 higher priority by patching the BIOS exception handler, causing IRQ10 to be
  23870 processed shortly before processing the priority chains (the resulting IRQ
  23871 priority isn't actually higher as when using 1st element of chain 0; the main
  23872 difference is that it skips some time consuming code which pushes registers
  23873 R4..R30). For details on that patch, see:
  23874 --> BIOS Patches
  23875 Even if IRQ10 has highest priority, execution of (older) other IRQs may cause a
  23876 new IRQ10 to be executed delayed (because IRQs are disabled during IRQ
  23877 handling), to avoid that problem: Best don't enable any other IRQs except IRQ0
  23878 and IRQ10, or, if you need other IRQs, best have them enabled only during
  23879 Vblank (there are no scanlines drawn during vblank, so IRQ10 should never
  23880 trigger during that period). DMAs might also slow down IRQ execution, so best
  23881 use them only during Vblank, too.
  23882 
  23883 IRQ10 Timer Reading
  23884 To read the current timer values the IRQ10 handler would be required to be
  23885 called <immediately> after receiving the IRQ10 signal, which is more or less
  23886 impossible; if the main program is trying to read a mul/div/gte result while
  23887 the mul/div/gte operation is still busy may stop the CPU for some dozens of
  23888 clock cycles, and active DMA transfers or cache hits and misses in the IRQ
  23889 handler may cause different timings, moreover, timings may become completely
  23890 different if IRQs are disabled (eg. while another IRQ is processed).
  23891 However, IRQ10 does also get triggered in the next some scanlines, so the first
  23892 IRQ10 is used only as a notification that the CPU should watch out for further
  23893 IRQ10's. Ie. the IRQ10 handler should disable all DMAs, acknowledge IRQ10, and
  23894 then enter a waitloop that waits for the IRQ10 bit in I_STAT to become set
  23895 again (or abort if a timeout occurs) and then read the timers, reportedly like
  23896 so:
  23897   IF NTSC then X=(Timer0-140)*0.198166, Y=Timer1
  23898   IF PAL  then X=(Timer0-140)*0.196358, Y=Timer1
  23899 No idea why PAL/NTSC should use different factors, that factors are looking
  23900 quite silly/bugged, theoretically, the pixel-to-clock ratio should be the
  23901 exactly same for PAL and NTSC...?
  23902 Mind that reading Timer values in Dotclock/Hblank mode is unstable, for Timer1
  23903 this can be fixed by the read-retry method, for Timer0 this could be done too,
  23904 but one would need to subtract the retry-time to get a correct coordinate;
  23905 alternately Timer0 can run at system clock (which doesn't require read-retry),
  23906 but it must be then converted to video clock (mul 11, div 7), and then from
  23907 video clock to dot clock (eg. div 8 for 320-pixel mode).
  23908 Above can be repeated for the next some scanlines (allowing to take the medium
  23909 values as result, and/or to eliminate faulty values which are much bigger or
  23910 smaller than the other values). Once when you have collected enough values,
  23911 disable IRQ10, so it won't trigger on further scanlines within the current
  23912 frame.
  23913 
  23914 IRQ10 Bugs
  23915 BUG: The "libgun" library doesn't acknowledge the old IRQ10 <immediately>
  23916 before waiting for a new IRQ10, so the timer values after sensing the new IRQ10
  23917 are somewhat random (especially for the first processed scanline) (the library
  23918 allows to read further IRQ10's in further scanlines, which return more stable
  23919 results).
  23920 No idea how many times IRQ10 gets typically repeated? Sporting Clays allocates
  23921 a buffer for up to 20 scanlines (which would cause pretty much of a slowdown
  23922 since the CPU is just waiting during that period) (nethertheless, the game uses
  23923 only the first timer values, ie. the bugged libgun-random values).
  23924 
  23925 Unknown if/how two-player games (with 2 lightguns) are working with the IRQ10
  23926 method... if IRQ10 is generated ONLY after pressing the trigger button, then it
  23927 may work, unless both players have Trigger pressed at the same time... and,
  23928 maybe one can enable/disable the lightguns by whatever commmand being sent to
  23929 the controller (presumably that "x0h" byte, see above), so that gun 1 generates
  23930 IRQ10 only in each second frame, and gun 2 only in each other frame...?
  23931 
  23932 Controllers - Lightguns - PSX Lightgun Games
  23933 --------------------------------------------
  23934 
  23935 PSX Lightgun Games
  23936 Some games are working only with IRQ10 or only with Cinch, some games support
  23937 both methods:
  23938   Area 51 (Mesa Logic/Midway) (IRQ10)
  23939   Crypt Killer (Konami) (IRQ10)
  23940   Die Hard Trilogy 1: (Probe Entertainment) (IRQ10)
  23941   Die Hard Trilogy 2: Viva Las Vegas (n-Space) (IRQ10/Cinch)
  23942   Elemental Gearbolt (Working Designs) (IRQ10/Cinch)
  23943   Extreme Ghostbusters: Ultimate Invasion (LSP) (Cinch)
  23944   Galaxian 3 (Cinch)
  23945   Ghoul Panic (Namco) (Cinch)
  23946   Gunfighter: The Legend of Jesse James (Rebellion) (Cinch)
  23947   Judge Dredd (Gremlin) (Cinch)
  23948   Lethal Enforcers 1-2 (Konami) (IRQ10)
  23949   Maximum Force (Midway) (IRQ10/Cinch)
  23950   Mighty Hits Special (Altron) (EU/JPN) (Cinch)
  23951   Moorhuhn series (Phenomedia) (Cinch)
  23952   Point Blank 1-3 (Namco) (Cinch)
  23953   Project Horned Owl (Sony) (IRQ10)
  23954   Rescue Shot (Namco) (Cinch)
  23955   Resident Evil: Gun Survivor (Capcom) (JPN/PAL versions) (Cinch)
  23956   Silent Hill (IRQ10) ("used for an easter egg")
  23957   Simple 1500 Series Vol.024 - The Gun Shooting (unknown type)
  23958   Simple 1500 Series Vol.063 - The Gun Shooting 2 (unknown type)
  23959   Snatcher (IRQ10)
  23960   Sporting Clays (Charles Doty) (homebrew with buggy source code) (IRQ10/Cinch)
  23961   Star Wars Rebel Assault II (IRQ10)
  23962   Time Crisis, and Time Crisis 2: Project Titan (Namco) (Cinch)
  23963 Note: The RPG game Dragon Quest Monsters does also contain IRQ10 lightgun code
  23964 (though unknown if/when/where the game does use that code).
  23965 
  23966 
  23967 Controllers - Configuration Commands
  23968 ------------------------------------
  23969 
  23970 Some controllers can be switched from Normal Mode to Config Mode. The Config
  23971 Mode was invented for activating the 2nd rumble motor in SCPH-1200 analog
  23972 joypads. Additionally, the Config commands can switch between analog/digital
  23973 inputs (without needing to manually press the Analog button), activate more
  23974 analog inputs (on Dualshock2), and read some type/status bytes.
  23975 
  23976 Normal Mode
  23977   42h "B" Read Buttons (and analog inputs when in analog mode)
  23978   43h "C" Enter/Exit Configuration Mode (stay normal, or enter)
  23979 Transfer length in Normal Mode is 5 bytes (Digital mode), or 9 bytes (Analog
  23980 mode), or up to 21 bytes (Dualshock2).
  23981 
  23982 Configuration Mode
  23983   40h "@" Unused, or Dualshock2: Get/Set ButtonAttr?
  23984   41h "A" Unused, or Dualshock2: Get Reply Capabilities
  23985   42h "B" Read Buttons AND analog inputs (even when in digital mode)
  23986   43h "C" Enter/Exit Configuration Mode (stay config, or exit)
  23987   44h "D" Set LED State (analog mode on/off)
  23988   45h "E" Get LED State (and Type/constants)
  23989   46h "F" Get Variable Response A (depending on incoming bit)
  23990   47h "G" Get whatever values (response HiZ F3h 5Ah 00h 00h 02h 00h 01h 00h)
  23991   48h "H" Unknown (response HiZ F3h 5Ah 00h 00h 00h 00h 01h 00h)
  23992   49h "I" Unused
  23993   4Ah "J" Unused
  23994   4Bh "K" Unused
  23995   4Ch "L" Get Variable Response B (depending on incoming bit)
  23996   4Dh "M" Get/Set RumbleProtocol
  23997   4Eh "N" Unused
  23998   4Fh "O" Unused, or Dualshock2: Set ReplyProtocol
  23999 Transfer length in Config Mode is always 9 bytes.
  24000 
  24001  ____________________________ Normal Mode Commands ____________________________
  24002 
  24003 Normal Mode - Command 42h "B" - Read Buttons (and analog inputs when enabled)
  24004   Send  01h 42h 00h xx  yy  (00h 00h 00h 00h) (...)
  24005   Reply HiZ id  5Ah buttons ( analog-inputs ) (dualshock2 buttons...)
  24006 The normal read command, see Standard Controller chapter for details on buttons
  24007 and analog inputs. The xx/yy bytes have effect only if rumble is unlocked; use
  24008 Command 43h to enter config mode, and Command 4Dh to unlock rumble. Command 4Dh
  24009 has billions of combinations, among others allowing to unlock only one of the
  24010 two motors, and to exchange the xx/yy bytes, however, with the default values,
  24011 xx/yy are assigned like so:
  24012   yy.bit0-7 ---> Left/Large Motor M1 (analog slow/fast) (00h=stop, FFh=fastest)
  24013   xx.bit0   ---> Right/small Motor M2 (digital on/off)  (0=off, 1=on)
  24014 The Left/Large motor starts spinning at circa min=50h..60h, and, once when
  24015 started keeps spinning downto circa min=38h. The exact motor start boundary
  24016 depends on the current position of the weight (if it's at the "falling" side,
  24017 then gravity helps starting), and also depends on external movements (eg. it
  24018 helps if the user or the other rumble motor is shaking the controller), and may
  24019 also vary from controller to controller, and may also depend on the room
  24020 temperature, dirty or worn-out mechanics, etc.
  24021 
  24022 Normal Mode - Command 43h "C" - Enter/Exit Configuration Mode
  24023   Send  01h 43h 00h xx  00h (zero padded...)   (...)
  24024   Reply HiZ id  5Ah buttons (analog inputs...) (dualshock2 buttons...)
  24025 When issuing command 43h from inside normal mode, the response is same as for
  24026 command 42h (button data) (and analog inputs when in analog mode) (but without
  24027 M1 and M2 parameters). While in config mode, the ID bytes are always "F3h 5Ah"
  24028 (instead of the normal analog/digital ID bytes).
  24029   xx=00h Stay in Normal mode
  24030   xx=01h Enter Configuration mode
  24031 Caution: Additionally to activating configuration commands, entering config
  24032 mode does also activate a Watchdog Timer which does reset the controller if
  24033 there's been no communication for about 1 second or so. The watchdog timer
  24034 remains active even when returning to normal mode via Exit Config command. The
  24035 reset does disable and lock rumble motors, and switches the controller to
  24036 Digital Mode (with LED=off, and analog inputs disabled). To prevent this, be
  24037 sure to keep issuing joypad reads even when not needing user input (eg. while
  24038 loading data from CDROM).
  24039 Caution 2: A similar reset occurs when the user pushes the Analog button; this
  24040 is causing rumble motors to be stopped and locked, and of course, the
  24041 analog/digital state gets changed.
  24042 Caution 3: If config commands were used, and the user does then push the analog
  24043 button, then the 5Ah-byte gets replaced by 00h (ie. responses change from "HiZ
  24044 id 5Ah ..." to "HiZ id 00h ...").
  24045 
  24046  ____________________________ Config Mode Commands ____________________________
  24047 
  24048 Config Mode - Command 42h "B" - Read Buttons AND analog inputs
  24049   Send  01h 42h 00h M2  M1  00h 00h 00h 00h
  24050   Reply HiZ F3h 5Ah buttons  analog-inputs
  24051 Same as command 42h in normal mode, but with forced analog response (ie. analog
  24052 inputs and L3/R3 buttons are returned even in Digital Mode with LED=Off).
  24053 
  24054 Config Mode - Command 43h "C" - Enter/Exit Configuration Mode
  24055   Send  01h 43h 00h xx  00h 00h 00h 00h 00h
  24056   Reply HiZ F3h 5Ah 00h 00h 00h 00h 00h 00h
  24057 Equivalent to command 43h in normal mode, but returning 00h bytes rather than
  24058 button data, can be used to return to normal mode.
  24059   xx=00h Enter Normal mode (Exit Configuration mode)
  24060   xx=01h Stay in Configuration mode
  24061 Back in normal mode, the rumble motors (if they were enabled) can be controlled
  24062 with normal command 42h.
  24063 
  24064 Config Mode - Command 44h "D" - Set LED State (analog mode on/off)
  24065   Send  01h 44h 00h Led Key 00h 00h 00h 00h
  24066   Reply HiZ F3h 5Ah 00h 00h Err 00h 00h 00h
  24067 The Led byte can be:
  24068   When Led=00h      --> Digital mode, with LED=Off
  24069   When Led=01h      --> Analog mode, with LED=On/red
  24070   When Led=02h..FFh --> Ignored (and, in case of dualshock2: set Err=FFh)
  24071 The Key byte can be:
  24072   When Key=00h..02h --> Unlock (allow user to push Analog button)
  24073   When Key=03h      --> Lock (stay in current mode, ignore Analog button)
  24074   When Key=04h..FFh --> Acts same as (Key AND 03h)
  24075 The Err byte is usually 00h (except, Dualshock2 sets Err=FFh upon Led=02h..FFh;
  24076 older PSX/PSone controllers don't do that).
  24077 
  24078 Config Mode - Command 45h "E" - Get LED State (and Type/constants)
  24079   Send  01h 45h 00h 00h 00h 00h 00h 00h 00h
  24080   Reply HiZ F3h 5Ah Typ 02h Led 02h 01h 00h
  24081 Returns two interesting bytes:
  24082   Led: Current LED State (00h=Off, 01h=On/red)
  24083   Typ: Controller Type (01h=PSX/Analog Pad, 03h=PS2/Dualshock2)
  24084 The other bytes might indicate the number of rumble motors, analog sticks, or
  24085 version information, or so.
  24086 
  24087 Config Mode - Command 46h "F" - Get Variable Response A
  24088   Send  01h 46h 00h ii  00h 00h 00h 00h 00h
  24089   Reply Hiz F3h 5Ah 00h 00h cc  dd  ee  ff
  24090 When ii=00h --> returns cc,dd,ee,ff = 01h,02h,00h,0ah
  24091 When ii=01h --> returns cc,dd,ee,ff = 01h,01h,01h,14h
  24092 Otherwise --> returns cc,dd,ee,ff = all zeroes
  24093 
  24094 Config Mode - Command 47h "G" - Get whatever values
  24095   Send  01h 47h 00h 00h 00h 00h 00h 00h 00h
  24096   Reply HiZ F3h 5Ah 00h 00h 02h 00h 01h 00h
  24097 Purpose unknown.
  24098 
  24099 Config Mode - Command 4Ch "L" - Get Variable Response B
  24100   Send  01h 4Ch 00h ii  00h 00h 00h 00h 00h
  24101   Reply Hiz F3h 5Ah 00h 00h 00h dd  00h 00h
  24102 When ii=00h --> returns dd=04h.
  24103 When ii=01h --> returns dd=07h.
  24104 Otherwise --> returns dd=00h.
  24105 
  24106 Config Mode - Command 48h "H" - Unknown (response HiZ F3h 5Ah 4x00h 01h 00h)
  24107   Send  01h 48h 00h ii  00h 00h 00h 00h 00h
  24108   Reply HiZ F3h 5Ah 00h 00h 00h 00h ee  00h
  24109 When ii=00h..01h --> returns ee=01h.
  24110 Otherwise --> returns ee=00h.
  24111 Purpose unknown. The command does not seem to be used by any games.
  24112 
  24113 Config Mode - Command 4Dh "M" - Get/Set RumbleProtocol
  24114 --> Controllers - Vibration/Rumble Control
  24115 
  24116 Config Mode - Command 40h "@" Dualshock2: Get/Set ButtonAttr?
  24117 Config Mode - Command 41h "A" Dualshock2: Get Reply Capabilities
  24118 Config Mode - Command 4Fh "O" Dualshock2: Set ReplyProtocol
  24119 --> Controllers - Analog Buttons (Dualshock2)
  24120 
  24121 Config Mode - Command 49h "I" - Unused
  24122 Config Mode - Command 4Ah "J" - Unused
  24123 Config Mode - Command 4Bh "K" - Unused
  24124 Config Mode - Command 4Eh "N" - Unused
  24125 Config Mode - Command 40h "@" - Unused (except, used by Dualshock2)
  24126 Config Mode - Command 41h "A" - Unused (except, used by Dualshock2)
  24127 Config Mode - Command 4Fh "O" - Unused (except, used by Dualshock2)
  24128   Send  01h 4xh 00h 00h 00h 00h 00h 00h 00h
  24129   Reply HiZ F3h 5Ah 00h 00h 00h 00h 00h 00h
  24130 These commands do return a bunch of 00h bytes. These commands do not seem to be
  24131 used by any games (apart from the Dualshock2 commands being used by Dualshock2
  24132 games).
  24133 
  24134 Note
  24135 Something called "Guitar Hero controller" does reportedly also support Config
  24136 commands. Unknown if that thing does have the same inputs & rumble motors as
  24137 normal analog PSX joypads, and if it does return special type values.
  24138 
  24139 Controllers - Vibration/Rumble Control
  24140 --------------------------------------
  24141 
  24142 Rumble (aka "Vibration Function") is basically controlled by two previously
  24143 unused bytes of the standard controller Read command.
  24144 There are two methods to control the rumble motors, the old method is very
  24145 simple (but supports only one motor), the new method envolves a bunch of new
  24146 configuration commands (and supports two motors).
  24147   SCPH-1150  DualAnalog Pad with 1 motor                  ;-old rumble method
  24148   SCPH-1200  DualAnalog Pad with 2 motors, PSX-design     ;\new rumble method
  24149   SCPH-110   DualAnalog Pad with 2 motors, PSone-design   ;/
  24150   SCPH-10010 DualAnalog Pad with 2 motors, PS2/Dualshock2 ;-plus analog buttons
  24151   Blaze Scorpion Lightgun with rumble      ;\unknow how to control rumble
  24152   Fishing controllers with rumble          ;/
  24153   SCPH-1180 Analog Pad without rumble      ;\unknow if there're config commands
  24154   SCPH-1110 Analog Stick without rumble    ;/for analog mode (probably not)
  24155 
  24156  _________________________________ Old Method _________________________________
  24157 
  24158 Old Method, one motor, no config commands (SCPH-1150, SCPH-1200, SCPH-110)
  24159 The SCPH-1150 doesn't support any special config commands, instead, rumble is
  24160 solely done via the normal joypad read command:
  24161   Send  01h 42h 00h xx  yy  (00h 00h 00h 00h)
  24162   Reply HiZ id  5Ah buttons ( analog-inputs )
  24163 The rumble motor is simply controlled by three bits in the xx/yy bytes:
  24164   xx --> must be 40h..7Fh            (ie. bit7=0, bit6=1) ;\switches motor on
  24165   yy --> must be 01h,03h,...,FDh,FFh (ie. bit0=1)         ;/
  24166 The motor control is digital on/off (no analog slow/fast), recommended values
  24167 would be yyxx=0140h=on, and yyxx=0000h=off.
  24168 LED state is don't care (rumble works with led OFF, RED, and GREEN). In absence
  24169 of config commands, the LED can be controlled only manually (via Analog
  24170 button), the current LED state is implied in the controller "id" byte.
  24171 For backwards compatibility, the above old method does also work on SCPH-1200
  24172 and SCPH-110 (for controlling the right/small motor), alternately those newer
  24173 pads can use the config commands (for gaining access to both motors).
  24174 
  24175  _________________________________ New Method _________________________________
  24176 
  24177 New Method, two motors, with config commands (SCPH-1200, SCPH-110)
  24178 For using the new rumble method, one must unlock the new rumble mode, for that
  24179 purpose Sony has invented a "slightly" overcomplicated protocol with not less
  24180 than 16 new commands (the rumble relevant commands are 43h and 4Dh, also,
  24181 command 44h may be useful for activating analog inputs by software, and, once
  24182 when rumble is unlocked, command 42h is used to control the rumble motors).
  24183 Anyways, here's the full command set...
  24184 Controllers - Configuration Commands
  24185 And, the rumble-specific config command is described below...
  24186 
  24187 Config Mode - Command 4Dh "M" - Get/Set RumbleProtocol
  24188   Send  01h 4Dh 00h aa  bb  cc  dd  ee  ff     ;<-- set NEW aa..ff values
  24189   Reply Hiz F3h 5Ah aa  bb  cc  dd  ee  ff     ;<-- returns OLD aa..ff values
  24190 Bytes aa,bb,cc,dd,ee,ff control the meaning of the 4th,5th,6th,7th,8th,9th
  24191 command byte in the controller read command (Command 42h).
  24192   00h      = Map Right/small Motor (Motor M2) to bit0 of this byte
  24193   01h      = Map Left/Large Motor (Motor M1) to bit0-7 of this byte
  24194   02h..FEh = Unknown (can be mapped, maybe for extra motors/outputs)
  24195   FFh      = Map nothing to this byte
  24196 In practice, one would usually send either one of these command/values:
  24197   Send  01h 4Dh 00h 00h 01h FFh FFh FFh FFh    ;enable new method (two motors)
  24198   Send  01h 4Dh 00h FFh FFh FFh FFh FFh FFh    ;disable motor control
  24199 Alternately, one could swap the motors by swapping values in aa/bb. Or one
  24200 could map the motors anywhere to cc/dd/ee/ff (this will increase the command
  24201 length in digital mode, hence changing digital mode ID from 41h to 42h or 43h).
  24202 Or, one could map further rumble motors or other outputs to the six bytes (if
  24203 any such controller would exist).
  24204 In the initial state, aa..ff are all FFh, and the controller does then use the
  24205 old rumble control method (with only one motor). However, that old method gets
  24206 disabled once when having messed with config commands (unknown if/how one can
  24207 re-enable the old method by software).
  24208 
  24209 Unknown Dualshock2 Vibration
  24210 Dualshock2 does reportedly have "two more levels of vibration", unknown what
  24211 that means and if it's used by any PSX or PS2 games... it might refer to the
  24212 small motor which usually has only 2 levels (on/off) and might have 4 levels
  24213 (fast/med/slow/off) on dualshock2... but, if so, it's unknown how to
  24214 control/unlock that feature.
  24215 Also, the PSone controller (SCPH-110) appear to have been released shortly
  24216 after Dualshock2, unknown if that means that it might have that feature, too.
  24217 
  24218 Note
  24219 Rumble is a potentially annoying feature, so games that do support rumble
  24220 should also include an option to disable it.
  24221 
  24222 Controllers - Analog Buttons (Dualshock2)
  24223 -----------------------------------------
  24224 
  24225 Dualshock2 has three new commands (40h,41h,4Fh) for configuring analog buttons.
  24226 Additionally, Command 45h does return a different type byte for Dualshock2.
  24227 Dualshock2 is a PS2 controller. However, it can be also used with PSX games
  24228 (either by connecting the controller to a PSX console, or by playing a PSX game
  24229 on a PS2 console).
  24230 The analog button feature is reportedly rarely used by PS2 games (and there
  24231 aren't any PSX games known to use it).
  24232 
  24233 Config Mode - Command 40h "@" Dualshock2: Get/Set ButtonAttr?
  24234   Send  01h 40h 00h Idx Val 00h 00h 00h 00h  ;<-- Set NEW Val, array[Idx]=Val
  24235   Reply HiZ F3h 5Ah 00h 00h Val 00h 00h 00h  ;<-- Old Val (or FFh when Idx>0Bh)
  24236 Allows to change twelve 3bit values (with Idx=00h..0Bh, and Val=00h..03h).
  24237 Default is Val=02h. Purpose is unknown, the 12 values might be related to the
  24238 12 analog buttons, but there is no noticable difference between Val=0,1,2,3.
  24239 Maybe it does have some subtle effects on things like...
  24240   Digital button sensitivity, or Analog button sensitivity, or
  24241   Analog button bit-depth/conversion speed, or something else?
  24242 
  24243 Config Mode - Command 41h "A" Dualshock2: Get Reply Capabilities
  24244   Send  01h 41h 00h 00h 00h 00h 00h 00h 00h
  24245   Reply HiZ F3h 5Ah FFh FFh 03h 00h 00h 00h
  24246 This seems to return a constant bitmask indicating which reply bytes can be
  24247 enabled/disabled via Command 4Fh (ie. 3FFFFh = 18 bits).
  24248 
  24249 Config Mode - Command 4Fh "O" Dualshock2: Set ReplyProtocol
  24250   Send  01h 41h 00h aa  bb  cc  dd  ee  ff
  24251   Reply HiZ F3h 5Ah 00h 00h 00h 00h 00h 00h
  24252 This can output some 48bit value (bit0=aa.bit0, bit47=ff.bit7), used to
  24253 enable/disable Reply bytes in the controller read command (Command 42h).
  24254   -      HighZ                   (always transferred)      1st byte
  24255   -      ID/Mode/Len             (always transferred)      2nd byte
  24256   -      5Ah                     (always transferred)      3rd byte
  24257   0      LSB of digital buttons  (0=No, 1=Yes)             4th byte
  24258   1      MSB of digital buttons  (0=No, 1=Yes)             5th byte
  24259   2      RightJoyX               (0=No, 1=Yes)             6th byte
  24260   3      RightJoyY               (0=No, 1=Yes)             7th byte
  24261   4      LeftJoyX                (0=No, 1=Yes)             8th byte
  24262   5      LeftJoyY                (0=No, 1=Yes)             9th byte
  24263   6      DPAD Right              (0=No, 1=Yes) button 00h  10th byte
  24264   7      DPAD Left               (0=No, 1=Yes) button 01h  11th byte
  24265   8      DPAD Uup                (0=No, 1=Yes) button 02h  12th byte
  24266   9      DPAD Down               (0=No, 1=Yes) button 03h  13th byte
  24267   10     Button /\               (0=No, 1=Yes) button 04h  14th byte
  24268   11     Button ()               (0=No, 1=Yes) button 05h  15th byte
  24269   12     Button ><               (0=No, 1=Yes) button 06h  16th byte
  24270   13     Button []               (0=No, 1=Yes) button 07h  17th byte
  24271   14     Button L1               (0=No, 1=Yes) button 08h  18th byte
  24272   15     Button R1               (0=No, 1=Yes) button 09h  19th byte
  24273   16     Button L2               (0=No, 1=Yes) button 0Ah  20th byte
  24274   17     Button R2               (0=No, 1=Yes) button 0Bh  21st byte
  24275   18-39  Must be 0 (otherwise command is ignored)
  24276   40-47  Unknown (no effect?)
  24277 Usually, one would use one of the following command/values:
  24278   Send  01h 41h 00h 03h 00h 00h 00h 00h 00h  Digital buttons
  24279   Send  01h 41h 00h 3Fh 00h 00h 00h 00h 00h  Digital buttons + analog sticks
  24280   Send  01h 41h 00h FFh FFh 03h 00h 00h 00h  Enable all 18 input bytes
  24281 The transfer order is 1st..21st byte as shown above (unless some bits are
  24282 cleared, eg. if bit0-5=0 and bit6=1 then DPAD Right would appear as 4th byte
  24283 instead of 10th byte). The command length increases/decreases depening on the
  24284 number of enabled bits. The transfer length is always 3+N*2 bytes (including a
  24285 00h padding byte when the number of enabled bits is odd). The analog mode ID
  24286 byte changes depending on number of halfwords.
  24287 CAUTION: Sending Command 44h does RESET the Command 4Fh setting (either to
  24288 DigitalMode=000003h or AnalogMode=00003Fh; same happens when toggling mode via
  24289 Analog button).
  24290 
  24291 Note: Some Dualshock2 Config Mode commands do occassionally send 00h, 5Ah, or
  24292 FFh as last (9th) reply byte (unknown if that is some error/status thing, or
  24293 garbage).
  24294 
  24295 Analog Button Sensitivity
  24296 The pressure sensors are rather imprecise and results may vary on various
  24297 factors, including the pressure angle.
  24298   00h       Button released
  24299   01h..2Fh  Normal (soft) pressure
  24300   30h..FEh  Medium pressure
  24301   FFh       Hard pressure
  24302 Software can safely distinguish between soft and hard pressure.
  24303 Medium pressure is less predictably: The values do not increase linearily, it's
  24304 difficult to apply a specific amount of medium pressure (such like 80h..9Fh),
  24305 increasing pressure may sometimes jump from 24h to FFh, completely skipping the
  24306 medium range.
  24307 Relying on the medium range might work for accelleration buttons (where the
  24308 user could still adjust the pressure when the accelleration is too high or too
  24309 low); but it would be very bad practice to assign irreversible actions to
  24310 medium pressure (such like Soft=Load, Medium=Save, Hard=Quit).
  24311 
  24312 Digital Button Sensitivity
  24313 Digital inputs are converting the analog inputs as so:
  24314   Analog=00h      --> not pressed
  24315   Analog=01h..FFh --> pressed (no matter if soft, medium, or hard pressure)
  24316 Digital inputs are working even when also having analog input enabled for the
  24317 same button.
  24318 
  24319 See also
  24320   https://gist.github.com/scanlime/5042071 - tech (=mentions unknown details)
  24321   https://store.curiousinventor.com/guides/PS2/ - guide (=omits unknown stuff)
  24322 
  24323 Controllers - Dance Mats
  24324 ------------------------
  24325 
  24326 PSX Dance Mats are essentially normal joypads with uncommonly arranged buttons,
  24327 the huge mats are meant to be put on the floor, so the user could step on them.
  24328 
  24329 Dance Mat vs Joypad Compatibility
  24330 There are some differences to normal joypads: First of, the L1/L2/R1/R2
  24331 shoulder buttons are missing in most variants. And, the mats are allowing to
  24332 push Left+Right and Up+Down at once, combinations that aren't mechanically
  24333 possible on normal joypads (some dancing games do actually require those
  24334 combinations, whilst some joypad games may get confused on them).
  24335 
  24336 Dance Mat Unknown Things
  24337 Unknown if the mat was sold in japan, and if so, with which SLPH/SCPH number.
  24338 Unknown if the mat's middle field is also having a button assigned.
  24339 Unknown if the mat is having a special controller ID, or if there are other
  24340 ways to detect mats (the mats are said to be compatible with skateboard games,
  24341 so the mats are probably identifying themselves as normal digital joypad;
  24342 assuming that those skateboard games haven't been specifically designed for
  24343 mats).
  24344 
  24345 Dance Mat Games
  24346   D.D.R. Dance Dance Revolution 2nd Remix
  24347   (and maybe whatever further games)
  24348 The mats can be reportedly also used with whatever skateboard games.
  24349 
  24350 Dance Mat Variants
  24351 There is the US version (DDR Dance Pad, SLUH-00071), and a slightly different
  24352 European version (Official Dance Mat, SLEH-00023: shiny latex style with
  24353 perverted colors, and Start/Select arranged differently). The japanese version
  24354 (RU017) resembles the US version, but without Triangle/Square symbols drawn in
  24355 lower left/right edges.
  24356 And there is a handheld version (with additional L1/L2/R2/R1 buttons; maybe
  24357 unlicensed; produced as MINI DDR, and also as Venom Mini Dance Pad).
  24358 
  24359    US Version (white/black/red/blue)         Handheld Version (blue/gray)
  24360     __________.---------.___________          _____/ MINI  \_____
  24361    |          \         /           |        |      D.D.R.       |
  24362    |  SELECT   '-------'    START   |        |L1 L2 SEL STA R2 R1|
  24363    |------------.------.------------|        | ___    ___    ___ |
  24364    |  .''''.   /        \   .''''.  |        || X |  | ^ |  | O ||
  24365    | |  \/  | |    /\    | | .''. | |        ||___|  |___|  |___||
  24366    | |  /\  | |   /..\   | | '..' | |        | ___   .---.   ___ |
  24367    |  '....'  '.   ||   .'  '....'  |        || < | |Stay | | > ||
  24368    | .-------. .''''''''. .-------. |        ||___| |Cool!| |___||
  24369    |/   /|   .'          '.   |\   \|        | ___   '___'   ___ |
  24370    |   / |-- |            | --| \   |        || []|  | v |  | /\||
  24371    |   \ |-- | Stay Cool! | --| /   |        ||___|  |___|  |___||
  24372    |\   \|   '.          .'   |/   /|        |___________________|
  24373    | '-------' '........' '-------' |
  24374    |  .''''.  .'   ||   '.  .''''.  |        Gothic Dance Mat (black/silver)
  24375    | |  /\  | |   \''/   | | |''| | |         _.----------._
  24376    | | /__\ | |    \/    | | |..| | |        | \ SEL  STA / | This one
  24377    |  '....'   \        /   '....'  |        |  '--------'  | wasn't ever
  24378    '------------'------'------------'        | .----------. | produced,
  24379                                              | |  .''''.  | | as cool as
  24380    European Version (pink/blue/yellow)       | | |  /\  | | | it could have
  24381     __________.---------.___________         | | | /..\ | | | been, the lame
  24382    |          \ SEL STA /           |        | |  '.||.'  | | marketing
  24383    |           '-------'            |        | +----------+ | people didn't
  24384    |----------.----------.----------|        | |  .''''.  | | even think
  24385    |  .''''.  |  .''''.  |  .''''.  |        | | |  /\  | | | about it.
  24386    | |  \/  | | |  /\  | | | .''. | |        | | | /..\ | | |
  24387    | |  /\  | | | /..\ | | | '..' | |        | |  '.||.'  | |
  24388    |  '....'  |  '.||.'  |  '....'  |        | +----------+ |
  24389    |----------+-..    ..-+----------|        | |  .'||'.  | |
  24390    |  .'/|'.  /   ''''   \  .'|\'.  |        | | | \''/ | | |
  24391    | | / |--|/            \|--| \ | |        | | |  \/  | | |
  24392    | | \ |--|\            /|--| / | |        | |  '....'  | |
  24393    |  '.\|.'  \   ....   /  '.|/.'  |        | +----------+ |
  24394    |----------+-''    ''-+----------|        | |  .'||'.  | |
  24395    |  .''''.  |  .'||'.  |  .''''.  |        | | | \''/ | | |
  24396    | |  /\  | | | \''/ | | | |''| | |        | | |  \/  | | |
  24397    | | /__\ | | |  \/  | | | |..| | |        | |  '....'  | |
  24398    |  '....'  |  '....'  |  '....'  |        | '----------' '
  24399    '----------|----------|----------'        '--------------'
  24400 
  24401 Stay Cool?
  24402 Despite of the "Stay Cool!" slogan, the mat wasn't very cool - not at all! It
  24403 offered only two steps back-and-forth, and also allowed to do extremly uncool
  24404 side-steps. Not to mention that it would melt when dropping a burning cigarette
  24405 on it. Stay Away!
  24406 
  24407 Controllers - Fishing Controllers
  24408 ---------------------------------
  24409 
  24410 The fishing rods are (next to lightguns) some of the more openly martial
  24411 playstation controllers - using the credo that "as long as you aren't using
  24412 dynamite: it's okay to kill them cause they don't have any feelings."
  24413 
  24414 PSX Fishing Controller Games
  24415   Action Bass (Syscom Entertainment) (1999) (SLPH-00100)
  24416   Bass Landing (ASCII/agetec) (1999) (SLPH-00100, SLUH-00063)
  24417   Bass Rise, Fishing Freaks (Bandai) (1999) (BANC-0001)
  24418   Bass Rise Plus, Fishing Freaks (Bandai) (2000) (BANC-0001, SLPH-00100)
  24419   Breath of Fire IV (Capcom) (SLUH-00063)
  24420   Championship Bass (EA Sports) (2000) (SLUH-00063)
  24421   Fish On! Bass (Pony Canyon) (1999) (BANC-0001, SLPH-00100)
  24422   Fisherman's Bait 2/Exiting Bass2 - Big Ol'Bass(Konami)(SLPH-00100,SLUH-00063)
  24423   Fishing Club: (series with 3 titles) (have "headset-logo" on back?)
  24424   Lake Masters II (1999) (Dazz/Nexus) (SLPH-00100)
  24425   Lake Masters Pro (1999) (Dazz/Nexus) (BANC-0001, SLPH-00100)
  24426   Let's Go Bassfishing!: Bass Tsuri ni Ikou! (Banpresto) (1999) (SLPH-00100)
  24427   Matsukata Hiroki no World Fishing (BPS The Choice) (1999) (SLPH-00100)
  24428   Murakoshi Seikai-Bakuchou Nihon Rettou (Victor) (SLPH-00100)
  24429   Murakoshi Masami-Bakuchou Nippon Rettou:TsuriConEdition (1999) (SLPH-00100)
  24430   Pakuchikou Seabass Fishing (JP, 03/25/99) (Victor) (SLPH-00100)
  24431   Perfect Fishing: Bass Fishing (2000) (Seta) (yellow/green logo)
  24432   Perfect Fishing: Rock Fishing (2000) (Seta) (yellow/green logo)
  24433   Oyaji no Jikan: Nechan, Tsuri Iku De! (2000) (Visit) (BANC-0001, SLPH-00100)
  24434   Reel Fishing II / Fish Eyes II (2000)(Natsume/Victor)(SLPH-00100, SLUH-00063)
  24435   Simple 1500 Series Vol. 29: The Tsuri (2000) (yellow/green logo)
  24436   Suizokukan Project: Fish Hunter e no Michi (1999)(Teichiku)(SLPH-00100)
  24437   Super Bass Fishing (1999) (King) (BANC-0001, SLPH-00100, yellow/green logo)
  24438   Super Black Bass X2 (2000) (Starfish) (SLPH-00100)
  24439   Tsuwadou Keiryuu Mizuumihen (Best Edition)(2000) (ASCII PS1+PS2 controllers?)
  24440   Tsuwadou Seabass Fishing (PlayStation the Best) (1999) (Oz Club) (SLPH-00100)
  24441   Uki Uki Tsuri Tengoku Nagami/Uokami Densetsu Oe (2000) (Teichiku)(SLPH-00100)
  24442   Umi no Nushi Tsuri-Takarajima ni Mukatte (1999)(Victor)(BANC-0001,SLPH-00100)
  24443   Winning Lure (Hori) (2000) (for Hori HPS-97 controller)  AKA HPS-98 ?
  24444 For more see: http://www.gamefaqs.com/ps/list-109 (sports->nature->fishing)
  24445 
  24446 Logos on CD Covers
  24447 US Fishing games should have a "SLUH-00063" logo. European Fishing games don't
  24448 have any fishing logos; apparently fishing controllers haven't been officially
  24449 released/supported in Europe.
  24450 Japanese Fishing games can have a bunch of logos: Usually BANC-0001 or
  24451 SLPH-00100 (or both).
  24452 Moreover, some japanese games have a yellow/green fishing logo with japanese
  24453 text (found on Perfect Fishing: Bass Fishing, Perfect Fishing: Rock Fishing,
  24454 Simple 1500 Series Vol. 29: The Tsuri, Super Bass Fishing) (unknown if that
  24455 logo refer to other special hardware, or if it means the "normal" BANC-0001 or
  24456 SLPH-00100 controllers.
  24457 And Moreover, some japanese games have some sort of "headset" logos with
  24458 japanese text, these seem to have same meaning as SLPH-00100; as indicated by
  24459 photos on CD cover of Tsuwadou Keiryuu Mizuumihen (Best Edition) (2000); that
  24460 CD cover also has a "headset 2" logo, which seems to mean a newer PS2 variant
  24461 of the SLPH-00100.
  24462 
  24463 PSX Fishing Controllers
  24464   ASCII SLPH-00100 (silver)
  24465   ASCII PS2-version? (silver) (similar to SLPH-00100, with new mode switch?)
  24466   agetec SLUS-00063 (silver) (US version of ASCII's SLPH-00100 controller)
  24467   Bandai BANC-0001 (dark gray/blue) (has less buttons than ASCII/agetec)
  24468   Interact Fission (light gray/blue)(similar to ASCII/agetec, 2 extra buttons?)
  24469   Naki (transparent blue) (looks like a clone of the ASCII/agetec controllers)
  24470   Hori HPS-97/HPS-98 (black/gray) (a fishing rod attached to a plastic fish)
  24471 Of these, the ASCII/agetec controllers seem to be most popular (and most
  24472 commonly supported). The Bandai contoller is also supported by a couple of
  24473 games (though the Bandai controller itself seems to be quite rare). The
  24474 Interact/Naki controllers are probably just clones of the ASCII/agetec ones.
  24475 The Hori controller is quite rare (and with its string and plastic fish, it's
  24476 apparently working completely different than the other fishing controllers).
  24477 
  24478 Tech Info (all unknown)
  24479 Unknown how to detect fishing controllers.
  24480 Unknown how to read buttons, joystick, crank, motion sensors.
  24481 Unknown how to control rumble/vibration.
  24482 Unknown if/how Bandai differs from ASCII/agetec (aside from less buttons).
  24483 Unknown how the Hori thing works.
  24484 
  24485 ASCII SLPH-00100 / agetec SLUH-00063 (silver)
  24486           ___
  24487        __|___|__
  24488      _|         |_     _   __
  24489     | |         | |   | |=|__| <--- crank handle
  24490     | | SEL STA | |   | |
  24491     | |         | |---|  \                         ASCII SLPH-00100
  24492     |  \       /  |---|  /                         agetec SLUH-00063
  24493    /  L1       R1  \  | |  __
  24494   |  L2  .---.  R2  | |_|=|__|
  24495   |     | joy |     |
  24496   |     |stick|     |  <------- analog thumb controlled joystick
  24497   | /\   '---'   >< |
  24498   |   []       ()   |
  24499    \     ASCII     /
  24500     '.___________.'   \___ 10 buttons (SEL,STA,L1,L2,R1,R2,/\,[],(),><)
  24501        \ _____ /
  24502         |     |           Note: many (not all) agetec controllers
  24503         |     |           have the >< and () buttons exchanged
  24504         |     |
  24505         |     |              Aside from the crank/buttons/joystick,
  24506         |     |              the controller reportedly contains:
  24507         |     |              some sort of motion sensors?
  24508         |     |              some kind of rumble/vibration?
  24509         |     |
  24510         '.___.'
  24511            '--...___ cable
  24512 
  24513 Bandai BANC-0001 (dark gray/blue)
  24514           ___
  24515        __|___|__
  24516      _|         |      _   __
  24517     | .---.     |\    | |=|__| <--- crank handle
  24518     || joy |    | |   | |
  24519     ||stick|    | |-#-|  \
  24520     | '---'     | |-#-|  /
  24521    / \          |  \  | |  __
  24522   |   |   ...   |   | |_|=|__|
  24523   |   |  :   :  | ()|
  24524   |   |O :___: O|   |   <--- two buttons: () and ><
  24525   |   |- |___| -| ><|        and some slide switch with I and 0 positions?
  24526   |   |         |   |
  24527    \  |  BANDAI |  /      unknown if the joystick is digital or analog
  24528     '._\_______/_.'
  24529        |       |          unknown if there are motion sensors and/or rumble
  24530        '.     .'
  24531         |     |
  24532         |     |
  24533         |     |
  24534         |     |
  24535         |     |
  24536         |     |
  24537         |     |
  24538         '.___.'
  24539            '--...___ cable
  24540 
  24541 Hori HPS-97 / HPS-98 (black/gray)
  24542               ....----------------O
  24543            .''                     \  HPS-97 (controller bundled with game)
  24544           _:_        \              \ HPS-98 (controller only, for HPS-96 game)
  24545        __|___|__      \ short        \
  24546      _|         |_      elastic       \
  24547     |             |     pole           \
  24548     |             |                     \    <--- string (from pole to
  24549     |     SW?     |     _   __           \        reel inside of fish)
  24550    /               \   | |=|__|           \
  24551   |      .---.      |  | |                 \
  24552   | ( ) | joy |     |--|  \                 \               ___
  24553   |     |stick|     |--|  /                  \             /   /
  24554   | ( )  '---'      |  | |  __                \     ...---''''''--.  /|
  24555   |                 |  |_|=|__| <--- crank     \   '               '/ |
  24556    \    ( ) ( )    /                 handle     '..|                  |.
  24557     '.___________.'                                |__________________| :
  24558        \       /     \                                plastic fish      :
  24559         |     |       joystick,                  (presumable some heavy :
  24560         |     |       four buttons,              stationary thing that  :
  24561         |     |       and a switch?              rests on floor)        :
  24562         |     |                                  (presumably with       :
  24563         |     |                                  motor-driven reel?)    :
  24564         |     |                                                         :
  24565         |     |     the two cables do probably connect                  :
  24566         |     |     to both of the PSX controller slots                 :
  24567         '.___.'                                            cable 2  ---'
  24568            '--...___ cable 1
  24569 
  24570 Controllers - I-Mode Adaptor (Mobile Internet)
  24571 ----------------------------------------------
  24572 
  24573 The I-Mode Adaptor cable (SCPH-10180) allows to connect an I-mode compatible
  24574 mobile phone to the playstation's controller port; granting a mobile internet
  24575 connection to japanese games.
  24576 
  24577 PSX Games for I-Mode Adaptor (Japan only)
  24578   Doko Demo Issyo (PlayStation the Best release only) (Sony) 2000
  24579   Doko Demo Issyo Deluxe Pack (Bomber eXpress/Sony) 2001
  24580   Hamster Club-I (SLPS-03266) (Jorudan) 2002
  24581   iMode mo Issyo: Dokodemo Issho Tsuika Disc (Bomber/Sony) 2001
  24582   Keitai Eddy (iPC) 2000 (but, phone connects to SIO port on REAR side of PSX?)
  24583   Komocchi (Victor) 2001
  24584   Mobile Tomodachi (Hamster) 2002
  24585   Motto Trump Shiyouyo! i-Mode de Grand Prix (Pure Sound) 2002
  24586   One Piece Mansion (Capcom) 2001 (japanese version only)
  24587 The supported games should have a I-Mode adaptor logo on the CD cover (the logo
  24588 depicts two plugs: the PSX controller plug, and the smaller I-Mode plug).
  24589 Note: "Dragon Quest Monsters 1 & 2" was announced/rumoured to support I-mode
  24590 (however, its CD cover doesn't show any I-Mode adapter logo).
  24591 
  24592 Tech Details (all unknown)
  24593 Unknown how to detect the thing, and how to do the actual data transfers.
  24594 The cable does contain a 64pin chip, an oscillator, and some smaller components
  24595 (inside of the PSX controller port connector).
  24596 
  24597 Hardware Variant
  24598 Keitai Eddy seems to have the phone connect to the SIO port (on rear side of
  24599 the PSX, at least it's depicted like so on the CD cover). This is apparently
  24600 something different than the SCPH-10180 controller-port cable. Unknown what it
  24601 is exactly - probably some mobile internet connection too, maybe also using
  24602 I-mode, or maybe some other protocol.
  24603 
  24604 Controllers - Keyboards
  24605 -----------------------
  24606 
  24607 There isn't any official retail keyboard for PSX, however, there is a shitload
  24608 of obscure ways to connect keyboards...
  24609 
  24610 Sony SCPH-2000 PS/2 Keyboard/Mouse Adaptor (prototype/with cable) (undated)
  24611 Sony SCPH-2000 PS/2 Keyboard/Mouse Adaptor (without cable) (undated)
  24612 A PS/2 to PSX controller port adaptor. Maybe for educational Lightspan titles?
  24613 There are two hardware variants of the adaptor:
  24614   Adaptor with short cable to PSX-controller port (and prototype marking)
  24615   Adaptor without cable, directly plugged into controller port (final version?)
  24616 Unknown ^how to access those adaptors, and unknown if the two versions differ
  24617 at software side. There seem to be not much more than a handful of people
  24618 owning that adaptors, and none of them seems to know how to use it, or even how
  24619 to test if it's working with existing software...
  24620 - Keyboard reading might work with the Online Connection CD.
  24621 - Mouse reading might work with normal mouse compatible PSX games.
  24622 
  24623 Lightspan Online Connection CD Keyboard (1997)
  24624 The Online Connection CD is a web browser from the educational Lightspan
  24625 series, the CD is extremly rare (there's only one known copy of the disc).
  24626 The thing requires a dial-up modem connected to the serial port (maybe simply
  24627 using the same RS232 adaptor as used by Yaroze). User input can be done via
  24628 joypad, or optionally, via some external keyboard (or keyboard adaptor)
  24629 hardware:
  24630   Send  01h 42h 00h 00h 00h 00h 00h 00h 00h 00h 00h 00h 00h 00h 06h
  24631   Reply HiZ 96h 5Ah num dat dat dat dat dat dat dat dat dat dat dat
  24632 The num byte indicates number of following scancodes (can be num=FFh, maybe
  24633 when no keyboard connected?, or num=00h..0Bh for max 11 bytes, unless the last
  24634 some bytes should have other meaning, like status/mouse data or so).
  24635 The keyboard scancodes are in "PS/2 Keyboard Scan Code Set 2" format.
  24636 The binary contains some (unused) code for sending data to the keyboard by
  24637 changing the 4th-11th byte, and resuming normal operation by setting 4th and
  24638 11th byte back to zero:
  24639   Send  ..  ..  ..  01h xxh FFh FFh FFh FFh FFh 00h ..  ..  ..  ..
  24640   Send  ..  ..  ..  00h ..  ..  ..  ..  ..  ..  00h ..  ..  ..  ..
  24641 Maybe 4th and 11th byte are number of following bytes, with xxh being some
  24642 command, and FFh's just being bogus padding; the xxh looks more like an
  24643 incrementing value though.
  24644 Despite of the mouse-based GUI, the browser software doesn't seem to support
  24645 mouse hardware (neither via PS/2 mice, nor PSX mice). Instead, the mouse arrow
  24646 can be merely moved via joypad's DPAD, or (in a very clumsy fashion) via
  24647 keyboard cursor keys.
  24648 Note: The browser uses SysEnqIntRP to install some weird IRQ handler that
  24649 forcefully aborts all controller (or memory card) transfers upon Vblank.
  24650 Unknown if that's somehow required to bypass bugs in the keyboard hardware. The
  24651 feature is kinda dangerous for memory card access (especially with fast memcard
  24652 access in nocash kernel, which allows to transfer more than one sector per
  24653 frame).
  24654 
  24655 Spectrum Emulator Keyboard Adaptor (v1/serial port) (undated)
  24656 Made by Anthony Ball. http://www.sinistersoft.com/psxkeyboard
  24657   [1F801058h]=00CEh  ;SIO_MODE 8bit, no parity, 2 stop bits (8N2)
  24658   [1F80105Ah]=771Ch  ;SIO_CTRL rx enable (plus whatever nonsense bits)
  24659   [1F80105Eh]=006Ch  ;SIO_BAUD 19200 bps
  24660   RX   Keyboard Scancode (same ASCII-style as in later versions?)
  24661   CTS  Caps-Lock state
  24662   DSR  Num-Lock state
  24663 
  24664 Spectrum Emulator Keyboard & Sega Sticks Adaptor (v2/controller port) (2000)
  24665 Made by Anthony Ball. http://www.sinistersoft.com/psxkeyboard
  24666 This adaptor can send pad/stick data,
  24667   Send  01h 42h 00h  0h 0h
  24668   Reply HiZ 41h 5Ah  PadA
  24669 as well as pad/sticks+keyboard data,
  24670   Send  01h 42h 00h  0h 0h 0h 0h 0h 0h 0h 0h  00h 00h   0h 0h 0h 0h 0h 0h
  24671   Reply HiZ E8h 5Ah  PadA  PadB  PadC  PadD   Ver Lock  Buffer(0..5)
  24672 The above mode(s) can be switched via ACPI Power/Sleep/Wake keys (on keyboards
  24673 that do have such keys).
  24674   Version=1     ; version number
  24675   0  SCROLL          ; scroll lock on
  24676   1  NUM             ; num lock on
  24677   2  CAPS            ; caps lock on
  24678   3  DONETEST        ; keyboard has just done a selftest
  24679   4  EMUA            ; emulation mode a
  24680   5  EMUB            ; emulation mode b
  24681 For whatever reason, the PS/2 scancodes are translated to ASCII-style scancode
  24682 values (with bit7=KeyUp flag):
  24683   01   11 12 13 14  15 16 17 18  19 1A 1B 1C  1D 69 1F
  24684   60 21 22 68 24 25 5E 26 2A 28 29 5F 3D  2D  0B 0E 0F  67 2F 1E 2D
  24685   27  51 57 45 52 54 59 55 49 4F 50 5B 5D 0D  10 61 62  37 38 39
  24686   3B   41 53 44 46 47 48 4A 4B 4C 3A 40 23              34 35 36 2B
  24687   02 5C 5A 58 43 56 42 4E 4D 3C 3E 3F     03     63     31 32 33
  24688   04 05 06           20          07 08 09 0A  65 64 66  30    2E 6A
  24689 BUG: The thing conflicts with memory cards: It responds to ANY byte with value
  24690 01h (it should do so only if the FIRST byte is 01h).
  24691 
  24692 Homebrew PS/2 Keyboard/Mouse Adaptor (undated/from PSone era)
  24693   Send  01h 42h 00h 00h 00h 00h 00h
  24694   Reply HiZ 12h 5Ah key flg dx  dy
  24695 flg:
  24696   bit0-1 = Always 11b (unlike Sony mouse)
  24697   bit2 = Left Mouse Button  (0=Pressed, 1=Released)
  24698   bit3 = Right Mouse Button (0=Pressed, 1=Released)
  24699   bit4-5 = Always 11b (like Sony mouse)
  24700   bit6 = Key Release  (aka F0h prefix) (0=Yes)
  24701   bit7 = Key Extended (aka E0h prefix) (0=Yes)
  24702 Made by Simon Armstrong. This thing emulates a standard PSX Mouse (and should
  24703 thus work with most or all mouse compatible games). Additionally, it's sending
  24704 keyboard flags/scancodes via unused mouse button bits.
  24705 
  24706 Runix hardware add-on USB Keyboard/Mouse Adaptor (2001) (PIO extension port)
  24707 Runix is a homebrew linux kernel for PSX, it can be considered being the holy
  24708 grail of the open source scene because nobody has successfully compiled it in
  24709 the past 16 years.
  24710 - USB host controller SL811H driver with keyboard and mouse support;
  24711 - RTC support.
  24712 file: drivers/usb/sl811h.c
  24713 
  24714 TTY Console
  24715 The PSX kernel allows to output "printf" debug messages via stdout. In the
  24716 opposite direction, it's supporting to receive ASCII user input via
  24717 "std_in_gets" (there isn't any software actually using that feature though,
  24718 except maybe debug consoles like DTL-H2000).
  24719 
  24720 Controllers - Additional Inputs
  24721 -------------------------------
  24722 
  24723 Reset Button
  24724 PSX only (not PSone). Reboots the PSX via /RESET signal. Probably including for
  24725 forcefully getting through the WHOLE BIOS Intro, making it rather
  24726 useless/annoying? No idea if it clears ALL memory during reboot?
  24727 
  24728 CDROM Shell Open
  24729 Status bit of the CDROM controller. Can be used to sense if the shell is opened
  24730 (and also memorizes if the shell was opened since last check; allowing to sense
  24731 possible disk changes).
  24732 
  24733 PocketStation
  24734 Memory Card with built-in LCD screen and Buttons (which can be used as
  24735 miniature handheld console). However, when it is connected to the PSX, the
  24736 buttons are vanishing in the cartridge slot, so the buttons cannot be used as
  24737 additional inputs for PSX games.
  24738 
  24739 Serial Port PSX only (not PSone)
  24740 With an external adaptor (voltage conversion), the serial port can be used
  24741 (among others) to connect a RS232 Serial Mouse. Although, most or all
  24742 commercial games with mouse input are probably (?) supporting only Sony's Mouse
  24743 (on the controller port) (rather than standard RS232 devices on the serial
  24744 port).
  24745 
  24746 TTY Debug Terminal
  24747 If present, the external DUART can be used for external keyboard input, at the
  24748 BIOS side, this is supported as "std_in".
  24749 
  24750 Controllers - Misc
  24751 ------------------
  24752 
  24753 Standard Controllers
  24754   SCPH-1010  digital joypad (with short cable)
  24755   SCPH-1080  digital joypad (with longer cable)
  24756   SCPH-1030  mouse (with short cable)
  24757   SCPH-1090  mouse (with longer cable)
  24758   SCPH-1092  mouse (european?)
  24759   SCPH-1110  analog joystick
  24760   SCPH-1150  analog joypad (with one vibration motor, with red/green led)
  24761   SCPH-1180  analog joypad (without vibration motors, with red/green led)
  24762   SCPH-1200  analog joypad (with two vibration motors) (dualshock)
  24763   SCPH-110   analog joypad (with two vibration motors) (dualshock for psone)
  24764   SCPH-10010 dualshock2 (analog buttons, except L3/R3/Start/Select) (for ps2)
  24765   SCPH-1070  multitap
  24766 
  24767 Special Controllers
  24768   SCPH-4010 VPick (guitar-pick controller) (for Quest for Fame, Stolen Song)
  24769 SLPH-0001 (nejicon)
  24770 BANDAI "BANC-0002" - 4 Buttons (Triangle, Circle, Cross, Square) (nothing more)
  24771 
  24772 Joystick
  24773      __________                     __________
  24774     |          |                   |    ^     |     ^
  24775     | L1    R1 |                   | X <+> O  |    <+> = Digital Stick
  24776      \      ___| <--- L2   [] ---> |___ v    /      v
  24777       |    |     <--- R2   /\ --->     |    |
  24778    ___|    |___________________________|    |___   Not sure if all buttons
  24779   |   |    | SEL STA              =?=  |    |   |  are shown at their
  24780   |   |    |                           |    |   |  correct locations?
  24781   |   |    |_         []   /\         _|    |   |    (drawing is based on
  24782   |  _|     /    L1             R1    \     |_  |    below riddle/lyrics)
  24783   |  \_____/          X     O          \_____/  |
  24784   |   /___\      L2             R2      /___\   |
  24785   |                                             |
  24786   |                                             |
  24787    \___________________________________________/
  24788 
  24789  The thumb buttons on the left act as L1 and R1,
  24790     the trigger is L2, the pinky button is R2
  24791  The thumb buttons on the right act as X and O,
  24792     the trigger is Square and the pinky button is Triangle.
  24793  I find this odd as the triggers should've been L1 and R1,
  24794     the pinkies L2 and R2.
  24795  The buttons are redundantly placed on the base as large buttons like what
  24796     you'd see on a fight/arcade stick. Also with Start and Select.
  24797  There is also a physical analog mode switch,
  24798     not a button like on dual shock.
  24799 
  24800 Memory Card Read/Write Commands
  24801 -------------------------------
  24802 
  24803 Reading Data from Memory Card
  24804   Send Reply Comment
  24805   81h  N/A   Memory Card Access (unlike 01h=Controller access), dummy response
  24806   52h  FLAG  Send Read Command (ASCII "R"), Receive FLAG Byte
  24807   00h  5Ah   Receive Memory Card ID1
  24808   00h  5Dh   Receive Memory Card ID2
  24809   MSB  (00h) Send Address MSB  ;\sector number (0..3FFh)
  24810   LSB  (pre) Send Address LSB  ;/
  24811   00h  5Ch   Receive Command Acknowledge 1  ;<-- late /ACK after this byte-pair
  24812   00h  5Dh   Receive Command Acknowledge 2
  24813   00h  MSB   Receive Confirmed Address MSB
  24814   00h  LSB   Receive Confirmed Address LSB
  24815   00h  ...   Receive Data Sector (128 bytes)
  24816   00h  CHK   Receive Checksum (MSB xor LSB xor Data bytes)
  24817   00h  47h   Receive Memory End Byte (should be always 47h="G"=Good for Read)
  24818 Non-sony cards additionally send eight 5Ch bytes after the end flag.
  24819 When sending an invalid sector number, original Sony memory cards respond with
  24820 FFFFh as Confirmed Address (and do then abort the transfer without sending any
  24821 data, checksum, or end flag), third-party memory cards typically respond with
  24822 the sector number ANDed with 3FFh (and transfer the data for that adjusted
  24823 sector number).
  24824 
  24825 Writing Data to Memory Card
  24826   Send Reply Comment
  24827   81h  N/A   Memory Card Access (unlike 01h=Controller access), dummy response
  24828   57h  FLAG  Send Write Command (ASCII "W"), Receive FLAG Byte
  24829   00h  5Ah   Receive Memory Card ID1
  24830   00h  5Dh   Receive Memory Card ID2
  24831   MSB  (00h) Send Address MSB  ;\sector number (0..3FFh)
  24832   LSB  (pre) Send Address LSB  ;/
  24833   ...  (pre) Send Data Sector (128 bytes)
  24834   CHK  (pre) Send Checksum (MSB xor LSB xor Data bytes)
  24835   00h  5Ch   Receive Command Acknowledge 1
  24836   00h  5Dh   Receive Command Acknowledge 2
  24837   00h  4xh   Receive Memory End Byte (47h=Good, 4Eh=BadChecksum, FFh=BadSector)
  24838 
  24839 Get Memory Card ID Command
  24840   Send Reply Comment
  24841   81h  N/A   Memory Card Access (unlike 01h=Controller access), dummy response
  24842   53h  FLAG  Send Get ID Command (ASCII "S"), Receive FLAG Byte
  24843   00h  5Ah   Receive Memory Card ID1
  24844   00h  5Dh   Receive Memory Card ID2
  24845   00h  5Ch   Receive Command Acknowledge 1
  24846   00h  5Dh   Receive Command Acknowledge 2
  24847   00h  04h   Receive 04h
  24848   00h  00h   Receive 00h
  24849   00h  00h   Receive 00h
  24850   00h  80h   Receive 80h
  24851 This command is supported only by original Sony memory cards. Not sure if all
  24852 sony cards are responding with the same values, and what meaning they have,
  24853 might be number of sectors (0400h) and sector size (0080h) or whatever.
  24854 
  24855 Invalid Commands
  24856   Send Reply Comment
  24857   81h  N/A   Memory Card Access (unlike 01h=Controller access), dummy response
  24858   xxh  FLAG  Send Invalid Command (anything else than "R", "W", or "S")
  24859 Transfer aborts immediately after the faulty command byte, or, occasionally
  24860 after one more byte (with response FFh to that extra byte).
  24861 
  24862 FLAG Byte
  24863 The initial value of the FLAG byte on power-up (and when re-inserting the
  24864 memory card) is 08h.
  24865 Bit3=1 is indicating that the directory wasn't read yet (allowing to sense
  24866 memory card changes). For some strange reason, bit3 is NOT reset when reading
  24867 from the card, but rather when writing to it. To reset the flag, games are
  24868 usually issuing a dummy write to sector number 003Fh, more or less
  24869 unneccessarily stressing the lifetime of that sector.
  24870 Bit2=1 seems to be intended to indicate write errors, however, the write
  24871 command seems to be always finishing without setting that bit, instead, the
  24872 error flag may get set on the NEXT command.
  24873 Note: Some (not all) non-sony cards also have Bit5 of the FLAG byte set.
  24874 
  24875 Timings
  24876 IRQ7 is usually triggered circa 1500 cycles after sending a byte (counted from
  24877 the begin of the first bit), except, the last byte doesn't trigger IRQ7, and,
  24878 after the 7th byte of the Read command, an additional delay of circa 31000
  24879 cycles occurs before IRQ7 gets triggered (that strange extra delay occurs only
  24880 on original Sony cards, not on cards from other manufacturers).
  24881 There seems to be no extra delays in the Write command, as it seems, the data
  24882 is written on the fly, and one doesn't need to do any write-busy handling...
  24883 although, theoretically, the write shouldn't start until verifying the
  24884 checksum... so it can't be done on the fly at all...?
  24885 
  24886 Notes
  24887 Responses in brackets are don't care, (00h) means usually zero, (pre) means
  24888 usually equal to the previous command byte (eg. the response to LSB is MSB).
  24889 
  24890 Memory cards are reportedly "Flash RAM" which sounds like bullshit, might be
  24891 battery backed SRAM, or FRAM, or slower EEPROM or FLASH ROM, or vary from card
  24892 to card...?
  24893 
  24894 Memory Card Data Format
  24895 -----------------------
  24896 
  24897 Data Size
  24898   Total Memory 128KB = 131072 bytes = 20000h bytes
  24899   1 Block 8KB = 8192 bytes = 2000h bytes
  24900   1 Frame 128 bytes = 80h bytes
  24901 The memory is split into 16 blocks (of 8 Kbytes each), and each block is split
  24902 into 64 sectors (of 128 bytes each). The first block is used as Directory, the
  24903 remaining 15 blocks are containing Files, each file can occupy one or more
  24904 blocks.
  24905 
  24906 Header Frame (Block 0, Frame 0)
  24907   00h-01h Memory Card ID (ASCII "MC")
  24908   02h-7Eh Unused (zero)
  24909   7Fh     Checksum (all above bytes XORed with each other) (usually 0Eh)
  24910 
  24911 Directory Frames (Block 0, Frame 1..15)
  24912   00h-03h Block Allocation State
  24913             00000051h - In use ;first-or-only block of a file
  24914             00000052h - In use ;middle block of a file (if 3 or more blocks)
  24915             00000053h - In use ;last block of a file   (if 2 or more blocks)
  24916             000000A0h - Free   ;freshly formatted
  24917             000000A1h - Free   ;deleted (first-or-only block of file)
  24918             000000A2h - Free   ;deleted (middle block of file)
  24919             000000A3h - Free   ;deleted (last block of file)
  24920   04h-07h Filesize in bytes (2000h..1E000h; in multiples of 8Kbytes)
  24921   08h-09h Pointer to the NEXT block number (minus 1) used by the file
  24922             (ie. 0..14 for Block Number 1..15) (or FFFFh if last-or-only block)
  24923   0Ah-1Eh Filename in ASCII, terminated by 00h (max 20 chars, plus ending 00h)
  24924   1Fh     Zero (unused)
  24925   20h-7Eh Garbage (usually 00h-filled)
  24926   7Fh     Checksum (all above bytes XORed with each other)
  24927 Filesize [04h..07h] and Filename [0Ah..1Eh] are stored only in the first
  24928 directory entry of a file (ie. with State=51h or A1h), other directory entries
  24929 have that bytes zero-filled.
  24930 
  24931 Filename Notes
  24932 The first some letters of the filename should indicate the game to which the
  24933 file belongs, in case of commercial games this is conventionally done like so:
  24934 Two character region code:
  24935   "BI"=Japan, "BE"=Europe, "BA"=America
  24936 followed by 10 character game code,
  24937   in "AAAA-NNNNN" form     ;for Pocketstation executables replace "-" by "P"
  24938 where the "AAAA" part does imply the region too; (SLPS/SCPS=Japan,
  24939 SLUS/SCUS=America, SLES/SCES=Europe) (SCxS=Made by Sony, SLxS=Licensed by
  24940 Sony), followed by up to 8 characters,
  24941   "abcdefgh"
  24942 (which may identify the file if the game uses multiple files; this part often
  24943 contains a random string which seems to be allowed to contain any chars in
  24944 range of 20h..7Fh, of course it shouldn't contain "?" and "*" wildcards).
  24945 
  24946 Broken Sector List (Block 0, Frame 16..35)
  24947   00h-03h Broken Sector Number (Block*64+Frame) (FFFFFFFFh=None)
  24948   04h-7Eh Garbage (usually 00h-filled) (some cards have [08h..09h]=FFFFh)
  24949   7Fh     Checksum (all above bytes XORed with each other)
  24950 If Block0/Frame(16+N) indicates that a given sector is broken, then the data
  24951 for that sector is stored in Block0/Frame(36+N).
  24952 
  24953 Broken Sector Replacement Data (Block 0, Frame 36..55)
  24954   00h-7Fh Data (usually FFh-filled, if there's no broken sector)
  24955 
  24956 Unused Frames (Block 0, Frame 56..62)
  24957   00h-7Fh Unused (usually FFh-filled)
  24958 
  24959 Write Test Frame (Block 0, Frame 63)
  24960 Reportedly "write test". Usually same as Block 0 ("MC", 253 zero-bytes, plus
  24961 checksum 0Eh).
  24962 
  24963 Title Frame (Block 1..15, Frame 0) (in first block of file only)
  24964   00h-01h  ID (ASCII "SC")
  24965   02h      Icon Display Flag
  24966              11h...Icon has 1 frame  (static) (same image shown forever)
  24967              12h...Icon has 2 frames (animated) (changes every 16 PAL frames)
  24968              13h...Icon has 3 frames (animated) (changes every 11 PAL frames)
  24969             Values other than 11h..13h seem to be treated as corrupted file
  24970             (causing the file not to be listed in the bootmenu)
  24971   03h      Block Number (1-15)  "icon block count"  Uh?
  24972                    (usually 01h or 02h... might be block number within
  24973                    files that occupy 2 or more blocks)
  24974                    (actually, that kind of files seem to HAVE title frames
  24975                    in ALL of their blocks; not only in their FIRST block)
  24976                    (at least SOME seem to have such duplicated title frame,
  24977                    but not all?)
  24978   04h-43h  Title in Shift-JIS format (64 bytes = max 32 characters)
  24979   44h-4Fh  Reserved (00h)
  24980   50h-5Fh  Reserved (00h)  ;<-- this region is used for the Pocketstation
  24981   60h-7Fh  Icon 16 Color Palette Data (each entry is 16bit CLUT)
  24982 For more info on entries [50h..5Fh], see
  24983 --> Pocketstation File Header/Icons
  24984 
  24985 Icon Frame(s) (Block 1..15, Frame 1..3) (in first block of file only)
  24986   00h-7Fh  Icon Bitmap (16x16 pixels, 4bit color depth)
  24987 Note: The icons are shown in the BIOS bootmenu (which appears when starting the
  24988 PlayStation without a CDROM inserted). The icons are drawn via GP0(2Ch)
  24989 command, ie. as Textured four-point polygon, opaque, with texture-blending,
  24990 whereas the 24bit blending color is 808080h (so it's quite the same as raw
  24991 texture without blending). As semi-transparency is disabled, Palette/CLUT
  24992 values can be 0000h=FullyTransparent, or 8000h=SolidBlack (the icons are
  24993 usually shown on a black background, so it doesn't make much of a difference).
  24994 
  24995 Data Frame(s) (Block 1..15, Frame N..63; N=excluding any Title/Icon Frames)
  24996   00h-7Fh  Data
  24997 Note: Files that occupy more than one block are having only ONE Title area, and
  24998 only one Icon area (in the first sector(s) of their first block), the
  24999 additional blocks are using sectors 0..63 for plain data.
  25000 
  25001 Shift-JIS Character Set (16bit) (used in Title Frames)
  25002 Can contain japanese or english text, english characters are encoded like so:
  25003   81h,40h      --> SPC
  25004   81h,43h..97h --> punctuation marks
  25005   82h,4Fh..58h --> "0..9"
  25006   82h,60h..79h --> "A..Z"
  25007   82h,81h..9Ah --> "a..z"
  25008 Titles shorter than 32 characters are padded with 00h-bytes.
  25009 Note: The titles are <usually> in 16bit format (even if they consist of raw
  25010 english text), however, the BIOS memory card manager does also accept 8bit
  25011 characters 20h..7Fh (so, in the 8bit form, the title could be theoretically up
  25012 to 64 characters long, but, nethertheless, the BIOS displays only max 32
  25013 chars).
  25014 For displaying Titles, the BIOS includes a complete Shift-JIS character set,
  25015 --> BIOS Character Sets
  25016 Shift-JIS is focused on asian languages, and does NOT include european letters
  25017 (eg. such with accent marks). Although the non-japanese PSX BIOSes DO include a
  25018 european character set, the BIOS memory card manager DOESN'T seem to translate
  25019 any title character codes to that character set region.
  25020 
  25021 Memory Card Images
  25022 ------------------
  25023 
  25024 There are a lot of different ways to get a save from a memory card onto your
  25025 PC's hard disk, and these ways sometimes involve sticking some additional
  25026 information into a header at the beginning of the file.
  25027 
  25028 Raw Memory Card Images (without header) (ie. usually 128K in size)
  25029   SmartLink .PSM,
  25030   WinPSM .PS,
  25031   DataDeck .DDF,
  25032   FPSX .MCR,
  25033   ePSXe .MCD...
  25034 don't stick any header on the data at all, so you can just read it in and treat
  25035 it like a raw memory card.
  25036 
  25037 All of these headers contain a signature at the top of the file. The three most
  25038 common formats and their signatures are:
  25039 
  25040      Connectix Virtual Game Station format (.MEM): "VgsM", 64 bytes
  25041      PlayStation Magazine format (.PSX): "PSV", 256 bytes
  25042 
  25043 some programs will OMIT any blank or unallocated blocks from the end of the
  25044 memory card -- if only three save blocks on the card are in use, for example,
  25045 saving the other twelve is pointless.
  25046 
  25047 Xploder and Action Replay Files (54 byte header)
  25048   00h..14h Filename in ASCII, terminated by 00h (max 20 chars, plus ending 00h)
  25049   15h..35h Title in ASCII, terminated by 00h (max 32 chars, plus ending 00h)
  25050   36h..    File Block(s) (starting with the Title sector)
  25051 This format contains only a single file (not a whole memory card). The filename
  25052 should be the same as used in the Memory Card Directory. The title is more or
  25053 less don't care; it may be the SHIFT-JIS title from the Title Sector converted
  25054 to ASCII.
  25055 
  25056 Other
  25057 "There exists another single-save format with a 128 byte header containing a
  25058 raw index frame for the initial block, which must be updated to match the
  25059 destination card, and the raw save data. I have seen this format once, but I
  25060 don't remember what it was called or where it came from. You may want to
  25061 account for this possibility in your format detection logic."
  25062 
  25063 .GME Files (usually 20F40h bytes)
  25064 InterAct GME format, produced by the DexDrive.
  25065   000h 12   ASCII String "123-456-STD",00h
  25066   00Ch 4    Usually zerofilled (or meaningless garbage in some files)
  25067   010h 5    Always 00h,00h,01h,00h,01h
  25068   015h 16   Copy of Sector 0..15 byte[00h] ;"M", followed by allocation states
  25069   025h 16   Copy of Sector 0..15 byte[08h] ;00h, followed by next block values
  25070   035h 11   Usually zerofilled (or meaningless garbage in some files)
  25071   040h F00h Fifteen Description Strings (each one 100h bytes, padded with 00h)
  25072   F40h 128K Memory Card Image (128K) (unused sectors 00h or FFh filled)
  25073 This is a very strange file format, no idea where it comes from. It contains a
  25074 F40h bytes header (mainly zerofilled), followed by the whole 128K of FLASH
  25075 memory (mainly zerofilled, too, since it usually contains only a small single
  25076 executable file).
  25077 
  25078 Memory Card Notes
  25079 -----------------
  25080 
  25081 Sony PSX Memory Cards
  25082 Sony has manufactured only 128KByte memory cards for PSX, no bigger/smaller
  25083 ones.
  25084 
  25085 Sony PS2 Memory Cards
  25086 A special case would be PS2 cards, these are bigger, but PS2 cards won't fit
  25087 into PSX cards slots (unless when cutting an extra notch in the card edge
  25088 connector), a PSX game played on a PS2 console could theoretically access PS2
  25089 cards (if it supports the different directory structure on that cards).
  25090 
  25091 Third Party Cards with bigger capacity
  25092 Some third party cards contain larger memory chips, however, the PSX
  25093 games/kernel are supporting only regular 128Kbyte cards, so the extra memory
  25094 can be used only by dividing it into several 128Kbyte memory card images.
  25095 Selecting a different memory card image can be done by a switch or button on
  25096 the card, or via joypad key combinations (joypad/card are sharing the same
  25097 signals, so the card could watch the traffic on joypad bus, provided that the
  25098 MIPS CPU is actually reading the joypad).
  25099 
  25100 Third Party Cards with bigger capacity and Data Compression
  25101 Some cards are additionally using data compression to increase the card
  25102 capacity, but that techinque is having rather bad reputation and could result
  25103 in data loss. For example, if a game has allocated four blocks on the memory
  25104 card, then it'll expect to be able to overwrite that four blocks at any time
  25105 (without needing to handle "memory card full" errors), however, if the card is
  25106 full, and if the newly written data has worse compression ratio, then the card
  25107 will be unable to store the new game position (and may have already overwritten
  25108 parts of the old game position). As a workaround, such cards may use a LED to
  25109 warn users when running low on memory (ideally, there should be always at least
  25110 128Kbytes of free memory).
  25111 
  25112 Joytech Smart Card Adaptor
  25113 The smart card adaptor plugs into memory card slot, and allows to use special
  25114 credit card-shaped memory cards. There don't seem to be any special features,
  25115 ie. the hardware setup does just behave like normal PSX memory cards.
  25116 
  25117 Datel VMEM (virtual memory card storage on expansion port)
  25118 The Datel/Interact VMEM exists as standalone VMEM cartridge, and some Datel
  25119 Cheat Devices do also include the VMEM feature. Either way, the VMEM connects
  25120 to expansion port, and contain some large FLASH memory, for storing multiple
  25121 memory cards on it. Unknown, how that memory is accessed (maybe it must be
  25122 copied to a regular memory card, or maybe they've somehow hooked the Kernel (or
  25123 even the hardware signals?) so that games could directly access the VMEM?
  25124 
  25125 Passwords (instead of Memory Cards)
  25126 Some older games are using passwords instead of memory cards to allow the user
  25127 to continue at certain game positions. That's nice for people without memory
  25128 card, but unfortunately many of that games are restricted to it - it'd be more
  25129 user friendly to support both passwords, and, optionally, memory cards.
  25130 
  25131 Yaroze Access Cards (DTL-H3020)
  25132 The Yaroze Access Card connects to memory card slot, the card resembles regular
  25133 memory cards, but it doesn't contain any storage memory. Instead, it does
  25134 merely support a very basic Access Card detection command:
  25135   Send Reply Comment
  25136   21h  N/A?  Probably replies HighZ (ie. probably reads FFh)?
  25137   53h  0xh?  Replies unknown 8bit value (upper 4bit are known to be zero)?
  25138 Ie. when receiving 21h as first byte, it replies by an ACK, and does then
  25139 output 0xh as response to the next byte.
  25140 Without the Access Card, the Yaroze Bootdisc will refuse to work (the disc
  25141 contains software for transferring data to/from PC, for developing homebrew
  25142 games).
  25143 
  25144 Pocketstation (Memory Card with built-in LCD screen and buttons)
  25145 --> Pocketstation
  25146 
  25147 Pocketstation
  25148 -------------
  25149 
  25150 Pocketstation
  25151 --> Pocketstation Overview
  25152 --> Pocketstation I/O Map
  25153 --> Pocketstation Memory Map
  25154 --> Pocketstation IO Video and Audio
  25155 --> Pocketstation IO Interrupts and Buttons
  25156 --> Pocketstation IO Timers and Real-Time Clock
  25157 --> Pocketstation IO Infrared
  25158 --> Pocketstation IO Memory-Control
  25159 --> Pocketstation IO Communication Ports
  25160 --> Pocketstation IO Power Control
  25161 --> Pocketstation SWI Function Summary
  25162 --> Pocketstation SWI Misc Functions
  25163 --> Pocketstation SWI Communication Functions
  25164 --> Pocketstation SWI Execute Functions
  25165 --> Pocketstation SWI Date/Time/Alarm Functions
  25166 --> Pocketstation SWI Flash Functions
  25167 --> Pocketstation SWI Useless Functions
  25168 --> Pocketstation BU Command Summary
  25169 --> Pocketstation BU Standard Memory Card Commands
  25170 --> Pocketstation BU Basic Pocketstation Commands
  25171 --> Pocketstation BU Custom Pocketstation Commands
  25172 --> Pocketstation File Header/Icons
  25173 --> Pocketstation File Images
  25174 --> Pocketstation XBOO Cable
  25175 
  25176 Pocketstation Overview
  25177 ----------------------
  25178 
  25179 Sony's Pocketstation (SCPH-4000) (1998)
  25180 The Pocketstation is a memory card with built-in LCD screen and buttons; aside
  25181 from using it as memory storage device, it can be also used as miniature
  25182 handheld console.
  25183 
  25184   CPU        ARM7TDMI (32bit RISC Processor) (variable clock, max 7.995MHz)
  25185   Memory     2Kbytes SRAM (battery backed), 16Kbytes BIOS ROM, 128Kbytes FLASH
  25186   Display    32x32 pixel LCD (black and white) (without any grayscales)
  25187   Sound      Mini Speaker "(12bit PCM) x 1 unit" / "8bit PCM with 12bit range"
  25188   Controls   5 input buttons, plus 1 reset button
  25189   Infrared   Bi-directional (IrDA based)
  25190   Connector  Playstation memory card interface
  25191   RTC        Battery backed Real-Time Clock with time/date function
  25192   Supply     CR2032 Battery (3VDC) (used in handheld mode, and for SRAM/RTC)
  25193     _________
  25194    / _______ \
  25195   | |       | |
  25196   | |  LCD  | |                                __
  25197   | |_______| |                Side Views     | _|
  25198   |\_________/|                               || <-------- Button Cover
  25199   |   O       |          (Closed)      (Open) ||
  25200   | O   O   O |    ____________          _____||  .------- Reset Button
  25201   |   O       |   | LCD  \____ |        | LCD \|__|_
  25202   |___________|   |___________||        |___________| <--- Memory card plug
  25203 
  25204 The RTC Problem
  25205 The main problem of the Pocketstation seems to be that it tends to reset the
  25206 RTC to 1st January 1999 with time 00:00:00 whenever possible.
  25207 The BIOS contains so many RTC-reset functions, RTC-reset buttons, RTC-reset
  25208 flags, RTC-reset communication commands, RTC-reset parameters, RTC-reset
  25209 exceptions, RTC-reset sounds, and RTC-reset animations that it seems as if Sony
  25210 actually WANTED the Time/Date to be destroyed as often as possible.
  25211 The only possible reason for doing this is that the clock hardware is so
  25212 inaccurate that Sony must have decided to "solve" the problem at software
  25213 engineering side, by erasing the RTC values before the user could even notice
  25214 time inaccuracies.
  25215 
  25216 CPU Specs
  25217 For details on the ARM7TDMI CPUs opcodes and exceptions, check GBATEK at,
  25218 http://problemkaputt.de/gbatek.htm (or .txt)
  25219 The GBA uses an ARM7TDMI CPU, too.
  25220 
  25221 Thanks to Exophase, Orion, Fezzik, Dr.Hell for Pocketstation info.
  25222 
  25223 Pocketstation I/O Map
  25224 ---------------------
  25225 
  25226 Memory and Memory-Control Registers
  25227   00000000h RAM        (2KB RAM) (first 512 bytes bytes reserved for kernel)
  25228   02000000h FLASH1     Flash ROM (virtual file-mapped addresses in this region)
  25229   04000000h BIOS_ROM      Kernel and GUI (16KB)
  25230   06000000h F_CTRL        Control of Flash ROM
  25231   06000004h F_STAT        Unknown?
  25232   06000008h F_BANK_FLG    FLASH virtual bank mapping enable flags(16 bits)(R/W)
  25233   0600000Ch F_WAIT1       waitstates...?
  25234   06000010h F_WAIT2       waitstates, and FLASH-Write-Control-and-Status...?
  25235   06000100h F_BANK_VAL    FLASH virtual bank mapping addresses (16 words) (R/W)
  25236   06000300h F_EXTRA       Extra FLASH (256 bytes, including below F_SN, F_CAL)
  25237   06000300h F_SN_LO       Extra FLASH Serial Number LSBs (nocash: 6BE7h)
  25238   06000302h F_SN_HI       Extra FLASH Serial Number MSBs (nocash: 426Ch)
  25239   06000304h F_?           Extra FLASH Unknown ?          (nocash: 05CAh)
  25240   06000306h F_UNUSED1     Extra FLASH Unused halfword    (nocash: FFFFh)
  25241   06000308h F_CAL         Extra FLASH LCD Calibration    (nocash: 001Ah)
  25242   0600030Ah F_UNUSED2     Extra FLASH Unused halfword    (nocash: FFFFh)
  25243   0600030Ch F_?           Extra FLASH Unknown ?          (nocash: 0010h)
  25244   0600030Eh F_UNUSED3     Extra FLASH Unused halfword    (nocash: FFFFh)
  25245   06000310h F_UNUSED4     Extra FLASH Unused (310..3FFh) (nocash: FFFFh-filled)
  25246   08000000h FLASH2        Flash ROM (128KB) (physical addresses in this region)
  25247   08002A54h F_KEY1        Flash Unlock Address 1 (W)
  25248   080055AAh F_KEY2        Flash Unlock Address 2 (W)
  25249 Interrupts and Timers
  25250   0A000000h INT_LATCH     Interrupt hold (R)
  25251   0A000004h INT_INPUT     Interrupt Status (R)
  25252   0A000008h INT_MASK_READ Read Interrupt Mask (R)
  25253   0A000008h INT_MASK_SET  Set Interrupt Mask (W)
  25254   0A00000Ch INT_MASK_CLR  Clear Interrupt Mask (W)
  25255   0A000010h INT_ACK       Clear Interrupt hold (W)
  25256   0A800000h T0_RELOAD     Timer 0 Maximum value
  25257   0A800004h T0_COUNT      Timer 0 Current value
  25258   0A800008h T0_MODE       Timer 0 Mode
  25259   0A800010h T1_RELOAD     Timer 1 Maximum value
  25260   0A800014h T1_COUNT      Timer 1 Current value
  25261   0A800018h T1_MODE       Timer 1 Mode
  25262   0A800020h T2_RELOAD     Timer 2 Maximum value
  25263   0A800024h T2_COUNT      Timer 2 Current value
  25264   0A800028h T2_MODE       Timer 2 Mode
  25265   0B000000h CLK_MODE      Clock control (CPU and Timer Speed) (R/W)
  25266   0B000004h CLK_STOP      Clock stop (Sleep Mode)
  25267   0B800000h RTC_MODE      RTC Mode
  25268   0B800004h RTC_ADJUST    RTC Adjust
  25269   0B800008h RTC_TIME      RTC Time (R)
  25270   0B80000Ch RTC_DATE      RTC Date (R)
  25271 Communication Ports, Audio/Video
  25272   0C000000h COM_MODE      Com Mode
  25273   0C000004h COM_STAT1     Com Status Register 1 (Bit1=Error)
  25274   0C000008h COM_DATA      Com RX Data (R) and TX Data (W)
  25275   0C000010h COM_CTRL1     Com Control Register 1
  25276   0C000014h COM_STAT2     Com Status Register 2 (Bit0=Ready)
  25277   0C000018h COM_CTRL2     Com Control Register 2
  25278   0C800000h IRDA_MODE     Infrared Control (R/W)
  25279   0C800004h IRDA_DATA     Infrared TX Data
  25280   0C80000Ch IRDA_MISC     Infrared Unknown/Reserved
  25281   0D000000h LCD_MODE      Video Control (R/W)
  25282   0D000004h LCD_CAL       Video Calibration (?)
  25283   0D000100h LCD_VRAM      Video RAM (80h bytes; 32x32bit) (R/W)
  25284   0D800000h IOP_CTRL      IOP control
  25285   0D800004h IOP_STAT      Read Current Start/Stop bits? (R)
  25286   0D800004h IOP_STOP      Stop bits? (W)
  25287   0D800008h IOP_START     Start bits? (W)
  25288   0D80000Ch IOP_DATA      IOP data?   (not used by bios)
  25289   0D800010h DAC_CTRL      DAC Control (R/W)
  25290   0D800014h DAC_DATA      DAC data
  25291   0D800020h BATT_CTRL     Battery Monitor Control
  25292 BIOS and FLASH can be read only in 16bit and 32bit units (not 8bit).
  25293 Upon reset, BIOS ROM is mirrored to address 00000000h (instead of RAM).
  25294 For most I/O ports, it is unknown if they are (R), (W), or (R/W)...?
  25295 I/O ports are usually accessed at 32bit width, occassionally some ports are
  25296 (alternately) accessed at 16bit width. A special case are the F_SN registers
  25297 which seem to be required to be accessed at 16bit (not 32bit).
  25298 
  25299 Memory Access Time
  25300 Memory Access Time for Opcode Fetch:
  25301   WRAM        1 cycle (for ARM and THUMB)
  25302   FLASH       2 cycles (for ARM), or 1 cycle (for THUMB)
  25303   BIOS        ?
  25304 Memory Access Time for Data Read/Write:
  25305   WRAM (and some F_xxx ports)                    1 cycle
  25306   VIRT/PHYS/XTRA_FLASH, BIOS, VRAM, I/O          2 cycles
  25307 For data access, it doesn't matter if the access is 8bit/16bit/32bit (unlike as
  25308 for opcode fetch, where 16bit/thumb can be faster than 32bit/arm). There seems
  25309 to be no timing differences for sequential/non-sequential access.
  25310 Additional memory waitstates can be added via F_WAIT2 (and F_WAIT1 maybe).
  25311 
  25312 Invalid/Unused Memory Locations
  25313   00000800h-00FFFFFFh  Mirrors of 00000000h-000007FFh (2K RAM)
  25314   01000000h-01FFFFFFh  Invalid (read causes data abort) (unused 16MB area)
  25315   020xxxxxh-0201FFFFh  Invalid (read causes data abort) (disabled FLASH banks)
  25316   02020000h-02FFFFFFh  Invalid (read causes data abort) (no Virt FLASH mirrors)
  25317   03000000h-03FFFFFFh  Invalid (read causes data abort) (unused 16MB area)
  25318   04004000h-04FFFFFFh  Mirrors of 04000000h-04003FFFh (16K BIOS)
  25319   05000000h-05FFFFFFh  Invalid (read causes data abort)
  25320   06000014h-060000FFh   Zerofilled (or maybe mirror of a ZERO port?) (F_xxx)
  25321   06000140h-060002FFh   Zerofilled (or maybe mirror of a ZERO port?) (F_xxx)
  25322   06000400h-06FFFFFFh   Zerofilled (or maybe mirror of a ZERO port?) (F_xxx)
  25323   07000000h-07FFFFFFh  Invalid (read causes data abort) (unused 16MB area)
  25324   08020000h-08FFFFFFh  Mirrors of 08000000h-0801FFFFh (128K Physical FLASH)
  25325   09000000h-09FFFFFFh  Invalid (read causes data abort) (unused 16MB area)
  25326   0A000014h-0A7FFFFFh  Mirrors of 0A000008h-0A00000Bh (INT_MASK_READ) (I_xxx)
  25327   0A80000Ch            Mirror of 0A800000h-0A800003h (T0_RELOAD) (T0_xxx)
  25328   0A80001Ch            Mirror of 0A800000h-0A800003h (T0_RELOAD) (T1_xxx)
  25329   0A80002Ch            Mirror of 0A800000h-0A800003h (T0_RELOAD) (T2_xxx)
  25330   0A800030h-0AFFFFFFh  Mirrors of 0A800000h-0A800003h (T0_RELOAD) (T_xxx)
  25331   0B000008h-0B7FFFFFh  Mirrors of .... ? (CLK_xxx)
  25332   0B800010h-0BFFFFFFh  Mirrors of 0B800008h-0B80000Bh (RTC_TIME)
  25333   0C00000Ch-0C00000Fh  Zero (COM_xxx)
  25334   0C00001Ch-0C7FFFFFh   Zerofilled (or maybe mirror of a ZERO port?) (COM_xxx)
  25335   0C800008h-0CFFFFFFh   ? (IRDA_xxx)
  25336   0D000008h-0D0000FFh   Zerofilled (or maybe mirror of a ZERO port?) (LCD_xxx)
  25337   0D000180h-0D7FFFFFh   Zerofilled (or maybe mirror of a ZERO port?) (LCD_xxx)
  25338   0D800018h             ? (DAC_xxx)
  25339   0D80001Ch             ? (DAC_xxx)
  25340   0D800024h-0DFFFFFFh   Zerofilled (or maybe mirror of a ZERO port?) (BATT_xxx)
  25341   0E000000h-FFFFFFFFh  Invalid (read causes data abort) (unused 3872MB area)
  25342 
  25343 Unsupported 8bit Reads
  25344   02000000h-0201FFFFh VIRT_FLASH   ;\
  25345   04000000h-04FFFFFFh BIOS_ROM     ; "garbage_byte" (see below)
  25346   06000300h-060003FFh EXTRA_FLASH  ;
  25347   08000000h-08FFFFFFh PHYS_FLASH   ;/
  25348   0A800001h-0AFFFFFFh Timer area, odd addresses (with A0=1) mirror to 0A800001h
  25349   0B800001h-0BFFFFFFh RTC area, odd addresses (with A0=1) mirror to ...?
  25350 
  25351 Unsupported 16bit Reads
  25352   0B800002h-0BFFFFFEh RTC area, odd addresses (with A1=1) mirror to 0B80000Ah
  25353 
  25354 garbage_byte (for unsupported 8bit reads)
  25355 The "garbage_byte" depends on the LSBs of the read address, prefetched opcodes,
  25356 and recent data fetches:
  25357   garbage_word = (prefetch OR (ramdata AND FFFFFFD0h))
  25358   garbage_byte = (garbage_word shr (8*(addr and 3))) AND FFh
  25359 For ARM code, the "prefetch" is the 2nd next opcode after the LDRB:
  25360   prefetch.bit0-31  = [curr_arm_opcode_addr+8]    ;-eg. from arm LDRB
  25361 For THUMB code, the "prefetch" is the 2nd next opcode after the LDRB (no matter
  25362 if that opcode is word-aligned or not), combined with the most recent ARM
  25363 opcode prefetch (eg. from the BX opcode switched from ARM to THUMB mode; that
  25364 value may get changed on interrupts):
  25365   prefetch.bit0-15  = [recent_arm_opcode_addr+8]  ;-eg. from arm BX to thumb
  25366   prefetch.bit16-31 = [curr_thumb_opcode_addr+4]  ;-eg. from thumb LDRB
  25367 The "ramdata" is related to most recent RAM read (eg. from POP or LDR opcodes
  25368 that have read data from RAM; however, writes to RAM, or literal pool reads
  25369 from FLASH don't affect it):
  25370   ramdata.bit0-31   = [recent_ram_read_addr]      ;-eg. from LDR/POP from RAM
  25371 There might be some more/unknown things that affect the garbage (eg. opcode
  25372 fetches from RAM instead of FLASH, partial 8bit/16bit data reads from RAM, or
  25373 reads from I/O areas, current CPU clock speed, or unpredictable things like
  25374 temperature).
  25375 Note: The garbage_byte is "used" by the pocketstation "Rockman" series games.
  25376 
  25377 Pocketstation Memory Map
  25378 ------------------------
  25379 
  25380 Overall Memory Map
  25381   00000000h RAM      RAM (2K)   (or mirror of BIOS ROM upon reset)
  25382   02000000h FLASH1   Flash ROM  (virtual file-mapped addresses in this region)
  25383   04000000h BIOS_ROM BIOS (16K) (Kernel and GUI)
  25384   06000300h F_SN...  Seems to contain a bunch of additional FLASH bytes?
  25385   08000000h FLASH2   Flash ROM  (128K) (physical addresses in this region)
  25386   0D000100h LCD_VRAM Video RAM  (128 bytes) (32x32 pixels, 1bit per pixel)
  25387 
  25388 00000000h..000001FFh - Kernel RAM
  25389 The first 200h bytes of RAM are reserved for the kernel.
  25390   0000000h 20h  Exception handler opcodes (filled with LDR R15,[$+20h] opcodes)
  25391   0000020h 20h  Exception handler addresses (in ARM state, no THUMB bit here)
  25392   0000040h 80h  Sector buffer (and BU command parameter work space)
  25393   00000C0h 8    ComFlags (see GetPtrToComFlags(), SWI 06h for details)
  25394   00000C8h 2    BU Command FUNC3 Address (see GetPtrToFunc3addr() aka SWI 17h)
  25395   00000CAh 1    Value from BU Command_50h, reset by SWI 05h (sense_auto_com)
  25396   00000CBh 2    Not used
  25397   00000CDh 1    Old Year (BCD, 00h..99h) (for sensing wrapping to new century)
  25398   00000CEh 1    Alternate dir_index (when [0D0h]=0) (see SWI 15h and SWI 16h)
  25399   00000CFh 1    Current Century (BCD, 00h..99h) (see GetBcdDate() aka SWI 0Dh)
  25400   00000D0h 2    Current dir_index (for currently executed file, or 0=GUI)
  25401   00000D2h 2    New dir_index (PrepareExecute(flag,dir_index,param), SWI 08h)
  25402   00000D4h 4    New param     (PrepareExecute(flag,dir_index,param), SWI 08h)
  25403   00000D8h 8    Alarm Setting        (see GetPtrToAlarmSetting() aka SWI 13h)
  25404   00000E0h 4    Pointer to SWI table (see GetPtrToPtrToSwiTable() aka SWI 14h)
  25405   00000E4h 3x4  Memory Card BU Command variables
  25406   00000F0h 1    Memory Card FLAG byte (bit3=new_card, bit2=write_error)
  25407   00000F1h 1    Memory Card Error offhold (0=none, 1=once)
  25408   00000F2h 6    Not used
  25409   00000F8h 4x4  Callback Addresses (set via SetCallbacks(index,proc), SWI 01h)
  25410   0000108h 4    Snapshot ID (0xh,00h,"SE")
  25411   000010Ch 74h  IRQ and SWI stack (stacktop at 180h)
  25412   0000180h 80h  FIQ stack (stacktop at 200h)
  25413 Although one can modify that memory, one usually shouldn't do that, or at least
  25414 one must backup and restore the old values before returning control to the GUI
  25415 or to other executables. Otherwise, the only way to restore the original values
  25416 would be to press the Reset button (which would erase the RTC time/date).
  25417 
  25418 00000200h..000007FFh - User RAM and User stack (stacktop at 800h)
  25419 This region can be freely used by the game. The memory is zerofilled when the
  25420 game starts.
  25421 
  25422 02000000h - FLASH1 - Flash ROM (virtual file-mapped addresses in this region)
  25423 This region usually contains the currently selected file (including its title
  25424 and icon sectors), used to execute the file in this region, mapped to continous
  25425 addresses at 2000000h and up.
  25426 
  25427 08000000h - FLASH2 - Flash ROM (128K) (physical addresses in this region)
  25428 This region is used by the BIOS when reading the memory card directory (and
  25429 when writing data to the FLASH memory). The banking granularity is 2000h bytes
  25430 (one memory card block), that means that the hardware cannot map Replacement
  25431 Sectors which may be specified in the for Broken Sector List.
  25432 
  25433 04000000h - BIOS ROM (16K) - Kernel and GUI
  25434   4000000h 1E00h Begin of Kernel (usually 1E00h bytes)
  25435   4000014h 4     BCD Date in YYYYMMDDh format (19981023h for ALL versions)
  25436   4001DFCh 4     Core Kernel Version  (usually "C061" or "C110")
  25437   4001E00h 2200h Begin of GUI (usually 2200h bytes)
  25438   4003FFCh 4     Japanese GUI Version (usually "J061" or "J110")
  25439 The "110" version does contain some patches, but does preserve same function
  25440 addresses as the "061" version, still it'd be no good to expect the BIOS to
  25441 contain any code/data at fixed locations (except maybe the GUI version string).
  25442 Kernel functions can be accessed via SWI Opcodes, and, from the PSX-side, via
  25443 BU Commands.
  25444 
  25445 Bus-Width Restrictions
  25446 FLASH and BIOS ROM seem to be allowed to be read only in 16bit and 32bit units,
  25447 not in 8bit units? Similar restrictions might apply for some I/O ports...? RAM
  25448 can be freely read/written in 8bit, 16bit, and 32bit units.
  25449 
  25450 Waitstates
  25451 Unknown if and how many waitstates are applied to the different memory regions.
  25452 The F_WAIT1 and F_WAIT2 registers seem to be somehow waitstate related. FLASH
  25453 memory does probably have a 16bit bus, so 32bit data/opcode fetches might be
  25454 slower then 16bit reads...? Similar delays might happen for other memory and
  25455 I/O regions...?
  25456 
  25457 Pocketstation IO Video and Audio
  25458 --------------------------------
  25459 
  25460 0D000000h - LCD_MODE - LCD control word (R/W)
  25461   0-2  Draw mode; seems to turn off bits of the screen;
  25462          0: All 32 rows on      ;\
  25463          1: First 8 rows on     ;
  25464          2: Second 8 rows on    ;
  25465          3: Third 8 rows on     ; (these are not necessarily all correct?)
  25466          4: Fourth 8 rows on    ;
  25467          5: First 16 rows on    ;
  25468          6: Middle 16 rows on   ;
  25469          7: Bottom 16 rows on   ;/
  25470   3    CPEN      (0=Does some weird fade out of the screen, 1=Normal)
  25471   4-5  Refresh rate
  25472          0: Makes a single blue (yes, blue, yes, on a black/white display)
  25473             line appear at the top or middle of the screen - don't use!
  25474          1: 64Hz? (might be 32Hz too, like 2)
  25475          2: 32Hz
  25476          3: 16Hz (results in less intensity on black pixels)
  25477   6    Display active                (0=Off, 1=On)
  25478   7    Rotate display by 180 degrees (0=For Handheld Mode, 1=For Docked Mode)
  25479   8-31 Unknown (should be zero)
  25480 Software should usually set LCD_MODE.7 equal to INT_INPUT.Bit11 (docking flag).
  25481 In handheld mode, the button-side is facing towards the player, whilst in
  25482 Docked mode (when the Pocketstation is inserted into the PSX controller port),
  25483 the button-side is facing towards the PSX, so the screen coordinates become
  25484 vice-versa, which can be "undone" by the Rotation flag.
  25485 
  25486 0D000004h - LCD_CAL - LCD Calibration (maybe contrast or so?)
  25487 Upon the reset, the kernel sets LCD_CAL = F_CAL AND 0000003Fh. Aside from that,
  25488 it doesn't use LCD_CAL.
  25489 
  25490 0D000100h..D00017Fh - LCD_VRAM - 32x32 pixels, 1bit color depth (R/W)
  25491 This region consists of 32 words (32bit values),
  25492   [D000100h]=Top, through [D00017Ch]=Bottom-most scanline
  25493 The separate scanlines consist of 32bit each,
  25494   Bit0=Left, through Bit31=Right-most Pixel (0=White, 1=Black)
  25495 That [D000100h].Bit0=Upper-left arrangement applies if the Rotate bit in
  25496 LCD_MODE.7 is set up in the conventional way, if it is set the opposite way,
  25497 then it becomes [D00017Ch].Bit31=Upper-left.
  25498 The LCD_VRAM area is reportedly mirrored to whatever locations?
  25499 
  25500 0D800010h - DAC_CTRL - Audio Control (R/W)
  25501   0     Audio Enable enable    (0=Off, 1=On)
  25502   1-31  Unknown, usually zero
  25503 Note: Aside from the bit in DAC_CTRL, audio must be also enabled/disabled via
  25504 IOP_STOP/IOP_START bit5. Unknown if/which different purposes that bits have.
  25505 
  25506 0D800014h - DAC_DATA - Audio D/A Converter
  25507 Unknown how many bits are passed to the D/A converter, probably bit8-15, ie. 8
  25508 bits...?
  25509   0-7   Probably unused, usually zero (or fractional part when lowered volume)
  25510   8-15  Signed Audio Outut Level (usually -7Fh..+7Fh) (probably -80h works too)
  25511   16-31 Probably unused, usually sign-expanded from bit15
  25512 The Pocketstation doesn't have any square wave or noise generator (nor a sound
  25513 DMA channel). So the output levels must be written to DAC_DATA by software,
  25514 this is usually done via Timer1/IRQ-8 (to reduce CPU load caused by high audio
  25515 frequencies, it may be much more recommended to use Timer2/FIQ-13, because the
  25516 FIQ handler doesn't need to push r8-r12).
  25517 For example, to produce a 1kHz square wave, the register must be toggled
  25518 high/low at 2kHz rate. If desired, multiple channels can be mixed by software.
  25519 High frequencies and multiple voices may require high CPU speed settings, and
  25520 thus increase battery consumption (aside from that, battery consumption is
  25521 probably increased anyways when the speaker is enabled).
  25522 
  25523 Pocketstation IO Interrupts and Buttons
  25524 ---------------------------------------
  25525 
  25526 0A000004h - INT_INPUT - Raw Interrupt Signal Levels (R)
  25527   Bit   Type    Meaning
  25528   0     IRQ     Button Fire     (0=Released, 1=Pressed)
  25529   1     IRQ     Button Right    (0=Released, 1=Pressed)
  25530   2     IRQ     Button Left     (0=Released, 1=Pressed)
  25531   3     IRQ     Button Down     (0=Released, 1=Pressed)
  25532   4     IRQ     Button Up       (0=Released, 1=Pressed)
  25533   5     ?       Unknown?        (?)
  25534   6     FIQ (!) COM              ;for the COM_registers?      (via /SEL Pin?)
  25535   7     IRQ     Timer 0
  25536   8     IRQ     Timer 1
  25537   9     IRQ     RTC (square wave) (usually 1Hz) (when RTC paused: 4096Hz)
  25538   10    IRQ     Battery Low     (0=Normal, 1=Battery Low)
  25539   11    IRQ     Docked ("IOP")  (0=Undocked, 1=Docked to PSX) (via VCC Pin?)
  25540   12    IRQ     Infrared Rx
  25541   13    FIQ (!) Timer 2
  25542   14-15 N/A     Not used
  25543 The buttons are usually read directly from this register (rather than being
  25544 configured to trigger IRQs) (except in Sleep mode, where the Fire Button IRQ is
  25545 usually used to wakeup). Also, bit9-11 are often read from this register.
  25546 The direction keys seem to be separate buttons, ie. unlike as on a joystick or
  25547 DPAD, Left/Right (and Up/Down) can be simultaneously pressed...?
  25548 
  25549 0A000008h - INT_MASK_SET - Set Interrupt Mask (W)
  25550 0A00000Ch - INT_MASK_CLR - Clear Interrupt Mask (W)
  25551 0A000008h - INT_MASK_READ - Read Interrupt Mask (R)
  25552   INT_MASK_SET  Enable Interrupt Flags         (0=No change, 1=Enable)   (W)
  25553   INT_MASK_CLR  Disable Interrupt Flags        (0=No change, 1=Disable)  (W)
  25554   INT_MASK_READ Current Interrupt Enable Flags (0=Disabled, 1=Enabled)   (R)
  25555 The locations of the separate bits are same as in INT_INPUT (see there).
  25556 
  25557 0A000000h - INT_LATCH - Interrupt Request Flags (R)
  25558 0A000010h - INT_ACK - Acknowledge Interrupts (W)
  25559   INT_LATCH Latched Interrupt Requests   (0=None, 1=Interrupt Request)   (R)
  25560   INT_ACK   Clear Interrupt Requests     (0=No change, 1=Acknowledge)    (W)
  25561 The locations of the separate bits are same as in INT_INPUT (see there).
  25562 The interrupts seem to be edge-triggered (?), ie. when the corresponding bits
  25563 in INT_INPUT change from 0-to-1. Unknown if the request bits get set when the
  25564 corresponding interrupt is disabled in INT_MASK...?
  25565 
  25566 ATTENTION: The GUI doesn't acknowledge Fire Button interrupts on wakeup... so,
  25567 it seems as if button interrupts are NOT latched... ie. the button "INT_LATCH"
  25568 bits seem to be just an unlatched mirror of the "INT_INPUT" bits... that might
  25569 also apply for some other interrupt...?
  25570 However, after wakeup, the gui does DISABLE the Fire Button interrupt, MAYBE
  25571 that does automatically acknowledge it... in that case it might be latched...?
  25572 
  25573 Reading outside the readable region (that is where exactly?) seems to mirror to
  25574 0A000008h. Enabling IRQs for the buttons seems to make it impossible to poll
  25575 them... is that really true?
  25576 
  25577 Pocketstation IO Timers and Real-Time Clock
  25578 -------------------------------------------
  25579 
  25580 Timer and RTC interrupts
  25581   INT_INPUT.7     Timer 0 IRQ    ;used as 30Hz frame rate IRQ by GUI
  25582   INT_INPUT.8     Timer 1 IRQ    ;used as Audio square wave IRQ by GUI
  25583   INT_INPUT.13    Timer 2 FIQ (this one via FIQ vector, not IRQ vector)
  25584   INT_INPUT.9     RTC IRQ (usually 1Hz) (or 4096Hz when RTC paused)
  25585 
  25586 0A800000h - T0_RELOAD - Timer 0 Reload Value
  25587 0A800010h - T1_RELOAD - Timer 1 Reload Value
  25588 0A800020h - T2_RELOAD - Timer 2 Reload Value
  25589   0-15  Reload Value (when timer becomes less than zero)
  25590 Writes to this register are ignored if the timer isn't stopped?
  25591 
  25592 0A800004h - T0_COUNT - Timer 0 Current value
  25593 0A800014h - T1_COUNT - Timer 1 Current value
  25594 0A800024h - T2_COUNT - Timer 2 Current value
  25595   0-15  Current value (decrementing)
  25596 Timer interrupts: The timers will automatically raise interrupts if they're
  25597 enabled, there's no need to set a bit anywhere for IRQs (but you need to enable
  25598 the respect interrupts in INT_MASK).
  25599 
  25600 0A800008h - T0_MODE - Timer 0 Control
  25601 0A800018h - T1_MODE - Timer 1 Control
  25602 0A800028h - T2_MODE - Timer 2 Control
  25603   0-1  Timer Divider (0=Div2, 1=Div32, 2=Div512, 3=Div2 too)
  25604   2    Timer Enable  (0=Stop, 1=Decrement)
  25605   3-15 Unknown (should be zero)
  25606 Timers are clocked by the System Clock (usually 4MHz, when CLK_MODE=7), divided
  25607 by the above divider setting. Note that the System Clock changes when changing
  25608 the CPU speed via CLK_MODE, so Timer Divider and/or Timer Reload must be
  25609 adjusted accordingly.
  25610 
  25611 0B800000h - RTC_MODE - RTC control word
  25612   0    Pause RTC (0=Run/1Hz, 1=Pause/4096Hz)
  25613   1-3  Select value to be modified via RTC_ADJUST
  25614   4-31 Not used?
  25615 The selection bits can be:
  25616   00h = Second        ;\
  25617   01h = Minute        ;
  25618   02h = Hour          ; used in combination with RTC_ADJUST
  25619   03h = Day of Week   ; while RTC is paused
  25620   04h = Day           ;
  25621   05h = Month         ;
  25622   06h = Year          ;/
  25623   07h = Unknown       ;-usually used when RTC isn't paused
  25624 When paused, the RTC IRQ bit in INT_INPUT.9 runs at 4096Hz (instead 1Hz).
  25625 
  25626 0B800004h - RTC_ADJUST - Modify value (write only)
  25627 Writing a value here seems to increment the current selected parameter (by the
  25628 RTC control). What is perhaps (?) clear is that you have to wait for the RTC
  25629 interrupt signal to go low before writing to this.
  25630 
  25631 0B800008h - RTC_TIME - Real-Time Clock Time (read only) (R)
  25632   0-7   Seconds     (00h..59h, BCD)
  25633   8-15  Minutes     (00h..59h, BCD)
  25634   16-23 Hours       (00h..23h, BCD)
  25635   24-31 Day of week (1=Sunday, ..., 7=Saturday)
  25636 Reading RTC_TIME seems to be somewhat unstable: the BIOS uses a read/retry
  25637 loop, until it has read twice the same value (although it does read the whole
  25638 32bit at once by a LDR opcode, the data is maybe passed through a 8bit or 16bit
  25639 bus; so the LSBs might be a few clock cycles older than the MSBs...?).
  25640 
  25641 0B80000Ch - RTC_DATE - Real-Time Clock Date (read only) (R)
  25642   0-7   Day     (01h..31h, BCD)
  25643   8-11  Month   (01h..12h, BCD)
  25644   16-23 Year    (00h..99h, BCD)
  25645   24-31 Unknown? (this is NOT used as century)
  25646 Reading RTC_DATE seems to require the same read/retry method as RTC_TIME (see
  25647 there). Note: The century is stored in battery-backed RAM (in the reserved
  25648 kernel RAM region) rather than in the RTC_DATE register. The whole date,
  25649 including century, can be read via SWI 0Dh, GetBcdDate().
  25650 
  25651 Pocketstation IO Infrared
  25652 -------------------------
  25653 
  25654 The BIOS doesn't contain any IR functions (aside from doing some basic
  25655 initialization and power-down stuff).
  25656 IR is used in Final Fantasy 8's Chocobo World (press Left/Right in the Map
  25657 screen to go to the IR menu), and in Metal Gear Solid Integral (Press Up in the
  25658 main screen), and in PDA Remote 1 & 2 (one-directional TV remote control).
  25659 
  25660 0C800000h - IRDA_MODE - Controlling the protocol - send/recv, etc. (R/W)
  25661   0    Transfer Direction  (0=Receive, 1=Transmit)
  25662   1    Disable IRDA        (0=Enable, 1=Disable)
  25663   2    Unknown (reportedly IR_SEND_READY, uh?)
  25664   3    Unknown (reportedly IR_RECV_READY, uh?)
  25665   4-31 Unknown (should be zero)
  25666 
  25667 0C800004h - IRDA_DATA - Infrared TX Data
  25668   0    Transmit Data in Send Direction (0=LED Off, 1=LED On)
  25669   1-31 Unknown (should be zero)
  25670 Bits are usually encoded as long or short ON pulses, separated by short OFF
  25671 pulses. Where long is usually twice as long as short.
  25672 
  25673 0C80000Ch - IRDA_MISC
  25674 Unknown? Reportedly reserved.
  25675 
  25676 INT_INPUT.12 - IRQ - Infrared RX Interrupt
  25677 Seems to get triggered on raising or falling (?) edges of incoming data. The
  25678 interrupt handler seems to read the current counter value from one of the
  25679 timers (usually Timer 2, with reload=FFFFh) to determine the length of the
  25680 incoming IR pulse.
  25681 
  25682 IR Notes
  25683 Mind that IR hardware usually adopts itself to the normal light conditions, so
  25684 if it receives an IR signal for a longer period, then it may treat that as the
  25685 normal light conditions (ie. as "OFF" state). To avoid that, one would usually
  25686 send a group of ON-OFF-ON-OFF pulses, instead of sending a single long ON
  25687 pulse:
  25688    ___------------------___  One HIGH bit send as SINGLE-LONG-ON pulse   (BAD)
  25689    ___-_-_-_-_-_-_-_-_-____  One HIGH bit send as MULTIPLE-ON-OFF pulses (OK)
  25690 that might be maybe done automatically by the hardware...?
  25691 
  25692 Reportedly, Bit4 of Port 0D80000Ch (IOP_DATA) is also somewhat IR related...?
  25693 
  25694 Pocketstation IO Memory-Control
  25695 -------------------------------
  25696 
  25697 06000000h - F_CTRL
  25698   0-31  Unknown
  25699 Written values are:
  25700   00000000h  Used when disabling all virtual flash banks
  25701   00000001h  Used before setting new virtual bank values
  25702   00000002h  Used after setting virtual bank enable bits
  25703   03h        Replace ROM at 00000000h by RAM (used after reset)
  25704 The GUI does additionally read from this register (and gets itself trapped in a
  25705 bizarre endless loop if bit0 was zero). Unknown if it's possible to re-enable
  25706 ROM at location 00000000h by writing any other values to this register?
  25707 
  25708 06000004h F_STAT
  25709   0-31  Unknown
  25710 The kernel issues a dummy read from this address (before setting F_CTRL to
  25711 00000001h).
  25712 
  25713 06000008h F_BANK_FLG  ;FLASH virtual bank mapping enable flags (16 bits)(R/W)
  25714   0-15   Enable physical banks 0..15 in virtual region (0=Disable, 1=Enable)
  25715   16-31  Unknown (should be zero)
  25716 
  25717 06000100h F_BANK_VAL  ;FLASH virtual bank mapping addresses (16 words)(R/W)
  25718 This region contains 16 words, the first word at 06000100h for physical bank 0,
  25719 the last word at 0600013Ch for physical bank 15. Each word is:
  25720   0-3    Virtual bank number
  25721   4-31   Should be 0
  25722 Unused physical banks are usually mapped to 0Fh (and are additionally disabled
  25723 in the F_BANK_FLG register).
  25724 
  25725 0600000Ch F_WAIT1     ;waitstates...?
  25726   0..3   Unknown/not tested
  25727   4      hangs hardware? but that bit is used in some cases!
  25728   5..31  Unknown/not tested
  25729 Unknown, seems to control some kind of memory waitstates for FLASH (or maybe
  25730 RAM or BIOS ROM). Normally it is set to the following values:
  25731   F_WAIT1=00000000h when CPU Speed = 00h..07h
  25732   F_WAIT1=00000010h when CPU Speed = 08h..0Fh
  25733 Note: The kernels Docking/Undocking IRQ-11 handler does additionally do this:
  25734 "F_WAIT1=max(08h,(CLK_MODE AND 0Fh))" (that is a bug, what it actually wants to
  25735 do is to READ the current F_WAIT.Bit4 setting).
  25736 
  25737 06000010h F_WAIT2     ;waitstates, and FLASH-Write-Control-and-Status...?
  25738   0      no effect? but that bit is used in some cases! maybe write-enable?
  25739   1      hangs hardware?
  25740   2      no effect?           READ: indicates 0=write-busy, 1=ready?  (R)
  25741   3      hangs hardware?
  25742   4      makes FLASH slower?
  25743   5      makes WRAM and F_xxx as slow as other memory (0=1 cycle, 1=2 cycles)
  25744   6      hangs hardware? but that bit is used in some cases!
  25745   7      no effect?
  25746   8..31  Unknown/not tested
  25747 Unknown, seems to control some kind of memory waitstates, maybe for another
  25748 memory region than F_WAIT1, or maybe F_WAIT2 is for writing, and F_WAIT1 for
  25749 reading or so. Normally it is set to the following values:
  25750   F_WAIT2=00000000h when CPU Speed = 00h..07h  ;\same as F_WAIT1
  25751   F_WAIT2=00000010h when CPU Speed = 08h..0Fh  ;/
  25752 In SWI 0Fh and SWI 10h it is also set to:
  25753   F_WAIT2=00000021h  ;SWI 10h, FlashWritePhysical(sector,src)
  25754   F_WAIT2=00000041h  ;SWI 0Fh, FlashWriteSerial(serial_number)
  25755 Before completion, those SWIs do additionally,
  25756   wait until reading returns F_WAIT2.Bit2 = 1
  25757   and then set F_WAIT2=00000000h
  25758 
  25759 08002A54h - F_KEY1 - Flash Unlock Address 1 (W)
  25760 080055AAh - F_KEY2 - Flash Unlock Address 2 (W)
  25761 Unlocks FLASH memory for writing. The complete flowchart for writing sector
  25762 data (or header values) is:
  25763   if write_sector                               ;\
  25764     F_WAIT2=00000021h                           ; write enable or so
  25765   if write_header                               ;
  25766     F_WAIT2=00000041h                           ;/
  25767   [80055AAh]=FFAAh                              ;\
  25768   [8002A54h]=FF55h                              ; unlock flash
  25769   [80055AAh]=FFA0h                              ;/
  25770   if write_sector                               ;\
  25771     for i=0 to 3Fh                              ;
  25772       [8000000h+sector*80h+i*2]=src[i*2]        ; write data
  25773   if write_header                               ;
  25774     [8000000h]=new F_SN_LO value                ;
  25775     [8000002h]=new F_SN_HI value                ;
  25776     [8000008h]=new F_CAL value                  ;/
  25777   first, wait 4000 clock cycles                 ;\wait
  25778   then, wait until F_WAIT2.Bit2=1               ;/
  25779   F_WAIT2=00000000h                             ;-write disable or so
  25780 During the write operation one can (probably?) not read data (nor opcodes) from
  25781 FLASH memory, so the above code must be executed either in RAM, or in BIOS ROM
  25782 (see SWI 03h, SWI 0Fh, SWI 10h).
  25783 
  25784 06000300h - F_SN_LO - Serial Number LSBs
  25785 06000302h - F_SN_HI - Serial Number MSBs
  25786 06000308h - F_CAL - Calibration value for LCD
  25787   0-15  Data
  25788 This seems to be an additional "header" region of the FLASH memory
  25789 (additionally to the 128K of data). The F_SN registers contain a serial number
  25790 or so (purpose unknown, maybe intended as some kind of an "IP" address for more
  25791 complex infrared network applications), the two LO/HI registers must be read by
  25792 separate 16bit LDRH opcodes (not by a single 32bit LDR opcode). The F_CAL
  25793 register contains a 6bit calibration value for LCD_CAL (contrast or so?).
  25794 Although only the above 3 halfwords are used by the BIOS, the "header" is
  25795 unlike to be 6 bytes in size, probably there are whatever number of additional
  25796 "header" locations at 06000300h and up...?
  25797 Note: Metal Gear Solid Integral uses F_SN as some kind of copy protection (the
  25798 game refuses to run and displays "No copy" if F_SN is different as when the
  25799 pocketstation file was initially created).
  25800 
  25801 F_BANK_VAL and F_BANK_FLG Notes
  25802 Observe that the physical_bank number (p) is used as array index, and that the
  25803 virtual bank number (v) is stored in that location, ie. table[p]=v, which is
  25804 unlike as one may have expected it (eg. on a 80386 CPU it'd be vice-versa:
  25805 table[v]=p).
  25806 Due to the table[p]=v assignment, a physical block cannot be mirrored to
  25807 multiple virtual blocks, instead, multiple physical blocks can be mapped to the
  25808 same virtual block (unknown what happens in that case, maybe the data becomes
  25809 ANDed together).
  25810 
  25811 Pocketstation IO Communication Ports
  25812 ------------------------------------
  25813 
  25814 0C000000h - COM_MODE - Com Mode
  25815   0     Data Output Enable  (0=None/HighZ, 1=Output Data Bits)
  25816   1     /ACK Output Level   (0=None/HighZ, 1=Output LOW)
  25817   2     Unknown (should be set when expecting a NEW command...?)
  25818   3-31  Unknown (should be zero)
  25819 
  25820 0C000008h - COM_DATA - Com RX/TX Data
  25821   0-7   Data (Write: to be transmitted to PSX, Read: been received from PSX)
  25822   8-31  Unknown
  25823 
  25824 0C000004h - COM_STAT1 - Com Status Register 1 (Bit1=Error)
  25825   0     Unknown
  25826   1     Error flag or so (0=Okay, 1=Error)
  25827   2-31  Unknown
  25828 Seems to indicate whatever error (maybe /SEL disabled during transfer, or
  25829 timeout, or parity error or something else?) in bit1. Meaning of the other bits
  25830 is unknown. Aside from checking the error flag, the kernel does issue a dummy
  25831 read at the end of each transfer, maybe to acknowledge something, maybe the
  25832 hardware simply resets the error bit after reading (although the kernel doesn't
  25833 handle the bit like so when receiving the 1st command byte).
  25834 Aside from the above error flag, one should check if INT_INPUT.11 becomes zero
  25835 during transfer (which indicates undocking).
  25836 
  25837 0C000014h - COM_STAT2 - Com Status Register 2 (Bit0=Ready)
  25838   0     Ready flag (0=Busy, 1=Ready) (when 8bits have been transferred)
  25839   1-31  Unknown
  25840 
  25841 0C000010h - COM_CTRL1 - Com Control Register 1
  25842   0     Unknown (should be set AT BEGIN OF A NEW command...?)
  25843   1     Unknown (0=Disable something, 1=Enable something)
  25844   2-31  Unknown (should be zero)
  25845 Used values are:
  25846   00000000h = unknown?  disable
  25847   00000002h = unknown?  enable
  25848   00000003h = unknown?  at BEGIN of a new command
  25849 When doing the enable thing, Bit1 should be set to 0-then-1...? Bit0 might
  25850 enable the data shift register... and bit1 might be a master enable and master
  25851 acknowledge for the COM interrupt... or something else?
  25852 
  25853 0C000018h - COM_CTRL2 - Com Control Register 2
  25854   0     Unknown (should be set, probably starts or acknowledges something)
  25855   1     Unknown (should be set when expecting a NEW command...?)
  25856   2-31  Unknown (should be zero)
  25857 Used values are:
  25858   00000001h = unknown?  used before AND after each byte-transfer
  25859   00000003h = unknown?  used after LAST byte of command (and when init/reset)
  25860 Maybe that two bits acknowledge the ready/error bits?
  25861 
  25862 INT_INPUT.6  FIQ (!) COM    for the COM_registers?      (via /SEL Pin?)
  25863   (via FIQ vector, not IRQ vector)
  25864 
  25865 INT_INPUT.11 IRQ Docked ("IOP")  (0=Undocked, 1=Docked to PSX)
  25866 Probably senses the voltage on the cartridge slots VCC Pin. Becomes zero when
  25867 Undocked (and probably also when the PSX is switched off).
  25868 The Kernel uses IRQ-11 for BOTH sensing docking and undocking, ie. as if the
  25869 IRQ would be triggered on both 0-to-1 and 1-to-0 transistions... though maybe
  25870 that feature just relies on switch-bounce. For the same reason (switch bounce),
  25871 the IRQ-11 handler performs a delay before it checks the new INT_INPUT.11
  25872 setting (ie. the delay skips the unstable switch bound period, and allows the
  25873 signal to stabilize).
  25874 
  25875 IOP_START/IOP_STOP.Bit1
  25876 The BIOS adjusts this bit somehow in relation to communication. Unknown
  25877 when/why/how it must be used. For details on IOP_START/IOP_STOP see Power
  25878 Control chapter.
  25879 
  25880 Opcode E6000010h (The Undefined Instruction) - Write chr(r0) to TTY
  25881 This opcode is used by the SN Systems emulator to write chr(r0) to a TTY style
  25882 text window. r0 can be ASCII characters 20h and up, or 0Ah for CRLF. Using that
  25883 opcode is a not too good idea because the default BIOS undef instruction
  25884 handler simply runs into an endless loop, so games that are using it (eg.
  25885 Break-Thru by Jason) won't work on real hardware. That, unless the game would
  25886 change the undef instruction vector at [04h] in Kernel RAM, either replacing it
  25887 by a MOVS R15,R14 opcode (ignore exception and return to next opcode), or by
  25888 adding exception handling that outputs the character via IR or via whatever
  25889 cable connection. Observe that an uninitialized FUNC3 accidently destroys
  25890 [04h], so first init FUNC3 handler via SWI 17h, before trying to change [04h],
  25891 moreover, mind that SWI 05h may reset FUNC3, causing the problem to reappear.
  25892 Altogether, it'd be MUCH more stable to write TTY characters to an unused I/O
  25893 port... only problem is that it's still unknown which I/O ports are unused...
  25894 ie. which do neither trap data aborts, nor do mirror to existing ports...?
  25895 
  25896 Pocketstation IO Power Control
  25897 ------------------------------
  25898 
  25899 0B000000h - CLK_MODE - Clock control (CPU and Timer Speed) (R/W)
  25900   0-3  Clock Ratio (01h..08h, see below) (usually 7 = 3.99MHz)    (R/W)
  25901   4    Clock Change State (0=Busy, 1=Ready)                       (Read-only)
  25902   5-15 ?
  25903 Allows to change the CPU clock (and Timer clock, which is usually one half of
  25904 the CPU clock, or less, depending on the Timer Divider). Possible values are:
  25905   00h = hangs hardware    ;-don't use
  25906   01h = 0.063488 MHz      ;\
  25907   02h = 0.126976 MHz      ;
  25908   03h = 0.253952 MHz      ; 31*8000h / 1,2,4,8,16
  25909   04h = 0.507904 MHz      ;
  25910   05h = 1.015808 MHz      ;/
  25911   06h = 1.998848 MHz      ;\
  25912   07h = 3.997696 MHz      ; 61*8000h * 1,2,4
  25913   08h = 7.995392 MHz      ;/
  25914   09h..0Fh = same as 08h  ;-aliases
  25915 Before changing CLK_MODE, F_WAIT1 and F_WAIT2 should be adjusted accordingly
  25916 (see there for details). Note that many memory regions have waitstates, the
  25917 full CPU speed can be reached mainly with code/data in WRAM.
  25918 
  25919 0B000004h - CLK_STOP - Clock stop (Sleep Mode)
  25920 Stops the CPU until an interrupt occurs. The pocketstation doesn't have a
  25921 power-switch nor standby button, the closest thing to switch "power off" is to
  25922 enter sleep mode. Software should do that when the user hasn't pressed buttons
  25923 for 1-2 seconds (that, only in handheld mode, not when docked to the PSX; where
  25924 it's using the PSX power supply instead of the battery).
  25925   0    Stop Clock (1=Stop)
  25926   1-15 ?
  25927 Wakeup is usually done by IRQ-0 (Fire Button) and IRQ-11 (Docking). If alarm is
  25928 enabled, then the GUI also enables IRQ-9 (RTC), and compares RTC_TIME against
  25929 the alarm setting each time when it wakes up.
  25930 Before writing to CLK_STOP, one should do:
  25931   DAC_CTRL=0                         ;\disable sound
  25932   IOP_STOP=20h                       ;/
  25933   LCD_MODE=0                         ;-disable video
  25934   IRDA=whatever                      ;-disable infrared (if it was used)
  25935   BATT_CTRL=BATT_CTRL AND FFFFFFFCh  ;-do whatever
  25936   INT_MASK_SET=801h                  ;-enable Docking/Fire wakeup interrupts
  25937 The GUI uses CLK_STOP only for Standby purposes (not for waiting for its 30Hz
  25938 "frame rate" timer 0 interrupt; maybe that isn't possible, ie. probably
  25939 CLK_STOP does completely disable the system clock, and thus does stop
  25940 Timer0-2...?)
  25941 
  25942 0D800000h - IOP_CTRL - Configures whatever...? (R/W)
  25943   0-3  Probably Direction for IOP_DATA bit0..3 (0=Input, 1=Output)
  25944   4-31 Unknown/Unused (seems to be always zero)
  25945 Unknown. Set to 0000000Fh by BIOS upon reset. Aside from that, the BIOS does
  25946 never use that register.
  25947 
  25948 0D800004h - IOP_STAT (R) - Read Current bits? -- No, seems to be always 0
  25949 0D800004h - IOP_STOP (W) - Set IOP_DATA Bits
  25950 0D800008h - IOP_START (W) - Clear IOP_DATA Bits
  25951 These two ports are probably accessing a single register, writing "1" bits to
  25952 IOP_STOP sets bits in that register, and writing "1" bits to IOP_START clears
  25953 bits... or vice-versa...? Writing "0" bits to either port seems to leave that
  25954 bits unchanged. The meaning of most bits is still unknown:
  25955   0    Unknown, STARTED by Kernel upon reset
  25956   1    Red LED, Communication related (START=Whatever, STOP=Whatelse) (?)
  25957   2    Unknown, STARTED by Kernel upon reset
  25958   3    Unknown, STARTED by Kernel upon reset
  25959   4    Never STARTED nor STOPPED by BIOS (maybe an INPUT, read via IOP_DATA)
  25960   5    Sound Enable (START=On, STOP=Off)
  25961   6    Unknown, STOPPED by Kernel upon reset
  25962   7-31 Unknown, never STARTED nor STOPPED by BIOS
  25963 Aside from Bit1, it's probably not neccessary to change the unknown bits...?
  25964 Sound is usually disabled by setting IOP_STOP=00000020h. IOP_STAT is rarely
  25965 used. Although, one piece of code in the BIOS disables sound by setting
  25966 IOP_STOP=IOP_STAT OR 00000020h, that is probably nonsense, probably intended to
  25967 keep bits stopped if they are already stopped (which would happen anyways),
  25968 however, the strange code implies that reading from 0D800004h returns the
  25969 current status of the register, and that the bits in that register seem to be
  25970 0=Started, and 1=Stopped...?
  25971 
  25972 0D80000Ch - IOP_DATA (R)
  25973   0    ?
  25974   1    Red LED (0=On, 1=Off)
  25975   2    ?
  25976   3    ?
  25977   4    Seems to be always 1 (maybe Infrared input?)
  25978   5-31 Unknown/Unused (seems to be always zero)
  25979 Unknown. Not used by the BIOS. Reportedly this register is 0010h if IR
  25980 Connection...? This register is read by Rewrite ID, and by Harvest Moon. Maybe
  25981 bit4 doesn't mean <if> IR connection exist, but rather <contains> the received
  25982 IR data level...?
  25983 
  25984 0D800020h - BATT_CTRL - Battery Monitor Control?
  25985 Unknown. Somehow battery saving related. Upon reset, and upon leaving sleep
  25986 mode, the BIOS does set BATT_CTRL=00000000h. Before entering sleep mode, it
  25987 does set BATT_CTRL=BATT_CTRL AND FFFFFFFCh, whereas, assuming that BATT_CTRL
  25988 was 00000000h, ANDing it with FFFFFFFCh would simply leave it unchanged...
  25989 unless the hardware (or maybe a game) sets some bits in BATT_CTRL to nonzero
  25990 values...?
  25991 
  25992 Battery Low Interrupt
  25993   INT_INPUT.10    IRQ     Battery Low     (0=Normal, 1=Battery Low)
  25994 Can be used to sense if the battery is low, if so, one may disable sound output
  25995 and/or reduce the CPU speed to increase the remaining battery lifetime. Unknown
  25996 how long the battery lasts, and how much the lifetime is affected by audio,
  25997 video, infrared, cpu speed, and sleep mode...?
  25998 The pocketstation can be also powered through the VCC pin (ie. when docked to
  25999 the PSX, then it's working even if the battery is empty; or even without
  26000 battery).
  26001 
  26002 Pocketstation SWI Function Summary
  26003 ----------------------------------
  26004 
  26005 SWI Function Summary
  26006 BIOS functions can be called via SWI opcodes (from both ARM and THUMB mode) (in
  26007 ARM mode, the SWI function number is in the lower 8bit of the 24bit field;
  26008 unlike as for example on the GBA, where it'd be in the upper 8bit). Parameters
  26009 (if any) are passed in r0,r1,r2. Return value is stored in r0 (all other
  26010 registers are left unchanged).
  26011   SWI 00h - Reset()   ;don't use            out: everything destroyed
  26012   SWI 01h - SetCallbacks(index,proc)        out: old proc
  26013   SWI 02h - CustomSwi2(r0..r6,r8..r10)      out: r0
  26014   SWI 03h - FlashWriteVirtual(sector,src)   out: 0=okay, 1=failed
  26015   SWI 04h - SetCpuSpeed(speed)              out: old_speed
  26016   SWI 05h - SenseAutoCom()                  out: garbage
  26017   SWI 06h - GetPtrToComFlags()              out: ptr (usually 0C0h)
  26018   SWI 07h - ChangeAutoDocking(flags.16-18)  out: incoming flags AND 70000h
  26019   SWI 08h - PrepareExecute(flag,dir_index,param)  out: dir_index (new or old)
  26020   SWI 09h - DoExecute(snapshot_saving_flag) out: r0=r0 (failed) or r0=param
  26021   SWI 0Ah - FlashReadSerial()               out: F_SN
  26022   SWI 0Bh - ClearComFlagsBit10()            out: new [ComFlags] (with bit10=0)
  26023   SWI 0Ch - SetBcdDateTime(date,time)       out: garbage (RTC_DATE/10000h)
  26024   SWI 0Dh - GetBcdDate()                    out: date (with century in MSBs)
  26025   SWI 0Eh - GetBcdTime()                    out: time and day-of-week
  26026   SWI 0Fh - FlashWriteSerial(serial_number) out: garbage (r0=0) ;old BIOS only!
  26027   SWI 10h - FlashWritePhysical(sector,src)  out: 0=okay, 1=failed
  26028   SWI 11h - SetComOnOff(flag)               out: garbage retadr to swi handler
  26029   SWI 12h - TestSnapshot(dir_index)         out: 0=normal, 1=MCX1 with 1,0,"SE"
  26030   SWI 13h - GetPtrToAlarmSetting()          out: ptr to alarm_setting
  26031   SWI 14h - GetPtrToPtrToSwiTable()         out: ptr-to-ptr to swi_table
  26032   SWI 15h - MakeAlternateDirIndex(flag,dir_index)  out: alt_dir_index (new/old)
  26033   SWI 16h - GetDirIndex()                   out: dir_index (or alternate)
  26034   SWI 17h - GetPtrToFunc3addr()             out: ptr to func3 address
  26035   SWI 18h - FlashReadWhateverByte(sector)   out: [8000000h+sector*80h+7Eh]
  26036   SWI 19h..FFh - garbage
  26037   SWI 100h..FFFFFFh - mirrors of SWI 00h..FFh
  26038 The BIOS uses the same memory region for SWI and IRQ stacks, so both may not
  26039 occur simultaneously, otherwise one stack would be destroyed by the other
  26040 (normally that is no problem; IRQs are automatically disabled by the CPU during
  26041 SWI execution, SWIs aren't used from inside of default IRQ handlers, and SWIs
  26042 shouldn't be used from inside of hooked IRQ handlers).
  26043 
  26044 Pocketstation SWI Misc Functions
  26045 --------------------------------
  26046 
  26047 SWI 01h - SetCallbacks(index,proc)
  26048   r0=0  Set SWI 02h callback               (r1=proc, or r1=0=reset/default)
  26049   r0=1  Set IRQ callback                   (r1=proc, or r1=0=none/default)
  26050   r0=2  Set FIQ callback                   (r1=proc, or r1=0=none/default)
  26051   r0=3  Set Download Notification callback (r1=proc, or r1=0=bugged/default)
  26052 All callbacks are called via BX opcodes (ie. proc.bit0 can be set for THUMB
  26053 code). SetCallbacks returns the old proc value (usually zero). The callbacks
  26054 are automatically reset to zero when (re-)starting an executable, or when
  26055 returning control to the GUI, so there's no need to restore the values by
  26056 software.
  26057 
  26058 IRQ and FIQ Callbacks
  26059 Registers r0,r1,r12 are pushed by the kernels FIQ/IRQ handlers (so the
  26060 callbacks can use that registers without needing to push them). The FIQ handler
  26061 can additionally use r8..r11 without pushing them (the CPU uses a separate set
  26062 of r8..r12 registers in FIQ mode, nethertheless, the kernel DOES push r12 in
  26063 FIQ mode, without reason). Available stack is 70h bytes for the FIQ callback,
  26064 and 64h bytes for the IRQ callback.
  26065 The callbacks don't receive any incoming parameters, and don't need to respond
  26066 with a return value. The callback should return to the FIQ/IRQ handler (via
  26067 normal BX r14) (ie. it should not try to return to User mode).
  26068 The kernel IRQ handler does (after the IRQ callback) process IRQ-11 (IOP)
  26069 (which does mainly handle docking/undocking), and IRQ-9 (RTC) (which increments
  26070 the century if the year wrapped from 99h to 00h).
  26071 And the kernel FIQ handler does (before the FIQ callback) process IRQ-6 (COM)
  26072 (which does, if ComFlags.Bit9 is set, handle bu_cmd's) (both IRQs and FIQs are
  26073 disabled, and the main program is stopped until the bu_cmd finishes, or until a
  26074 joypad command is identified irrelevant, among others that means that
  26075 sound/timer IRQs aren't processed during that time, so audio output may become
  26076 distorted when docked).
  26077 When docked, the FIQ callback should consist of only a handful of opcodes, eg.
  26078 it may contain a simple noise, square wave generator, or software based sound
  26079 "DMA" function, but it should not contain more time-consuming code like sound
  26080 envelope processing; otherwise IRQ-6 (COM) cannot be executed fast enough to
  26081 handle incoming commands.
  26082 
  26083 SWI 02h - CustomSwi2(r0..r6,r8..r10)      out: r0
  26084 Calls the SWI2 callback function (which can be set via SWI 01h). The default
  26085 callback address is 00000000h (so, by default, it behaves identically as SWI
  26086 00h). Any parameters can be passed in r0..r6 and r8..r10 (the other registers
  26087 aren't passed to the callback function). Return value can be stored in r0 (all
  26088 other registers are pushed/popped by the swi handler, as usually). Available
  26089 space on the swi stack is 38h bytes.
  26090 SWI2 can be useful to execute code in privileged mode (eg. to initialize FIQ
  26091 registers r8..r12 for a FIQ based sound engine) (which usually isn't possible
  26092 because the main program runs in non-privileged user mode).
  26093 
  26094 SWI 04h - SetCpuSpeed(speed)              out: old_speed
  26095 Changes the CPU speed. The BIOS uses it with values in range 01h..07h. Unknown
  26096 if value 00h can be also used? The function also handles values bigger than
  26097 07h, of which, some pieces of BIOS code look as if 08h would be the maximum
  26098 value...?
  26099 Before setting the new speed, the function sets F_WAIT1 and F_WAIT2 to
  26100 00000000h (or to 00000010h if speed.bit3=1). After changing the speed (by
  26101 writing the parameter to CLK_MODE) it does wait until the new speed is applied
  26102 (by waiting for CLK_MODE.bit4 to become zero). The function returns the old
  26103 value of CLK_MODE, anded with 0Fh.
  26104 
  26105 Pocketstation SWI Communication Functions
  26106 -----------------------------------------
  26107 
  26108 Communication (aka BU Commands, received from the PSX via the memory card slot)
  26109 can be handled by the pocketstations kernel even while a game is running.
  26110 However, communications are initially disabled when starting a game, so the
  26111 game should enable them via SWI 11h, and/or via calling SWI 05h once per frame.
  26112 
  26113 SWI 11h - SetComOnOff(flag)
  26114 Can be used to enable/disable communication. When starting an executable,
  26115 communication is initially disabled, so it'd be a good idea to enable them
  26116 (otherwise the PSX cannot communicate with the Pocketstation while the game is
  26117 running).
  26118 When flag=0, disables communication: Intializes the COM_registers, disables
  26119 IRQ-6 (COM), and clears ComFlags.9. When flag=1, enables communication:
  26120 Intializes the COM_registers, enables IRQ-6 (COM), sets ComFlags.9 (when
  26121 docked), or clears Sys.Flags.9 (when undocked), and sets FAST cpu_speed=7 (only
  26122 when docked). The function returns garbage (r0=retadr to swi_handler).
  26123 
  26124 SWI 06h - GetPtrToComFlags()
  26125 Returns a pointer to the ComFlags word in RAM, which contains several
  26126 communication related flags (which are either modified upon docking/undocking,
  26127 or upon receiving certain bu_cmd's). The ComFlags word consists of the
  26128 following bits:
  26129   0-3   Whatever (set/cleared when docked/undocked, and modified by bu_cmd's)
  26130   4-7   Not used (should be zero)
  26131   8     IRQ-11 (IOP) occurred  (set by irq handler, checked/cleared by SWI 05h)
  26132   9     Communication Enabled And Docked (0=No, 1=Yes; prevents DoExecute)
  26133   10    Reject writes to Broken Sector Region (sector 16..55)     (0=No, 1=Yes)
  26134   11    Start file request (set by bu_cmd_59h, processed by GUI, not by Kernel)
  26135   12-15 Not used (should be zero)
  26136   16    Automatically power-down DAC audio on insert/removal      (0=No, 1=Yes)
  26137   17    Automatically power-down IRDA infrared on insert/removal  (0=No, 1=Yes)
  26138   18    Automatically adjust LCD screen rotate on insert/removal  (0=No, 1=Yes)
  26139   19-27 Not used (should be zero)
  26140   28    Indicates if a standard bu_cmd (52h/53h/57h) was received (0=No, 1=Yes)
  26141   29    Set date/time request  (set by bu_cmd FUNC0, processed by BIOS)
  26142   30    Destroy RTC and Start GUI request  (set by bu_cmd_59h, dir_index=FFFEh)
  26143   31    Not used (should be zero)
  26144 Bit16-18 can be changed via SWI 07h, ChangeAutoDocking(flags). Bit10 can be
  26145 cleared by SWI 0Bh, ClearComFlagsBit10().
  26146 
  26147 SWI 07h - ChangeAutoDocking(flags.16-18)
  26148   0-15  Not used (should be zero)
  26149   16    Automatically power-down DAC audio on insert/removal     (0=No, 1=Yes)
  26150   17    Automatically power-down IRDA infrared on insert/removal (0=No, 1=Yes)
  26151   18    Automatically adjust LCD screen rotate on insert/removal (0=No, 1=Yes)
  26152   19-31 Not used (should be zero)
  26153 Copies bit16-18 of the incoming parameter to ComFlags.16-18, specifying how the
  26154 kernel IRQ-11 (IOP) handler shall process docking/undocking from the PSX
  26155 cartridge slot. The function returns the incoming flags value ANDed with
  26156 70000h.
  26157 
  26158 SWI 0Bh - ClearComFlagsBit10()
  26159 Resets ComFlags.Bit10, ie. enables bu_cmd_57h (write_sector) to write to the
  26160 Broken Sector region in FLASH memory (sector 16..55). SWI 0Bh returns the
  26161 current ComFlags value (the new value, with bit10=0).
  26162 Aside from calling SWI 0Bh, ComFlags.10 is also automatically cleared upon
  26163 IRQ-10 (IOP) (docking/undocking). ComFlags.10 can get set/cleared by the
  26164 Download Notification callback.
  26165 
  26166 SWI 05h - SenseAutoCom()
  26167 Checks if docking/undocking has occurred (by examining ComFlags.8, which gets
  26168 set by the kernel IRQ-11 (IOP) handler). If that flag was set, then the
  26169 function does reset it, and does then reset FUNC3=0000h and [0CAh]=00h (both
  26170 only if docked, not when undocked), and, no matter if docked or undocked, it
  26171 enables communication; equivalent to SetComOnOff(1); which sets/clears
  26172 ComFlags.9. The function returns garbage (r0=whatever).
  26173 The GUI is calling SWI 05h once per frame. The overall purpose is unknown. It's
  26174 a good idea to reset FUNC3 and to Enable Communication (although that'd be
  26175 required only when docked, not when undocked), but SWI 05h is doing that only
  26176 on (un-)docking transitions (not when it was already docked). In general, it'd
  26177 make more sense to do proper initializations via SWI 11h and SWI 17h as than
  26178 trusting SWI 05h to do the job. The only possibly useful effect is that SWI 05h
  26179 does set/clear ComFlags.9 when docked/undocked.
  26180 
  26181 SWI 17h - GetPtrToFunc3addr()
  26182 Returns a pointer to a halfword in RAM which contains the FUNC3 address (for
  26183 bu_cmd_5bh and bu_cmd_5ch). The address is only 16bit, originated at 02000000h
  26184 in FLASH (ie. it can be only in the first 64K of the file), bit0 can be set for
  26185 THUMB code. The default address is zero, which behaves bugged: It accidently
  26186 sets [00000004h]=00000000h, ie. replaces the Undefined Instruction exception
  26187 vector by a "andeq r0,r0,r0" opcode, due to that NOP-like opcode, any Undefined
  26188 Instruction exceptions will run into the SWI vector at [00000008h], and
  26189 randomly execute an SWI function; with some bad luck that may execute one of
  26190 the FlashWrite functions and destroy the saved files.
  26191 Although setting 0000h acts bugged, one should restore that setting before
  26192 returning control to GUI or other executables; otherwise the address would
  26193 still point to the FUNC3 address of the old unloaded executable, which is worse
  26194 than the bugged effect.
  26195 The FUNC3 address is automatically reset to 0000h when (if) SWI 05h
  26196 (SenseAutoCom) senses new docking.
  26197 
  26198 Download Notification callback
  26199 Can be used to mute sound during communication, see SWI 01h,
  26200 SetCallbacks(index,proc), and BU Command 5Dh for details.
  26201 
  26202 Pocketstation SWI Execute Functions
  26203 -----------------------------------
  26204 
  26205 SWI 08h - PrepareExecute(flag,dir_index,param)
  26206 dir_index should be 0=GUI, or 1..15=First block of game. When calling
  26207 DoExecute, param is passed to the entrypoint of the game or GUI in r0 register
  26208 (see notes on GUI <param> values belows). For games, param may be interpreted
  26209 in whatever way.
  26210 When flag=0, the function simply returns the old dir_index value. When flag=1,
  26211 the new dir_index and param values are stored in Kernel RAM (for being used by
  26212 DoExecute); the values are stored only if dir_index=0 (GUI), or if dir_index
  26213 belongs to a file with "SC" and "MCX0" or "MCX1" IDs in it's title sector. If
  26214 dir_index was accepted, then the new dir_index value is returned, otherwise the
  26215 old dir_index is returned.
  26216 
  26217 GUI <param> values - for PrepareExecute(1,0,param)
  26218 PrepareExecute(1,0,param) prepares to execute the GUI (rather than a file).
  26219 When executing the GUI, <param> consists of the following destructive bits:
  26220   0-7  Command number (see below, MSBs=Primary command, LSBs=another dir_index)
  26221   8    Do not store Alarm setting in Kernel RAM (0=Normal, 1=Don't store)
  26222   9-31 Not used (should be zero)
  26223 The command numbers can be:
  26224   Command 0xh --> Erase RTC time/date
  26225   Command 1xh --> Enter GUI Time Screen with speaker symbol
  26226   Command 20h --> Enter GUI Time Screen with alarm symbol
  26227   Command 2xh --> Prompt for new Date/Time, then start dir_index (x)
  26228   Command 3xh --> Enter GUI File Selection Screen, with dir_index (x) selected
  26229   Command xxh --> Erase RTC time/date (same as Command 0xh)
  26230 For Command 2xh and 3xh, the lower 4bit of the command (x) must be a valid
  26231 dir_index of the 1st block of a pocketstation executable, otherwise the BIOS
  26232 erases the RTC time/date. Bit8 is just a "funny" nag feature, allowing the user
  26233 to change the alarm setting, but with the changes being ignored (bit8 can be
  26234 actually useful in BU Command 59h, after FUNC2 was used for changing alarm).
  26235 
  26236 SWI 09h - DoExecute(), or DoExecute(snapshot_saving_flag) for MCX1
  26237 Allows to return control to the GUI (when dir_index=0), or to start an
  26238 executable (when dir_index=1..15). Prior to calling DoExecute, parameters
  26239 should be set via PrepareExecute(1,dir_index,param), when not doing that,
  26240 DoExecute would simply restart the current executable (which may be a desired
  26241 effect in some cases).
  26242 The "snapshot_saving_flag" can be ommited for normal (MCX0) files, that
  26243 parameter is used only for special (MCX1) files (see Snapshot Notes for
  26244 details).
  26245 Caution: DoExecute fails (and returns r0=unchanged) when ComFlags.9=1 (which
  26246 indicates that communications are enabled, and that the Pocketstation is
  26247 believed to be docked to the PSX). ComFlags.9 can be forcefully cleared by
  26248 calling SetComOnOff(0), or it can be updated according to the current
  26249 docking-state by calling SetComOnOff(1) or SenseAutoCom().
  26250 
  26251 SWI 16h - GetDirIndex()
  26252 Returns the dir_index for the currently executed file. If that value is zero,
  26253 ie. if there is no file executed, ie. if the function is called by the GUI,
  26254 then it does instead return the "alternate" dir_index (as set via SWI 15h).
  26255 
  26256 SWI 15h - MakeAlternateDirIndex(flag,dir_index)  out: alt_dir_index (new/old)
  26257 Applies the specified dir_index as "alternate" dir_index (for being retrieved
  26258 via SWI 16h for whatever purpose). The dir_index is applied only when flag=1,
  26259 and only if dir_index is 0=none, or if it is equal to the dir_index of the
  26260 currently executed file (ie. attempts to make other files being the "alternate"
  26261 one are rejected). If successful, the new dir_index is returned, otherwise the
  26262 old dir_index is returned (eg. if flag=0, or if the index was rejected).
  26263 
  26264 SWI 12h - TestSnapshot(dir_index)
  26265 Tests if the specified file contains a load-able snapshot, ie. if it does have
  26266 the "SC" and "MCX1" IDs in the title sector, and the 01h,00h,"SE" ID in the
  26267 snapshot header. If so, it returns r0=1, and otherwise returns r0=0.
  26268 
  26269 Snapshot Notes (MCX1 Files)
  26270 Snapshots are somewhat automatically loaded/saved when calling DoExecute:
  26271 If the old file (the currently executed file) contains "SC" AND "MCX1" IDs in
  26272 the title sector, then the User Mode CPU registers and User RAM at 200h..7FFh
  26273 are automatically saved in the files snapshot region in FLASH memory, with the
  26274 snapshot_saving_flag being applied as bit0 of the 0xh,00h,"SE" ID of the
  26275 snapshot header).
  26276 If the new file (specified in dir_index) contains load-able snapshot data (ie.
  26277 if it has "SC" and "MCX1" IDs in title sector, and 01h,00h,"SE" ID in the
  26278 snapshot region), then the BIOS starts the saved snapshot data (instead of
  26279 restarting the executable at its entrypoint). Not too sure if that feature is
  26280 really working... the snapshot loader seems to load User RAM from the wrong
  26281 sectors... and it seems to jump directly to User Mode return address... without
  26282 removing registers that are still stored on SWI stack... causing the SWI stack
  26283 to underflow after loading one or two snapshots...?
  26284 
  26285 Pocketstation SWI Date/Time/Alarm Functions
  26286 -------------------------------------------
  26287 
  26288 SWI 0Ch - SetBcdDateTime(date,time)
  26289 Sets the time and date, the parameters are having the same format as SWI 0Dh
  26290 and SWI 0Eh return values (see there). The SWI 0Ch return value contains only
  26291 garbage (r0=RTC_DATE/10000h).
  26292 
  26293 SWI 0Dh - GetBcdDate()
  26294   0-7   Day     (01h..31h, BCD)
  26295   8-11  Month   (01h..12h, BCD)
  26296   16-31 Year    (0000h..9999h, BCD)
  26297 Returns the current date, the lower 24bit are read from RTC_DATE, the century
  26298 in upper 8bit is read from Kernel RAM.
  26299 
  26300 SWI 0Eh - GetBcdTime()
  26301   0-7   Seconds     (00h..59h, BCD)
  26302   8-15  Minutes     (00h..59h, BCD)
  26303   16-23 Hours       (00h..23h, BCD)
  26304   24-31 Day of week (1=Sunday, ..., 7=Saturday)
  26305 Returns the current time and day of week, read from RTC_TIME.
  26306 
  26307 SWI 13h - GetPtrToAlarmSetting()
  26308 Returns a pointer to a 64bit value in Kernel RAM, the upper word (Bit32-63)
  26309 isn't actually used by the BIOS, except that, the bu_cmd FUNC3 does transfer
  26310 the whole 64bits. The meaning of the separate bits is:
  26311   0-7   Alarm Minute    (00h..59h, BCD)
  26312   8-15  Alarm Hour      (00h..23h, BCD)
  26313   16    Alarm Enable    (0=Off, 1=On)
  26314   17    Button Lock     (0=Normal, 1=Lock) (pressing all 5 buttons in GUI)
  26315   18-19 Volume Shift    (0=Normal/Loud, 1=Medium/Div4, 2=Mute/Off)
  26316   20-22 Not used        (should be zero)
  26317   23    RTC Initialized (0=Not yet, 1=Yes, was initialized from within GUI)
  26318   24-31 Not used        (should be zero)
  26319   32-63 Pointer to 8x8 BIOS Charset (characters "0"..."9" plus strange symbols)
  26320 The RTC hardware doesn't have a hardware-based alarm feature, instead, the
  26321 alarm values must be compared with the current time by software. Alarm is
  26322 handled only by the GUI portion of the BIOS. The Kernel doesn't do any alarm
  26323 handling, so alarm won't occur while a game is executed (unless the game
  26324 contains code that handles alarm).
  26325 Games are usually using only the lower 16bit of the charset address, ORed with
  26326 04000000h (although the full 32bit is stored in RAM).
  26327   CHR(00h..09h) = Digits "0..9"
  26328   CHR(0Ah) = Space " "
  26329   CHR(0Bh) = Colon ":"
  26330   CHR(0Ch) = Button Lock (used by Final Fantasy 8's Chocobo World)
  26331   CHR(0Dh) = Speaker Medium; or loud if followed by chr(0Eh)
  26332   CHR(0Eh) = Speaker Loud; to be appended to chr(0Dh)
  26333   CHR(0Fh) = Speaker Off
  26334   CHR(10h) = Battery Low (used by PocketMuuMuu's Cars)
  26335   CHR(11h) = Alarm Off
  26336   CHR(12h) = Alarm On
  26337   CHR(13h) = Memory Card symbol
  26338 
  26339 Pocketstation SWI Flash Functions
  26340 ---------------------------------
  26341 
  26342 SWI 10h - FlashWritePhysical(sector,src)
  26343 Writes 80h-bytes at src to the physical sector number (0..3FFh, originated at
  26344 08000000h), and does then compare the written data with the source data.
  26345 Returns 0=okay, or 1=failed.
  26346 
  26347 SWI 03h - FlashWriteVirtual(sector,src)
  26348 The sector number (0..3FFh) is a virtual sector number (originated at
  26349 02000000h), the function uses the F_BANK_VAL settings to translate it to a
  26350 physical sector number, and does then write the 80h-bytes at src to that
  26351 location (via the FlashWritePhysical function). Returns 0=okay, or 1=failed (if
  26352 the write failed, or if the sector number exceeded the filesize aka the
  26353 virtually mapped memory region).
  26354 
  26355 SWI 0Ah - FlashReadSerial()
  26356 Returns the 32bit value from the two 16bit F_SN registers (see F_SN for
  26357 details).
  26358 
  26359 SWI 0Fh - FlashWriteSerial(serial_number)    ;old BIOS only!
  26360 Changes the 32bit F_SN value in the "header" region of the FLASH memory. The
  26361 function also rewrites the F_CAL value (but it simply rewrites the old value,
  26362 so it's left unchanged). The function isn't used by the BIOS, no idea if it is
  26363 used by any games. No return value (always returns r0=0).
  26364 This function is supported by the old "061" version BIOS only (the function is
  26365 padded with jump opcodes which hang the CPU in endless loops on newer "110"
  26366 version).
  26367 
  26368 SWI 18h - FlashReadWhateverByte(sector)
  26369 Returns [8000000h+sector*80h+7Eh] AND 00FFh. Purpose is totally unknown... the
  26370 actual FLASH memory doesn't contain any relevant information at that locations
  26371 (eg. the in the directory sectors, that byte is unused, usually zero)... and,
  26372 reading some kind of status or manufacturer information would first require to
  26373 command the hardware to output that info...?
  26374 
  26375 Pocketstation SWI Useless Functions
  26376 -----------------------------------
  26377 
  26378 SWI 00h - Reset()   ;don't use, destroys RTC settings
  26379 Reboots the pocketstation, similar as when pressing the Reset button. Don't
  26380 use! The BIOS bootcode does (without any good reason) reset the RTC registers
  26381 and alarm/century settings in RAM to Time 00:00:00, Date 01 Jan 1999, and Alarm
  26382 00:00 disabled, so, after reset, the user would need to re-enter that values.
  26383 Aside from the annoying destroyed RTC settings, the function is rather
  26384 unstable: it does jump to address 00000000h in RAM, which should usually
  26385 redirect to 04000000h in ROM, however, most pocketstation games are programmed
  26386 in C language, where "pointer" is usually pronounced "pointer?" without much
  26387 understanding of whether/why/how to initialize that "strange things", so
  26388 there's a good probability that one of the recently executed games has
  26389 accidently destroyed the reset vector at [00000000h] in battery-backed RAM.
  26390 
  26391 SWI 14h - GetPtrToPtrToSwiTable()
  26392 Returns a pointer to a word in RAM, which contains another pointer which
  26393 usually points to SWI table in ROM. Changing that word could be (not very)
  26394 useful for setting up a custom SWI table in FLASH or in RAM. When doing that,
  26395 one must restore the original setting before returning control to the GUI or to
  26396 another executable (the setting isn't automatically restored).
  26397 
  26398 Pocketstation BU Command Summary
  26399 --------------------------------
  26400 
  26401 The Pocketstation supports the standard Memory Card commands (Read Sector,
  26402 Write Sector, Get Info), plus a couple of special commands.
  26403 
  26404 BU Command Summary
  26405   50h  Change a FUNC 03h related value or so
  26406   51h  N/A
  26407   52h  Standard Read Sector command
  26408   53h  Standard Get ID command
  26409   54h  N/A
  26410   55h  N/A
  26411   56h  N/A
  26412   57h  Standard Write Sector command
  26413   58h  Get an ID or Version value or so
  26414   59h  Prepare File Execution with Dir_index, and Parameter
  26415   5Ah  Get Dir_index, ComFlags, F_SN, Date, and Time
  26416   5Bh  Execute Function and transfer data from Pocketstation to PSX
  26417   5Ch  Execute Function and transfer data from PSX to Pocketstation
  26418   5Dh  Execute Custom Download Notification Function   ;via SWI 01h with r0=3
  26419   5Eh  Get-and-Send ComFlags.bit1,3,2
  26420   5Fh  Get-and-Send ComFlags.bit0
  26421 Commands 5Bh and 5Ch can use the following functions:
  26422   FUNC 00h - Get or Set Date/Time
  26423   FUNC 01h - Get or Set Memory Block
  26424   FUNC 02h - Get or Set Alarm/Flags
  26425   FUNC 03h - Custom Function 3              ;via SWI 17h, GetPtrToFunc3addr()
  26426   FUNC 80h..FFh - Custom Functions 80h..FFh ;via Function Table in File Header
  26427 
  26428 Pocketstation BU Standard Memory Card Commands
  26429 ----------------------------------------------
  26430 
  26431 For general info on the three standard memory card commands (52h, 53h, 57h),
  26432 and for info on the FLAG response value, see:
  26433 --> Memory Card Read/Write Commands
  26434 
  26435 BU Command 52h (Read Sector)
  26436 Works much as on normal memory cards, except that, on the Pocketstation, the
  26437 Read Sector command return 00h as dummy values; instead of the "(pre)" dummies
  26438 that occur on normal memory cards.
  26439 The Read Sector command does reproduce the strange delay (that occurs between
  26440 5Ch and 5Dh bytes), similar as on normal original Sony memory cards, maybe
  26441 original cards did (maybe) actually DO something during that delay period, the
  26442 pocketstation BIOS simply blows up time in a wait loop (maybe for compatibility
  26443 with original cards).
  26444 
  26445 BU Command 53h (Get ID)
  26446 The Get ID command (53h) returns exactly the same values as normal original
  26447 Sony memory cards.
  26448 
  26449 BU Command 57h (Write Sector)
  26450 The Write Sector command has two new error codes (additonally to the normal
  26451 47h="G"=Good, 4Eh="N"=BadChecksum, FFh=BadSector responses). The new error
  26452 codes are (see below for details):
  26453   FDh Reject write to Directory Entries of currently executed file
  26454   FEh Reject write to write-protected Broken Sector region (sector 16..55)
  26455 And, like Read Sector, it returns 00h instead of "(pre)" as dummy values.
  26456 
  26457 Write Error Code FDh (Directory Entries of currently executed file)
  26458 The FDh error code is intended to prevent the PSX bootmenu (or other PSX games)
  26459 to delete the currently executed file (which would crash the pocketstation -
  26460 once when the deleted region gets overwritten by a new file), because the PSX
  26461 bootmenu and normal PSX games do not recognize the new FDh error code the
  26462 pocketstation does additionally set FLAG.3 (new card), which should be
  26463 understood by all PSX programs.
  26464 The FDh error code occurs only on directory sectors of the file (not on its
  26465 data blocks). However, other PSX games should never modify files that belong to
  26466 other games (so there should be no compatibility problem with other PSX
  26467 programs that aren't aware of the file being containing currently executed
  26468 code).
  26469 However, the game that has created the executable pocketstation file must be
  26470 aware of that situation. If the file is broken into a Pocketstation Executable
  26471 region and a PSX Gameposition region, then it may modify the Gameposition stuff
  26472 even while the Executable is running. If the PSX want to overwrite the
  26473 executable then it must first ensure that it isn't executed (eg. by retrieving
  26474 the dir_index of the currently executed file via BU Command 5Ah, and comparing
  26475 it against the first block number in the files FCB at the PSX side; for file
  26476 handle "fd", the first block is found at "[104h]+fd*2Ch+24h" in PSX memory).
  26477 
  26478 Write Error Code FEh (write-protected Broken Sector region, sector 16..55)
  26479 The write-protection is enabled by ComFlags.bit10 (which can be set/cleared via
  26480 BU Command 5Dh). That bit should be set before writing Pocketstation
  26481 excecutables (the Virtual Memory banking granularity is 2000h bytes, which
  26482 allows to map whole blocks only, but cannot map single sectors, which would be
  26483 required for files with broken sector replacements).
  26484 Unlike Error FDh, this error code doesn't set FLAG.3 for notifying normal PSX
  26485 programs about the error (which is no problem since normally Error FEh should
  26486 never occur since ComFlags.10 is usually zero). For more info on ComFlags.10,
  26487 see SWI 0Bh aka ClearComFlagsBit10(), and BU Command 5Dh.
  26488 
  26489 Pocketstation BU Basic Pocketstation Commands
  26490 ---------------------------------------------
  26491 
  26492 BU Command 50h (Change a FUNC 03h related value or so)
  26493   Send Reply Comment
  26494   81h  N/A   Memory Card Access
  26495   50h  FLAG  Send Command 50h
  26496   VAL  00h   Send new [0CAh], receive length of following data (00h)
  26497 Might be somehow related to FUNC 03h...?
  26498 
  26499 BU Command 58h (Get an ID or Version value or so)
  26500   Send Reply Comment
  26501   81h  N/A   Memory Card Access
  26502   58h  FLAG  Send Command 58h
  26503   (0)  02h   Send dummy/zero, receive length of following data (02h)
  26504   (0)  01h   Send dummy/zero, receive whatever value           (01h)
  26505   (0)  01h   Send dummy/zero, receive another value            (01h)
  26506 
  26507 BU Command 59h (Prepare File Execution with Dir_index, and Parameter)
  26508   Send Reply Comment
  26509   81h  N/A   Memory Card Access
  26510   59h  FLAG  Send Command 59h
  26511   (0)  06h   Send dummy/zero, receive length of following data (06h)
  26512   NEW  OLD   Send new dir_index.8-15, receive old dir_index.8-15
  26513   NEW  OLD   Send new dir_index.0-7, receive old dir_index.0-7
  26514   PAR  (0)   Send exec_parameter.0-7, receive dummy/zero
  26515   PAR  (0)   Send exec_parameter.8-15, receive dummy/zero
  26516   PAR  (0)   Send exec_parameter.16-23, receive dummy/zero
  26517   PAR  (0)   Send exec_parameter.24-31, receive dummy/zero
  26518 The new dir_index can be the following:
  26519   0000h..000Fh --> Request to Start GUI or File (with above parameter bits)
  26520   0010h..FFFDh --> Not used, acts same as FFFFh (see below)
  26521   FFFEh --> Request to Destroy RTC and Start GUI (with parameter 00000000h)
  26522   FFFFh --> Do nothing (transfer all bytes, but don't store the new values)
  26523 Upon dir_index=0000h (Start GUI) or 0001..000Fh (start file), a request flag in
  26524 ComFlags.11 is set, the GUI does handle that request, but the Kernel doesn't
  26525 handle it (so it must be handled in the game; ie. check ComFlags.11 in your
  26526 mainloop, and call DoExecute when that bit is set, there's no need to call
  26527 PrepareExecute, since that was already done by the BU Command).
  26528 Caution: When dir_index=0000h, then <param> should be a value that does NOT
  26529 erase the RTC time/date (eg. 10h or 20h) (most other values do erase the RTC,
  26530 see SWI 08h for details).
  26531 Upon dir_index=FFFEh, a similar request flag is set in ComFlags.30, and, the
  26532 Kernel (not the GUI) does handle that request in its FIQ handler (however, the
  26533 request is: To reset the RTC time/date and to start the GUI with uninitialized
  26534 irq/svc stack pointers, so this unpleasant and bugged feature shouldn't ever be
  26535 used). Finally, dir_index=FFFFh allows to read the current dir_index value
  26536 (which could be also read via BU Command 5Ah).
  26537 
  26538 BU Command 5Ah (Get Dir_index, ComFlags, F_SN, Date, and Time)
  26539   Send Reply Comment
  26540   81h  N/A   Memory Card Access
  26541   5Ah  FLAG  Send Command 5Ah
  26542   (0)  12h   Send dummy/zero, receive length of following data (12h)
  26543   (0)  INDX  Send dummy/zero, receive curr_dir_index.bit8-15   (00h)
  26544   (0)  INDX  Send dummy/zero, receive curr_dir_index.bit0-7    (00h..0Fh)
  26545   (0)  FLG   Send dummy/zero, receive ComFlags.bit0            (00h or 01h)
  26546   (0)  FLG   Send dummy/zero, receive ComFlags.bit1            (00h or 01h)
  26547   (0)  FLG   Send dummy/zero, receive ComFlags.bit3            (00h or 01h)
  26548   (0)  FLG   Send dummy/zero, receive ComFlags.bit2            (00h or 01h)
  26549   (0)  SN    Send dummy/zero, receive F_SN.bit0-7              (whatever)
  26550   (0)  SN    Send dummy/zero, receive F_SN.bit8-15             (whatever)
  26551   (0)  SN    Send dummy/zero, receive F_SN.bit16-23            (whatever)
  26552   (0)  SN    Send dummy/zero, receive F_SN.bit24-31            (whatever)
  26553   (0)  DATE  Send dummy/zero, receive BCD Day                  (01h..31h)
  26554   (0)  DATE  Send dummy/zero, receive BCD Month                (01h..12h)
  26555   (0)  DATE  Send dummy/zero, receive BCD Year                 (00h..99h)
  26556   (0)  DATE  Send dummy/zero, receive BCD Century              (00h..99h)
  26557   (0)  TIME  Send dummy/zero, receive BCD Second               (00h..59h)
  26558   (0)  TIME  Send dummy/zero, receive BCD Minute               (00h..59h)
  26559   (0)  TIME  Send dummy/zero, receive BCD Hour                 (00h..23h)
  26560   (0)  TIME  Send dummy/zero, receive BCD Day of Week          (01h..07h)
  26561 At midnight, the function may accidently return the date for the old day, and
  26562 the time for the new day.
  26563 
  26564 BU Command 5Eh (Get-and-Send ComFlags.bit1,3,2)
  26565   Send Reply Comment
  26566   81h  N/A   Memory Card Access
  26567   5Eh  FLAG  Send Command 5Eh
  26568   (0)  03h   Send dummy/zero, receive length of following data (03h)
  26569   NEW  OLD   Send new ComFlags.bit1, receive old ComFlags.bit1 (00h or 01h)
  26570   NEW  OLD   Send new ComFlags.bit3, receive old ComFlags.bit3 (00h or 01h)
  26571   NEW  OLD   Send new ComFlags.bit2, receive old ComFlags.bit2 (00h or 01h)
  26572 
  26573 BU Command 5Fh (Get-and-Send ComFlags.bit0)
  26574   Send Reply Comment
  26575   81h  N/A   Memory Card Access
  26576   5Fh  FLAG  Send Command 5Fh
  26577   (0)  01h   Send dummy/zero, receive length of following data (01h)
  26578   NEW  OLD   Send new ComFlags.bit0, receive old ComFlags.bit0 (00h or 01h)
  26579 
  26580 Pocketstation BU Custom Pocketstation Commands
  26581 ----------------------------------------------
  26582 
  26583 BU Command 5Bh (Execute Function and transfer data from Pocketstation to PSX)
  26584   Send Reply Comment
  26585   81h  N/A   Memory Card Access
  26586   5Bh  FLAG  Send Command 5Bh
  26587   FUNC FFh   Send Function Number, receive FFh (indicating variable length)
  26588   (0)  LEN1  Send dummy/zero, receive length of parameters (depending on FUNC)
  26589   ...  (0)   Send parameters (LEN1 bytes), and receive dummy/zero
  26590    <-------- at this point, the function is executed for the first time
  26591   (0)  LEN2  Send dummy/zero, receive length of data (depending on FUNC)
  26592   (0)  ...   Send dummy/zero, receive data (LEN2 bytes) from pocketstation
  26593   (0)  FFh   Send dummy/zero, receive FFh
  26594    <-------- at this point, the function is executed for the second time
  26595 See below for more info on the FUNC value and the corresponding functions.
  26596 
  26597 BU Command 5Ch (Execute Function and transfer data from PSX to Pocketstation)
  26598   Send Reply Comment
  26599   81h  N/A   Memory Card Access
  26600   5Ch  FLAG  Send Command 5Ch
  26601   FUNC FFh   Send Function Number, receive FFh (indicating variable length)
  26602   (0)  LEN1  Send dummy/zero, receive length of parameters (depending on FUNC)
  26603   ...  (0)   Send parameters (LEN1 bytes), and receive dummy/zero
  26604    <-------- at this point, the function is executed for the first time
  26605   (0)  LEN2  Send dummy/zero, receive length of data (depending on FUNC)
  26606   ...  (0)   Send data (LEN2 bytes) to pocketstation, receive dummy/zero
  26607   (0)  FFh   Send dummy/zero, receive FFh
  26608    <-------- at this point, the function is executed for the second time
  26609 See below for more info on the FUNC value and the corresponding functions.
  26610 
  26611 BU Command 5Dh (Execute Custom Download Notification Function)
  26612 Can be used to notify the GUI (or games that do support this function) about
  26613 following "download" operations (or uploads or other BU commands).
  26614 BU commands are handled inside of the kernels FIQ handler, that means both IRQs
  26615 and FIQs are disabled during a BU command transmission, so any IRQ or FIQ based
  26616 audio frequency generators will freeze during BU commands. To avoid distorted
  26617 noise, it's best to disable sound for the duration specified in bit0-7. If the
  26618 PSX finishes before the originally specified duration has expired, then it can
  26619 resend this command with bit8=1 to notify the pocketstation that the "download"
  26620 has completed.
  26621   Send Reply Comment
  26622   81h  N/A   Memory Card Access
  26623   5Dh  FLAG  Send Command 5Dh
  26624   (0)  03h   Send dummy/zero, receive length of following data (03h)
  26625   VAL  (0)   Send receive value.16-23 (whatever), receive dummy/zero
  26626   VAL  (0)   Send receive value.8-15 (download flags), receive dummy/zero
  26627   VAL  (0)   Send receive value.0-7 (download duration), receive dummy/zero
  26628 The Download Notification callback address can be set via SWI 01h,
  26629 SetCallbacks(3,proc), see there for details. At kernel side, the function
  26630 execution is like so:
  26631   If value.8-15 = 00h, then ComFlags.bit10=1, else ComFlags.bit10=0.
  26632   If download_callback<>0 then call download_callback with r0=value.0-23.
  26633 In the GUI, the bu_cmd_5dh_hook/callback handles parameter bits as so (and
  26634 games should probably handle that bits in the same fashion, too):
  26635   bit0-7  download duration   (in whatever units... 30Hz, RTC, seconds...?)
  26636   bit8    download finished   (0=no, 1=yes, cancel any old/busy duration)
  26637   bit9-23 not used by gui
  26638 If PSX games send any of the standard commands (52h,53h,57h) to access the
  26639 memory card without using command 5Dh, then GUI automatically sets the duration
  26640 to 01h (and pauses sound only for that short duration).
  26641 
  26642 FUNC 00h - Get or Set Date/Time (FUNC0)
  26643 LEN1 is 00h (no parameters), and LEN2 is 08h (eight data bytes):
  26644   DATE  Get or Send BCD Day         (01h..31h)
  26645   DATE  Get or Send BCD Month       (01h..12h)
  26646   DATE  Get or Send BCD Year        (00h..99h)
  26647   DATE  Get or Send BCD Century     (00h..99h)
  26648   TIME  Get or Send BCD Second      (00h..59h)
  26649   TIME  Get or Send BCD Minute      (00h..59h)
  26650   TIME  Get or Send BCD Hour        (00h..23h)
  26651   TIME  Get or Send BCD Day of Week (01h..07h)
  26652 At midnight, the function may accidently return the date for the old day, and
  26653 the time for the new day.
  26654 
  26655 FUNC 01h - Get or Set Memory Block (FUNC1)
  26656 LEN1 is 05h (five parameters bytes):
  26657   ADDR  Send Pocketstation Memory Address.bit0-7
  26658   ADDR  Send Pocketstation Memory Address.bit8-15
  26659   ADDR  Send Pocketstation Memory Address.bit16-23
  26660   ADDR  Send Pocketstation Memory Address.bit24-31
  26661   LEN2  Send Desired Data Length (00h..80h, automatically clipped to max=80h)
  26662 LEN2 is variable (using the 5th byte of the above parameters):
  26663   ...   Get or Send LEN2 Data byte(s), max 80h bytes
  26664 Can be used to write to RAM (and eventually also to I/O ports; when you know
  26665 what you are doing). In the read direction it can read almost anything: RAM,
  26666 BIOS ROM, I/O Ports, Physical and Virtual FLASH memory. Of which, trying to
  26667 read unmapped Virtual FLASH does probably (?) cause a Data Abort exception (and
  26668 crash the Pocketstation), so that region may be read only if a file is loaded
  26669 (check that dir_index isn't zero, via BU Command 5Ah, and, take care not to
  26670 exceed the filesize of that file).
  26671 BUG: When sending more than 2 data bytes in the PSX-to-Pocketstation direction,
  26672 then ADDR must be word-aligned (the BIOS tries to handle odd destination
  26673 addresses, but when doing that, it messes up the alignment of another internal
  26674 pointer).
  26675 
  26676 FUNC 02h - Get or Set Alarm/Flags (FUNC2)
  26677 LEN1 is 00h (no parameters), and LEN2 is 08h (eight data bytes):
  26678   DATA  Get or Send Alarm.bit0-7,   Alarm Minute    (00h..59h, BCD)
  26679   DATA  Get or Send Alarm.bit8-15,  Alarm Hour      (00h..23h, BCD)
  26680   DATA  Get or Send Alarm.bit16-23, Flags, see SWI 13h, GetPtrToAlarmSetting()
  26681   DATA  Get or Send Alarm.bit24-31, Not used (usually 00h)
  26682   DATA  Get or Send Alarm.bit32-39, BIOS Charset Address.0-7
  26683   DATA  Get or Send Alarm.bit40-47, BIOS Charset Address.8-15
  26684   DATA  Get or Send Alarm.bit48-55, BIOS Charset Address.16-23
  26685   DATA  Get or Send Alarm.bit56-63, BIOS Charset Address.24-31
  26686 Changing the alarm value while the GUI is running works only with some
  26687 trickery: For a sinister reason, the GUI copies the alarm setting to User RAM
  26688 when it gets started, that copy isn't affected by FUNC2, so the GUI believes
  26689 that the old alarm setting does still apply (and writes that old values back to
  26690 Kernel RAM when leaving the GUI). The only workaround is:
  26691 Test if the GUI is running, if so, restart it via Command 59h (with
  26692 dir_index=0, and param=0120h or similar, ie. with param.bit8 set), then execute
  26693 FUNC2, then restart the GUI again (this time with param.bit8 zero).
  26694 
  26695 FUNC 03h - Custom Function 3 (aka FUNC3)
  26696 LEN1 is 04h (fixed) (four parameters bytes):
  26697   VAL   Send Parameter Value.bit0-7
  26698   VAL   Send Parameter Value.bit8-15
  26699   VAL   Send Parameter Value.bit16-23
  26700   VAL   Send Parameter Value.bit24-31
  26701 LEN2 is variable (depends on the return value of the 1st function call):
  26702   ...   Get or Send LEN2 Data byte(s)
  26703 The function address can be set via SWI 17h, GetPtrToFunc3addr(), see there for
  26704 details.
  26705 Before using FUNC 03h one must somehow ensure that the desired file is loaded
  26706 (and that it does have initialized the function address via SWI 17h, otherwise
  26707 the pocketstation would crash).
  26708 The FUNC3 address is automatically reset to 0000h when (if) SWI 05h
  26709 (SenseAutoCom) senses new docking.
  26710 Note: The POC-XBOO circuit uses FUNC3 to transfer TTY debug messages.
  26711 
  26712 FUNC 80h..FFh - Custom Function 80h..FFh
  26713 LEN1 is variable (depends on the LEN1 value in Function Table in File Header):
  26714   ...   Send LEN1 Parameter Value(s), max 80h bytes (destroys Kernel when >80h)
  26715 LEN2 is variable (depends on the return value of the 1st function call):
  26716   ...   Get or Send LEN2 Data byte(s), max 80h bytes (clipped to max=80h)
  26717 The function addresses (and LEN1 values) are stored in the Function Table FLASH
  26718 memory (see Pocketstation File Header for details).
  26719       ;above LEN1 should be 00h..80h (the parameters are stored
  26720       ;in a 80h-byte buffer in kernel RAM, so len LEN1=81h..FFh would
  26721       ;destroy the kernel RAM that is located after that buffer)
  26722 Before using FUNC 80h..FFh one must somehow ensure that the desired file is
  26723 loaded (ie. that the function table with the desired functions is mapped to
  26724 flash memory; otherwise the pocketstation would crash).
  26725 
  26726 First Function Call (Pre-Data)
  26727 Incoming parameters on 1st Function Call:
  26728   r0=flags (09h=Pre-Data to PSX, or 0Ah=Pre-Data from PSX)
  26729   r1=pointer to parameter buffer (which contains LEN1 bytes) (in Kernel RAM)
  26730 Return Value on 1st Function Call:
  26731   r0 = Pointer to 64bit memory location (or r0=00000000h=Failed)
  26732 That 64bits are:
  26733   0-31    BUF2 address of data buffer (src/dst)
  26734   32-63   LEN2 (00000000h..00000080h) (clipped to max 00000080h if bigger)
  26735 dst is written in 8bit units
  26736 src is read in 16bit units (and then split to 8bit units)
  26737 
  26738 Second Function Call (Post-Data)
  26739 Incoming parameters on 2nd Function Call:
  26740   r0=flags (11h=Post-Data to PSX, 12h=Post-Data from PSX; plus 04h if Bad-Data)
  26741   r1=pointer to data buffer (which contains LEN2 bytes) (BUF2 address)
  26742 Return Value on 2nd Function Call:
  26743   There's no return value required on 2nd call (although the kernel
  26744   functions seem to return the same stuff as on 1st call).
  26745 
  26746 Function flags (r0)
  26747 For each function, there is only one single function vector which is called for
  26748 both To- and From-PSX, and both Pre- and Post-Data, and also on errors. The
  26749 function must decipher the flags in r0 to figure out which of that operations
  26750 it should handle:
  26751   0    To-PSX   (when used by Command 5Bh)
  26752   1    From-PSX (when used by Command 5Ch)
  26753   2    Error occurred during Data transfer
  26754   3    Pre-Data
  26755   4    Post-Data
  26756   5-31 Not used (zero)
  26757 There are only six possible flags combinations:
  26758   09h Pre-Data to PSX
  26759   0Ah Pre-Data from PSX
  26760   11h Post-Data to PSX
  26761   12h Post-Data from PSX
  26762   15h Post-Bad-Data to PSX
  26763   16h Post-Bad-Data from PSX
  26764 The kernel doesn't call FUNC 03h if the Error bit is set (ie. Post-Bad-Data
  26765 needs to be handled only by FUNC 80h..FFh, not by FUNC 03h.)
  26766 
  26767 Pocketstation File Header/Icons
  26768 -------------------------------
  26769 
  26770 Pocketstation File Content
  26771 Pocketstation files consists of the following elements (in that order):
  26772   PSX Title Sector              ;80h bytes
  26773   PSX Colored Icon(s)           ;(hdr[02h] AND 0Fh)*80h bytes
  26774   Pocketstation Saved Snapshot  ;800h bytes if hdr[52h]="MCX1", else 0 bytes
  26775   Pocketstation Function Table  ;(hdr[57h]*8+7Fh) AND NOT 7Fh bytes
  26776   Pocketstation File Viewer Mono Icon     ;hdr[50h]*80h bytes
  26777   Pocketstation Executable Mono Icon List ;hdr[56h]*8 bytes
  26778   Body (Pocketstation Executable Code/Data, PSX Game Position, Exec-Icons)
  26779 The Title sector contains some information about the size of the above regions,
  26780 but not about their addresses (ie. to find a given region, one must compute the
  26781 size of the preceeding regions).
  26782 
  26783 Special "P" Filename in Directory Sector
  26784 For pocketstation executables, the 7th byte of the filename must be a "P" (for
  26785 other files that location does usually contain a "-", assuming the file uses a
  26786 standard filename, eg. "BESLES-12345abcdefgh" for a Sony licensed european
  26787 title).
  26788 
  26789 Special Pocketstation Entries in the Title Sector at [50h..5Fh]
  26790   50h 2  Number of File Viewer Mono Icon Frames (or 0000h=Use Exec-Icons)
  26791   52h 4  Pocketstation Identifier ("MCX0"=Normal, "MCX1"=With Snapshot)
  26792   56h 1  Number of entries in Executable Mono Icon List (01h..FFh)
  26793   57h 1  Number of BU Command 5Bh/5Ch Get/Set Functions (00h..7Fh, usually 00h)
  26794   58h 4  Reserved (zero)
  26795   5Ch 4  Entrypoint in FLASH1 (ie. Fileoffset plus 02000000h) (bit0=THUMB)
  26796 In normal PSX files, the region at 50h..5Fh is usually zerofilled. For more
  26797 info on the standard entries in the Title Sector (and for info on Directory
  26798 Entries), see:
  26799 --> Memory Card Data Format
  26800 
  26801 Snapshot Region (in "MCX1" Files only)
  26802 For a load-able snapshot the Snapshot ID must be 01h,00h,"SE", the Kernel uses
  26803 snapshots only once (after loading a snapshot, it forcefully changes the ID to
  26804 00h,00h,"SE" in FLASH memory).
  26805   000h  r1..r12 (ie. without r0)
  26806   030h  r13_usr (sp_usr)
  26807   034h  r14_usr (lr_usr)
  26808   038h  r15     (pc)
  26809   03Ch  psr_fc
  26810   040h  Snapshot ID (0xh,00h,"SE")
  26811   044h  unused (3Ch bytes)
  26812   200h  Copy of user RAM at 200h..7FFh
  26813 For MCX1 files, snapshots can be automatically loaded and saved via the SWI
  26814 09h, DoExecute function (the snapshot handling seems to be bugged though; see
  26815 SWI 09h for details).
  26816 
  26817 Function Table (FUNC 80h..FFh)
  26818 The table can contain 00h..7Fh entries, for FUNC 80h..FFh. Each entry occupies
  26819 8 bytes:
  26820   00h 4   LEN1 (00000000h..00000080h) (destroys Kernel RAM if bigger)
  26821   04h 4   Function Address (bit0 can be set for THUMB code)
  26822 If the number of table entries isn't a multiple of 10h, then the table should
  26823 be zero-padded to a multiple of 80h bytes (the following File Viewer Mono Icon
  26824 data is located on the next higher 80h-byte boundary after the Function Table).
  26825 For details see BU Commands 5Bh and 5Ch.
  26826 
  26827 File Viewer Mono Icon
  26828 Animation Length (0001h..any number) (icon frames) is stored in hdr[50h], for
  26829 the File Viewer Icon, the Animation Delay is fixed (six 30Hz units per frame).
  26830 The File Viewer Icon is shown in the Directory Viewer (which is activated when
  26831 holding the Down-button pressed for some seconds in the GUI screen with the
  26832 speaker and memory card symbols, and which shows icons for all files, including
  26833 regular PSX game positions, whose colored icons are converted without any
  26834 contrast optimizations to unidentify-able dithered monochrome icons). If the
  26835 animation length of the File Viewer Icon is 0000h, then the Directory Viewer
  26836 does instead display the first Executable Mono Icon.
  26837 Each icon frame is 32x32 pixels with 1bit color depth (32 words, =128 bytes),
  26838   1st word = top-most scanline, 31st word = bottom-most scanline
  26839   bit0 = left-most pixel, bit31 = right-most pixel (0=white, 1=black)
  26840 A normal icon occupies 80h bytes, animated icons have more than one frame and
  26841 do occupy N*80h bytes.
  26842 
  26843 Executable Mono Icon List
  26844 The number of entries in the Executable Mono Icon List is specified in hdr[56h]
  26845 (usually 01h). Each entry in the Icon List occupies 8 bytes:
  26846   00h 2  Animation Length (0001h..any number) (icon frames)
  26847   02h 2  Animation Delay (N 30Hz units per icon frame)
  26848   04h 4  Address of icon frame(s) in Virtual FLASH (at 02000000h and up)
  26849 The icon frame(s) can be anywhere on a word-aligned location in the file Body
  26850 (as specified in the above Address entry), the format of the frame(s) is the
  26851 same as for File Viewer Mono Icons (see there).
  26852 The Executable Icons are shown in the Executable File Selection Menu (which
  26853 occurs when pressing Left/Right buttons in the GUI). Pressing Fire button in
  26854 that menu starts the selected executable. If the Icon List has more than 1
  26855 entry, then pressing Up/Down buttons moves to the previous/next entry (this
  26856 just allows to view the corresponding icons, but doesn't have any other
  26857 purpose, namely, the current list index is NOT passed to the game when starting
  26858 it).
  26859 The Executable Mono Icon List is usually zero-padded to 80h-bytes size
  26860 (although that isn't actually required, the following file Body could start at
  26861 any location).
  26862 
  26863 Entrypoint
  26864 The whole file (including the header and icons) gets mapped to 02000000h and
  26865 up. The entrypoint can be anywhere in the file Body, and it gets called with a
  26866 parameter value in r0 (when started by the GUI, that parameter is always zero,
  26867 but it may be nonzero when the executable was started by a game, ie. the
  26868 <param> from SWI 08h, PrepareExecute, or the <param> from BU Command 59h).
  26869 Caution: Games (and GUI) are started with the ARM CPU running in Non-privileged
  26870 User Mode (however, there are several ways to hook IRQ/FIQ handlers, and from
  26871 there one can switch to Privileged System Mode).
  26872 
  26873 Returning to the GUI
  26874 Games should always include a way to return to the GUI (eg. an option in the
  26875 game over screen, a key combination, a watchdog timer, and/or the docking
  26876 signal) (conventionally, games should prompt Exit/Continue when holding Fire
  26877 pressed for 5 seconds), otherwise it wouldn't be possible to start other games
  26878 - except by pushing the Reset button (which is no good idea since the bizarre
  26879 BIOS reset handler does reset the RTC time for whatever reason).
  26880 The kernel doesn't pass any return address to the entrypoint (neither in R14,
  26881 nor on stack). To return control to the GUI, use SWI functions
  26882 PrepareExecute(1,0,GetDirIndex()+30h), and then DoExecute(0).
  26883 
  26884 Pocketstation File Images
  26885 -------------------------
  26886 
  26887 Pocketstation files are normally stored in standard Memory Card images,
  26888 --> Memory Card Images
  26889 
  26890 Pocketstation specific files
  26891 Aside from that standard formats, there are two Pocketstation specific formats,
  26892 the "SC" and "SN" variants. Both contain only the raw file, without any
  26893 Directory sectors, and thus not including a "BESLESP12345"-style filename
  26894 string. The absence of the filename means that a PSX game couldn't (re-)open
  26895 these files via filenames, so they are suitable only for "standalone"
  26896 pocketstation games.
  26897 
  26898 Pocketstation .BIN Files ("SC" variant)
  26899 Contains the raw Pocketstation Executable (ie. starting with the "SC" bytes in
  26900 the title sector, followed by icons, etc.), the filesize should be padded to a
  26901 2000h-byte block boundary.
  26902 
  26903 Pocketstation .BIN Files ("SN" variant)
  26904 This is a strange incomplete .BIN file variant which starts with a 4-byte ID
  26905 ("SN",00h,00h), which is directly followed by executable code, without any
  26906 title sector, and without any icons.
  26907   It seems as if the file (including the 4-byte ID) is intended to be
  26908   mapped to address 02000000h, and that the entrypoint is fixed at
  26909   02000004h (in ARM state).
  26910   Since the File doesn't have a valid file header with "SC" and "MCXn" IDs,
  26911   it won't be recognized by real hardware, the PSX BIOS would treat it as
  26912   a corrupted/deleted file, the Pocketstation BIOS would treat it as a
  26913   non-executable file.
  26914   So, that fileformat is apparently working only on whatever emulators,
  26915   apparently on the one developed by SN Systems.
  26916   If one should want to use that files on real hardware, one could add
  26917   a 2000h byte stub at the begin of the file; with valid headers, and
  26918   with a small executable that remaps the "SN" stuff to 02000000h via
  26919   the F_BANK_VAL registers.
  26920   Ah, and the "SN" files seem to access RAM at 01000000h and up, unknown
  26921   if RAM is mirrored to that location on real hardware, reportedly that
  26922   region is unused... and doesn't contain RAM...?
  26923     Some games use The Undefined Instruction for TTY Output.
  26924     Most games do strange 8bit writes to LCD_MODE+0 and LCD_MODE+1
  26925     The games usually don't allow to return to the GUI (except by Reset).
  26926 The filesize is don't care (no padding to block, sector, word, or halfword
  26927 boundaries required).
  26928 
  26929 Pocketstation XBOO Cable
  26930 ------------------------
  26931 
  26932 This circuit allows to connect a pocketstation to PC parallel port, allowing to
  26933 upload executables to real hardware, and also allowing to download TTY debug
  26934 messages (particulary useful as the 32x32 pixel LCD screen is ways too small to
  26935 display any detailed status info).
  26936 
  26937 POC-XBOO Circuit
  26938 Use a standard parallel port cable (with 36pin centronics connector or 25pin DB
  26939 connector) and then build a small adaptor like this:
  26940   Pin CNTR  DB25          Pocketstation          _______________________
  26941   ACK 10    10  --------- 1 JOYDTA              |       |       |       |
  26942   D0  2     2   --------- 2 JOYCMD              | 9 7 6 | 5 4 3 |  2 1  | CARD
  26943   GND 19-30 18-25 ------- 4 GND                 |_______|_______|_______|
  26944   D1  3     3   --------- 6 /JOYSEL              _______________________
  26945   D2  4     4   --------- 7 JOYCLK              |       |       |       |
  26946   PE  12    12  --------- 9 /JOYACK (/IRQ7)     | 9 8 7 | 6 5 4 | 3 2 1 | PAD
  26947   NC -------------------- 8 /JOYGUN (/IRQ10)     \______|_______|______/
  26948   NC -------------------- 3 7.5V (rumble.supply)
  26949   SUPPLY.5V --|>|---|>|-- 5 3.5V (VCC) (eg. PC's +5V via two 1N4001 diodes)
  26950   SUPPLY.0V ------------- 4 GND (not needed when same as GND on CNTR/DB25)
  26951 The circuit is same as for "Direct Pad Pro" (but using a memory card connector
  26952 instead of joypad connector, and needing +5V from PC power supply instead of
  26953 using parallel port D3..D7 as supply). Note: IRQ7 is optional (for faster/early
  26954 timeout).
  26955 
  26956 POC-XBOO Upload
  26957 The upload function is found in no$gba "Utility" menu. It does upload the
  26958 executable and autostart it via standard memory card/pocketstation commands
  26959 (ie. it doesn't require any special transmission software installed on the
  26960 pocketstation side).
  26961 Notes: Upload is overwriting ALL files on the memory card, and does then
  26962 autostart the first file. Upload is done as "read and write only if different",
  26963 this provides faster transfers and higher lifetime.
  26964 
  26965 POC-XBOO TTY Debug Messages
  26966 TTY output is conventionally done by executing the ARM CPU's Undefined Opcode
  26967 with an ASCII character in R0 register (for that purpose, the undef opcode
  26968 handler should simply point to a MOVS PC,LR opcode).
  26969 That kind of TTY output works in no$gba's pocketstation emulation. It can be
  26970 also used via no$gba's POC-XBOO cable, but requires some small customization in
  26971 the executable:
  26972 First of, the executable needs "TTY+" ID in some reserved bytes of the title
  26973 sector (telling the xboo uploader to stay in transmission mode and to keep
  26974 checking for TTY messages after the actual upload):
  26975   TitleSector[58h] = "TTY+"
  26976 With that ID, and with the XBOO-hardware being used, the game will be started
  26977 with "TTY+" in R0 (notifying it that the XBOO hardware is present, and that it
  26978 needs to install special transmission handlers):
  26979  ;------------------
  26980  .data?
  26981  org  200h
  26982  ...
  26983  tty_bufsiz equ 128  ;max=128=fastest (can be smaller if you are short of RAM)
  26984  func3_info:                                       ;\ ;\
  26985   func3_buf_base     dd 0   ;fixed="func3_buf"     ;  ;  func3_info+00h
  26986   func3_buf_len      dd 0   ;range=0..128          ;/ ;  func3_info+04h
  26987   func3_stack        dd 0                             ;  func3_info+08h
  26988   func3_buffer:      defs tty_bufsiz                  ;/ func3_info+0Ch
  26989  ptr_to_comflags     dd 0
  26990  ...
  26991  .code
  26992  ...
  26993  ;------------------
  26994  tty_wrchr:   ;in: r0=char
  26995   dd      0e6000010h ;=undef opcode            ;-Write chr(r0) to TTY
  26996   bx      lr
  26997  ;------------------
  26998  init_tty:  ;in: r0=param (from entrypoint)
  26999   ldr     r1,=2B595454h ;"TTY+"                ;\check if xboo-cable present
  27000   cmp     r1,r0                                ; (r0=incoming param from
  27001   beq     @@tty_by_xboo_cable                  ;/executable's entrypoint)
  27002  ;- - -
  27003   mov     r1,0                                 ;\dummy und_handler
  27004   ldr     r2,=0e1b0f00eh  ;=movs r15,r14       ; (just return from exception,
  27005   str     r2,[r1,04h]  ;und_handler            ;/for normal cable-less mode)
  27006   b       @@finish
  27007  ;---
  27008  @@tty_by_xboo_cable:
  27009   swi     17h  ;GetPtrToFunc3addr()            ;\
  27010   ldr     r1,=(tty_func3_handler AND 0ffffh)   ; init FUNC3 aka TTY handler
  27011   strh    r1,[r0]                              ;/
  27012   ldr     r1,=func3_info                       ;\
  27013   mov     r0,0                             ;\  ; mark TTY as len=empty
  27014   str     r0,[r1,4]        ;func3_buf_len  ;/  ; and
  27015   add     r0,r1,0ch ;=func3_buffer         ;\  ; init func3 base
  27016   str     r0,[r1,0]        ;func3_buf_base ;/  ;/
  27017   mov     r1,0                                 ;\
  27018   ldr     r2,=0e59ff018h  ;=ldr r15,[pc,NN]    ;
  27019   str     r2,[r1,04h]  ;und_handler            ; special xboo und_handler
  27020   add     r2,=tty_xboo_und_handler             ;
  27021   str     r2,[r1,24h]  ;und_vector             ;/
  27022  @@finish:
  27023   swi     06h ;GetPtrToComFlags()              ;\
  27024   ldr     r1,=ptr_to_comflags                  ; get ptr to ComFlags
  27025   str     r0,[r1]                              ;/
  27026   bx      lr
  27027  ;------------------
  27028  tty_xboo_und_handler:   ;in: r0=char
  27029   ldr     r13,=func3_info ;aka sp_und          ;-base address (in sp_und)
  27030   str     r12,[r13,8] ;func3_stack             ;-push r12
  27031  @@wait_if_buffer_full:                        ;\
  27032   ldr     r12,=ptr_to_comflags                 ; ;\exit if execute file request
  27033   ldr     r12,[r12]  ;ptr to ComFlags          ; ; ComFlg.Bit11 ("bu_cmd_59h"),
  27034   ldr     r12,[r12]  ;read ComFlags            ; ; ie. allow that flag to be
  27035   tst     r12,1 shl 11  ;test bit11            ; ; processed by main program,
  27036   bne     @@exit                               ; ;/without hanging here
  27037   ldrb    r12,[r13,4] ;func3_buf_len           ; wait if buffer full
  27038   cmp     r12,tty_bufsiz                       ; (until drained by FIQ)
  27039   beq     @@wait_if_buffer_full                ;/
  27040   mov     r12,1bh+0c0h  ;mode=und, FIQ/IRQ=off ;\disable FIQ (no COMMUNICATION
  27041   mov     cpsr_ctl,r12                         ;/interrupt during buffer write)
  27042   ldrb    r12,[r13,4]  ;func3_buf_len          ;\
  27043   add     r12,1        ;raise len              ; write char to buffer
  27044   strb    r12,[r13,4]  ;func3_buf_len          ; and raise buffer length
  27045   add     r12,0ch-1    ;=func3_buffer+INDEX    ;
  27046   strb    r0,[r13,r12] ;append char to buf     ;/
  27047  @@exit:
  27048   ldr     r12,[r13,8]  ;func3_stack            ;-pop r12
  27049   movs    r15,r14        ;return from exception (and restore old IRQ/FIQ state)
  27050  ;------------------
  27051  tty_func3_handler:   ;in: r0=flags, r1=ptr
  27052   tst     r0,10h  ;test if PRE/POST data (pre: Z, post: NZ)
  27053  ;ldreq   r1,[r1]   ;read 32bit param (aka the four LEN1 bytes of FUNC3)
  27054   ldr     r0,=func3_info   ;ptr to two 32bit values (FUNC3 return value)
  27055   movne   r1,0                           ;\for POST data: mark buffer empty
  27056   strne   r1,[r0,4] ;func3_buf_len=0     ;/
  27057   bx      lr                             ;-for PRE data: return r0=func3_info
  27058 Usage: Call "init_tty" at the executable's entrypoint (with incoming R0 passed
  27059 on). Call "tty_wrchr" to output ASCII characters.
  27060 Note: The TTY messages are supported only in no$gba debug version (not no$gba
  27061 gaming version).
  27062 
  27063 Serial Port (SIO)
  27064 -----------------
  27065 
  27066 1F801050h SIO_TX_DATA (W)
  27067   0-7   Data to be sent
  27068   8-31  Not used
  27069 Writing to this register starts transmit (if, or as soon as, TXEN=1 and CTS=on
  27070 and SIO_STAT.2=Ready). Writing to this register while SIO_STAT.0=Busy causes
  27071 the old value to be overwritten.
  27072 The "TXEN=1" condition is a bit more complex: Writing to SIO_TX_DATA latches
  27073 the current TXEN value, and the transfer DOES start if the current TXEN value
  27074 OR the latched TXEN value is set (ie. if TXEN gets cleared after writing to
  27075 SIO_TX_DATA, then the transfer may STILL start if the old latched TXEN value
  27076 was set; this appears for SIO transfers in Wipeout 2097).
  27077 
  27078 1F801050h SIO_RX_DATA (R)
  27079   0-7   Received Data      (1st RX FIFO entry) (oldest entry)
  27080   8-15  Preview            (2nd RX FIFO entry)
  27081   16-23 Preview            (3rd RX FIFO entry)
  27082   24-31 Preview            (4th RX FIFO entry) (5th..8th cannot be previewed)
  27083 A data byte can be read when SIO_STAT.1=1. Data should be read only via 8bit
  27084 memory access (the 16bit/32bit "preview" feature is rather unusable).
  27085 
  27086 1F801054h SIO_STAT (R)
  27087   0     TX Ready Flag 1   (1=Ready/Started)  (depends on CTS) (TX requires CTS)
  27088   1     RX FIFO Not Empty (0=Empty, 1=Not Empty)
  27089   2     TX Ready Flag 2   (1=Ready/Finished) (depends on TXEN and on CTS)
  27090   3     RX Parity Error   (0=No, 1=Error; Wrong Parity, when enabled) (sticky)
  27091   4     RX FIFO Overrun   (0=No, 1=Error; Received more than 8 bytes) (sticky)
  27092   5     RX Bad Stop Bit   (0=No, 1=Error; Bad Stop Bit) (when RXEN)   (sticky)
  27093   6     RX Input Level    (0=Normal, 1=Inverted) ;only AFTER receiving Stop Bit
  27094   7     DSR Input Level   (0=Off, 1=On) (remote DTR) ;DSR not required to be on
  27095   8     CTS Input Level   (0=Off, 1=On) (remote RTS) ;CTS required for TX
  27096   9     Interrupt Request (0=None, 1=IRQ)                             (sticky)
  27097   10    Unknown           (always zero)
  27098   11-25 Baudrate Timer    (15bit timer, decrementing at 33MHz)
  27099   26-31 Unknown (usually zero, sometimes all bits set)
  27100 Note: Bit0 gets cleared after sending the Startbit, Bit2 gets cleared after
  27101 sending all bits up to including the Stopbit.
  27102 
  27103 1F801058h SIO_MODE (R/W) (eg. 004Eh --> 8N1 with Factor=MUL16)
  27104   0-1   Baudrate Reload Factor (1=MUL1, 2=MUL16, 3=MUL64) (or 0=STOP)
  27105   2-3   Character Length       (0=5bits, 1=6bits, 2=7bits, 3=8bits)
  27106   4     Parity Enable          (0=No, 1=Enable)
  27107   5     Parity Type            (0=Even, 1=Odd) (seems to be vice-versa...?)
  27108   6-7   Stop bit length        (0=Reserved/1bit, 1=1bit, 2=1.5bits, 3=2bits)
  27109   8-15  Not used (always zero)
  27110 
  27111 1F80105Ah SIO_CTRL (R/W)
  27112   0     TX Enable (TXEN)  (0=Disable, 1=Enable, when CTS=On)
  27113   1     DTR Output Level  (0=Off, 1=On)
  27114   2     RX Enable (RXEN)  (0=Disable, 1=Enable)  ;Disable also clears RXFIFO
  27115   3     TX Output Level   (0=Normal, 1=Inverted, during Inactivity & Stop bits)
  27116   4     Acknowledge       (0=No change, 1=Reset SIO_STAT.Bits 3,4,5,9)      (W)
  27117   5     RTS Output Level  (0=Off, 1=On)
  27118   6     Reset             (0=No change, 1=Reset most SIO_registers to zero) (W)
  27119   7     Unknown? (read/write-able when FACTOR non-zero) (otherwise always zero)
  27120   8-9   RX Interrupt Mode    (0..3 = IRQ when RX FIFO contains 1,2,4,8 bytes)
  27121   10    TX Interrupt Enable  (0=Disable, 1=Enable) ;when SIO_STAT.0-or-2 ;Ready
  27122   11    RX Interrupt Enable  (0=Disable, 1=Enable) ;when N bytes in RX FIFO
  27123   12    DSR Interrupt Enable (0=Disable, 1=Enable) ;when SIO_STAT.7  ;DSR=On
  27124   13-15 Not used (always zero)
  27125 
  27126 1F80105Ch SIO_MISC (R/W)
  27127 This is an internal register, which usually shouldn't be accessed by software.
  27128 Messing with it has rather strange effects: After writing a value "X" to this
  27129 register, reading returns "X ROR 8" eventually "ANDed with 1F1Fh and ORed with
  27130 C0C0h or 8080h" (depending on the character length in SIO_MODE).
  27131 
  27132 1F80105Eh SIO_BAUD (R/W) (eg. 00DCh --> 9600 bauds; when Factor=MUL16)
  27133   0-15  Baudrate Reload value for decrementing Baudrate Timer
  27134 The Baudrate is calculated (based on SIO_BAUD, and on Factor in SIO_MODE):
  27135   BitsPerSecond = (44100Hz*300h) / MIN(((Reload*Factor) AND NOT 1),Factor)
  27136 
  27137 SIO_TX_DATA Notes
  27138 The hardware can hold (almost) 2 bytes in the TX direction (one being currently
  27139 transferred, and, once when the start bit was sent, another byte can be stored
  27140 in SIO_TX_DATA). When writing to SIO_TX_DATA, both SIO_STAT.0 and SIO_STAT.2
  27141 become zero. As soon as the transfer starts, SIO_STAT.0 becomes set (indicating
  27142 that one can write a new byte to SIO_TX_DATA; although the transmission is
  27143 still busy). As soon as the transfer of the most recently written byte ends,
  27144 SIO_STAT.2 becomes set.
  27145 
  27146 SIO_RX_DATA Notes
  27147 The hardware can hold 8 bytes in the RX direction (when receiving further
  27148 byte(s) while the RX FIFO is full, then the last FIFO entry will by overwritten
  27149 by the new byte, and SIO_STAT.4 gets set; the hardware does NOT automatically
  27150 disable RTS when the FIFO becomes full).
  27151 Data can be read from SIO_RX_DATA when SIO_STAT.1 is set, that flag gets
  27152 automatically cleared after reading from SIO_RX_DATA (unless there are still
  27153 further bytes in the RX FIFO). Note: The hardware does always store incoming
  27154 data in RX FIFO (even when Parity or Stop bits are invalid).
  27155 Note: A 16bit read allows to read two FIFO entries at once; nethertheless, it
  27156 removes only ONE entry from the FIFO. On the contrary, a 32bit read DOES remove
  27157 FOUR entries (although, there's nothing that'd indicate if the FIFO did
  27158 actually contain four entries).
  27159 Reading from Empty RX FIFO returns either the most recently received byte or
  27160 zero (the hardware stores incoming data in ALL unused FIFO entries; eg. if five
  27161 entries are used, then the data gets stored thrice, after reading 6 bytes, the
  27162 FIFO empty flag gets set, but nethertheless, the last byte can be read two more
  27163 times, but doing further reads returns 00h).
  27164 
  27165 Interrupt Acknowledge Notes
  27166 First reset I_STAT.8, then set SIO.CTRL.4 (when doing it vice-versa, the
  27167 hardware may miss a new IRQ which may occur immediately after setting
  27168 SIO.CTRL.4) (and I_STAT.8 is edge triggered, so that bit can be reset even
  27169 while SIO_STAT.9 is still set).
  27170 When acknowledging via SIO_CTRL.4 with the enabled condition(s) in
  27171 SIO_CTRL.10-12 still being true (eg. the RX FIFO is still not empty): the IRQ
  27172 does trigger again (almost) immediately (it goes off only for a very short
  27173 moment; barely enough to allow I_STAT.8 to sense a edge).
  27174 
  27175 SIO_BAUD Notes
  27176 Timer reload occurs when writing to SIO_BAUD, and, automatically when the
  27177 Baudrate Timer reaches zero. There should be two 16bit SIO timers (for TX and
  27178 RX), the upper 15bit of one of that timers can be read from SIO_STAT (not sure
  27179 which one, and no idea if there's a way to read the other timer, too).
  27180 Or... maybe there is only ONE timer, and RX/TX are separated only by separate
  27181 "timer ellapsed" counters, in that case the MUL1 factor won't work properly,
  27182 but, with the MUL16 or MUL64 factors, RX could start anytime (eg. when TX has
  27183 already ellapsed a bunch of times)...?
  27184 The maximum baud rate may vary depending on the length and quality of the
  27185 cable, whether and how many inverters and anti-inverters are used (on the
  27186 mainboard and in external adaptor, and on whether signals are externally
  27187 converted to +/-12V levels)... anyways, rates up to 9600 baud should be working
  27188 in all cases.
  27189 However, running in no$psx, Wipeout 2097 seems to use about 2 million bauds...
  27190 although, in older no$psx versions, I believe I did see it using some kind of
  27191 baudrate detection, where it did try different rates in steps of 200 bauds or
  27192 so...?
  27193 
  27194 SIO Ports vs JOY Ports
  27195 SIO uses I/O Addresses 1F801050h..1F80105Fh, which seem to be organized similar
  27196 to the Controller/Memory Card registers at 1F801040h..1F80104Fh, though not
  27197 identical, and with an additional register at 1F80105Ch, which has no
  27198 corresponding port at 1F80104Ch.
  27199 SIO_BAUD is <effectively> same as for JOY_BAUD, but, <internally> they are a
  27200 bit different:
  27201   JOY_BAUD is multiplied by Factor, and does then ellapse "2" times per bit.
  27202   SIO_BAUD is NOT multiplied, and, instead, ellapses "2*Factor" times per bit.
  27203 Unlike for the Controller/Memory Card ports, the data is transferred without
  27204 CLK signal, instead, it's using RS232 format, ie. the transfer starts with a
  27205 start bit, and is then transferred at a specific baudrate (which must be
  27206 configured identically at the receiver side). For RS232, data is usually 8bit,
  27207 and may optionally end with a parity bit, and one or two stop bits.
  27208 
  27209 Note
  27210 For SIO Pinouts, PSone SIO upgrading, and for building RS232 adaptors, see:
  27211 --> Pinouts - SIO Pinouts
  27212 Aside from the internal SIO port, the PSX BIOS supports two additional external
  27213 serial ports, connected to the expansion port,
  27214 --> EXP2 Dual Serial Port (for TTY Debug Terminal)
  27215 
  27216 SIO Games
  27217 The serial port is used (for 2-player link) by Wipeout 2097 (that game
  27218 accidently assumes BAUDs based on 64*1024*1025 Hz rather than on 600h*44100
  27219 Hz).
  27220 Ridge Racer Revolution is also said to support 2P link.
  27221 Keitai Eddy seems to allow to connect a mobile phone to the SIO port (the games
  27222 CD cover suggests so; this seems to be something different than the "normal"
  27223 I-Mode adaptor, which would connect to controller port, not to SIO port).
  27224 
  27225 8251A Note
  27226 The Playstation Serial Port is apparently based/inspired on the Intel 8251A
  27227 USART chip; which has very similar 8bit Mode/Command/Status registers.
  27228 
  27229 Expansion Port (PIO)
  27230 --------------------
  27231 
  27232 Expansion Port can contain ROM, RAM, I/O Ports, etc. For ROM, the first 256
  27233 bytes would contain the expansion ROM header.
  27234 
  27235 For region 1, the CPU outputs a chip select signal (CPU Pin 98, /EXP).
  27236 For region 2, the CPU doesn't produce a chip select signal (the region is
  27237 intended to contain multiple I/O ports, which do require an address decoder
  27238 anyways, that address decoder could treat any /RD or /WR with A13=Hi and A23=Hi
  27239 and A22=Lo as access to expansion region 2 (for /WR, A22 may be ignored;
  27240 assuming that the BIOS is read-only).
  27241 
  27242 Size/Bus-Width
  27243 The BIOS initalizes Expansion Region 1 to 512Kbyte with 8bit bus, and Region 2
  27244 to 128 bytes with 8bit bus. However, the size and data bus-width of these
  27245 regions can be changed, see:
  27246 --> Memory Control
  27247 For Region 1, 32bit reads are supported even in 8bit mode (eg. 32bit opcode
  27248 fetches are automatically processed as four 8bit reads).
  27249 For Region 2, only 8bit access seems to be supported (except that probably
  27250 16bit mode allows 16bit access), anyways, larger accesses seem to cause
  27251 exceptions... not sure if that can be disabled...?
  27252 
  27253 Expansion 1 - EXP1 - Intended to contain ROM
  27254 --> EXP1 Expansion ROM Header
  27255 
  27256 Expansion 2 - EXP2 - Intended to contain I/O Ports
  27257 --> EXP2 Dual Serial Port (for TTY Debug Terminal)
  27258 --> EXP2 DTL-H2000 I/O Ports
  27259 --> EXP2 Post Registers
  27260 --> EXP2 Nocash Emulation Expansion
  27261 
  27262 Expansion 3 - EXP3 - Intended to contain RAM
  27263 Not used by BIOS nor by any games. Seems to contain 1Mbyte RAM with 16bit
  27264 databus (ie. 512Kx16) in DTL-H2000.
  27265 
  27266 Other Expansions
  27267 Aside from the above, the Expansion regions can be used for whatever purpose,
  27268 however, mind that the BIOS is reading from the ROM header region, and is
  27269 writing to the POST register (so 1F000000h-1F0000FFh and 1F802041h should be
  27270 used only if the hardware isn't disturbed by those accesses).
  27271 
  27272 Missing Expansion Port
  27273 The expansion port is installed only on older PSX boards, newer PSX boards and
  27274 all PSone boards don't have that port. However, the CPU should still output all
  27275 expansion signals, and there should be big soldering points on the board, so
  27276 it'd be easy to upgrade the console.
  27277 
  27278 Latched Address Bus
  27279 Note that A0..A23 are latched outputs, so they can be used as general purpuse
  27280 24bit outputs, provided that the system bus isn't used for other purposes (such
  27281 like /BIOS, /SPU, /CD accesses) (A0..A23 are not affected by Main RAM and GPU
  27282 addressing, nor by internal I/O ports like Timer and IRQ registers).
  27283 
  27284 EXP1 Expansion ROM Header
  27285 -------------------------
  27286 
  27287 Expansion 1 - ROM Header (accessed with 8bit databus setting)
  27288   Address  Size Content
  27289   1F000000h 4   Post-Boot Entrypoint (eg. 1F000100h and up)
  27290   1F000004h 2Ch Post-Boot ID ("Licensed by Sony Computer Entertainment Inc.")
  27291   1F000030h 50h Post-Boot TTY Message (must contain at least one 00h byte)
  27292   1F000080h 4   Pre-Boot Entrypoint  (eg. 1F000100h and up)
  27293   1F000084h 2Ch Pre-Boot ID  ("Licensed by Sony Computer Entertainment Inc.")
  27294   1F0000B0h 50h Not used     (should be zero, but may contain code/data/io)
  27295   1F000100h ..  Code, Data, I/O Ports, etc.
  27296 The entrypoints are called if their corresonding ID strings are present, return
  27297 address to BIOS is passed in R31, so the expansion ROM may return control to
  27298 BIOS, if that should be desired.
  27299 Aside from verifying the IDs, the BIOS will also display the Post-Boot ID
  27300 string (and the following message string) via TTY (done right before calling
  27301 the Post-Boot Entrypoint).
  27302 
  27303 Pre-Boot Function
  27304 The Pre-Boot function is called almost immediately after Reset, with only some
  27305 Memory Control registers initialized, the BIOS function vectors at A0h, B0h,
  27306 and C0h are NOT yet initialized, so the Pre-Boot function can't use them.
  27307 
  27308 Post-Boot Function
  27309 The Post-Boot function gets called while showing the "PS" logo, but before
  27310 loading the .EXE file. The BIOS function vectors at A0h, B0h, and C0h are
  27311 already installed and can be used by the Post-Boot Function.
  27312 Note that the Post-Boot Function is called ONLY when the "PS" logo is shown
  27313 (ie. not if the CDROM drive is empty, or if it contains an Audio CD).
  27314 
  27315 Mid-Boot Hook
  27316 One common trick to hook the Kernel after BIOS initialization, but before CDROM
  27317 loading is to use the Pre-Boot handler to set a COP0 opcode fetch hardware
  27318 breakpoint at 80030000h (after returning from the Pre-Boot handler, the Kernel
  27319 will initialize important things like A0h/B0h/C0h tables, and will then break
  27320 again when starting the GUI code at 80030000h) (this trick is used by Action
  27321 Replay v2.0 and up).
  27322 
  27323 Note
  27324 Expansion ROMs are most commonly used in cheat devices,
  27325 --> Cheat Devices
  27326 
  27327 EXP2 Dual Serial Port (for TTY Debug Terminal)
  27328 ----------------------------------------------
  27329 
  27330 SCN2681 Dual Asynchronous Receiver/Transmitter (DUART)
  27331 The PSX/PSone retail BIOS contains some TTY Debug Terminal code; using an
  27332 external SCN2681 chip which can be connected to the expansion port.
  27333 Whilst supported by all PSX/PSone retail BIOSes on software side, there aren't
  27334 any known PSX consoles/devboards/expansions actually containing DUARTs on
  27335 hardware side.
  27336 
  27337 1F802023h/Read - RHRA - DUART Rx Holding Register A (FIFO) (R)
  27338 1F80202Bh/Read - RHRB - DUART Rx Holding Register B (FIFO) (R)
  27339 1F802023h/Write - THRA - DUART Tx Holding Register A (W)
  27340 1F80202Bh/Write - THRB - DUART Tx Holding Register B (W)
  27341   7-0  Data (aka Character)
  27342 The hardware can hold max 2 Tx characters per channel (1 in the THR register,
  27343 and one currently processed in the Tx Shift Register), and max 4 Rx characters
  27344 (3 in the RHR FIFO, plus one in the Rx Shift Register) (when receiving a 5th
  27345 character, the "old newest" value in the Rx Shift Register is lost, and the
  27346 overrun flag is set).
  27347 
  27348 1F802020h/FirstAccess - MR1A - DUART Mode Register 1.A (R/W)
  27349 1F802028h/FirstAccess - MR1B - DUART Mode Register 1.B (R/W)
  27350   7    RxRTS Control       (0=No, 1=Yes)
  27351   6    RxINT Select        (0=RxRDY, 1=FFULL)
  27352   5    Error Mode          (0=Char, 1=Block)
  27353   4-3  Parity Mode   (0=With Parity, 1=Force Parity, 2=No Parity, 3=Multidrop)
  27354   2    Parity Type         (0=Even, 1=Odd)
  27355   1-0  Bits per Character  (0=5bit, 1=6bit, 2=7bit, 3=8bit)
  27356 Note: In block error mode, block error conditions must be cleared by using the
  27357 error reset command (command 4) or a receiver reset (command 2).
  27358 
  27359 1F802020h/SecondAccess - MR2A - DUART Mode Register 2.A (R/W)
  27360 1F802028h/SecondAccess - MR2B - DUART Mode Register 2.B (R/W)
  27361   7-6  Channel Mode       (0=Normal, 1=Auto-Echo, 2=Local loop, 3=Remote loop)
  27362   5    TxRTS Control      (0=No, 1=Yes) (when 1 --> OP0=RTSA / OP1=RTSB)
  27363   4    CTS Enable         (0=No, 1=Yes) (when 1 --> IP0=CTSA / IP1=CTSB)
  27364   3-0  Tx Stop Bit Length (00h..0Fh = see below)
  27365 Stop Bit Lengths:
  27366   0=0.563  1=0.625  2=0.688  3=0.750  4=0.813  5=0.875  6=0.938  7=1.000
  27367   8=1.563  9=1.625  A=1.688  B=1.750  C=1.813  D=1.875  E=1.938  F=2.000
  27368 Add 0.5 to values shown for 0..7 if channel is programmed for 5 bits/char.
  27369 
  27370 1F802021h/Write - CSRA - DUART Clock Select Register A (W)
  27371 1F802029h/Write - CSRB - DUART Clock Select Register B (W)
  27372   7-4  Rx Clock Select  (0..0Ch=See Table, 0Dh=Timer, 0Eh=16xIP, 0Fh=1xIP)
  27373   3-0  Tx Clock Select  (0..0Ch=See Table, 0Dh=Timer, 0Eh=16xIP, 0Fh=1xIP)
  27374 The 2681 has some sets of predefined baud rates (set1/set2 selected via ACR.7),
  27375 additionally, in BRG Test Mode, set3/set4 are used instead of set1/set2), the
  27376 baud rates for selections 00h..0Dh are:
  27377   Rate 00h  01h 02h   03h   04h   05h   06h    07h  08h   09h  0Ah   0Bh  0Ch
  27378   Set1 50   110 134.5 200   300   600   1200   1050 2400  4800 7200  9600 38400
  27379   Set2 75   110 134.5 150   300   600   1200   2000 2400  4800 1800  9600 19200
  27380   Set3 4800 880 1076  19200 28800 57600 115200 1050 57600 4800 57600 9600 38400
  27381   Set4 7200 880 1076  14400 28800 57600 115200 2000 57600 4800 14400 9600 19200
  27382 Selection 0Eh/0Fh are using an external clock source (derived from
  27383 IP3,IP4,IP5,IP6 pins; for TxA,RxA,TxB,RxB respectively).
  27384 
  27385 1F802022h/Write - CRA - DUART Command Register A (W)
  27386 1F80202Ah/Write - CRB - DUART Command Register B (W)
  27387   7    Not used    (should be 0)
  27388   6-4  Miscellaneous Commands (0..7 = see below)
  27389   3    Disable Tx  (0=No change, 1=Disable)
  27390   2    Enable Tx   (0=No change, 1=Enable) ;Don't use with Command 3 (Reset Rx)
  27391   1    Disable Rx  (0=No change, 1=Disable)
  27392   0    Enable Rx   (0=No change, 1=Enable) ;Don't use with Command 2 (Reset Tx)
  27393 The command values for CRA (or CRB) are:
  27394   0 No command          ;no effect
  27395   1 Reset MR pointer    ;force "FirstAccess" state for MR1A (or MR1B) access
  27396   2 Reset receiver      ;reset RxA (or RxB) registers, disable Rx, flush Fifo
  27397   3 Reset transmitter   ;reset TxA (or TxB) registers
  27398   4 Reset Error Flags           ;reset SRA.7-4 (or SRB.7-4) to zero
  27399   5 Reset Break-Change IRQ Flag ;reset ISR.2 (or ISR.6) to zero
  27400   6 Start break  ;after current char, pause Tx with TxDA=Low (or TxDB=Low)
  27401   7 Stop break   ;output one High bit, then continue Tx (ie. undo pause)
  27402 Access to the upper four bits of the command register should be separated by 3
  27403 edges of the X1 clock. A disabled transmitter cannot be loaded.
  27404 
  27405 1F802025h/Read - ISR - DUART Interrupt Status Register (R)
  27406 1F802025h/Write - IMR - DUART Interrupt Mask Register (W)
  27407   7    Input Port Change   (0=No, 1=Yes) (Ack via reading IPCR) ;see ACR.3-0
  27408   6    Break Change B      (0=No, 1=Yes) (Ack via CRB/Command5)
  27409   5    RxRDYB/FFULLB       (0=No, 1=Yes) (Ack via reading data) ;see MR1B.6
  27410   4    THRB Empty (TxRDYB) (0=No, 1=Yes) (Ack via writing data) ;same as SRB.2
  27411   3    Counter Ready       (0=No, 1=Yes) (Ack via CT_STOP)
  27412   2    Break Change A      (0=No, 1=Yes) (Ack via CRA/Command5)
  27413   1    RxRDYA/FFULLA       (0=No, 1=Yes) (Ack via reading data) ;see MR1A.6
  27414   0    THRA Empty (TxRDYA) (0=No, 1=Yes) (Ack via writing data) ;same as SRA.2
  27415 
  27416 1F802021h/Read - SRA - DUART Status Register A (R)
  27417 1F802029h/Read - SRB - DUART Status Register B (R)
  27418   7    Rx Received Break*        (0=No, 1=Yes) ;received 00h without stop bit
  27419   6    Rx Framing Error*         (0=No, 1=Yes) ;received data without stop bit
  27420   5    Rx Parity Error*          (0=No, 1=Yes) ;received data with bad parity
  27421   4    Rx Overrun Error          (0=No, 1=Yes) ;Rx FIFO full + RxShiftReg full
  27422   3    Tx Underrun  (TxEMT)      (0=No, 1=Yes) ;both TxShiftReg and THR empty
  27423   2    Tx THR Empty (TxRDY)      (0=No, 1=Yes) ;same as ISR.0 / ISR.4
  27424   1    Rx FIFO Full (FFULL)      (0=No, 1=Yes) ;set upon 3 or more characters
  27425   0    Rx FIFO Not Empty (RxRDY) (0=No, 1=Yes) ;set upon 1 or more characters
  27426 Bit7-5 are appended to the corresponding data character in the receive FIFO. A
  27427 read of the status provides these bits (7:5) from the top of the FIFO together
  27428 with bits (4:0). These bits are cleared by a "reset error status" command. In
  27429 character mode they are discarded when the corresponding data character is read
  27430 from the FIFO. In block error mode, block error conditions must be cleared by
  27431 using the error reset command (command 4x) or a receiver reset.
  27432 
  27433 1F802024h/Write - ACR - DUART Aux. Control Register (W)
  27434   7    Select Baud Rate Generator (BRG) Set   (0=Set1/Set3, 1=Set2/Set4)
  27435   6-4  Counter/Timer Mode and Source          (see below)
  27436   3-0  IP3..IP0 Change Interrupt Enable Flags (0=Off, 1=On)
  27437 Counter/Timer Mode and Clock Source Settings:
  27438   Num  Mode      Clock Source
  27439   0h   Counter   External (IP2)
  27440   1h   Counter   TxCA - 1x clock of Channel A transmitter
  27441   2h   Counter   TxCB - 1x clock of Channel B transmitter
  27442   3h   Counter   Crystal or external clock (x1/CLK) divided by 16
  27443   4h   Timer     External (IP2)
  27444   5h   Timer     External (IP2) divided by 16
  27445   6h   Timer     Crystal or external clock (x1/CLK)
  27446   7h   Timer     Crystal or external clock (x1/CLK) divided by 16
  27447 In Counter Mode, the Counter Ready flag is set on any underflow, and the
  27448 counter wraps to FFFFh and keeps running (but may get stopped by software).
  27449 In Timer Mode, automatic reload occurs on any underflow, the counter flag
  27450 (which can be output to OP3) is toggled on any underflow, but the Counter Ready
  27451 flag is set only on each 2nd underflow (unlike as in Counter mode).
  27452 
  27453 1F802024h/Read - IPCR - DUART Input Port Change Register (R)
  27454   7-4  IP3..IP0 Change Occured Flags (0=No, 1=Yes)    ;auto reset after read
  27455   3-0  Current IP3-IP0 Input states  (0=Low, 1=High)  ;Same as IP.3-0
  27456 Reading from this register automatically resets IPCR.7-4 and ISR.7.
  27457 
  27458 1F80202Dh/Read - IP - DUART Input Port (R)
  27459   7    Not used (always 1)
  27460   6-0  Current IP6-IP0 Input states (0=Low, 1=High)  ;LSBs = Same as IPCR.3-0
  27461 IP0-6 can be used as general purpose inputs, or for following special purposes:
  27462   IP6 External RxB Clock     ;see CSRB.7-4
  27463   IP5 External TxB Clock     ;see CSRB.3-0
  27464   IP4 External RxA Clock     ;see CSRA.7-4
  27465   IP3 External TxA Clock     ;see CSRA.3-0
  27466   IP2 External Timer Input   ;see AUX.6-4
  27467   IP1 Clear to Send B (CTSB) ;see MR2B.5
  27468   IP0 Clear to Send A (CTSA) ;see MR2A.5
  27469 Note: The 24pin chip doesn't have any inputs, the 28pin chip has only one input
  27470 (IP2), the 40pin/44pin chips have seven inputs (IP0-IP6).
  27471 
  27472 1F80202Eh/Write - DUART Set Output Port Bits Command (Set means Out=LOW)
  27473 1F80202Fh/Write - DUART Reset Output Port Bits Command (Reset means Out=HIGH)
  27474   7-0  Change "OPR" OP7-OP0 Output states (0=No change, 1=Set/Reset)
  27475 Note: The 24pin chip doesn't have any outputs, the 28pin chip has only two
  27476 outputs (OP0,OP1), the 40pin/44pin chips have eight outputs (OP0-OP7).
  27477 
  27478 1F80202Dh/Write - OPCR - DUART Output Port Configuration Register (W)
  27479   7    OP7      (0=OPR.7, 1=TxRDYB)
  27480   6    OP6      (0=OPR.6, 1=TxRDYA)
  27481   5    OP5      (0=OPR.5, 1=RxRDY/FFULLB)
  27482   4    OP4      (0=OPR.4, 1=RxRDY/FFULLA)
  27483   3-2  OP3      (0=OPR.3, 1=Clock/Timer Output, 2=TxCB(1x), 3=RxCB(1x))
  27484   1-0  OP2      (0=OPR.2, 1=TxCA(16x), 2=TxCA(1x), 3=RxCA(1x))
  27485 Additionally, the OP0 and OP1 outputs are controlled via MR2A.5 and MR2B.5.
  27486 
  27487 1F802022h/Read - - DUART Toggle Baud Rate Generator Test Mode (Read=Strobe)
  27488 1F80202Ah/Read - - DUART Toggle 1X/16X Test Mode (Read=Strobe)
  27489   7-0  Not used (just issue a dummy-read to toggle the test mode on/off)
  27490 BGR Test switches between Baud Rate Set1/Set2 and Set3/Set4.
  27491 1X/16X Test switches between whatever...?
  27492 
  27493 1F80202Eh/Read - CT_START - DUART Start Counter Command (Read=Strobe)
  27494 1F80202Fh/Read - CT_STOP - DUART Stop Counter Command (Read=Strobe)
  27495   7-0  Not used (just issue a dummy-read to strobe start/stop command)
  27496 Start: Forces reload (copies CTLR/CTUR to CTL/CTU), and starts the timer.
  27497 Stop-in-Counter-Mode: Resets ISR.3, and stops the timer.
  27498 Stop-in-Timer-Mode: Resets ISR.3, but doesn't stop the timer.
  27499 
  27500 1F802026h/Read - CTU - DUART Counter/Timer Current Value, Upper/Bit15-8 (R)
  27501 1F802027h/Read - CTL - DUART Counter/Timer Current Value, Lower/Bit7-0 (R)
  27502 1F802026h/Write - CTUR - DUART Counter/Timer Reload Value, Upper/Bit15-8 (W)
  27503 1F802027h/Write - CTLR - DUART Counter/Timer Reload Value, Lower/Bit7-0 (W)
  27504 The CTLR/CTUR reload value is copied to CTL/CTU upon Start Counter Command. In
  27505 Timer mode (not in Counter mode), it is additionally copied automatically when
  27506 the timer undeflows.
  27507 
  27508 1F80202Ch - N/A - DUART Reserved Register (neither R nor W)
  27509 Reserved.
  27510 
  27511 Chip versions
  27512 The SCN2681 is manufactured with 24..44 pins, the differences are:
  27513   24pin basic cut-down version          ;without IP0-1/OP0-1 = without CTS/RTS
  27514   28pin additional IP2,OP0,OP1,X2       ;without IP0-1 = without CTS
  27515   40pin additional IP0-IP6,OP0-OP7,X2   ;full version
  27516   44pin same as 40pin with four NC pins ;full version (SMD)
  27517 Unknown which of them is supposed to be used with the PSX?
  27518 Note: The Motorola 68681 should be the same as the Philips/Signetics 2681.
  27519 
  27520 Notes
  27521 Unknown if the Interrupt signal is connected to the PSX... there seems to be no
  27522 spare IRQ for it, though it <might> share an IRQ with whatever other
  27523 hardware...?
  27524 The BIOS seems to use only one of the two channels; for the std_io functions:
  27525 --> BIOS TTY Console (std_io)
  27526 Aside from the external DUART, the PSX additionally contains an internal UART,
  27527 --> Serial Port (SIO)
  27528 The DTL-H2000 devboard uses a non-serial "ATCONS" channel for TTY stuff,
  27529 --> EXP2 DTL-H2000 I/O Ports
  27530 
  27531 EXP2 DTL-H2000 I/O Ports
  27532 ------------------------
  27533 
  27534 The DTL-H2000 contains extended 8Mbyte Main RAM (instead of normal 2Mbyte),
  27535 plus additional 1MByte RAM in Expansion Area at 1FA00000h, plus some I/O ports
  27536 at 1F8020xxh:
  27537 
  27538 1F802000h - DTL-H2000: EXP2:  - ATCONS STAT (R)
  27539   0    Unknown, used for something
  27540   1    Unknown/unused
  27541   2    Unknown, used for something
  27542   3    TTY/Atcons TX Ready     (0=Busy, 1=Ready)
  27543   4    TTY/Atcons RX Available (0=None, 1=Yes)
  27544   5-7  Unknown/unused
  27545 
  27546 1F802002h - DTL-H2000: EXP2:  - ATCONS DATA (R and W)
  27547   0-7  TTY/Atcons RX/TX Data
  27548 TTY channel for message output (TX) and debug console keyboard input (RX). The
  27549 DTL-H2000 is using this "ATCONS" stuff instead of the DUART stuff used in
  27550 retail console BIOSes ("CONS" seems to refer to "Console", and "AT" might refer
  27551 to PC/AT or whatever).
  27552 
  27553 1F802004h - DTL-H2000: EXP2:  - 16bit - ?
  27554   0-15 Data...?
  27555 
  27556 1F802030h - DTL-H2000: Secondary IRQ10 Controller (IRQ Flags)
  27557 This register does expand IRQ10 (Lightgun) to more than one IRQ source. The
  27558 register contains only Secondary IRQ Flags (there seem to be no Secondary IRQ
  27559 Enable bits; at least not for Lightguns).
  27560   0     ... used for something
  27561   1    Lightgun IRQ (write: 0=No change, 1=Acknowledge) (read: 0=None, 1=IRQ)
  27562   2-3  Unknown/unused (write: 0=Normal)
  27563   4     ... acknowledged at 1FA00B04h, otherwise unused
  27564   5     ... TTY RX ?
  27565   6-7  Unknown/unused (write: 0=Normal)
  27566   8-31 Not used by DTL-H2000 BIOS (but Lightgun games write 0 to these bits)
  27567 Retail games that support IRQ10-based "Konami" Lightguns are containing code
  27568 for detecting and accessing port 1F802030h. The detection works by examining a
  27569 value in the BIOS ROM like so:
  27570   IF [BFC00104h]=00002000h then Port 1F802030h does exist     (DTL-H2000)
  27571   IF [BFC00104h]=00002500h then Port 1F802030h does NOT exist
  27572   IF [BFC00104h]=00000003h then Port 1F802030h does NOT exist (default)
  27573   IF [BFC00104h]= <other>  then Port 1F802030h does NOT exist
  27574 Normal consoles don't include Port 1F802030h, and IRQ10 is wired directly to
  27575 the controller port, and the value at [BFC00104h] is always 00000003h.
  27576 Accordingly, one cannot upgrade the console just by plugging a Secondary IRQ10
  27577 controller to the expansion port (instead, one would need to insert the
  27578 controller between the CPU and controller plug, and to install a BIOS with
  27579 [BFC00104h]=00002000h).
  27580 The DTL-H2000 BIOS accesses 1F802030h with 8bit load/store opcodes, however,
  27581 the Lightgun games use 32bit load/store - which is theoretically overlapping
  27582 port 1F802032h, though maybe the memory system does ignore the upper bits.
  27583 
  27584 1F802032h - DTL-H2000: EXP2:  - maybe IRQ enable?
  27585   0    Used for something (CLEARED on some occassions)
  27586   1-3  Unknown/unused
  27587   4    Used for something (SET on some occassions)
  27588   5-7  Unknown/unused
  27589 
  27590 1F802040h - DTL-H2000: EXP2: 1-byte - DIP Switch?
  27591   0-7  DIP Value (00h..FFh, but should be usually 00h..02h)
  27592 This register selects the DTL-H2000 boot mode, for whatever reason it's called
  27593 "DIP Switch" register, although the DTL-H2000 boards don't seem to contain any
  27594 such DIP Switches (instead, it's probably configured via some I/O ports on PC
  27595 side). Possible values are:
  27596   DIP=0 --> .. long delay before TTY?   with "PSX>" prompt, throws CDROM cmds
  27597   DIP=1 --> .. long delay before TTY?   no "PSX>" prompt           PSY-Q?
  27598   DIP=2 --> .. instant TTY?             with "PSX>" prompt
  27599   DIP=3 --> Lockup
  27600   DIP=04h..FFh --> Lockup with POST=04h..FFh
  27601 
  27602 1F802042h - DTL-H2000: EXP2: POST/LED (R/W)
  27603 --> EXP2 Post Registers
  27604 
  27605 EXP2 Post Registers
  27606 -------------------
  27607 
  27608 1F802041h - POST - External 7-segment Display (W)
  27609   0-3  Current Boot Status (00h..0Fh)
  27610   4-7  Not used by BIOS    (always set to 0)
  27611 During boot, the BIOS writes incrementing values to this register, allowing to
  27612 display the current boot status on an external 7 segment display (much the same
  27613 as Port 80h used in PC BIOSes).
  27614 
  27615 1F802042h - DTL-H2000: EXP2: POST/LED (R/W)
  27616   0-7 Post/LED value
  27617 8bit wide, otherwise same as POST 1F802041h on retail consoles.
  27618 
  27619 1F802070h - POST2 - Unknown? (W) - PS2
  27620 Might be a configuration port, or it's another POST register (which is used
  27621 prior to writing the normal POST bytes to 1FA00000h).
  27622 The first write to 1F802070h is 32bit, all further writes seem to be 8bit.
  27623 
  27624 1FA00000h - POST3 - External 7-segment Display (W) - PS2
  27625 Similar to POST, but PS2 BIOS uses this address.
  27626 
  27627 EXP2 Nocash Emulation Expansion
  27628 -------------------------------
  27629 
  27630 1F802060h Emu-Expansion ID1 "E" (R)
  27631 1F802061h Emu-Expansion ID2 "X" (R)
  27632 1F802062h Emu-Expansion ID3 "P" (R)
  27633 1F802063h Emu-Expansion Version (01h) (R)
  27634 Contains ID and Version.
  27635 
  27636 1F802064h Emu-Expansion Enable1 "O" (R/W)
  27637 1F802065h Emu-Expansion Enable2 "N" (R/W)
  27638 Activates the Halt and Turbo Registers (when set to "ON").
  27639 
  27640 1F802066h Emu-Expansion Halt (R)
  27641 When enabled (see above), doing an 8bit read from this address stops the CPU
  27642 emulation unless/until an Interrupt occurs (when "CAUSE AND SR AND FF00h"
  27643 becomes nonzero). Can be used to reduce power consumption, and to make the
  27644 emulation faster.
  27645 
  27646 1F802067h Emu-Expansion Turbo Mode Flags (R/W)
  27647 When enabled (see above), writing to this register activates/deactivates
  27648 "turbo" mode, which is causing new data to arrive immediately after
  27649 acknowledging the previous interrupt.
  27650   0   CDROM Turbo       (0=Normal, 1=Turbo)
  27651   1   Memory Card Turbo (0=Normal, 1=Turbo)
  27652   2   Controller Turbo  (0=Normal, 1=Turbo)
  27653   3-7 Reserved (must be zero)
  27654 
  27655 Memory Control
  27656 --------------
  27657 
  27658 The Memory Control registers are initialized by the BIOS, and, normally
  27659 software doesn't need to change that settings. Some registers are useful for
  27660 expansion hardware (allowing to increase the memory size and bus width).
  27661 
  27662 1F801000h - Expansion 1 Base Address (usually 1F000000h)
  27663 1F801004h - Expansion 2 Base Address (usually 1F802000h)
  27664   0-23   Base Address   (Read/Write)
  27665   24-31  Fixed          (Read only, always 1Fh)
  27666 For Exansion 1, the address is forcefully aligned to the selected expansion
  27667 size (see below), ie. if the size is bigger than 1 byte, then the lower bit(s)
  27668 of the base address are ignored.
  27669 For Expansion 2, trying to use ANY other value than 1F802000h seems to disable
  27670 the Expansion 2 region, rather than mapping it to the specified address (ie.
  27671 Port 1F801004h doesn't seem to work).
  27672 For Expansion 3, the address seems to be fixed (1FA00000h).
  27673 
  27674 1F801008h - Expansion 1 Delay/Size (usually 0013243Fh) (512Kbytes, 8bit bus)
  27675 1F80100Ch - Expansion 3 Delay/Size (usually 00003022h) (1 byte)
  27676 1F801010h - BIOS ROM Delay/Size (usually 0013243Fh) (512Kbytes, 8bit bus)
  27677 1F801014h - SPU Delay/Size (200931E1h) (use 220931E1h for SPU-RAM reads)
  27678 1F801018h - CDROM Delay/Size (00020843h or 00020943h)
  27679 1F80101Ch - Expansion 2 Delay/Size (usually 00070777h) (128 bytes, 8bit bus)
  27680   0-3   Unknown (R/W)
  27681   4-7   Access Time        (00h..0Fh=00h..0Fh Cycles)
  27682   8     Use COM0 Time      (0=No, 1=Yes, add to Access Time)
  27683   9     Use COM1 Time      (0=No, 1=Probably Yes, but has no effect?)
  27684   10    Use COM2 Time      (0=No, 1=Yes, add to Access Time)
  27685   11    Use COM3 Time      (0=No, 1=Yes, clip to MIN=(COM3+6) or so?)
  27686   12    Data Bus-width     (0=8bit, 1=16bit)
  27687   13-15 Unknown (R/W)
  27688   16-20 Memory Window Size (1 SHL N bytes) (0..1Fh = 1 byte ... 2 gigabytes)
  27689   21-23 Unknown (always zero)
  27690   24-27 Unknown (R/W) ;must be non-zero for SPU-RAM reads
  27691   28    Unknown (always zero)
  27692   29    Unknown (R/W)
  27693   30    Unknown (always zero)
  27694   31    Unknown (R/W) (Port 1F801008h only; always zero for other ports)
  27695 Trying to access addresses that exceed the selected size causes an exception.
  27696 Maximum size would be Expansion 1 = 17h (8MB), BIOS = 16h (4MB), Expansion 2 =
  27697 0Dh (8KB), Expansion 3 = 15h (2MB). Trying to select larger sizes would overlap
  27698 the internal I/O ports, and crash the PSX. The Size bits seem to be ignored for
  27699 SPU/CDROM. The SPU timings seem to be applied for both the 200h-byte SPU region
  27700 at 1F801C00h and for the 200h-byte unknown region at 1F801E00h.
  27701 
  27702 1F801020h - COM_DELAY / COMMON_DELAY (00031125h or 0000132Ch or 00001325h)
  27703   0-3   COM0 - Offset A   ;used for SPU/EXP2 (and for adjusted CDROM timings)
  27704   4-7   COM1 - No effect? ;used for EXP2
  27705   8-11  COM2 - Offset B   ;used for BIOS/EXP1/EXP2
  27706   12-15 COM3 - Min Value  ;used for CDROM
  27707   16-17 COM? - Unknown    ;used for whatever
  27708   18-31 Unknown/unused (read: always 0000h)
  27709 This register contains clock cycle offsets that can be added to the Access Time
  27710 values in Port 1F801008h..1Ch. Works (somehow) like so:
  27711   1ST=0, SEQ=0, MIN=0
  27712   IF Use_COM0 THEN 1ST=1ST+COM0-1, SEQ=SEQ+COM0-1
  27713   IF Use_COM2 THEN 1ST=1ST+COM2,   SEQ=SEQ+COM2
  27714   IF Use_COM3 THEN MIN=COM3
  27715   IF 1ST<6 THEN 1ST=1ST+1   ;(somewhat like so)
  27716   1ST=1ST+AccessTime+2, SEQ=SEQ+AccessTime+2
  27717   IF 1ST<(MIN+6) THEN 1ST=(MIN+6)
  27718   IF SEQ<(MIN+2) THEN SEQ=(MIN+2)
  27719 The total access time is the sum of First Access, plus any Sequential
  27720 Access(es), eg. for a 32bit access with 8bit bus: Total=1ST+SEQ+SEQ+SEQ.
  27721 If the access is done from code in (uncached) RAM, then 0..4 cycles are added
  27722 to the Total value (the exact number seems to vary depending on the used COMx
  27723 values or so).
  27724 And the purpose... probably allows to define the length of the chipselect
  27725 signals, and of gaps between that signals...?
  27726 
  27727 1F801060h - RAM_SIZE (R/W) (usually 00000B88h) (or 00000888h)
  27728   0-2   Unknown (no effect)
  27729   3     Crashes when zero (except PU-7 and EARLY-PU-8, which <do> use bit3=0)
  27730   4-6   Unknown (no effect)
  27731   7     Delay on simultaneous CODE+DATA fetch from RAM (0=None, 1=One Cycle)
  27732   8     Unknown (no effect) (should be set for 8MB, cleared for 2MB)
  27733   9-11  Define 8MB Memory Window (first 8MB of KUSEG,KSEG0,KSEG1)
  27734   12-15 Unknown (no effect)
  27735   16-31 Unknown (Garbage)
  27736 Possible values for Bit9-11 are:
  27737   0 = 1MB Memory + 7MB Locked
  27738   1 = 4MB Memory + 4MB Locked
  27739   2 = 1MB Memory + 1MB HighZ + 6MB Locked
  27740   3 = 4MB Memory + 4MB HighZ
  27741   4 = 2MB Memory + 6MB Locked              ;<--- would be correct for PSX
  27742   5 = 8MB Memory                           ;<--- default by BIOS init
  27743   6 = 2MB Memory + 2MB HighZ + 4MB Locked     ;<-- HighZ = Second /RAS
  27744   7 = 8MB Memory
  27745 The BIOS initializes this to setting 5 (8MB) (ie. the 2MB RAM repated 4 times),
  27746 although the "correct" would be setting 4 (2MB, plus other 6MB Locked). The
  27747 remaining memory, after the first 8MB, and up to the Expansion/IO/BIOS region
  27748 seems to be always Locked.
  27749 The HighZ regions are FFh-filled, that even when grounding data lines on the
  27750 system bus (ie. it is NOT a mirror of the PIO expansion region).
  27751 Locked means that the CPU generates an exception when accessing that area.
  27752 Note: Wipeout uses a BIOS function that changes RAM_SIZE to 00000888h (ie. with
  27753 corrected size of 2MB, and with the unknown Bit8 cleared). Gundam Battle
  27754 Assault 2 does actually use the "8MB" space (with stacktop in mirrored RAM at
  27755 807FFFxxh).
  27756 Clearing bit7 causes many games to hang during CDROM loading on both EARLY-PU-8
  27757 and LATE-PU-8 (but works on PU-18 through PM-41).
  27758 
  27759 FFFE0130h Cache Control (R/W)
  27760   0-2   Unknown (Read/Write)                                            (R/W)
  27761   3     Scratchpad Enable 1 (0=Disable, 1=Enable when Bit7 is set, too) (R/W)
  27762   4-5   Unknown (Read/Write)                                            (R/W)
  27763   6     Unknown (read=always zero)                  (R) or (W) or unused..?
  27764   7     Scratchpad Enable 2 (0=Disable, 1=Enable when Bit3 is set, too) (R/W)
  27765   8     Unknown                                                         (R/W)
  27766   9     Crash (0=Normal, 1=Crash if code-cache enabled)                 (R/W)
  27767   10    Unknown (read=always zero)                  (R) or (W) or unused..?
  27768   11    Code-Cache Enable (0=Disable, 1=Enable)                         (R/W)
  27769   12-31 Unknown                                                         (R/W)
  27770 Used by BIOS to initialize cache (in combination with COP0), like so:
  27771  Init Cache Step 1:
  27772   [FFFE0130h]=00000804h, then set cop0_sr=00010000h, then
  27773   zerofill each FOURTH word at [0000..0FFFh], then set cop0_sr=zero.
  27774  Init Cache Step 2:
  27775   [FFFE0130h]=00000800h, then set cop0_sr=00010000h, then
  27776   zerofill ALL words at [0000h..0FFFh], then set cop0_sr=zero.
  27777  Finish Initialization:
  27778   read 8 times 32bit from [A0000000h], then set [FFFE0130h]=0001E988h
  27779 Note: FFFE0130h is described in LSI's "L64360" datasheet, chapter 14 (and
  27780 probably also in their LR33300/LR33310 datasheet, if it were available in
  27781 internet).
  27782 
  27783 Unpredictable Things
  27784 --------------------
  27785 
  27786 Normally, I/O ports should be accessed only at their corresponding size (ie.
  27787 16bit read/write for 16bit ports), and of course, only existing memory and I/O
  27788 addresses should be used. When not recursing that rules, some more or less
  27789 (un-)predictable things may happen...
  27790 
  27791 I/O Write Datasize
  27792   Address               Content         W.8bit  W.16bit W.32bit
  27793   00000000h-00xFFFFFh   Main RAM        OK      OK      OK
  27794   1F800000h-1F8003FFh   Scratchpad      OK      OK      OK
  27795   1F801000h-1F801023h   MEMCTRL         (w32)   (w32)   OK
  27796   1F80104xh             JOY_xxx         (w16)   OK      CROP
  27797   1F80105xh             SIO_xxx         (w16)   OK      CROP
  27798   1F801060h-1F801063h   RAM_SIZE        (w32)   (w32)   OK        (with crash)
  27799   1F801070h-1F801077h   IRQCTRL         (w32)   (w32)   OK
  27800   1F8010x0h-1F8010x3h   DMAx.ADDR       (w32)   (w32)   OK
  27801   1F8010x4h-1F8010x7h   DMAx.LEN        OK      OK      OK
  27802   1F8010x8h-1F8010xFh   DMAx.CTRL/MIRR  (w32)   (w32)   OK
  27803   1F8010F0h-1F8010F7h   DMA.DPCR/DICR   (w32)   (w32)   OK
  27804   1F8010F8h-1F8010FFh   DMA.unknown     IGNORE  IGNORE  IGNORE
  27805   1F801100h-1F80110Bh   Timer 0         (w32)   (w32)   OK
  27806   1F801110h-1F80111Bh   Timer 1         (w32)   (w32)   OK
  27807   1F801120h-1F80112Bh   Timer 2         (w32)   (w32)   OK
  27808   1F801800h-1F801803h   CDROM           OK      ?       ?
  27809   1F801810h-1F801813h   GPU.GP0         ?       ?       OK
  27810   1F801814h-1F801817h   GPU.GP1         ?       ?       OK
  27811   1F801820h-1F801823h   MDEC.CMD/DTA    ?       ?       OK
  27812   1F801824h-1F801827h   MDEC.CTRL       ?       ?       OK
  27813   1F801C00h-1F801E7Fh   SPU             (i16)   OK      OK
  27814   1F801E80h-1F801FFFh   SPU.UNUSED      IGNORE  IGNORE  IGNORE
  27815   1F802020h-1F80202Fh   DUART           OK      ?       ?
  27816   1F802041h             POST            OK      ?       ?
  27817   FFFE0130h-FFFE0133h   CACHE.CTRL      (i32)   (i32)   OK
  27818 Whereas,
  27819   OK    works
  27820   (w32) write full 32bits (left-shifted if address isn't word-aligned)
  27821   (w16) write full 16bits (left-shifted if address isn't halfword-aligned)
  27822   (i32) write full 32bits (ignored if address isn't word-aligned)
  27823   (i16) write full 16bits (ignored if address isn't halfword-aligned)
  27824   CROP  write only lower 16bit (and leave upper 16bit unchanged)
  27825 It's somewhat "legit" to use 16bit writes on 16bit registers like RAM_SIZE,
  27826 I_STAT, I_MASK, and Timer 0-2.
  27827 Non-4-byte aligned 8bit/16bit writes to RAM_SIZE do crash (probably because the
  27828 "(w32)" effect is left-shifting the value, so lower 8bit become zero).
  27829 Results on unaligned I/O port writes (via SWL/SWR opcodes) are unknown.
  27830 
  27831 I/O Read Datasize
  27832 In most cases, I/O ports can be read in 8bit, 16bit, or 32bit units, regardless
  27833 of their size, among others allowing to read two 16bit ports at once with a
  27834 single 32bit read. If there's only one 16bit port within a 32bit region, then
  27835 32bit reads often return garbage in the unused 16bits. Also, 8bit or 16bit VRAM
  27836 data reads via GPUREAD probably won't work? Expansion 2 Region can be accessed
  27837 only via 8bit reads, and 16bit/32bit reads seem to cause exceptions (or rather:
  27838 no such exception!) (except, probably 16bit reads are allowed when the region
  27839 is configured to 16bit databus width).
  27840 There are at least some special cases:
  27841   FFFE0130h-FFFE0133h  8bit (+16bit?) read works ONLY from word-aligned address
  27842 
  27843 Cache Problems
  27844 The functionality of the Cache is still widely unknown. Not sure if DMA
  27845 transfers are updating or invalidating cache. Cached Data within KSEG0 should
  27846 be automatically also cached at the corresponding mirrored address in KUSEG and
  27847 vice versa. Mirrors within KSEG1 (or within KUSEG) may be a different thing,
  27848 eg. when using addresses spead across the first 8MB region to access the 2MB
  27849 RAM. Same problems may occor for Expansion and BIOS mirrors, although, not sure
  27850 if that regions are cached.
  27851 
  27852 Writebuffer Problems
  27853 The writebuffer seems to be disabled for the normal I/O area at 1F801000h,
  27854 however, it appears to be enabled for the Expansion I/O region at 1F802000h
  27855 (after writing to 1F802041h, the BIOS issues 4 dummy writes to RAM, apparently
  27856 (?) in order to flush the writebuffer). The same might apply for Expansion
  27857 Memory region at 1F000000h, although usually that region would contain ROM, so
  27858 it'd be don't care whether it is write-buffered or not.
  27859 
  27860 CPU Load/Store Problems
  27861 XXcpuREG ---> applies ONLY to LOAD (not to store)
  27862 Memory read/write opcodes take a 1-cycle delay until the data arrives at the
  27863 destination, ie. the next opcode should not use the destination register (or
  27864 more unlikely, the destination memory location) as source operand. Usually,
  27865 when trying to do so, the second opcode would receive the OLD value - however,
  27866 if an exception occurs between the two opcodes, then the read/write operation
  27867 may finish, and the second opcode would probably receive the NEW value.
  27868 
  27869 CPU Register Problems - R1 (AT), R26 (K0), R29 (SP)
  27870 Exception handlers cannot preserve all registers, before returning, they must
  27871 load the return address into a general purpose register (conventionally R26 aka
  27872 K0), so be careful not to use that register, unless you are 100% sure that no
  27873 interrupts and no other exceptions can occur. Some exception handlers might
  27874 also destroy R27 aka K1 (though execption handler in the PSX Kernel leaves that
  27875 register unchanged).
  27876 Some assemblers (not a22i in nocash syntax mode) are internally using R1 aka AT
  27877 as scratch register for some pseudo opcodes, including for a "sw rx,imm32"
  27878 pseudo opcode (which is nearly impossible to separate from the normal "sw
  27879 rx,imm16" opcode), be careful not to use R1, unless you can trust your
  27880 assembler not to destroy that register behind your back.
  27881 The PSX Kernel uses "Full-Decrementing-Wasted-Stack", where "Wasted" means that
  27882 when calling a sub-function with N parameters, then the caller must
  27883 pre-allocate N works on stack, and the sub-function may freely use and destroy
  27884 these words; at [SP+0..N*4-1].
  27885 
  27886 Locked Locations in Memory and I/O Area
  27887   00800000h           ;-when Main RAM configured to end at 7FFFFFh
  27888   1F080000h 780000h   ;-when Expansion 1 configured to end at 7FFFFh
  27889   1F800400h C00h      ;-region after Scratchpad
  27890   1F801024h 1Ch       ;\
  27891   1F801064h 0Ch       ;
  27892   1F801078h 08h       ;
  27893   1F801140h 6C0h      ; gaps in I/O region
  27894   1F801804h 0Ch       ;
  27895   1F801818h 08h       ;
  27896   1F801828h 3D8h      ;/
  27897   1F802080h 3FDF80h   ;-when Expansion 2 configured to end at 7Fh
  27898   1FC80000h 60380000h ;-when BIOS ROM configured to end at 7FFFFh
  27899   C0000000h 1FFE0000h ;\
  27900   FFFE0020h E0h       ; gaps in KSEG2 (cache control region)
  27901   FFFE0140h 1FEC0h    ;/
  27902 Trying to access these locations generates an exception. For KSEG0 and KSEG1,
  27903 locked regions are same as for first 512MB of KUSEG.
  27904 
  27905 Mirrors in I/O Area
  27906   1F80108Ch+N*10h - D#_CHCR Mirrors - (N=0..6, for DMA channel 0..6)
  27907 Read/writeable mirrors of DMA Control registers at 1F801088h+N*10h.
  27908 
  27909 Garbage Locations in I/O Area
  27910   1F801062h (2 bytes)  ;\
  27911   1F801072h (2 bytes)  ; unused addresses in Memory and Interrupt Control area
  27912   1F801076h (2 bytes)  ;/
  27913   1F801102h (2 bytes)  ;\
  27914   1F801106h (2 bytes)  ; unused addresses in Timer 0 area
  27915   1F80110Ah (6 bytes)  ;/
  27916   1F801112h (2 bytes)  ;\
  27917   1F801116h (2 bytes)  ; unused addresses in Timer 1 area
  27918   1F80111Ah (6 bytes)  ;/
  27919   1F801122h (2 bytes)  ;\
  27920   1F801126h (2 bytes)  ; unused addresses in Timer 2 area and next some bytes
  27921   1F80112Ah (6 bytes)  ;
  27922   1F801130h (16 bytes) ;/
  27923   1F801820h (4 bytes)  ;-read MDEC Data-Out port (if there is no data)
  27924   FFFE0000h (32 bytes) ;\
  27925   FFFE0100h (48 bytes) ; unused addresses in Cache control area
  27926   FFFE0132h (2 bytes)  ; (including write-only upper 16bit of Port FFFE0130h)
  27927   FFFE0134h (12 bytes) ;/
  27928 Unlike all other unused I/O addresses, these addresses are unlocked (ie. they
  27929 do not trigger exceptions on access), however they do not seem to contain
  27930 anything useful. The BIOS never seems to use them. Writing any values to them
  27931 seems to have no effect. And reading acts somewhat unstable:
  27932 Usually returns zeros in most cases. Except that, the first byte on a 10h-byte
  27933 boundary often returns the lower 8bit of the memory address (eg.
  27934 [FFFE0010h]=10h). And, if Code-Cache is disabled via [FFFE0130h].Bit11=0, then
  27935 reading from these registers does return the 32bit opcode that is to be
  27936 executed next (or at some locations, the opcode thereafter).
  27937 Note: Gran Turismo 2 (MagDemo27: GT2\*) reads 16bit from 1F801130h for
  27938 generating a random seed (the game seems to think that there are four (not
  27939 three) hardware timers at 1F8011x0h).
  27940 
  27941 PSX as Abbreviation for Playstation 1
  27942 In gaming and programming scene, "PSX" is most commonly used as abbreviation
  27943 for the original Playstation series (occasionally including PSone). Sony has
  27944 never officially used that abbreviation, however, the Playstation BIOS contains
  27945 the ASCII strings "PSX" and "PS-X" here and there. The letters "PS" are widely
  27946 believed to stand for PlayStation, and the meaning of the "X" is totally
  27947 unknown (although, actually it may stand for POSIX.1, see below).
  27948 
  27949 PSX as Abbreviation for POSIX.1
  27950 According to JMI Software Systems, "PSX" is a trademark of themselves, and
  27951 stands for "single-user, single-group, subset of POSIX.1" (POSIX stands for
  27952 something commonly used by HLL programmers under UNIX or so). That "PSX" kernel
  27953 from JMI is available for various processors, including MIPS processors, and
  27954 like the playstation, it does include functions like "atoi", and does support
  27955 TTY access via Signetics 2681 DUART chips. The DTL-H2000 does also have
  27956 POSIX-style "PSX>" prompt. So, altogether, it's quite possible that Sony has
  27957 licensed the kernel from JMI.
  27958 
  27959 PSX as Abbreviation for an Extended Playstation 2
  27960 As everybody agrees, PSX should be used only as abbreviation for Playstation 1,
  27961 and nobody should never ever use it for the Playstation 2. Well, nobody, except
  27962 Sony... despite of the common use as abbreviation for Playstation 1 (and
  27963 despite of the JMI trademark)... in 2003, Sony has have released a "Playstation
  27964 2 with built-in HDD/DVD Videorecorder" and called that thing "PSX" for the best
  27965 of confusion.
  27966 
  27967 CPU Specifications
  27968 ------------------
  27969 
  27970 CPU
  27971 --> CPU Registers
  27972 --> CPU Opcode Encoding
  27973 --> CPU Load/Store Opcodes
  27974 --> CPU ALU Opcodes
  27975 --> CPU Jump Opcodes
  27976 --> CPU Coprocessor Opcodes
  27977 --> CPU Pseudo Opcodes
  27978 
  27979 System Control Coprocessor (COP0)
  27980 --> COP0 - Register Summary
  27981 --> COP0 - Exception Handling
  27982 --> COP0 - Misc
  27983 --> COP0 - Debug Registers
  27984 
  27985 CPU Registers
  27986 -------------
  27987 
  27988 All registers are 32bit wide.
  27989   Name       Alias    Common Usage
  27990   (R0)       zero     Constant (always 0) (this one isn't a real register)
  27991   R1         at       Assembler temporary (destroyed by some pseudo opcodes!)
  27992   R2-R3      v0-v1    Subroutine return values, may be changed by subroutines
  27993   R4-R7      a0-a3    Subroutine arguments, may be changed by subroutines
  27994   R8-R15     t0-t7    Temporaries, may be changed by subroutines
  27995   R16-R23    s0-s7    Static variables, must be saved by subs
  27996   R24-R25    t8-t9    Temporaries, may be changed by subroutines
  27997   R26-R27    k0-k1    Reserved for kernel (destroyed by some IRQ handlers!)
  27998   R28        gp       Global pointer (rarely used)
  27999   R29        sp       Stack pointer
  28000   R30        fp(s8)   Frame Pointer, or 9th Static variable, must be saved
  28001   R31        ra       Return address (used so by JAL,BLTZAL,BGEZAL opcodes)
  28002   -          pc       Program counter
  28003   -          hi,lo    Multiply/divide results, may be changed by subroutines
  28004 R0 is always zero.
  28005 R31 can be used as general purpose register, however, some opcodes are using it
  28006 to store the return address: JAL, BLTZAL, BGEZAL. (Note: JALR can optionally
  28007 store the return address in R31, or in R1..R30. Exceptions store the return
  28008 address in cop0r14 - EPC).
  28009 
  28010 R29 (SP) - Full Decrementing Wasted Stack Pointer
  28011 The CPU doesn't explicitly have stack-related registers or opcodes, however,
  28012 conventionally, R29 is used as stack pointer (SP). The stack can be accessed
  28013 with normal load/store opcodes, which do not automatically increase/decrease
  28014 SP, so the SP register must be manually modified to (de-)allocate data.
  28015 The PSX BIOS is using "Full Decrementing Wasted Stack".
  28016 Decrementing means that SP gets decremented when allocating data (that's common
  28017 for most CPUs) - Full means that SP points to the first ALLOCATED word on the
  28018 stack, so the allocated memory is at SP+0 and above, free memory at SP-1 and
  28019 below, Wasted means that when calling a sub-function with N parameters, then
  28020 the caller must pre-allocate N works on stack, and the sub-function may freely
  28021 use and destroy these words; at [SP+0..N*4-1].
  28022 
  28023 For example, "push ra,r16,r17" would be implemented as:
  28024   sub  sp,20h
  28025   mov  [sp+14h],ra
  28026   mov  [sp+18h],r16
  28027   mov  [sp+1Ch],r17
  28028 where the allocated 20h bytes have the following purpose:
  28029   [sp+00h..0Fh]  wasted stack (may, or may not, be used by sub-functions)
  28030   [sp+10h..13h]  8-byte alignment padding (not used)
  28031   [sp+14h..1Fh]  pushed registers
  28032 
  28033 
  28034 CPU Opcode Encoding
  28035 -------------------
  28036 
  28037 Primary opcode field (Bit 26..31)
  28038   00h=SPECIAL 08h=ADDI  10h=COP0 18h=N/A   20h=LB   28h=SB   30h=LWC0 38h=SWC0
  28039   01h=BcondZ  09h=ADDIU 11h=COP1 19h=N/A   21h=LH   29h=SH   31h=LWC1 39h=SWC1
  28040   02h=J       0Ah=SLTI  12h=COP2 1Ah=N/A   22h=LWL  2Ah=SWL  32h=LWC2 3Ah=SWC2
  28041   03h=JAL     0Bh=SLTIU 13h=COP3 1Bh=N/A   23h=LW   2Bh=SW   33h=LWC3 3Bh=SWC3
  28042   04h=BEQ     0Ch=ANDI  14h=N/A  1Ch=N/A   24h=LBU  2Ch=N/A  34h=N/A  3Ch=N/A
  28043   05h=BNE     0Dh=ORI   15h=N/A  1Dh=N/A   25h=LHU  2Dh=N/A  35h=N/A  3Dh=N/A
  28044   06h=BLEZ    0Eh=XORI  16h=N/A  1Eh=N/A   26h=LWR  2Eh=SWR  36h=N/A  3Eh=N/A
  28045   07h=BGTZ    0Fh=LUI   17h=N/A  1Fh=N/A   27h=N/A  2Fh=N/A  37h=N/A  3Fh=N/A
  28046 
  28047 Secondary opcode field (Bit 0..5) (when Primary opcode = 00h)
  28048   00h=SLL   08h=JR      10h=MFHI 18h=MULT  20h=ADD  28h=N/A  30h=N/A  38h=N/A
  28049   01h=N/A   09h=JALR    11h=MTHI 19h=MULTU 21h=ADDU 29h=N/A  31h=N/A  39h=N/A
  28050   02h=SRL   0Ah=N/A     12h=MFLO 1Ah=DIV   22h=SUB  2Ah=SLT  32h=N/A  3Ah=N/A
  28051   03h=SRA   0Bh=N/A     13h=MTLO 1Bh=DIVU  23h=SUBU 2Bh=SLTU 33h=N/A  3Bh=N/A
  28052   04h=SLLV  0Ch=SYSCALL 14h=N/A  1Ch=N/A   24h=AND  2Ch=N/A  34h=N/A  3Ch=N/A
  28053   05h=N/A   0Dh=BREAK   15h=N/A  1Dh=N/A   25h=OR   2Dh=N/A  35h=N/A  3Dh=N/A
  28054   06h=SRLV  0Eh=N/A     16h=N/A  1Eh=N/A   26h=XOR  2Eh=N/A  36h=N/A  3Eh=N/A
  28055   07h=SRAV  0Fh=N/A     17h=N/A  1Fh=N/A   27h=NOR  2Fh=N/A  37h=N/A  3Fh=N/A
  28056 
  28057 Opcode/Parameter Encoding
  28058   31..26 |25..21|20..16|15..11|10..6 |  5..0  |
  28059    6bit  | 5bit | 5bit | 5bit | 5bit |  6bit  |
  28060   -------+------+------+------+------+--------+------------
  28061   000000 | N/A  | rt   | rd   | imm5 | 0000xx | shift-imm
  28062   000000 | rs   | rt   | rd   | N/A  | 0001xx | shift-reg
  28063   000000 | rs   | N/A  | N/A  | N/A  | 001000 | jr
  28064   000000 | rs   | N/A  | rd   | N/A  | 001001 | jalr
  28065   000000 | <-----comment20bit------> | 00110x | sys/brk
  28066   000000 | N/A  | N/A  | rd   | N/A  | 0100x0 | mfhi/mflo
  28067   000000 | rs   | N/A  | N/A  | N/A  | 0100x1 | mthi/mtlo
  28068   000000 | rs   | rt   | N/A  | N/A  | 0110xx | mul/div
  28069   000000 | rs   | rt   | rd   | N/A  | 10xxxx | alu-reg
  28070   000001 | rs   | 00000| <--immediate16bit--> | bltz
  28071   000001 | rs   | 00001| <--immediate16bit--> | bgez
  28072   000001 | rs   | 10000| <--immediate16bit--> | bltzal
  28073   000001 | rs   | 10001| <--immediate16bit--> | bgezal
  28074   00001x | <---------immediate26bit---------> | j/jal
  28075   00010x | rs   | rt   | <--immediate16bit--> | beq/bne
  28076   00011x | rs   | N/A  | <--immediate16bit--> | blez/bgtz
  28077   001xxx | rs   | rt   | <--immediate16bit--> | alu-imm
  28078   001111 | N/A  | rt   | <--immediate16bit--> | lui-imm
  28079   100xxx | rs   | rt   | <--immediate16bit--> | load rt,[rs+imm]
  28080   101xxx | rs   | rt   | <--immediate16bit--> | store rt,[rs+imm]
  28081   x1xxxx | <------coprocessor specific------> | coprocessor (see below)
  28082 
  28083 Coprocessor Opcode/Parameter Encoding
  28084   31..26 |25..21|20..16|15..11|10..6 |  5..0  |
  28085    6bit  | 5bit | 5bit | 5bit | 5bit |  6bit  |
  28086   -------+------+------+------+------+--------+------------
  28087   0100nn |0|0000| rt   | rd   | N/A  | 000000 | MFCn rt,rd_dat  ;rt = dat
  28088   0100nn |0|0010| rt   | rd   | N/A  | 000000 | CFCn rt,rd_cnt  ;rt = cnt
  28089   0100nn |0|0100| rt   | rd   | N/A  | 000000 | MTCn rt,rd_dat  ;dat = rt
  28090   0100nn |0|0110| rt   | rd   | N/A  | 000000 | CTCn rt,rd_cnt  ;cnt = rt
  28091   0100nn |0|1000|00000 | <--immediate16bit--> | BCnF target ;jump if false
  28092   0100nn |0|1000|00001 | <--immediate16bit--> | BCnT target ;jump if true
  28093   0100nn |1| <--------immediate25bit--------> | COPn imm25
  28094   010000 |1|0000| N/A  | N/A  | N/A  | 000001 | COP0 01h  ;=TLBR
  28095   010000 |1|0000| N/A  | N/A  | N/A  | 000010 | COP0 02h  ;=TLBWI
  28096   010000 |1|0000| N/A  | N/A  | N/A  | 000110 | COP0 06h  ;=TLBWR
  28097   010000 |1|0000| N/A  | N/A  | N/A  | 001000 | COP0 08h  ;=TLBP
  28098   010000 |1|0000| N/A  | N/A  | N/A  | 010000 | COP0 10h  ;=RFE
  28099   1100nn | rs   | rt   | <--immediate16bit--> | LWCn rt_dat,[rs+imm]
  28100   1110nn | rs   | rt   | <--immediate16bit--> | SWCn rt_dat,[rs+imm]
  28101 
  28102 Illegal Opcodes
  28103 All opcodes that are marked as "N/A" in the Primary and Secondary opcode tables
  28104 are causing a Reserved Instruction Exception (excode=0Ah).
  28105 The unused operand bits (eg. Bit21-25 for LUI opcode) should be usually zero,
  28106 but do not necessarily trigger exceptions if set to nonzero values.
  28107 
  28108 CPU Load/Store Opcodes
  28109 ----------------------
  28110 
  28111 Load instructions
  28112   movbs rt,[imm+rs]  lb  rt,imm(rs)    rt=[imm+rs]  ;byte sign-extended
  28113   movb  rt,[imm+rs]  lbu rt,imm(rs)    rt=[imm+rs]  ;byte zero-extended
  28114   movhs rt,[imm+rs]  lh  rt,imm(rs)    rt=[imm+rs]  ;halfword sign-extended
  28115   movh  rt,[imm+rs]  lhu rt,imm(rs)    rt=[imm+rs]  ;halfword zero-extended
  28116   mov   rt,[imm+rs]  lw  rt,imm(rs)    rt=[imm+rs]  ;word
  28117 Load instructions can read from the data cache (if the data is not in the
  28118 cache, or if the memory region is uncached, then the CPU gets halted until it
  28119 has read the data) (however, the PSX doesn't have a data cache).
  28120 
  28121 Caution - Load Delay
  28122 The loaded data is NOT available to the next opcode, ie. the target register
  28123 isn't updated until the next opcode has completed. So, if the next opcode tries
  28124 to read from the load destination register, then it would (usually) receive the
  28125 OLD value of that register (unless an IRQ occurs between the load and next
  28126 opcode, in that case the load would complete during IRQ handling, and so, the
  28127 next opcode would receive the NEW value).
  28128 
  28129 Store instructions
  28130   movb  [imm+rs],rt  sb  rt,imm(rs)    [imm+rs]=(rt AND FFh)   ;store 8bit
  28131   movh  [imm+rs],rt  sh  rt,imm(rs)    [imm+rs]=(rt AND FFFFh) ;store 16bit
  28132   mov   [imm+rs],rt  sw  rt,imm(rs)    [imm+rs]=rt             ;store 32bit
  28133 Store operations are passed to the write-buffer, so they can execute within a
  28134 single clock cycle (unless the write-buffer was full, in that case the CPU gets
  28135 halted until there's room in the buffer). But, the PSX doesn't have a
  28136 writebuffer...?
  28137 
  28138 Load/Store Alignment
  28139 Halfword addresses must be aligned by 2, word addresses must be aligned by 4,
  28140 trying to access mis-aligned addresses will cause an exception. There's no
  28141 alignment restriction for bytes.
  28142 
  28143 Unaligned Load/Store
  28144   lwr   rt,imm(rs)     load right bits of rt from memory (usually imm+0)
  28145   lwl   rt,imm(rs)     load left  bits of rt from memory (usually imm+3)
  28146   swr   rt,imm(rs)     store right bits of rt to memory (usually imm+0)
  28147   swl   rt,imm(rs)     store left  bits of rt to memory (usually imm+3)
  28148 There's no delay required between lwl and lwr, so you can use them directly
  28149 following eachother, eg. to load a word anywhere in memory without regard to
  28150 alignment:
  28151   lwl   r2,$0003(t0)   ;\no delay required between these
  28152   lwr   r2,$0000(t0)   ;/(although both access r2)
  28153   nop                  ;-requires load delay HERE (before reading from r2)
  28154   and   r2,r2,0ffffh   ;-access r2 (eg. reducing it to unaligned 16bit data)
  28155 
  28156 Unaligned Load/Store (Details)
  28157 LWR/SWR transfers the right (=lower) bits of Rt, up-to 32bit memory boundary:
  28158   lwr/swr [N*4+0]     transfer whole 32bit of Rt to/from [N*4+0..3]
  28159   lwr/swr [N*4+1]     transfer lower 24bit of Rt to/from [N*4+1..3]
  28160   lwr/swr [N*4+2]     transfer lower 16bit of Rt to/from [N*4+2..3]
  28161   lwr/swr [N*4+3]     transfer lower  8bit of Rt to/from [N*4+3]
  28162 LWL/SWL transfers the left (=upper) bits of Rt, down-to 32bit memory boundary:
  28163   lwl/swl [N*4+0]     transfer upper  8bit of Rt to/from [N*4+0]
  28164   lwl/swl [N*4+1]     transfer upper 16bit of Rt to/from [N*4+0..1]
  28165   lwl/swl [N*4+2]     transfer upper 24bit of Rt to/from [N*4+0..2]
  28166   lwl/swl [N*4+3]     transfer whole 32bit of Rt to/from [N*4+0..3]
  28167 The CPU has four separate byte-access signals, so, within a 32bit location, it
  28168 can transfer all fragments of Rt at once (including for odd 24bit amounts). The
  28169 transferred data is not zero- or sign-expanded, eg. when transferring 8bit
  28170 data, the other 24bit of Rt and [mem] will remain intact.
  28171 
  28172 Note: The aligned variant can also misused for blocking memory access on
  28173 aligned addresses (in that case, if the address is known to be aligned, only
  28174 one of the opcodes are needed, either LWL or LWR).... Uhhhhhhhm, OR is that NOT
  28175 allowed... more PROBABLY that doesn't work?
  28176 
  28177 CPU ALU Opcodes
  28178 ---------------
  28179 
  28180 arithmetic instructions
  28181   addt rd,rs,rt    add   rd,rs,rt         rd=rs+rt (with overflow trap)
  28182   add  rd,rs,rt    addu  rd,rs,rt         rd=rs+rt
  28183   subt rd,rs,rt    sub   rd,rs,rt         rd=rs-rt (with overflow trap)
  28184   sub  rd,rs,rt    subu  rd,rs,rt         rd=rs-rt
  28185   addt rt,rs,imm   addi  rt,rs,imm        rt=rs+(-8000h..+7FFFh) (with ov.trap)
  28186   add  rt,rs,imm   addiu rt,rs,imm        rt=rs+(-8000h..+7FFFh)
  28187 The opcodes "with overflow trap" do trigger an exception (and leave rd
  28188 unchanged) in case of overflows.
  28189 
  28190 comparison instructions
  28191   setlt slt   rd,rs,rt  if rs<rt then rd=1 else rd=0 (signed)
  28192   setb  sltu  rd,rs,rt  if rs<rt then rd=1 else rd=0 (unsigned)
  28193   setlt slti  rt,rs,imm if rs<(-8000h..+7FFFh)  then rt=1 else rt=0 (signed)
  28194   setb  sltiu rt,rs,imm if rs<(FFFF8000h..7FFFh) then rt=1 else rt=0(unsigned)
  28195 
  28196 logical instructions
  28197   and  rd,rs,rt    and  rd,rs,rt         rd = rs AND rt
  28198   or   rd,rs,rt    or   rd,rs,rt         rd = rs OR  rt
  28199   xor  rd,rs,rt    xor  rd,rs,rt         rd = rs XOR rt
  28200   nor  rd,rs,rt    nor  rd,rs,rt         rd = FFFFFFFFh XOR (rs OR rt)
  28201   and  rt,rs,imm   andi rt,rs,imm        rt = rs AND (0000h..FFFFh)
  28202   or   rt,rs,imm   ori  rt,rs,imm        rt = rs OR  (0000h..FFFFh)
  28203   xor  rt,rs,imm   xori rt,rs,imm        rt = rs XOR (0000h..FFFFh)
  28204 
  28205 shifting instructions
  28206   shl  rd,rt,rs    sllv rd,rt,rs          rd = rt SHL (rs AND 1Fh)
  28207   shr  rd,rt,rs    srlv rd,rt,rs          rd = rt SHR (rs AND 1Fh)
  28208   sar  rd,rt,rs    srav rd,rt,rs          rd = rt SAR (rs AND 1Fh)
  28209   shl  rd,rt,imm   sll  rd,rt,imm         rd = rt SHL (00h..1Fh)
  28210   shr  rd,rt,imm   srl  rd,rt,imm         rd = rt SHR (00h..1Fh)
  28211   sar  rd,rt,imm   sra  rd,rt,imm         rd = rt SAR (00h..1Fh)
  28212   mov  rt,i*10000h lui  rt,imm            rt = (0000h..FFFFh) SHL 16
  28213 Unlike many other opcodes, shifts use 'rt' as second (not third) operand.
  28214 The hardware does NOT generate exceptions on SHL overflows.
  28215 
  28216 Multiply/divide
  28217   smul rs,rt       mult   rs,rt           hi:lo = rs*rt (signed)
  28218   umul rs,rt       multu  rs,rt           hi:lo = rs*rt (unsigned)
  28219   sdiv rs,rt       div    rs,rt           lo = rs/rt, hi=rs mod rt (signed)
  28220   udiv rs,rt       divu   rs,rt           lo = rs/rt, hi=rs mod rt (unsigned)
  28221   mov  rd,hi       mfhi   rd              rd=hi  ;move from hi
  28222   mov  rd,lo       mflo   rd              rd=lo  ;move from lo
  28223   mov  hi,rs       mthi   rs              hi=rs  ;move to hi
  28224   mov  lo,rs       mtlo   rs              lo=rs  ;move to lo
  28225 The mul/div opcodes are starting the multiply/divide operation, starting takes
  28226 only a single clock cycle, however, trying to read the result from the hi/lo
  28227 registers while the mul/div operation is busy will halt the CPU until the
  28228 mul/div has completed. For multiply, the execution time depends on rs (ie.
  28229 "small*large" can be much faster than "large*small").
  28230   __umul_execution_time_____________________________________________________
  28231   Fast  (6 cycles)   rs = 00000000h..000007FFh
  28232   Med   (9 cycles)   rs = 00000800h..000FFFFFh
  28233   Slow  (13 cycles)  rs = 00100000h..FFFFFFFFh
  28234   __smul_execution_time_____________________________________________________
  28235   Fast  (6 cycles)   rs = 00000000h..000007FFh, or rs = FFFFF800h..FFFFFFFFh
  28236   Med   (9 cycles)   rs = 00000800h..000FFFFFh, or rs = FFF00000h..FFFFF801h
  28237   Slow  (13 cycles)  rs = 00100000h..7FFFFFFFh, or rs = 80000000h..FFF00001h
  28238   __udiv/sdiv_execution_time________________________________________________
  28239   Fixed (36 cycles)  no matter of rs and rt values
  28240 For example, when executing "umul 123h,12345678h" and "mov r1,lo", one can
  28241 insert up to six (cached) ALU opcodes, or read one value from PSX Main RAM
  28242 (which has 6 cycle access time) between the "umul" and "mov" opcodes without
  28243 additional slowdown.
  28244 The hardware does NOT generate exceptions on divide overflows, instead, divide
  28245 errors are returning the following values:
  28246   Opcode  Rs              Rd       Hi/Remainder  Lo/Result
  28247   udiv    0..FFFFFFFFh    0   -->  Rs            FFFFFFFFh
  28248   sdiv    0..+7FFFFFFFh   0   -->  Rs            -1
  28249   sdiv    -80000000h..-1  0   -->  Rs            +1
  28250   sdiv    -80000000h      -1  -->  0             -80000000h
  28251 For udiv, the result is more or less correct (as close to infinite as
  28252 possible). For sdiv, the results are total garbage (about farthest away from
  28253 the desired result as possible).
  28254 Note: After accessing the lo/hi registers, there seems to be a strange rule
  28255 that one should not touch the lo/hi registers in the next 2 cycles or so... not
  28256 yet understood if/when/how that rule applies...?
  28257 
  28258 CPU Jump Opcodes
  28259 ----------------
  28260 
  28261 jumps and branches
  28262 Note that the instruction following the branch will always be executed.
  28263   jmp  dest        j      dest        pc=(pc and F0000000h)+(imm26bit*4)
  28264   call dest        jal    dest        pc=(pc and F0000000h)+(imm26bit*4),ra=$+8
  28265   jmp  rs          jr     rs          pc=rs
  28266   call rs,ret=rd   jalr (rd,)rs(,rd)  pc=rs, rd=$+8 ;see caution
  28267   je   rs,rt,dest  beq    rs,rt,dest  if rs=rt  then pc=$+4+(-8000h..+7FFFh)*4
  28268   jne  rs,rt,dest  bne    rs,rt,dest  if rs<>rt then pc=$+4+(-8000h..+7FFFh)*4
  28269   js   rs,dest     bltz   rs,dest     if rs<0   then pc=$+4+(-8000h..+7FFFh)*4
  28270   jns  rs,dest     bgez   rs,dest     if rs>=0  then pc=$+4+(-8000h..+7FFFh)*4
  28271   jgtz rs,dest     bgtz   rs,dest     if rs>0   then pc=$+4+(-8000h..+7FFFh)*4
  28272   jlez rs,dest     blez   rs,dest     if rs<=0  then pc=$+4+(-8000h..+7FFFh)*4
  28273   calls  rs,dest   bltzal rs,dest     if rs<0   then pc=$+4+(..)*4, ra=$+8
  28274   callns rs,dest   bgezal rs,dest     if rs>=0  then pc=$+4+(..)*4, ra=$+8
  28275 
  28276 JALR cautions
  28277 Caution: The JALR source code syntax varies (IDT79R3041 specs say "jalr rs,rd",
  28278 but MIPS32 specs say "jalr rd,rs"). Moreover, JALR may not use the same
  28279 register for both operands (eg. "jalr r31,r31") (doing so would destroy the
  28280 target address; which is normally no problem, but it can be a problem if an IRQ
  28281 occurs between the JALR opcode and the following branch delay opcode; in that
  28282 case BD gets set, and EPC points "back" to the JALR opcode, so JALR is executed
  28283 twice, with destroyed target address in second execution).
  28284 
  28285 exception opcodes
  28286 Unlike for jump/branch opcodes, exception opcodes are immediately executed (ie.
  28287 without executing the following opcode).
  28288   syscall  imm20        generates a system call exception
  28289   break    imm20        generates a breakpoint exception
  28290 The 20bit immediate doesn't affect the CPU (however, the exception handler may
  28291 interprete it by software; by examing the opcode bits at [epc-4]).
  28292 
  28293 CPU Coprocessor Opcodes
  28294 -----------------------
  28295 
  28296 Coprocessor Instructions (COP0..COP3)
  28297   mov  rt,cop#Rd(0-31)       mfc# rt,rd       ;rt = cop#datRd ;data regs
  28298   mov  rt,cop#Rd(32-63)      cfc# rt,rd       ;rt = cop#cntRd ;control regs
  28299   mov  cop#Rd(0-31),rt       mtc# rt,rd       ;cop#datRd = rt ;data regs
  28300   mov  cop#Rd(32-63),rt      ctc# rt,rd       ;cop#cntRd = rt ;control regs
  28301   mov  cop#cmd,imm25         cop# imm25       ;exec cop# command 0..1FFFFFFh
  28302   mov  cop#Rt(0-31),[rs+imm] lwc# rt,imm(rs)  ;cop#dat_rt = [rs+imm]  ;word
  28303   mov  [rs+imm],cop#Rt(0-31) swc# rt,imm(rs)  ;[rs+imm] = cop#dat_rt  ;word
  28304   jf   cop#flg,dest          bc#f dest        ;if cop#flg=false then pc=$+disp
  28305   jt   cop#flg,dest          bc#t dest        ;if cop#flg=true  then pc=$+disp
  28306   rfe                        rfe              ;return from exception (COP0)
  28307   tlb<xx>                    tlb<xx>          ;virtual memory related (COP0)
  28308 Unknown if any tlb-opcodes (tlbr,tlbwi,tlbwr,tlbp) are implemented in the psx?
  28309 
  28310 Caution - Load Delay
  28311 When reading from a coprocessor register, the next opcode cannot use the
  28312 destination register as operand (much the same as the Load Delays that occur
  28313 when reading from memory; see there for details).
  28314 Reportedly, the Load Delay applies for the next TWO opcodes after coprocessor
  28315 reads, but, that seems to be nonsense (the PSX does finish both COP0 and COP2
  28316 reads after ONE opcode).
  28317 
  28318 Caution - Store Delay
  28319 In some cases, a similar delay occurs when writing to a coprocessor register.
  28320 COP0 is more or less free of store delays (eg. one can read from a cop0
  28321 register immediately after writing to it), the only known exception is the cop2
  28322 enable bit in cop0r12.bit30 (setting that cop0 bit acts delayed, and cop2 isn't
  28323 actually enabled until after 2 clock cycles or so).
  28324 Writing to cop2 registers has a delay of 2..3 clock cycles. In most cases, that
  28325 is probably (?) only 2 cycles, but special cases like writing to IRGB (which
  28326 does additionally affect IR1,IR2,IR3) take 3 cycles until the result arrives in
  28327 all registers).
  28328 Note that Store Delays are counted in numbers of clock cycles (not in numbers
  28329 of opcodes). For 3 cycle delay, one must usually insert 3 cached opcodes (or
  28330 one uncached opcode).
  28331 
  28332 CPU Pseudo Opcodes
  28333 ------------------
  28334 
  28335 Pseudo instructions (native/spasm)
  28336   nop                  ;alias for sll r0,r0,0
  28337   move rd,rs           ;alias for addu rd,rs,r0
  28338   la   rx,imm32        ;load address   (alias for lui rx / addiu rx)
  28339   li   rx,imm32        ;load immediate (alias for lui rx / ori   rx)
  28340   li   rx,imm16        ;load immediate (alias for ori, range 0..FFFFh)
  28341   li   rx,-imm15       ;load immediate (alias for addiu, range -1..-8000h)
  28342   li   rx,imm16*10000h ;load immediate (alias for lui)
  28343   lw   rx,imm32        ;load from address (lui rx / lw rx,rx)
  28344   sw   rx,imm32        ;store to address  (lui r1 / sw rx,r1) (destroys r1!)
  28345   lb,lh,lwl,lwr,lbu,lhu;as above pseudo lw
  28346   sb,sh,swl,swr        ;as above pseudo sw (ie. also destroys r1!)
  28347   alu  rx,op           ;alias for alu  rx,rx,op
  28348   alu(u) rx,rx,imm     ;alias for alui(u) rx,rx,imm
  28349   jalr  rx             ;alias for jalr (RA,)rx(,RA)
  28350   subi(u) rt,rs,imm    ;alias for addi(u) rt,rs,-imm
  28351   beqz rx,dest         ;alias for beq rx,r0,dest
  28352   bnez rx,dest         ;alias for bne rx,r0,dest
  28353   b   dest             ;alias for beq r0,r0,dest (jump relative/spasm)
  28354   bra dest             ;alias for ...? (jump relative/gnu)
  28355   bal dest             ;alias for ...? (call relative/spasm)
  28356 
  28357 Pseudo instructions (nocash/a22i)
  28358   mov  rx,NNNN0000h    ;alias for lui  rx,NNNNh
  28359   mov  rx,0000NNNNh    ;alias for or   rx,r0,NNNNh  ;max +FFFFh
  28360   mov  rx,-imm15       ;alias for add  rx,r0,-NNNNh ;min -8000h
  28361   mov  rx,ry           ;alias for or   rx,ry,0  (or "addiu")
  28362   nop                  ;alias for shl  r0,r0,0
  28363   jrel dest            ;alias for blez R0,dest   ;relative jump
  28364   crel dest            ;alias for callns R0,dest ;relative call
  28365   jz   rx,dest         ;alias for je   rx,R0,dest
  28366   jnz  rx,dest         ;alias for jne  rx,R0,dest
  28367   call rx              ;alias for call rx,ret=RA
  28368   ret                  ;alias for jmp  ra
  28369   subt rt,rs,imm       ;alias for addt rt,rs,-imm
  28370   sub  rt,rs,imm       ;alias for add  rt,rs,-imm
  28371   alu  rx,op           ;alias for alu  rx,rx,op
  28372   neg(t) rx,ry         ;alias for sub(t) rx,R0,ry
  28373   not    rx,ry         ;alias for nor    rx,R0,ry
  28374   neg(t)/not rx        ;alias for neg(t)/not rx,rx
  28375   setz rx,ry           ;alias for setb rx,ry,1   (set if zero)
  28376   setnz rx,ry          ;alias for setb rx,R0,ry  (set if nonzero)
  28377   syscall/break        ;alias for syscall/break 000000h
  28378 Below are pseudo instructions combined of two 32bit opcodes...
  28379   movp rx,imm32        ;alias for lui  rx,imm16 -plus- ori rx,rx,imm16)
  28380   movpa rx,imm32       ;alias for lui  rx,imm16 -plus- addiu rx,rx,imm16)
  28381   mov(bhs)p rx,[imm32] ;load from address (lui rx,imm16 / mov rx,[rx+imm16])
  28382   movu [rs+imm]        ;alias for lwr/swr [rs+imm] plus lwl/swl [rs+imm+3]
  28383   reti                 ;alias for jmp k0 plus rfe
  28384 Below are pseudo instructions combined of two or more 32bit opcodes...
  28385   push rlist           ;alias for sub sp,n*4 -- mov [sp+(1..n)*4],r1..rn
  28386   pop  rlist           ;alias for mov r1..rn,[sp+(1..n)*4] -- add sp,n*4
  28387   pop  pc,rlist        ;alias for pop ra,rlist -- jmp ra
  28388 
  28389 Possible more Pseudos...
  28390   call x0000000h ;call y0000000h (could be half-working for mem mirrors?)
  28391   setae,setge    ;--> setb,setlt with swapped operands
  28392 
  28393 Directives (nocash)
  28394   .mips          ;select MIPS instruction set (alternately .hc05 for MC68HC05)
  28395   .bios          ;create a .ROM file (instead of .EXE)
  28396   .auto_nop      ;append NOPs to jumps ;unless next opcode starts with a +
  28397   org imm        ;assume following code to be originated at address "imm"
  28398   db n(,n(..)))  ;define 8bit data values(s) or quoted ASCII strings
  28399   dw n(,n(..)))  ;define 16bit data values(s) (not 32bit data!)
  28400   dd n(,n(..)))  ;define 32bit data values(s)
  28401   .align imm
  28402   0              ;alias for immediate 0 and register R0 (whichever fits)
  28403 
  28404 Directives (native)
  28405   org imm        ;self-explaining (but, default=$80010000 for spasm!)
  28406   align imm      ;self-explaining (probably zeropadded?)
  28407   db n(,n(..)))  ;define 8bit data values(s) or quoted ASCII strings
  28408   dh n(,n(..)))  ;define 16bit data values(s)
  28409   dw n(,n(..)))  ;define 32bit data values(s) (not 16bit data!)
  28410   dcb len,value  ;fill <len> bytes by <value> (different as DCB on ARM CPUs)
  28411   xyz            ;define label "xyz" at current address (without colon)
  28412   xyz equ n      ;assign value n to xyz
  28413   xyz = n        ;probably same/sililar as "equ"
  28414   ;xyz           ;comments invoked with semicolon (spasm)
  28415   incbin file.bin       ;import binary file
  28416   include file.asm      ;import asm file
  28417   zero           ;alias for r0
  28418   >imm32         ;alias for (i-(i AND 8000h))/10000h,  and/or i/10000h ?
  28419   <imm32         ;alias for (i AND 0FFFFh), used for SW(+/-) and ORI(+)?
  28420   end       ;N/A ;no "end" or ".end" directive needed/used by spasm
  28421   r1 aka at ;N/A ;some assemblers may (optionally) reject to use r1/at
  28422 
  28423 Syntax for unknown assembler (for pad.s)
  28424 It uses "0x" for HEX values (but doesn't use "$" for registers).
  28425 It uses "#" instead of ";" for comments.
  28426 It uses ":" for labels (fortunately).
  28427 The assembler has at least one directive: ".byte" (equivalent to "db" on other
  28428 assemblers).
  28429 I've no clue which assembler is used for that syntax... could that be the Psy-Q
  28430 assembler?
  28431 
  28432 COP0 - Register Summary
  28433 -----------------------
  28434 
  28435 COP0 Register Summary
  28436   cop0r0-r2   - N/A
  28437   cop0r3      - BPC - Breakpoint on execute (R/W)
  28438   cop0r4      - N/A
  28439   cop0r5      - BDA - Breakpoint on data access (R/W)
  28440   cop0r6      - JUMPDEST - Randomly memorized jump address (R)
  28441   cop0r7      - DCIC - Breakpoint control (R/W)
  28442   cop0r8      - BadVaddr - Bad Virtual Address (R)
  28443   cop0r9      - BDAM - Data Access breakpoint mask (R/W)
  28444   cop0r10     - N/A
  28445   cop0r11     - BPCM - Execute breakpoint mask (R/W)
  28446   cop0r12     - SR - System status register (R/W)
  28447   cop0r13     - CAUSE - (R)  Describes the most recently recognised exception
  28448   cop0r14     - EPC - Return Address from Trap (R)
  28449   cop0r15     - PRID - Processor ID (R)
  28450   cop0r16-r31 - Garbage
  28451   cop0r32-r63 - N/A - None such (Control regs)
  28452 
  28453 COP0 - Exception Handling
  28454 -------------------------
  28455 
  28456 cop0r13 - CAUSE - (Read-only, except, Bit8-9 are R/W)
  28457 Describes the most recently recognised exception
  28458   0-1   -      Not used (zero)
  28459   2-6   Excode Describes what kind of exception occured:
  28460                  00h INT     Interrupt
  28461                  01h MOD     Tlb modification (none such in PSX)
  28462                  02h TLBL    Tlb load         (none such in PSX)
  28463                  03h TLBS    Tlb store        (none such in PSX)
  28464                  04h AdEL    Address error, Data load or Instruction fetch
  28465                  05h AdES    Address error, Data store
  28466                              The address errors occur when attempting to read
  28467                              outside of KUseg in user mode and when the address
  28468                              is misaligned. (See also: BadVaddr register)
  28469                  06h IBE     Bus error on Instruction fetch
  28470                  07h DBE     Bus error on Data load/store
  28471                  08h Syscall Generated unconditionally by syscall instruction
  28472                  09h BP      Breakpoint - break instruction
  28473                  0Ah RI      Reserved instruction
  28474                  0Bh CpU     Coprocessor unusable
  28475                  0Ch Ov      Arithmetic overflow
  28476                  0Dh-1Fh     Not used
  28477   7     -      Not used (zero)
  28478   8-15  Ip     Interrupt pending field. Bit 8 and 9 are R/W, and
  28479                contain the last value written to them. As long
  28480                as any of the bits are set they will cause an
  28481                interrupt if the corresponding bit is set in IM.
  28482   16-27 -      Not used (zero)
  28483   28-29 CE     Contains the coprocessor number if the exception
  28484                occurred because of a coprocessor instruction for
  28485                a coprocessor which wasn't enabled in SR.
  28486   30    -      Not used (zero)
  28487   31    BD     Is set when last exception points to the
  28488                branch instruction instead of the instruction
  28489                in the branch delay slot, where the exception
  28490                occurred.
  28491 
  28492 cop0r12 - SR - System status register (R/W)
  28493   0     IEc Current Interrupt Enable  (0=Disable, 1=Enable) ;rfe pops IUp here
  28494   1     KUc Current Kernal/User Mode  (0=Kernel, 1=User)    ;rfe pops KUp here
  28495   2     IEp Previous Interrupt Disable                      ;rfe pops IUo here
  28496   3     KUp Previous Kernal/User Mode                       ;rfe pops KUo here
  28497   4     IEo Old Interrupt Disable                       ;left unchanged by rfe
  28498   5     KUo Old Kernal/User Mode                        ;left unchanged by rfe
  28499   6-7   -   Not used (zero)
  28500   8-15  Im  8 bit interrupt mask fields. When set the corresponding
  28501             interrupts are allowed to cause an exception.
  28502   16    Isc Isolate Cache (0=No, 1=Isolate)
  28503               When isolated, all load and store operations are targetted
  28504               to the Data cache, and never the main memory.
  28505               (Used by PSX Kernel, in combination with Port FFFE0130h)
  28506   17    Swc Swapped cache mode (0=Normal, 1=Swapped)
  28507               Instruction cache will act as Data cache and vice versa.
  28508               Use only with Isc to access & invalidate Instr. cache entries.
  28509               (Not used by PSX Kernel)
  28510   18    PZ  When set cache parity bits are written as 0.
  28511   19    CM  Shows the result of the last load operation with the D-cache
  28512             isolated. It gets set if the cache really contained data
  28513             for the addressed memory location.
  28514   20    PE  Cache parity error (Does not cause exception)
  28515   21    TS  TLB shutdown. Gets set if a programm address simultaneously
  28516             matches 2 TLB entries.
  28517             (initial value on reset allows to detect extended CPU version?)
  28518   22    BEV Boot exception vectors in RAM/ROM (0=RAM/KSEG0, 1=ROM/KSEG1)
  28519   23-24 -   Not used (zero)
  28520   25    RE  Reverse endianness   (0=Normal endianness, 1=Reverse endianness)
  28521               Reverses the byte order in which data is stored in
  28522               memory. (lo-hi -> hi-lo)
  28523               (Has affect only to User mode, not to Kernel mode) (?)
  28524               (The bit doesn't exist in PSX ?)
  28525   26-27 -   Not used (zero)
  28526   28    CU0 COP0 Enable (0=Enable only in Kernal Mode, 1=Kernal and User Mode)
  28527   29    CU1 COP1 Enable (0=Disable, 1=Enable) (none such in PSX)
  28528   30    CU2 COP2 Enable (0=Disable, 1=Enable) (GTE in PSX)
  28529   31    CU3 COP3 Enable (0=Disable, 1=Enable) (none such in PSX)
  28530 
  28531 cop0r14 - EPC - Return Address from Trap (R)
  28532   0-31  Return Address from Exception
  28533 This address is the instruction at which the exception took place, unless BD is
  28534 set in CAUSE, then the instruction was at EPC+4.
  28535 Interrupts should always return to EPC+0, no matter of the BD flag. That way,
  28536 if BD=1, the branch gets executed again, that's required because EPC stores
  28537 only the current program counter, but not additionally the branch destination
  28538 address.
  28539 Other exceptions may require to handle BD. In simple cases, when BD=0, the
  28540 exception handler may return to EPC+0 (retry execution of the opcode), or to
  28541 EPC+4 (skip the opcode that caused the exception). Note that jumps to faulty
  28542 memory locations are executed without exception, but will trigger address
  28543 errors and bus errors at the target location, ie. EPC (and BadVAddr, in case of
  28544 address errors) point to the faulty address, not to the opcode that has jumped
  28545 to that address).
  28546 
  28547 Interrupts vs GTE Commands
  28548 If an interrupt occurs "on" a GTE command (cop2cmd), then the GTE command is
  28549 executed, but nethertheless, the return address in EPC points to the GTE
  28550 command. So, if the exception handler would return to EPC as usually, then the
  28551 GTE command would be executed twice. In best case, this would be a waste of
  28552 clock cycles, in worst case it may lead to faulty result (if the results from
  28553 the 1st execution are re-used as incoming parameters in the 2nd execution). To
  28554 fix the problem, the exception handler must do:
  28555   if (cause AND 7Ch)=00h                ;if excode=interrupt
  28556    if ([epc] AND FE000000h)=4A000000h   ;and opcode=cop2cmd
  28557     epc=epc+4                           ;then skip that opcode
  28558 Note: The above exception handling is working only in newer PSX BIOSes, but in
  28559 very old PSX BIOSes, it is only incompletely implemented (see "BIOS Patches"
  28560 chapter for common workarounds; or write your own exception handler without
  28561 using the BIOS).
  28562 Of course, the above exeption handling won't work in branch delays (where BD
  28563 gets set to indicate that EPC was modified) (best workaround is not to use GTE
  28564 commands in branch delays).
  28565 
  28566 cop0cmd=10h - RFE opcode - Prepare Return from Exception
  28567 The RFE opcode moves some bits in cop0r12 (SR): bit2-3 are copied to bit0-1,
  28568 and bit4-5 are copied to bit2-3, all other bits (including bit4-5) are left
  28569 unchanged.
  28570 The RFE opcode does NOT automatically jump to EPC. Instead, the exception
  28571 handler must copy EPC into a register (usually R26 aka K0), and then jump to
  28572 that address. Because of branch delays, that would look like so:
  28573   mov  k0,epc  ;get return address
  28574   push k0      ;save epc in memory (if you expect nested exceptions)
  28575   ...          ;whatever (ie. process CAUSE)
  28576   pop  k0      ;restore from memory (if you expect nested exceptions)
  28577   jmp  k0      ;jump to K0 (after executing the next opcode)
  28578   +rfe         ;move SR bit4/5 --> bit2/3 --> bit0/1
  28579 If you expect exceptions to be nested deeply, also push/pop SR. Note that
  28580 there's no way to leave all registers intact (ie. above code destroys K0).
  28581 
  28582 cop0r8 - BadVaddr - Bad Virtual Address (R)
  28583 Contains the address whose reference caused an exception. Set on any MMU type
  28584 of exceptions, on references outside of kuseg (in User mode) and on any
  28585 misaligned reference. BadVaddr is updated ONLY by Address errors (Excode 04h
  28586 and 05h), all other exceptions (including bus errors) leave BadVaddr unchanged.
  28587 
  28588 Exception Vectors (depending on BEV bit in SR register)
  28589   Exception     BEV=0         BEV=1
  28590   Reset         BFC00000h     BFC00000h   (Reset)
  28591   UTLB Miss     80000000h     BFC00100h   (Virtual memory, none such in PSX)
  28592   COP0 Break    80000040h     BFC00140h   (Debug Break)
  28593   General       80000080h     BFC00180h   (General Interrupts & Exceptions)
  28594 Note: Changing vectors at 800000xxh (kseg0) seems to be automatically reflected
  28595 to the instruction cache without needing to flush cache (at least it worked
  28596 SOMETIMES in my test proggy... but NOT always? ...anyways, it'd be highly
  28597 recommended to flush cache when changing any opcodes), whilst changing mirrors
  28598 at 000000xxh (kuseg) seems to require to flush cache.
  28599 The PSX uses only the BEV=0 vectors (aside from the reset vector, the PSX BIOS
  28600 ROM doesn't contain any of the BEV=1 vectors).
  28601 
  28602 Exception Priority
  28603   Reset At any time (highest)            ;-reset
  28604   AdEL Memory (Load instruction)         ;\
  28605   AdES Memory (Store instruction)        ; memory (data load/store)
  28606   DBE  Memory (Load or store)            ;/
  28607   MOD  ALU (Data TLB)                    ;\
  28608   TLBL ALU (DTLB Miss)                   ; none such
  28609   TLBS ALU (DTLB Miss)                   ;/
  28610   Ovf  ALU                               ;-overflow
  28611   Int  ALU                               ;-interrupt
  28612   Sys  RD (Instruction Decode)           ;\
  28613   Bp   RD (Instruction Decode)           ;
  28614   RI   RD (Instruction Decode)           ;
  28615   CpU  RD (Instruction Decode)           ;/
  28616   TLBL I-Fetch (ITLB Miss)               ;-none such
  28617   AdEL IVA (Instruction Virtual Address) ;\memory (opcode fetch)
  28618   IBE  RD (end of I-Fetch, lowest)       ;/
  28619 
  28620 COP0 - Misc
  28621 -----------
  28622 
  28623 cop0r15 - PRID - Processor ID (R)
  28624   0-7   Revision
  28625   8-15  Implementation
  28626   16-31 Not used
  28627 PRID=00000001h on Playstation with CPU CXD8530BQ/CXD8530CQ
  28628 PRID=00000002h on Playstation with CPU CXD8606CQ
  28629 
  28630 cop0r6 - JUMPDEST - Randomly memorized jump address (R)
  28631 The is a rather strange totally useless register. After certain exceptions, the
  28632 CPU does memorize a jump destination address in the register. Once when it has
  28633 memorized an address, the register becomes locked, and the memorized value
  28634 won't change until it becomes unlocked by a new exception. Exceptions that do
  28635 unlock the register are Reset and Interrupts (cause.bit10). Exceptions that do
  28636 NOT unlock the register are syscall/break opcodes, and software generated
  28637 interrupts (eg. cause.bit8).
  28638 In the unlocked state, the CPU does more or less randomly memorize one of the
  28639 next some jump destinations - eg. the destination from the second jump after
  28640 reset, or from a jump that occured immediately before executing the IRQ
  28641 handler, or from a jump inside of the IRQ handler, or even from a later jump
  28642 that occurs shortly after returning from the IRQ handler.
  28643 The register seems to be read-only (although the Kernel initialization code
  28644 writes 0 to it for whatever reason).
  28645 
  28646 cop0r0..r2, cop0r4, cop0r10, cop0r32..r63 - N/A
  28647 Registers 0,1,2,4,10 control virtual memory on some MIPS processors (but
  28648 there's none such in the PSX), and Registers 32..63 (aka "control registers")
  28649 aren't used in any MIPS processors. Trying to read any of these registers
  28650 causes a Reserved Instruction Exception (excode=0Ah).
  28651 
  28652 cop0cmd=01h,02h,06h,08h - TLBR,TLBWI,TLBWR,TLBP
  28653 The PSX supports only one cop0cmd (cop0cmd=10h aka RFE). Trying to execute the
  28654 TLBxx opcodes causes a Reserved Instruction Exception (excode=0Ah).
  28655 
  28656 jf/jt cop0flg,dest - conditional cop0 jumps
  28657 mov [mem],cop0reg / mov cop0reg,[mem] - coprocessor cop0 load/store
  28658 Not supported by the CPU. Trying to execute these opcodes causes a Coprocessor
  28659 Unusable Exception (excode=0Bh, ie. unlike above, not 0Ah).
  28660 
  28661 cop0r16-r31 - Garbage
  28662 Trying to read these registers returns garbage (but does not trigger an
  28663 exception). When reading one of the garbage registers shortly after reading a
  28664 valid cop0 register, the garbage value is usually the same as that of the valid
  28665 register. When doing the read later on, the return value is usually 00000020h,
  28666 or when reading much later it returns 00000040h, or even 00000100h. No idea
  28667 what is causing that effect...?
  28668 Note: The garbage registers can be accessed (without causing an exception) even
  28669 in "User mode with cop0 disabled" (SR.Bit1=1 and SR.Bit28=0); accessing any
  28670 other existing cop0 registers (or executing the rfe opcode) in that state is
  28671 causing Coprocessor Unusable Exceptions (excode=0Bh).
  28672 
  28673 COP0 - Debug Registers
  28674 ----------------------
  28675 
  28676 The COP0 debug registers seem to be PSX specific, normal R30xx CPUs like IDT's
  28677 R3041 and R3051 don't have anything similar.
  28678 
  28679 cop0r7 - DCIC - Breakpoint control (R/W)
  28680   0      Automatically set by hardware upon Any break            (R/W)
  28681   1      Automatically set by hardware upon BPC Code break       (R/W)
  28682   2      Automatically set by hardware upon BDA Data break       (R/W)
  28683   3      Automatically set by hardware upon BDA Data-Read break  (R/W)
  28684   4      Automatically set by hardware upon BDA Data-Write break (R/W)
  28685   5      Automatically set by hardware upon any-jump break       (R/W)
  28686   6-11   Not used (always zero)
  28687   12-13  Jump Redirection (0=Disable, 1..3=Enable) (see note)    (R/W)
  28688   14-15  Unknown? (R/W)
  28689   16-22  Not used (always zero)
  28690   23     Super-Master Enable 1 for bit24-29
  28691   24     Execution breakpoint     (0=Disabled, 1=Enabled) (see BPC, BPCM)
  28692   25     Data access breakpoint   (0=Disabled, 1=Enabled) (see BDA, BDAM)
  28693   26     Break on Data-Read       (0=No, 1=Break/when Bit25=1)
  28694   27     Break on Data-Write      (0=No, 1=Break/when Bit25=1)
  28695   28     Break on any-jump        (0=No, 1=Break on branch/jump/call/etc.)
  28696   29     Master Enable for bit28 (..and/or exec-break at address>=80000000h?)
  28697   30     Master Enable for bit24-27
  28698   31     Super-Master Enable 2 for bit24-29
  28699 When a breakpoint address match occurs the PSX jumps to 80000040h (ie. unlike
  28700 normal exceptions, not to 80000080h). The Excode value in the CAUSE register is
  28701 set to 09h (same as BREAK opcode), and EPC contains the return address, as
  28702 usually. One of the first things to be done in the exception handler is to
  28703 disable breakpoints (eg. if the any-jump break is enabled, then it must be
  28704 disabled BEFORE jumping from 80000040h to the actual exception handler).
  28705 
  28706 cop0r7.bit12-13 - Jump Redirection Note
  28707 If one or both of these bits are nonzero, then the PSX seems to check for the
  28708 following opcode sequence,
  28709   mov rx,[mem]   ;load rx from memory
  28710   ...            ;one or more opcodes that do not change rx
  28711   jmp/call rx    ;jump or call to rx
  28712 if it does sense that sequence, then it sets PC=[00000000h], but does not store
  28713 any useful information in any cop0 registers, namely it does not store the
  28714 return address in EPC, so it's impossible to determine which opcode has caused
  28715 the exception. For the jump target address, there are 31 registers, so one
  28716 could only guess which of them contains the target value; for "POP PC" code
  28717 it'd be usually R31, but for "JMP [vector]" code it may be any register. So far
  28718 the feature seems to be more or less unusable...?
  28719 
  28720 cop0r5 - BDA - Breakpoint on Data Access Address (R/W)
  28721 cop0r9 - BDAM - Breakpoint on Data Access Mask (R/W)
  28722 Break condition is "((addr XOR BDA) AND BDAM)=0".
  28723 
  28724 cop0r3 - BPC - Breakpoint on Execute Address (R/W)
  28725 cop0r11 - BPCM - Breakpoint on Execute Mask (R/W)
  28726 Break condition is "((PC XOR BPC) AND BPCM)=0".
  28727 
  28728 Note (BREAK Opcode)
  28729 Additionally, the BREAK opcode can be used to create further breakpoints by
  28730 patching the executable code. The BREAK opcode uses the same Excode value (09h)
  28731 in CAUSE register. However, the BREAK opcode jumps to the normal exception
  28732 handler at 80000080h (not 80000040h).
  28733 
  28734 Note (LibCrypt)
  28735 The debug registers are mis-used by "Legacy of Kain: Soul Reaver" (and maybe
  28736 also other games) for storing libcrypt copy-protection related values (ie. just
  28737 as a "hidden" location for storing data, not for actual debugging purposes).
  28738 --> CDROM Protection - LibCrypt
  28739 
  28740 Note (Cheat Devices/Expansion ROMs)
  28741 The Expansion ROM header supports only Pre-Boot and Post-Boot vectors, but no
  28742 Mid-Boot vector. Cheat Devices are often using COP0 breaks for Mid-Boot Hooks,
  28743 either with BPC=BFC06xxxh (break address in ROM, used in older cheat
  28744 firmwares), or with BPC=80030000h (break address in RAM aka relocated GUI
  28745 entrypoint, used in later cheat firmwares). Moreover, aside from the Mid-Boot
  28746 Hook, the Xplorer cheat device is also supporting a special cheat code that
  28747 uses the COP0 break feature.
  28748 
  28749 Note (Datasheet)
  28750 Note: COP0 debug registers are described in LSI's "L64360" datasheet, chapter
  28751 14. And in their LR33300/LR33310 datasheet, chapter 4.
  28752 
  28753 Kernel (BIOS)
  28754 -------------
  28755 
  28756 --> BIOS Overview
  28757 --> BIOS Memory Map
  28758 --> BIOS Function Summary
  28759 --> BIOS File Functions
  28760 --> BIOS File Execute and Flush Cache
  28761 --> BIOS CDROM Functions
  28762 --> BIOS Memory Card Functions
  28763 --> BIOS Interrupt/Exception Handling
  28764 --> BIOS Event Functions
  28765 --> BIOS Event Summary
  28766 --> BIOS Thread Functions
  28767 --> BIOS Timer Functions
  28768 --> BIOS Joypad Functions
  28769 --> BIOS GPU Functions
  28770 --> BIOS Memory Allocation
  28771 --> BIOS Memory Fill/Copy/Compare (SLOW)
  28772 --> BIOS String Functions
  28773 --> BIOS Number/String/Character Conversion
  28774 --> BIOS Misc Functions
  28775 --> BIOS Internal Boot Functions
  28776 --> BIOS More Internal Functions
  28777 --> BIOS PC File Server
  28778 --> BIOS TTY Console (std_io)
  28779 --> BIOS Character Sets
  28780 --> BIOS Control Blocks
  28781 --> BIOS Boot State
  28782 --> BIOS Versions
  28783 --> BIOS Patches
  28784 
  28785 BIOS Overview
  28786 -------------
  28787 
  28788 BIOS CDROM Boot
  28789 The main purpose of the BIOS is to boot games from CDROM, unfortunately, before
  28790 doing that, it displays the Sony intro. It's also doing some copy protection
  28791 and region checks, and refuses to boot unlicensed games, or illegal copies, or
  28792 games for other regions.
  28793 
  28794 BIOS Bootmenu
  28795 The bootmenu shows up when starting the Playstation without CDROM inserted. The
  28796 menu allows to play Audio CDs, and to erase or copy game positions on Memory
  28797 Cards.
  28798 
  28799 BIOS Functions
  28800 The BIOS contains a number of more or less useful, and probably more or less
  28801 inefficient functions that can be used by software.
  28802 No idea if it's easy to take full control of the CPU, ie. to do all hardware
  28803 access and interrupt handling by software, without using the BIOS at all?
  28804 Eventually the BIOS functions for accessing the CDROM drive are important, not
  28805 sure how complicated/compatible it'd be to access the CDROM drive directly via
  28806 I/O ports... among others, there might be different drives used in different
  28807 versions of the Playstation, which aren't fully compatible with each other?
  28808 
  28809 BIOS Memory
  28810 The BIOS occupies 512Kbyte ROM with 8bit address bus (so the BIOS ROM is rather
  28811 slow, for faster execution, portions of it are relocated to the first 64K of
  28812 RAM). For some very strange reason, the original PSX BIOS executes all ROM
  28813 functions in uncached ROM, which is incredible slow (nocash BIOS uses cached
  28814 ROM, which does work without problems).
  28815 The first 64Kbyte of the 2Mbyte Main RAM are reserved for the BIOS (containing
  28816 exception handlers, jump tables, other data, and relocated code). That reserved
  28817 region does unfortunately include the "valuable" first 32Kbytes (valuable
  28818 because that memory could be accessed directly via [R0+immediate], without
  28819 needing to use R1..R31 as base register).
  28820 
  28821 BIOS Memory Map
  28822 ---------------
  28823 
  28824 BIOS ROM Map (512Kbytes)
  28825   BFC00000h Kernel Part 1  (code/data executed in uncached ROM)
  28826   BFC10000h Kernel Part 2  (code/data relocated to cached RAM)
  28827   BFC18000h Intro/Bootmenu (code/data decompressed and relocated to RAM)
  28828   BFC64000h Character Sets
  28829 
  28830 BIOS ROM Header/Footer
  28831   BFC00100h Kernel BCD date  (YYYYMMDDh)
  28832   BFC00104h Console Type     (see Port 1F802030h, Secondary IRQ10 Controller)
  28833   BFC00108h Kernel Maker/Version Strings (separated by one or more 00h bytes)
  28834   BFC7FF32h GUI Version/Copyright Strings (if any) (separated by one 00h byte)
  28835 
  28836 BIOS RAM Map (1st 64Kbytes of RAM) (fixed addresses mainly in 1st 500h bytes)
  28837   00000000h 10h    Garbage Area (see notes below)
  28838   00000010h 30h    Unused/reserved
  28839   00000040h 20h    COP0 debug-break vector (not used by Kernel) (in KSEG0)
  28840   00000060h 4      RAM Size (in megabytes) (2 or 8)
  28841   00000064h 4      Unknown (set to 00000000h)
  28842   00000068h 4      Unknown (set to 000000FFh)
  28843   0000006Ch 14h    Unused/reserved
  28844   00000080h 10h    Exception vector (actually in KSEG0, ie. at 80000080h)
  28845   00000090h 10h    Unused/reserved
  28846   000000A0h 10h    A(nnh) Function Vector
  28847   000000B0h 10h    B(nnh) Function Vector
  28848   000000C0h 10h    C(nnh) Function Vector
  28849   000000D0h 30h    Unused/reserved
  28850   00000100h 58h    Table of Tables (BIOS Control Blocks) (see below)
  28851   00000158h 28h    Unused/reserved
  28852   00000180h 80h    Command line argument from SYSTEM.CNF; BOOT = fname argument
  28853   00000200h 300h   A(nnh) Jump Table
  28854   00000500h ...    Kernel Code/Data (relocated from ROM)
  28855   0000Cxxxh ...    Unused/reserved
  28856   0000DF80h 80h    Used for BIOS Patches (ie. used by games, not used by BIOS)
  28857   0000DFFCh 4      Response value from Intro/Bootmenu
  28858   0000E000h 2000h  Kernel Memory; ExCBs, EvCBs, and TCBs allocated via B(00h)
  28859 
  28860 User Memory (not used by Kernel)
  28861   00010000h ...    Begin of User RAM (Exefile, Data, Heap, Stack, etc.)
  28862   001FFF00h ...    Default Stacktop (usually in KSEG0)
  28863   1F800000h 400h   Scratchpad (Data-Cache mis-used as Fast RAM)
  28864 
  28865 Table of Tables (see BIOS Control Blocks for details)
  28866 Each table entry consists of two 32bit values; containing the base address, and
  28867 total size (in bytes) of the corresponding control blocks.
  28868   00000100h  ExCB Exception Chain Entrypoints (addr=var, size=4*08h)
  28869   00000108h  PCB  Process Control Block       (addr=var, size=1*04h)
  28870   00000110h  TCB  Thread Control Blocks       (addr=var, size=N*C0h)
  28871   00000118h  -    Unused/reserved
  28872   00000120h  EvCB Event Control Blocks        (addr=var, size=N*1Ch)
  28873   00000128h  -    Unused/reserved
  28874   00000130h  -    Unused/reserved
  28875   00000138h  -    Unused/reserved
  28876   00000140h  FCB  File Control Blocks         (addr=fixed, size=10h*2Ch)
  28877   00000148h  -    Unused/reserved
  28878   00000150h  DCB  Device Control Blocks       (addr=fixed, size=0Ah*50h)
  28879 File handles (fd=00h..0Fh) can be simply converted as fcb=[140h]+fd*2Ch.
  28880 Event handles (event=F10000xxh) as evcb=[120h]+(event AND FFFFh)*1Ch.
  28881 
  28882 Garbage Area at Address 00000000h
  28883 The first some bytes of memory address 00000000h aren't actually used by the
  28884 Kernel, except for storing some garbage at that locations. However, this
  28885 garbage is actually important for bugged games like R-Types and Fade to Black
  28886 (ie. games that do read from address 00000000h due to using uninitialized
  28887 pointers).
  28888 Initially, the garbage area is containing a copy of the 16-byte exception
  28889 handler at address 80h, but the first 4-bytes are typically smashed (set to
  28890 00000003h from some useless dummy writes in some useless CDROM delays). Ie. the
  28891 16-bytes should have these values:
  28892   [00000000h]=3C1A0000h  ;<-- but overwritten by 00000003h after soon
  28893   [00000004h]=275A0C80h  ;<-- or 275A0C50h (in older BIOS)
  28894   [00000008h]=03400008h
  28895   [0000000Ch]=00000000h
  28896 For R-Types, the halfword at [0] must non-zero (else the game will do a DMA to
  28897 address 0, and thereby destroy kernel memory). Fade to Black does several
  28898 garbage reads from [0..9], a wrong byte value at [5] can cause the game to
  28899 crash with an invalid memory access exception upon memory card access.
  28900 
  28901 BIOS Function Summary
  28902 ---------------------
  28903 
  28904 Parameters, Registers, Stack
  28905 Argument(s) are passed in R4,R5,R6,R7,[SP+10h],[SP+14h],etc.
  28906 Caution: When calling a sub-function with N parameters, the caller MUST always
  28907 allocate N words on the stack, and, although the first four parameters are
  28908 passed in registers rather than on stack, the sub-function is allowed to
  28909 use/destroy these words at [SP+0..N*4-1].
  28910 BIOS Functions (and custom callback functions) are allowed to destroy registers
  28911 R1-R15, R24-R25, R31 (RA), and HI/LO. Registers R16-R23, R29 (SP), and R30 (FP)
  28912 must be left unchanged (if the function uses that registers, then it must
  28913 push/pop them). R26 (K0) is reserved for exception handler and should be
  28914 usually not used by other functions. R27 (K1) and R28 (GP) are left more or
  28915 less unused by the BIOS, so one can more or less freely use them for whatever
  28916 purpose.
  28917 The return value (if any) is stored in R2 register.
  28918 
  28919 A-Functions (Call 00A0h with function number in R9 Register)
  28920   A(00h) or B(32h) FileOpen(filename,accessmode)
  28921   A(01h) or B(33h) FileSeek(fd,offset,seektype)
  28922   A(02h) or B(34h) FileRead(fd,dst,length)
  28923   A(03h) or B(35h) FileWrite(fd,src,length)
  28924   A(04h) or B(36h) FileClose(fd)
  28925   A(05h) or B(37h) FileIoctl(fd,cmd,arg)
  28926   A(06h) or B(38h) exit(exitcode)
  28927   A(07h) or B(39h) FileGetDeviceFlag(fd)
  28928   A(08h) or B(3Ah) FileGetc(fd)
  28929   A(09h) or B(3Bh) FilePutc(char,fd)
  28930   A(0Ah) todigit(char)
  28931   A(0Bh) atof(src)     ;Does NOT work - uses (ABSENT) cop1 !!!
  28932   A(0Ch) strtoul(src,src_end,base)
  28933   A(0Dh) strtol(src,src_end,base)
  28934   A(0Eh) abs(val)
  28935   A(0Fh) labs(val)
  28936   A(10h) atoi(src)
  28937   A(11h) atol(src)
  28938   A(12h) atob(src,num_dst)
  28939   A(13h) SaveState(buf)
  28940   A(14h) RestoreState(buf,param)
  28941   A(15h) strcat(dst,src)
  28942   A(16h) strncat(dst,src,maxlen)
  28943   A(17h) strcmp(str1,str2)
  28944   A(18h) strncmp(str1,str2,maxlen)
  28945   A(19h) strcpy(dst,src)
  28946   A(1Ah) strncpy(dst,src,maxlen)
  28947   A(1Bh) strlen(src)
  28948   A(1Ch) index(src,char)
  28949   A(1Dh) rindex(src,char)
  28950   A(1Eh) strchr(src,char)  ;exactly the same as "index"
  28951   A(1Fh) strrchr(src,char) ;exactly the same as "rindex"
  28952   A(20h) strpbrk(src,list)
  28953   A(21h) strspn(src,list)
  28954   A(22h) strcspn(src,list)
  28955   A(23h) strtok(src,list)  ;use strtok(0,list) in further calls
  28956   A(24h) strstr(str,substr) - buggy
  28957   A(25h) toupper(char)
  28958   A(26h) tolower(char)
  28959   A(27h) bcopy(src,dst,len)
  28960   A(28h) bzero(dst,len)
  28961   A(29h) bcmp(ptr1,ptr2,len)      ;Bugged
  28962   A(2Ah) memcpy(dst,src,len)
  28963   A(2Bh) memset(dst,fillbyte,len)
  28964   A(2Ch) memmove(dst,src,len)     ;Bugged
  28965   A(2Dh) memcmp(src1,src2,len)    ;Bugged
  28966   A(2Eh) memchr(src,scanbyte,len)
  28967   A(2Fh) rand()
  28968   A(30h) srand(seed)
  28969   A(31h) qsort(base,nel,width,callback)
  28970   A(32h) strtod(src,src_end) ;Does NOT work - uses (ABSENT) cop1 !!!
  28971   A(33h) malloc(size)
  28972   A(34h) free(buf)
  28973   A(35h) lsearch(key,base,nel,width,callback)
  28974   A(36h) bsearch(key,base,nel,width,callback)
  28975   A(37h) calloc(sizx,sizy)            ;SLOW!
  28976   A(38h) realloc(old_buf,new_siz)     ;SLOW!
  28977   A(39h) InitHeap(addr,size)
  28978   A(3Ah) SystemErrorExit(exitcode)
  28979   A(3Bh) or B(3Ch) std_in_getchar()
  28980   A(3Ch) or B(3Dh) std_out_putchar(char)
  28981   A(3Dh) or B(3Eh) std_in_gets(dst)
  28982   A(3Eh) or B(3Fh) std_out_puts(src)
  28983   A(3Fh) printf(txt,param1,param2,etc.)
  28984   A(40h) SystemErrorUnresolvedException()
  28985   A(41h) LoadExeHeader(filename,headerbuf)
  28986   A(42h) LoadExeFile(filename,headerbuf)
  28987   A(43h) DoExecute(headerbuf,param1,param2)
  28988   A(44h) FlushCache()
  28989   A(45h) init_a0_b0_c0_vectors
  28990   A(46h) GPU_dw(Xdst,Ydst,Xsiz,Ysiz,src)
  28991   A(47h) gpu_send_dma(Xdst,Ydst,Xsiz,Ysiz,src)
  28992   A(48h) SendGP1Command(gp1cmd)
  28993   A(49h) GPU_cw(gp0cmd)   ;send GP0 command word
  28994   A(4Ah) GPU_cwp(src,num) ;send GP0 command word and parameter words
  28995   A(4Bh) send_gpu_linked_list(src)
  28996   A(4Ch) gpu_abort_dma()
  28997   A(4Dh) GetGPUStatus()
  28998   A(4Eh) gpu_sync()
  28999   A(4Fh) SystemError
  29000   A(50h) SystemError
  29001   A(51h) LoadAndExecute(filename,stackbase,stackoffset)
  29002   A(52h) SystemError ----OR---- "GetSysSp()" ?
  29003   A(53h) SystemError            ;PS2: set_ioabort_handler(src)
  29004   A(54h) or A(71h) CdInit()
  29005   A(55h) or A(70h) _bu_init()
  29006   A(56h) or A(72h) CdRemove()
  29007   A(57h) return 0
  29008   A(58h) return 0
  29009   A(59h) return 0
  29010   A(5Ah) return 0
  29011   A(5Bh) dev_tty_init()                                      ;PS2: SystemError
  29012   A(5Ch) dev_tty_open(fcb,and unused:"path\name",accessmode) ;PS2: SystemError
  29013   A(5Dh) dev_tty_in_out(fcb,cmd)                             ;PS2: SystemError
  29014   A(5Eh) dev_tty_ioctl(fcb,cmd,arg)                          ;PS2: SystemError
  29015   A(5Fh) dev_cd_open(fcb,"path\name",accessmode)
  29016   A(60h) dev_cd_read(fcb,dst,len)
  29017   A(61h) dev_cd_close(fcb)
  29018   A(62h) dev_cd_firstfile(fcb,"path\name",direntry)
  29019   A(63h) dev_cd_nextfile(fcb,direntry)
  29020   A(64h) dev_cd_chdir(fcb,"path")
  29021   A(65h) dev_card_open(fcb,"path\name",accessmode)
  29022   A(66h) dev_card_read(fcb,dst,len)
  29023   A(67h) dev_card_write(fcb,src,len)
  29024   A(68h) dev_card_close(fcb)
  29025   A(69h) dev_card_firstfile(fcb,"path\name",direntry)
  29026   A(6Ah) dev_card_nextfile(fcb,direntry)
  29027   A(6Bh) dev_card_erase(fcb,"path\name")
  29028   A(6Ch) dev_card_undelete(fcb,"path\name")
  29029   A(6Dh) dev_card_format(fcb)
  29030   A(6Eh) dev_card_rename(fcb1,"path\name1",fcb2,"path\name2")
  29031   A(6Fh) ?   ;card ;[r4+18h]=00000000h  ;card_clear_error(fcb) or so
  29032   A(70h) or A(55h) _bu_init()
  29033   A(71h) or A(54h) CdInit()
  29034   A(72h) or A(56h) CdRemove()
  29035   A(73h) return 0
  29036   A(74h) return 0
  29037   A(75h) return 0
  29038   A(76h) return 0
  29039   A(77h) return 0
  29040   A(78h) CdAsyncSeekL(src)
  29041   A(79h) return 0               ;DTL-H: Unknown?
  29042   A(7Ah) return 0               ;DTL-H: Unknown?
  29043   A(7Bh) return 0               ;DTL-H: Unknown?
  29044   A(7Ch) CdAsyncGetStatus(dst)
  29045   A(7Dh) return 0               ;DTL-H: Unknown?
  29046   A(7Eh) CdAsyncReadSector(count,dst,mode)
  29047   A(7Fh) return 0               ;DTL-H: Unknown?
  29048   A(80h) return 0               ;DTL-H: Unknown?
  29049   A(81h) CdAsyncSetMode(mode)
  29050   A(82h) return 0               ;DTL-H: Unknown?
  29051   A(83h) return 0               ;DTL-H: Unknown?
  29052   A(84h) return 0               ;DTL-H: Unknown?
  29053   A(85h) return 0               ;DTL-H: Unknown?, or reportedly, CdStop (?)
  29054   A(86h) return 0               ;DTL-H: Unknown?
  29055   A(87h) return 0               ;DTL-H: Unknown?
  29056   A(88h) return 0               ;DTL-H: Unknown?
  29057   A(89h) return 0               ;DTL-H: Unknown?
  29058   A(8Ah) return 0               ;DTL-H: Unknown?
  29059   A(8Bh) return 0               ;DTL-H: Unknown?
  29060   A(8Ch) return 0               ;DTL-H: Unknown?
  29061   A(8Dh) return 0               ;DTL-H: Unknown?
  29062   A(8Eh) return 0               ;DTL-H: Unknown?
  29063   A(8Fh) return 0               ;DTL-H: Unknown?
  29064   A(90h) CdromIoIrqFunc1()
  29065   A(91h) CdromDmaIrqFunc1()
  29066   A(92h) CdromIoIrqFunc2()
  29067   A(93h) CdromDmaIrqFunc2()
  29068   A(94h) CdromGetInt5errCode(dst1,dst2)
  29069   A(95h) CdInitSubFunc()
  29070   A(96h) AddCDROMDevice()
  29071   A(97h) AddMemCardDevice()     ;DTL-H: SystemError
  29072   A(98h) AddDuartTtyDevice()    ;DTL-H: AddAdconsTtyDevice ;PS2: SystemError
  29073   A(99h) AddDummyTtyDevice()
  29074   A(9Ah) SystemError            ;DTL-H: AddMessageWindowDevice
  29075   A(9Bh) SystemError            ;DTL-H: AddCdromSimDevice
  29076   A(9Ch) SetConf(num_EvCB,num_TCB,stacktop)
  29077   A(9Dh) GetConf(num_EvCB_dst,num_TCB_dst,stacktop_dst)
  29078   A(9Eh) SetCdromIrqAutoAbort(type,flag)
  29079   A(9Fh) SetMemSize(megabytes)
  29080 Below functions A(A0h..B4h) not supported on pre-retail DTL-H2000 devboard:
  29081   A(A0h) WarmBoot()
  29082   A(A1h) SystemErrorBootOrDiskFailure(type,errorcode)
  29083   A(A2h) EnqueueCdIntr()  ;with prio=0 (fixed)
  29084   A(A3h) DequeueCdIntr()
  29085   A(A4h) CdGetLbn(filename) ;get 1st sector number (or garbage when not found)
  29086   A(A5h) CdReadSector(count,sector,buffer)
  29087   A(A6h) CdGetStatus()
  29088   A(A7h) bu_callback_okay()
  29089   A(A8h) bu_callback_err_write()
  29090   A(A9h) bu_callback_err_busy()
  29091   A(AAh) bu_callback_err_eject()
  29092   A(ABh) _card_info(port)
  29093   A(ACh) _card_async_load_directory(port)
  29094   A(ADh) set_card_auto_format(flag)
  29095   A(AEh) bu_callback_err_prev_write()
  29096   A(AFh) card_write_test(port)  ;CEX-1000: jump_to_00000000h
  29097   A(B0h) return 0               ;CEX-1000: jump_to_00000000h
  29098   A(B1h) return 0               ;CEX-1000: jump_to_00000000h
  29099   A(B2h) ioabort_raw(param)     ;CEX-1000: jump_to_00000000h
  29100   A(B3h) return 0               ;CEX-1000: jump_to_00000000h
  29101   A(B4h) GetSystemInfo(index)   ;CEX-1000: jump_to_00000000h
  29102   A(B5h..BFh) N/A ;jump_to_00000000h
  29103 
  29104 B-Functions (Call 00B0h with function number in R9 Register)
  29105   B(00h) alloc_kernel_memory(size)
  29106   B(01h) free_kernel_memory(buf)
  29107   B(02h) init_timer(t,reload,flags)
  29108   B(03h) get_timer(t)
  29109   B(04h) enable_timer_irq(t)
  29110   B(05h) disable_timer_irq(t)
  29111   B(06h) restart_timer(t)
  29112   B(07h) DeliverEvent(class, spec)
  29113   B(08h) OpenEvent(class,spec,mode,func)
  29114   B(09h) CloseEvent(event)
  29115   B(0Ah) WaitEvent(event)
  29116   B(0Bh) TestEvent(event)
  29117   B(0Ch) EnableEvent(event)
  29118   B(0Dh) DisableEvent(event)
  29119   B(0Eh) OpenThread(reg_PC,reg_SP_FP,reg_GP)
  29120   B(0Fh) CloseThread(handle)
  29121   B(10h) ChangeThread(handle)
  29122   B(11h) jump_to_00000000h
  29123   B(12h) InitPad(buf1,siz1,buf2,siz2)
  29124   B(13h) StartPad()
  29125   B(14h) StopPad()
  29126   B(15h) OutdatedPadInitAndStart(type,button_dest,unused,unused)
  29127   B(16h) OutdatedPadGetButtons()
  29128   B(17h) ReturnFromException()
  29129   B(18h) SetDefaultExitFromException()
  29130   B(19h) SetCustomExitFromException(addr)
  29131   B(1Ah) SystemError  ;PS2: return 0
  29132   B(1Bh) SystemError  ;PS2: return 0
  29133   B(1Ch) SystemError  ;PS2: return 0
  29134   B(1Dh) SystemError  ;PS2: return 0
  29135   B(1Eh) SystemError  ;PS2: return 0
  29136   B(1Fh) SystemError  ;PS2: return 0
  29137   B(20h) UnDeliverEvent(class,spec)
  29138   B(21h) SystemError  ;PS2: return 0
  29139   B(22h) SystemError  ;PS2: return 0
  29140   B(23h) SystemError  ;PS2: return 0
  29141   B(24h) jump_to_00000000h
  29142   B(25h) jump_to_00000000h
  29143   B(26h) jump_to_00000000h
  29144   B(27h) jump_to_00000000h
  29145   B(28h) jump_to_00000000h
  29146   B(29h) jump_to_00000000h
  29147   B(2Ah) SystemError  ;PS2: return 0
  29148   B(2Bh) SystemError  ;PS2: return 0
  29149   B(2Ch) jump_to_00000000h
  29150   B(2Dh) jump_to_00000000h
  29151   B(2Eh) jump_to_00000000h
  29152   B(2Fh) jump_to_00000000h
  29153   B(30h) jump_to_00000000h
  29154   B(31h) jump_to_00000000h
  29155   B(32h) or A(00h) FileOpen(filename,accessmode)
  29156   B(33h) or A(01h) FileSeek(fd,offset,seektype)
  29157   B(34h) or A(02h) FileRead(fd,dst,length)
  29158   B(35h) or A(03h) FileWrite(fd,src,length)
  29159   B(36h) or A(04h) FileClose(fd)
  29160   B(37h) or A(05h) FileIoctl(fd,cmd,arg)
  29161   B(38h) or A(06h) exit(exitcode)
  29162   B(39h) or A(07h) FileGetDeviceFlag(fd)
  29163   B(3Ah) or A(08h) FileGetc(fd)
  29164   B(3Bh) or A(09h) FilePutc(char,fd)
  29165   B(3Ch) or A(3Bh) std_in_getchar()
  29166   B(3Dh) or A(3Ch) std_out_putchar(char)
  29167   B(3Eh) or A(3Dh) std_in_gets(dst)
  29168   B(3Fh) or A(3Eh) std_out_puts(src)
  29169   B(40h) chdir(name)
  29170   B(41h) FormatDevice(devicename)
  29171   B(42h) firstfile(filename,direntry)
  29172   B(43h) nextfile(direntry)
  29173   B(44h) FileRename(old_filename,new_filename)
  29174   B(45h) FileDelete(filename)
  29175   B(46h) FileUndelete(filename)
  29176   B(47h) AddDevice(device_info)  ;subfunction for AddXxxDevice functions
  29177   B(48h) RemoveDevice(device_name_lowercase)
  29178   B(49h) PrintInstalledDevices()
  29179 Below functions B(4Ah..5Dh) not supported on pre-retail DTL-H2000 devboard:
  29180   B(4Ah) InitCard(pad_enable)  ;uses/destroys k0/k1 !!!
  29181   B(4Bh) StartCard()
  29182   B(4Ch) StopCard()
  29183   B(4Dh) _card_info_subfunc(port)  ;subfunction for "_card_info"
  29184   B(4Eh) write_card_sector(port,sector,src)
  29185   B(4Fh) read_card_sector(port,sector,dst)
  29186   B(50h) allow_new_card()
  29187   B(51h) Krom2RawAdd(shiftjis_code)
  29188   B(52h) SystemError  ;PS2: return 0
  29189   B(53h) Krom2Offset(shiftjis_code)
  29190   B(54h) GetLastError()
  29191   B(55h) GetLastFileError(fd)
  29192   B(56h) GetC0Table
  29193   B(57h) GetB0Table
  29194   B(58h) get_bu_callback_port()
  29195   B(59h) testdevice(devicename)
  29196   B(5Ah) SystemError  ;PS2: return 0
  29197   B(5Bh) ChangeClearPad(int)
  29198   B(5Ch) get_card_status(slot)
  29199   B(5Dh) wait_card_status(slot)
  29200   B(5Eh..FFh) N/A ;jump_to_00000000h    ;CEX-1000: B(5Eh..F6h) only
  29201   B(100h....) N/A ;garbage              ;CEX-1000: B(F7h.....) and up
  29202 
  29203 C-Functions (Call 00C0h with function number in R9 Register)
  29204   C(00h) EnqueueTimerAndVblankIrqs(priority) ;used with prio=1
  29205   C(01h) EnqueueSyscallHandler(priority)     ;used with prio=0
  29206   C(02h) SysEnqIntRP(priority,struc)
  29207   C(03h) SysDeqIntRP(priority,struc)
  29208   C(04h) get_free_EvCB_slot()
  29209   C(05h) get_free_TCB_slot()
  29210   C(06h) ExceptionHandler()
  29211   C(07h) InstallExceptionHandlers()  ;destroys/uses k0/k1
  29212   C(08h) SysInitMemory(addr,size)
  29213   C(09h) SysInitKernelVariables()
  29214   C(0Ah) ChangeClearRCnt(t,flag)
  29215   C(0Bh) SystemError  ;PS2: return 0
  29216   C(0Ch) InitDefInt(priority) ;used with prio=3
  29217   C(0Dh) SetIrqAutoAck(irq,flag)
  29218   C(0Eh) return 0               ;DTL-H2000: dev_sio_init
  29219   C(0Fh) return 0               ;DTL-H2000: dev_sio_open
  29220   C(10h) return 0               ;DTL-H2000: dev_sio_in_out
  29221   C(11h) return 0               ;DTL-H2000: dev_sio_ioctl
  29222   C(12h) InstallDevices(ttyflag)
  29223   C(13h) FlushStdInOutPut()
  29224   C(14h) return 0               ;DTL-H2000: SystemError
  29225   C(15h) tty_cdevinput(circ,char)
  29226   C(16h) tty_cdevscan()
  29227   C(17h) tty_circgetc(circ)    ;uses r5 as garbage txt for ioabort
  29228   C(18h) tty_circputc(char,circ)
  29229   C(19h) ioabort(txt1,txt2)
  29230   C(1Ah) set_card_find_mode(mode)  ;0=normal, 1=find deleted files
  29231   C(1Bh) KernelRedirect(ttyflag)   ;PS2: ttyflag=1 causes SystemError
  29232   C(1Ch) AdjustA0Table()
  29233   C(1Dh) get_card_find_mode()
  29234   C(1Eh..7Fh) N/A ;jump_to_00000000h
  29235   C(80h.....) N/A ;mirrors to B(00h.....)
  29236 
  29237 SYS-Functions (Syscall opcode with function number in R4 aka A0 Register)
  29238   SYS(00h) NoFunction()
  29239   SYS(01h) EnterCriticalSection()
  29240   SYS(02h) ExitCriticalSection()
  29241   SYS(03h) ChangeThreadSubFunction(addr) ;syscall with r4=03h, r5=addr
  29242   SYS(04h..FFFFFFFFh) calls DeliverEvent(F0000010h,4000h)
  29243 The 20bit immediate in the "syscall imm" opcode is unused (should be zero).
  29244 
  29245 BREAK-Functions (Break opcode with function number in opcode's immediate)
  29246 BRK opcodes may be used within devkits, however, the standard BIOS simply calls
  29247 DeliverEvent(F0000010h,1000h) and SystemError_A_40h upon any BRK opcodes (as
  29248 well as on any other unresolved exceptions).
  29249   BRK(1C00h) Division by zero (commonly checked/invoked by software)
  29250   BRK(1800h) Division overflow (-80000000h/-1, sometimes checked by software)
  29251 Below breaks are used in DTL-H2000 BIOS:
  29252   BRK(1h) Whatever lockup or so?
  29253   BRK(101h) PCInit()   Inits the fileserver
  29254   BRK(102h) PCCreat(filename, fileattributes)
  29255   BRK(103h) PCOpen(filename, accessmode)
  29256   BRK(104h) PCClose(filehandle)
  29257   BRK(105h) PCRead(filehandle, length, memory_destination_address)
  29258   BRK(106h) PCWrite(filehandle, length, memory_source_address)
  29259   BRK(107h) PClSeek(filehandle, file_offset, seekmode)
  29260   BRK(3C400h) User has typed "break" command in debug console
  29261 The break functions have argument(s) in A1,A2,A3 (ie. unlike normal BIOS
  29262 functions not in A0,A1,A2), and TWO return values (in R2, and R3). These
  29263 functions require a commercial/homebrew devkit... consisting of a Data Cable
  29264 (for accessing the PC's harddisk)... and an Expansion ROM (for handling the
  29265 BREAK opcodes)... or so?
  29266 
  29267 BIOS File Functions
  29268 -------------------
  29269 
  29270 A(00h) or B(32h) - FileOpen(filename, accessmode) - Opens a file for IO
  29271   out: V0  File handle (00h..0Fh), or -1 if error.
  29272 Opens a file on the target device for io. Accessmode is set like this:
  29273   bit0     1=Read  ;\These bits aren't actually used by the BIOS, however, at
  29274   bit1     1=Write ;/least 1 should be set; won't work when all 32bits are zero
  29275   bit2     1=Exit without waiting for incoming data (when TTY buffer empty)
  29276   bit9     0=Open Existing File, 1=Create New file (memory card only)
  29277   bit15    1=Asynchronous mode (memory card only; don't wait for completion)
  29278   bit16-31 Number of memory card blocks for a new file on the memory card
  29279 The PSX can have a maximum of 16 files open at any time, of which, 2 handles
  29280 are always reserved for std_io, so only 14 handles are available for actual
  29281 files. Some functions (chdir, testdevice, FileDelete, FileUndelete,
  29282 FormatDevice, firstfile, FileRename) are temporarily allocating 1 filehandle
  29283 (FileRename tries to use 2 filehandles, but, it does accidently use only 1
  29284 handle, too). So, for example, FileDelete would fail if more than 13 file
  29285 handles are opened by the game.
  29286 
  29287 A(01h) or B(33h) - FileSeek(fd, offset, seektype) - Move the file pointer
  29288    seektype 0 = from start of file        (with positive offset)
  29289             1 = from current file pointer (with positive/negative offset)
  29290             2 = Bugs. Should be from end of file.
  29291 Moves the file pointer the number of bytes in A1, relative to the location
  29292 specified by A2. Movement from the eof is incorrect. Also, movement beyond the
  29293 end of the file is not checked.
  29294 
  29295 A(02h) or B(34h) - FileRead(fd, dst, length) - Read data from an open file
  29296   out: V0  Number of bytes actually read, -1 if failed.
  29297 Reads the number of bytes from the specified open file. If length is not
  29298 specified an error is returned. Read per $0080 bytes from memory card (bu:) and
  29299 per $0800 from cdrom (cdrom:).
  29300 
  29301 A(03h) or B(35h) - FileWrite(fd, src, length) - Write data to an open file
  29302   out: V0  Number of bytes written.
  29303 Writes the number of bytes to the specified open file. Write to the memory card
  29304 per $0080 bytes. Writing to the cdrom returns 0.
  29305 
  29306 A(04h) or B(36h) - FileClose(fd) - Close an open file
  29307 Returns r2=fd (or r2=-1 if failed).
  29308 
  29309 A(08h) or B(3Ah) - FileGetc(fd) - read one byte from file
  29310   out: R2=character (sign-expanded) or FFFFFFFFh=error
  29311 Internally redirects to "FileRead(fd,tempbuf,1)". For some strange reason, the
  29312 returned character is sign-expanded; so, a return value of FFFFFFFFh could mean
  29313 either character FFh, or error.
  29314 
  29315 A(09h) or B(3Bh) - FilePutc(char,fd) - write one byte to file
  29316 Observe that "fd" is the 2nd paramter (not the 1st paramter as usually).
  29317   out:  R2=Number of bytes actually written, -1 if failed
  29318 Internally redirects to "FileWrite(fd,tempbuf,1)".
  29319 
  29320 B(40h) - chdir(name) - Change the current directory on target device
  29321 Changes the current directory on the specified device, which should be "cdrom:"
  29322 (memory cards don't support directories). The PSX supports only a current
  29323 directory, but NOT a current device (ie. after chdir, the directory name may be
  29324 ommited from filenames, but the device name must be still included in all
  29325 filenames).
  29326   in:  A0  Pointer to new directory path (eg. "cdrom:\path")
  29327 Returns 1=okay, or 0=failed.
  29328 The function doesn't verify if the directory exists. Caution: For cdrom, the
  29329 function does always load the path table from the disk (even if it was already
  29330 stored in RAM, so chdir is causing useless SLOW read/seek delays).
  29331 
  29332 B(42h) - firstfile(filename,direntry) - Find first file to match the name
  29333 Returns r2=direntry (or r2=0 if no matching files).
  29334 Searches for the first file to match the specified filename; the filename may
  29335 contain "?" and "*" wildcards. "*" means to ignore ALL following characters;
  29336 accordingly one cannot specify any further characters after the "*" (eg.
  29337 "DATA*" would work, but "*.DAT" won't work). "?" is meant to ignore a single
  29338 character cell. Note: The "?" wildcards (but not "*") can be used also in all
  29339 other file functions; causing the function to use the first matching name (eg.
  29340 FileDelete "????" would erase the first matching file, not all matching files).
  29341 Start the name with the device you want to address. (ie. pcdrv:) Different
  29342 drives can be accessed as normally by their drive names (a:, c:, huh?) if path
  29343 is omitted after the device, the current directory will be used.
  29344 A direntry structure looks like this:
  29345   00h 14h Filename, terminated with 00h
  29346   14h 4   File attribute (always 0 for cdrom) (50h=norm or A0h=del for card)
  29347   18h 4   File size
  29348   1Ch 4   Pointer to next direntry? (not used?)
  29349   20h 4   First Sector Number
  29350   24h 4   Reserved (not used)
  29351 BUG: If "?" matches the ending 00h byte of a name, then any further characters
  29352 in the search expression are ignored (eg. "FILE?.DAT" would match to
  29353 "FILE2.DAT", but accidently also to "FILE").
  29354 BUG: For CDROM, the BIOS includes some code that is intended to realize disk
  29355 changes during firstfile/nextfile operations, however, that code is so bugged
  29356 that it does rather ensure that the BIOS does NOT realize new disks being
  29357 inserted during firstfile/nextfile.
  29358 BUG: firstfile/nextfile is internally using a FCB. On the first call to
  29359 firstfile, the BIOS is searching a free FCB, and does apply that as "search
  29360 fcb", but it doesn't mark that FCB as allocated, so other file functions may
  29361 accidently use the same FCB. Moreover, the BIOS does memorize that "search
  29362 fcb", and, even when starting a new search via another call to firstfile, it
  29363 keeps using that FCB for search (without checking if the FCB is still free). A
  29364 possible workaround is not to have any files opened during firstfile/nextfile
  29365 operations.
  29366 
  29367 B(43h) - nextfile(direntry) - Searches for the next file to match the name
  29368 Returns r2=direntry (or r2=0 if no more matching files).
  29369 Uses the settings of a previous firstfile/nextfile command.
  29370 
  29371 B(44h) - FileRename(old_filename, new_filename)
  29372 Returns 1=okay, or 0=failed.
  29373 
  29374 B(45h) - FileDelete(filename) - Delete a file on target device
  29375 Returns 1=okay, or 0=failed.
  29376 
  29377 B(46h) - FileUndelete(filename)
  29378 Returns 1=okay, or 0=failed.
  29379 
  29380 B(41h) - FormatDevice(devicename)
  29381 Erases all files on the device (ie. for formatting memory cards).
  29382 Returns 1=okay, or 0=failed.
  29383 
  29384 B(54h) - GetLastError()
  29385 Indicates the reason of the most recent file function error (FileOpen,
  29386 FileSeek, FileRead, FileWrite, FileClose, GetLastFileError, FileIoctl, chdir,
  29387 testdevice, FileDelete, FileUndelete, FormatDevice, FileRename). Use
  29388 GetLastError() ONLY if an error has occured (the error code isn't reset to zero
  29389 by functions that are passing okay). firstfile/nextfile do NOT affect
  29390 GetLastError(). See below list of File Error Numbers for more info.
  29391 
  29392 B(55h) - GetLastFileError(fd)
  29393 Basically same as B(54h), but allowing to specify a file handle for which error
  29394 information is to be received; accordingly it doesn't work for functions that
  29395 do use 'hidden' internal file handles (eg. FileDelete, or unsuccessful
  29396 FileOpen). Returns FCB[18h], or FFFFFFFFh if the handle is invalid/unused.
  29397 
  29398 A(05h) or B(37h) FileIoctl(fd,cmd,arg)
  29399 Used only for TTY.
  29400 
  29401 A(07h) or B(39h) FileGetDeviceFlag(fd)
  29402 Returns bit1 of the file's DCB flags. That bit is set only for Duart/TTY, and
  29403 is cleared for Dummy/TTY, Memory Card, and CDROM.
  29404 
  29405 B(59h) - testdevice(devicename)
  29406 Whatever. Checks the devicename, and if it's accepted, calls a device specific
  29407 function. For the existing devices (cdrom,bu,tty) that specific function simply
  29408 returns without doing anything. Maybe other devices (like printers or modems)
  29409 would do something more interesting.
  29410 
  29411 File Error Numbers for B(54h) and B(55h)
  29412   00h okay (though many successful functions leave old error code unchanged)
  29413   02h file not found
  29414   06h bad device port number (tty2 and up)
  29415   09h invalid or unused file handle
  29416   10h general error (physical I/O error, unformatted, disk changed for old fcb)
  29417   11h file already exists error (create/undelete/rename)
  29418   12h tried to rename a file from one device to another device
  29419   13h unknown device name
  29420   16h sector alignment error, or fpos>=filesize, unknown seektype or ioctl cmd
  29421   18h not enough free file handles
  29422   1Ch not enough free memory card blocks
  29423   FFFFFFFFh invalid or unused file handle passed to B(55h) function
  29424 
  29425 BIOS File Execute and Flush Cache
  29426 ---------------------------------
  29427 
  29428 A(41h) - LoadExeHeader(filename, headerbuf)
  29429 Loads the 800h-byte exe file header to an internal sector buffer, and does then
  29430 copy bytes [10h..4Bh] of that header to headerbuf[00h..3Bh].
  29431 
  29432 A(42h) - LoadExeFile(filename, headerbuf)
  29433 Same as LoadExeHeader (see there for details), but additionally loads the body
  29434 of the executable (using the size and destination address in the file header),
  29435 and does call FlushCache. The exe can be then started via DoExecute (this isn't
  29436 done automatically by LoadExeFile). Unlike "LoadAndExecute", the
  29437 "LoadExeFile/DoExecute" combination allows to return the new exe file to return
  29438 to the old exe file (instead of restarting the boot executable).
  29439 BUG: Uses the unstable FlushCache function (see there for details).
  29440 
  29441 A(43h) - DoExecute(headerbuf, param1, param2)
  29442 Can be used to start a previously loaded executable. The function saves
  29443 R16,R28,R30,SP,RA in the reserved region of headerbuf (rather than on stack),
  29444 more or less slowly zerofills the memfill region specified in headerbuf, reads
  29445 the stack base and offset values and sets SP and FP to base+offset (or leaves
  29446 them unchanged if base=0), reads the GP value from headerbuf and sets GP to
  29447 that value. Then calls the excecutables entrypoint, with param1 and param2
  29448 passed in r4,r5.
  29449 If the executable (should) return, then R16,R28,R30,SP,RA are restored from
  29450 headerbuf, and the function returns with r2=1.
  29451 
  29452 A(51h) - LoadAndExecute(filename, stackbase, stackoffset)
  29453 This is a rather bizarre function. In short, it does load and execute the
  29454 specified file, and thereafter, it (tries to) reload and restart to boot
  29455 executable.
  29456 Part1: Takes a copy of the filename, with some adjustments: Everything up to
  29457 the first ":" or 00h byte is copied as is (ie. the device name, if it does
  29458 exist, or otherwise the whole path\filename.ext;ver), the remaining characters
  29459 are copied and converted to uppercase (ie. the path\filename.ext;ver part, or
  29460 none if the device name didn't exist), finally, checks if a ";" exists (ie. the
  29461 version suffix), if there's none, then it appends ";1" as default version.
  29462 CAUTION: The BIOS allocates ONLY 28 bytes on stack for the copy of the
  29463 filename, that region is followed by 4 unused bytes, so the maximum length
  29464 would be 32 bytes (31 characters plus EOL) (eg.
  29465 "device:\pathname\filename.ext;1",00h).
  29466 Part2: Enables IRQs via ExitCriticalSection, memorizes the stack base/offset
  29467 values from the previously loaded executable (which should have been the boot
  29468 executable, unless LoadAndExecute should have been used in nested fashion),
  29469 does then use LoadExeFile to load the desired file, replaces the stack
  29470 base/offset values in its headerbuf by the LoadAndExecute parameter values, and
  29471 does then execute it via DoExecute(headerbuf,1,0).
  29472 Part3: If the exefile returns, or if it couldn't be loaded, then the boot file
  29473 is (unsuccessfully) attempted to be reloaded: Enables IRQs via
  29474 ExitCriticalSection, loads the boot file via LoadExeFile, replaces the stack
  29475 base/offset values in its headerbuf by the values memorized in Part2 (which
  29476 <should> be the boot executable's values from SYSTEM.CNF, unless the nesting
  29477 stuff occurred), and does then execute the boot file via
  29478 DoExecute(headerbuf,1,0).
  29479 Part4: If the boot file returns, or if it couldn't be loaded, then the function
  29480 looks up in a "JMP $" endless loop (normally, returning from the boot exe
  29481 causes SystemErrorBootOrDiskFailure("B",38Ch), however, after using
  29482 LoadAndExecute, this functionality is replaced by the "JMP $" lockup.
  29483 BUG: Uses the unstable FlushCache function (see there for details).
  29484 BUG: Part3 accidently treats the first 4 characters of the exename as memory
  29485 address (causing an invalid memory address exception on address 6F726463h, for
  29486 "cdrom:filename.exe").
  29487 
  29488 A(9Ch) - SetConf(num_EvCB, num_TCB, stacktop)
  29489 Changes the number of EvCBs and TCBs, and the stacktop. That values are usually
  29490 initialized from the settings in the SYSTEM.CNF file, so using this function
  29491 usually shouldn't ever be required.
  29492 The function deallocates all old ExCBs, EvCBs, TCBs (so all Exception handlers,
  29493 Events, and Threads (except the current one) are lost, and all other memory
  29494 that may have been allocated via alloc_kernel_memory(size) is deallocated, too.
  29495 It does then allocate the new control blocks, and enqueue the default handlers.
  29496 Despite of the changed stacktop, the current stack pointer is kept intact, and
  29497 the function returns to the caller.
  29498 
  29499 A(9Dh) - GetConf(num_EvCB_dst, num_TCB_dst, stacktop_dst)
  29500 Returns the number of EvCBs, TCBs, and the initial stacktop. There's no return
  29501 value in the R2 register, instead, the three 32bit return values are stored at
  29502 the specified "dst" addresses.
  29503 
  29504 A(44h) - FlushCache()
  29505 Flushes the Code Cache, so opcodes are ensured to be loaded from RAM. This is
  29506 required when loading program code via DMA (ie. from CDROM) (the cache
  29507 controller apparently doesn't realize changes to RAM that are caused by DMA).
  29508 The LoadExeFile and LoadAndExecute functions are automatically calling
  29509 FlushCache (so FlushCache is required only when loading program code via
  29510 "FileRead" or via "CdReadSector").
  29511 FlushCache may be also required when relocating or modifying program code by
  29512 software (the cache controller doesn't seem to realize modifications to memory
  29513 mirrors, eg. patching the exception handler at 80000080h seems to be work
  29514 without FlushCache, but patching the same bytes at 00000080h doesn't).
  29515 Note: The PSX doesn't have a Data Cache (or actually, it has, but it's misused
  29516 as Fast RAM, mapped to a fixed memory region, and which isn't accessable by
  29517 DMA), so FlushCache isn't required for regions that contain data.
  29518 BUG: The FlushCache function contains a handful of opcodes that do use the k0
  29519 register without having IRQs disabled at that time, if an IRQ occurs during
  29520 those opcodes, then the k0 value gets destroyed by the exception handler,
  29521 causing FlushCache to get trapped in an endless loop.
  29522 One workaround would be to disable all IRQs before calling FlushCache, however,
  29523 the BIOS does internally call the function without IRQs disabled, that applies
  29524 to:
  29525   load_file  A(42h)
  29526   load_exec  A(51h)
  29527   add_device B(47h) (and all "add_xxx_device" functions)
  29528   init_card  B(4Ah)
  29529   and by intro/boot code
  29530 for load_file/load_exec, IRQ2 (cdrom) and IRQ3 (dma) need to be enabled, so the
  29531 "disable all IRQs" workaround cannot be used for that functions, however, one
  29532 can/should disable as many IRQs as possible, ie. everything except IRQ2/IRQ3,
  29533 and all DMA interrupts except DMA3 (cdrom).
  29534 
  29535 Executable Memory Allocation
  29536 LoadExeFile and LoadAndExecute are simply loading the file to the address
  29537 specified in the exe file header. There's absolutely no verification whether
  29538 that memory is (or isn't) allocated via malloc, or if it is used by the boot
  29539 executable, or by the kernel, or if it does contain RAM at all.
  29540 When using the "malloc" function combined with loading exe files, it may be
  29541 recommended not to pass all memory to InitHeap (ie. to keep a memory region
  29542 being reserved for loading executables).
  29543 
  29544 Note
  29545 For more info about EXE files and their headers, see
  29546 --> CDROM File Formats
  29547 
  29548 BIOS CDROM Functions
  29549 --------------------
  29550 
  29551 General File Functions
  29552 CDROMs are basically accessed via normal file functions, with device name
  29553 "cdrom:" (which is an abbreviation for "cdrom0:", anyways, the port number is
  29554 ignored).
  29555 --> BIOS File Functions
  29556 --> BIOS File Execute and Flush Cache
  29557 Before starting the boot executable, the BIOS automatically calls CdInit(), so
  29558 the game doesn't need to do any initializations before using CDROM file
  29559 functions.
  29560 
  29561 Absent CD-Audio Support
  29562 The Kernel doesn't include any functions for playing Audio tracks. Also,
  29563 there's no BIOS function for setting the XA-ADPCM file/channel filter values.
  29564 So CD Audio can be used only by directly programming the CDROM I/O ports.
  29565 
  29566 Asynchronous CDROM Access
  29567 The normal File functions are always using synchroneous access for CDROM (ie.
  29568 the functions do wait until all data is transferred) (unlike as for memory
  29569 cards, accessmode.bit15 cannot be used to activate asynchronous cdrom access).
  29570 However, one can read files in asynchrouneous fashion via CdGetLbn,
  29571 CdAsyncSeekL, and CdAsyncReadSector. CDROM files are non-fragmented, so they
  29572 can be read simply from incrementing sector numbers.
  29573 
  29574 A(A4h) - CdGetLbn(filename)
  29575 Returns the first sector number used by the file, or -1 in case of error.
  29576 BUG: The function accidently returns -1 for the first file in the directory
  29577 (the first file should be a dummy entry for the current or parent directory or
  29578 so, so that bug isn't much of a problem), if the file is not found, then the
  29579 function accidently returns garbage (rather than -1).
  29580 
  29581 A(A5h) - CdReadSector(count,sector,buffer)
  29582 Reads <count> sectors, starting at <sector>, and writes data to <buffer>. The
  29583 read is done in mode=80h (double speed, 800h-bytes per sector). The function
  29584 waits until all sectors are transferred, and does then return the number of
  29585 sectors (ie. count), or -1 in case of error.
  29586 
  29587 A(A6h) - CdGetStatus()
  29588 Retrieves the cdrom status via CdAsyncGetStatus(dst) (see there for details;
  29589 especially for cautions on door-open flag). The function waits until the event
  29590 indicates completion, and does then return the status byte (or -1 in case of
  29591 error).
  29592 
  29593 A(78h) - CdAsyncSeekL(src)
  29594 Issues Setloc and SeekL commands. The parameter (src) is a pointer to a 3-byte
  29595 sector number (MM,SS,FF) (in BCD format).
  29596 The function returns 0=failed, or 1=okay. Completion is indicated by events
  29597 (class=F0000003h, and spec=20h, or 8000h).
  29598 
  29599 A(7Ch) - CdAsyncGetStatus(dst)
  29600 Issues a GetStat command. The parameter (dst) is a pointer to a 1-byte location
  29601 that receives the status response byte.
  29602 The function returns 0=failed, or 1=okay. Completion is indicated by events
  29603 (class=F0000003h, and spec=20h, or 8000h).
  29604 Caution: The command acknowledges the door-open flag, but doesn't automatically
  29605 reload the path table (which is required if a new disk is inserted); if the
  29606 door-open flag was set, one should call a function that does forcefully load
  29607 the path table (like chdir).
  29608 
  29609 A(7Eh) - CdAsyncReadSector(count,dst,mode)
  29610 Issues SetMode and ReadN (when mode.bit8=0), or ReadS (when mode.bit8=1)
  29611 commands. count is the number of sectors to be read, dst is the destination
  29612 address in RAM, mode.bit0-7 are passed as parameter to the SetMode command,
  29613 mode.bit8 is the ReadN/ReadS flag (as described above). The sector size (for
  29614 DMA) depends on the mode value: 918h-bytes (bit4=1, bit5=X), 924h-bytes
  29615 (bit4=0, bit5=1), or 800h-bytes (bit4,5=0).
  29616 Before CdAsyncReadSector, the sector number should be set via
  29617 CdAsyncSeekL(src).
  29618 The function returns 0=failed, or 1=okay. Completion is indicated by events
  29619 (class=F0000003h, and spec=20h, 80h, or 8000h).
  29620 
  29621 A(81h) - CdAsyncSetMode(mode)
  29622 Similar to CdAsyncReadSector (see there for details), but issues only the
  29623 SetMode command, without any following ReadN/ReadS command.
  29624 
  29625 A(94h) - CdromGetInt5errCode(dst1,dst2)
  29626 Returns the first two response bytes from the most recent INT5 error:
  29627 [dst1]=status, [dst2]=errorcode. The BIOS doesn't reset these values in case of
  29628 successful completion, so the values are quite useless.
  29629 
  29630 A(54h) or A(71h) - CdInit()
  29631 A(56h) or A(72h) - CdRemove()
  29632 A(90h) - CdromIoIrqFunc1()
  29633 A(91h) - CdromDmaIrqFunc1()
  29634 A(92h) - CdromIoIrqFunc2()
  29635 A(93h) - CdromDmaIrqFunc2()
  29636 A(95h) - CdInitSubFunc()  ;subfunction for CdInit()
  29637 A(9Eh) - SetCdromIrqAutoAbort(type,flag)
  29638 A(A2h) - EnqueueCdIntr()  ;with prio=0 (fixed)
  29639 A(A3h) - DequeueCdIntr()
  29640 Internally used CDROM functions for initialization and IRQ handling.
  29641 
  29642 BIOS Memory Card Functions
  29643 --------------------------
  29644 
  29645 General File Functions
  29646 Memory Cards aka Backup Units (bu) are basically accessed via normal file
  29647 functions, with device names "bu00:" (Slot 1) and "bu10:" (Slot 2),
  29648 --> BIOS File Functions
  29649 Before using the file functions for memory cards, first call
  29650 InitCard(pad_enable), then StartCard(), and then _bu_init().
  29651 
  29652 File Header, Filesize, and Sector Alignment
  29653 The first 100h..200h bytes (2..4 sectors) of the file must contain the title
  29654 and icon bitmap(s). For details, see:
  29655 --> Memory Card Data Format
  29656 The filesize must be a multiple of 2000h bytes (one block), the maximum size
  29657 would be 1E000h bytes (when using all 15 blocks on the memory card). The
  29658 filesize must be specified when creating the file (ie. accessmode bit9=1, and
  29659 bit16-31=number of blocks). Once when the file is created, the BIOS does NOT
  29660 allow to change the filesize (unless by deleting and re-creating the file).
  29661 When reading/writing files, the amount of data must be a multiple of 80h bytes
  29662 (one sector), and the file position must be aligned to a 80h-byte boundary,
  29663 too. There's no restriction on fragmented files (ie. one may cross 2000h-byte
  29664 block boundaries within the file).
  29665 
  29666 Poor Memcard Performance
  29667 PSX memory card accesses are typically super-slow. That, not so much because
  29668 the hardware would be slow, but rather because of improper inefficent code at
  29669 the BIOS side. The original BIOS tries to synchronize memory card accesses with
  29670 joypad accesses simply by accessing only one sector per frame (although it
  29671 could access circa two sectors). To the worst, the BIOS accesses Slot 1 only on
  29672 each second frame, and Slot 2 only each other frame (although in 99% of all
  29673 cases only one slot is accessed at once, so the access time drops to 0.5
  29674 sectors per frame).
  29675 Moreover, the memory card id, directory, and broken sector list do occupy 26
  29676 sectors (although the whole information would fit into 4 or 5 sectors) (a
  29677 workaround would be to read only the first some bytes, and to skip the
  29678 additional unused bytes - though that'd also mean to skip the checksums which
  29679 are unfortunately stored at the end of the sector).
  29680 And, anytime when opening a file (in synchronous mode), the BIOS does
  29681 additionally read sector 0 (which is totally useless, and gets especially slow
  29682 when opening a bunch of files; eg. when extracting the title/icon from all
  29683 available files on the card).
  29684 
  29685 Asynchronous Access
  29686 The BIOS supports synchronous and asynchronous memory card access. Synchronous
  29687 means that the BIOS function doesn't return until the access has completed
  29688 (which means, due to the poor performance, that the function spends about 75%
  29689 of the time on inactivity) (except in nocash PSX bios, which has better
  29690 performance), whilst asynchronous access means that the BIOS function returns
  29691 immediately after invoking the access (which does then continue on interrupt
  29692 level, and does return an event when finished).
  29693 The file "FileRead" and "FileWrite" functions act asynchronous when accessmode
  29694 bit15 is set when opening the file. Additionally, the A(ACh)
  29695 _card_async_load_directory(port) function can be used to tell the BIOS to load
  29696 the directory entries and broken sector list to its internal RAM buffers (eg.
  29697 during the games title screen, so the BIOS doesn't need to load that data once
  29698 when the game enters its memory card menu). All other functions like FileDelete
  29699 or FormatDevice always act synchronous. The FileOpen/findfirst/findnext
  29700 functions do normally complete immediately without accessing the card at all
  29701 (unless the directory wasn't yet read; in that case the directory is loading in
  29702 synchronous fashion).
  29703 Unfortunately, the asynchronous response doesn't rely on a single callback
  29704 event, but rather on a bunch of different events which must be all allocated
  29705 and tested by the game (and of which, one event is delivered on completion)
  29706 (which one depends on whether function completed okay, or if an error
  29707 occurred).
  29708 
  29709 Multitap Support (and Multitap Problems)
  29710 The BIOS does have some partial support for accessing more than two memory
  29711 cards (via Multitap adaptors). Device/port names "bu01:", "bu02:", "bu03:"
  29712 allow to access extra memory carts in slot1 (and "bu11:", "bu12:", "bu13:" in
  29713 slot2). Namely, those names will send values 82h, 83h, 84h to the memory card
  29714 slot (instead of the normal 81h value).
  29715 However, the BIOS directory_buffer and broken_sector_list do support only two
  29716 memory cards (one in slot1 and one in slot2). So, trying to access more memory
  29717 cards may cause great data corruption (though there might be a way to get the
  29718 BIOS to reload those buffers before accessing a different memory card).
  29719 Aside from that problem, the BIOS functions are very-very-very slow even when
  29720 accessing only two memory cards. Trying to use the BIOS to access up to eight
  29721 memory cards would be very-extremly-very slow, which would be more annoying
  29722 than useful.
  29723 
  29724 B(4Ah) - InitCard(pad_enable)  ;uses/destroys k0/k1 !!!
  29725 B(4Bh) - StartCard()
  29726 B(4Ch) - StopCard()
  29727 A(55h) or A(70h) - _bu_init()
  29728 
  29729   --- Below are some lower level memory card functions ---
  29730 
  29731 A(ABh) - _card_info(port)
  29732 B(4Dh) - _card_info_subfunc(port)  ;subfunction for "_card_info"
  29733 Can be used to check if the most recent call to write_card_sector has completed
  29734 okay. Issues an incomplete dummy read command (similar to B(4Fh) -
  29735 read_card_sector). The read command is aborted once when receiving the status
  29736 byte from the memory card (the actual data transfer is skipped).
  29737 
  29738 A(AFh) - card_write_test(port)  ;not supported by old CEX-1000 version
  29739 Resets the card changed flag. For some strange reason, this flag isn't
  29740 automatically reset after reading the flag, instead, the flag is reset upon
  29741 sector writes. To do that, this function issues a dummy write to sector 3Fh.
  29742 
  29743 B(50h) - allow_new_card()
  29744 Normally any memory card read/write functions fail if the BIOS senses the card
  29745 change flag to be set. Calling this function tells the BIOS to ignore the card
  29746 change flag on the next read/write operation (the function is internally used
  29747 when loading the "MC" ID from sector 0, and when calling the card_write_test
  29748 function to acknowledge the card change flag).
  29749 
  29750 B(4Eh) - write_card_sector(port,sector,src)
  29751 B(4Fh) - read_card_sector(port,sector,dst)
  29752 Invokes asynchronous reading/writing of a single sector. The function returns
  29753 1=okay, or 0=failed (on invalid sector numbers). The actual I/O is done on IRQ
  29754 level, completion of the I/O command transmission can be checked, among others,
  29755 via get/wait_card_status(slot) functions (with slot=port/10h).
  29756 In case of the write function, completion of the <transmission> does NOT mean
  29757 that the actual <writing> has completed, instead, write errors are indicated
  29758 upon completion of the <next sector> read/write transmission (or, if there are
  29759 no further sectors to be accessed; one can use _card_info to verify completion
  29760 of the last written sector).
  29761 The sector number should be in range of 0..3FFh, for some strange reason,
  29762 probably a BUG, the function also accepts sector 400h. The specified sector
  29763 number is directly accessed (it is NOT parsed through the broken sector
  29764 replacement list).
  29765 
  29766 B(5Ch) - get_card_status(slot)
  29767 B(5Dh) - wait_card_status(slot)
  29768 Returns the status of the most recent I/O command, possible values are:
  29769   01h=ready
  29770   02h=busy/read
  29771   04h=busy/write
  29772   08h=busy/info
  29773   11h=failed/timeout (eg. when no cartridge inserted)
  29774   21h=failed/general error
  29775 get_card_status returns immediately, wait_card_status waits until a non-busy
  29776 state occurs.
  29777 
  29778 A(A7h) - bu_callback_okay()
  29779 A(A8h) - bu_callback_err_write()
  29780 A(A9h) - bu_callback_err_busy()
  29781 A(AAh) - bu_callback_err_eject()
  29782 A(AEh) - bu_callback_err_prev_write()
  29783 These five callback functions are internally used by the BIOS, notifying other
  29784 BIOS functions about (un-)successful completion of memory card I/O commands.
  29785 
  29786 B(58h) - get_bu_callback_port()
  29787 This is a subfunction for the five bu_callback_xxx functions (indicating
  29788 whether the callback occured for a slot1 or slot2 access).
  29789 
  29790 A(ACh) - _card_async_load_directory(port)
  29791 Invokes asynchronous reading of the memory card directory. The function isn't
  29792 too useful because the BIOS tends to read the directory automatically in
  29793 various places in synchronous mode, so there isn't too much chance to replace
  29794 the automatic synchronous reading by asynchronous reading.
  29795 
  29796 A(ADh) - set_card_auto_format(flag)
  29797 Can be used to enable/disable auto format (0=off, 1=on). The _bu_init function
  29798 initializes auto format as disabled. If auto format is enabled, then the BIOS
  29799 does automatically format memory cards if it has failed to read the "MC" ID
  29800 bytes on sector 0. Although potentially useful, activating this feature is
  29801 rather destructive (for example, read errors on sector 0 might occur accidently
  29802 due to improperly inserted cards with dirty contacts, so it'd be better to
  29803 prompt the user whether or not to format the card, rather than doing that
  29804 automatically).
  29805 
  29806 C(1Ah) - set_card_find_mode(mode)
  29807 C(1Dh) - get_card_find_mode()
  29808 Allows to get/set the card find mode (0=normal, 1=find deleted files), the mode
  29809 setting affects only the firstfile/nextfile functions. All other file functions
  29810 are used fixed mode settings (always mode=0 for FileOpen, FileRename,
  29811 FileDelete, and mode=1 for FileUndelete).
  29812 
  29813 BIOS Interrupt/Exception Handling
  29814 ---------------------------------
  29815 
  29816 The Playstation's Kernel uses an uncredible inefficient and unstable exception
  29817 handler; which may have been believed to be very powerful and flexible.
  29818 
  29819 Inefficiency
  29820 For a maximum of slowness, it does always save and restore all CPU registers
  29821 (including such that aren't used in the exception handler). It does then go
  29822 through a list of installed interrupt handlers - and executes ALL of them. For
  29823 example, a Timer0 IRQ is first passed to the Cdrom and Vblank handlers (which
  29824 must reject it, no thanks), before it does eventually reach the Timer0 handler.
  29825 
  29826 Unstable IRQ Handling
  29827 A fundamental mistake in the exception handler is that it doesn't memorize the
  29828 incoming IRQ flags. So the various interrupt handlers must check Port 1F801070h
  29829 one after each other. That means, if a high priority handler has rejected IRQ
  29830 processing (because the desired IRQ flag wasn't set at that time), then a lower
  29831 priority handler may process it (assuming that the IRQ flag got set in the
  29832 meantime), and, in worst case it may even acknowledge it (so the high priority
  29833 handler does never receive it).
  29834 To avoid such problems, there should be only ONE handler installed for each IRQ
  29835 source. However, that isn't always possible because the Kernel automatically
  29836 installs some predefined handlers. Most noteworthy, the totally bugged
  29837 DefaultInterruptHandlers is always installed (and cannot be removed), so it
  29838 does randomly trigger Events. Fortunately, it does not acknowledge the IRQs
  29839 (unless SetIrqAutoAck was used to enable that fatal behaviour).
  29840 
  29841 B(18h) - SetDefaultExitFromException()
  29842 Applies the default "Exit" structure (which consists of a pointer to
  29843 ReturnFromException, and the Kernel's exception stacktop (minus 4, for whatever
  29844 reason), and zeroes for the R16..R23,R28,R30 registers. Returns the address of
  29845 that structure.
  29846 See SetCustomExitFromException for details.
  29847 
  29848 B(19h) - SetCustomExitFromException(addr)
  29849 addr points to a structure (with same format as for the SaveState function):
  29850   00h 4    r31/ra,pc ;usually ptr to ReturnFromException function
  29851   04h 4    r28/sp    ;usually exception stacktop, minus 4, for whatever reason
  29852   08h 4    r30/fp    ;usually 0
  29853   0Ch 4x8  r16..r23  ;usually 0
  29854   2Ch 4    r28/gp    ;usually 0
  29855 The hook function is executed only if the ExceptionHandler has been fully
  29856 executed (after processing an IRQ, many interrupt handlers are calling
  29857 ReturnFromException to abort further exception handling, and thus do skip the
  29858 hook function). Once when the hook function has finished, it should execute
  29859 ReturnFromException. The hook function is called with r2=1 (that is important
  29860 if the hook address was recorded with SaveState, where it "returns" to the
  29861 SaveState caller, with r2 as "return value").
  29862 
  29863 Priority Chains
  29864 The Kernel's exception handler has four priority chains, each may contain one
  29865 or more Interrupt or Exception handlers. The default handlers are:
  29866   Prio Chain Content
  29867   0    CdromDmaIrq, CdromIoIrq, SyscallException
  29868   1    CardSpecificIrq, VblankIrq, Timer2Irq, Timer1Irq, Timer0Irq
  29869   2    PadCardIrq
  29870   3    DefInt
  29871 The exception handler calls all handlers, starting with the first element in
  29872 the priority 0 chain (ie. usually CdromDmaIrq). The separate handlers must
  29873 check if they want to process the IRQ (eg. CdromDmaIrq would process only CDROM
  29874 DMA IRQs, but not joypad IRQs or so). If it has processed and acknowledged the
  29875 IRQ, then the handler may execute ReturnFromException, which causes the
  29876 handlers of lower priority to be skipped (if there are still other
  29877 unacknowledge IRQs pending, then the hardware will re-enter the exception
  29878 handler as soon as the RFE opcode in ReturnFromException does re-enable
  29879 interrupts).
  29880 
  29881 C(02h) - SysEnqIntRP(priority,struc)
  29882 Inserts a new element in the specified priority chain. The new element is
  29883 inserted at the begin of the chain, so (within that priority chain) the new
  29884 element has highest priority.
  29885   00h 4  pointer to next element    (0=none)  ;this pointer is inserted by BIOS
  29886   04h 4  pointer to SECOND function (0=none)  ;executed if func1 returns r2<>0
  29887   08h 4  pointer to FIRST  function (0=none)  ;executed first
  29888   0Ch 4  Not used (usually zero)
  29889 
  29890 XXX...
  29891 The BIOS seems to be occassionally adding/removing the "CardSpecificIrq" and
  29892 "PadCardIrq" (with priority 1 and 2). DequeueCdIntr and CdRemove remove
  29893 priority 0 elements.
  29894 
  29895 C(03h) - SysDeqIntRP(priority,struc)
  29896 Removes the specified element from the specified priority chain. Returns
  29897 r2=struc (or 0 if the struc didn't exist in the chain).
  29898 Note: The function contains several nonsense opcodes that are never executed
  29899 (they are skipped via conditional jumps with fixed "jump always" condition).
  29900 
  29901 SYS(01h) - EnterCriticalSection()  ;syscall with r4=01h
  29902 Disables interrupts by clearing SR (cop0r12) Bit 2 and 10 (of which, Bit2 gets
  29903 copied to Bit0 once when returning from the syscall exception). Returns 1 if
  29904 both bits were set, returns 0 if one or both of the bits were already zero.
  29905 
  29906 SYS(02h) - ExitCriticalSection()   ;syscall with r4=02h
  29907 Enables interrupts by set SR (cop0r12) Bit 2 and 10 (of which, Bit2 gets copied
  29908 to Bit0 once when returning from the syscall exception). There's no return
  29909 value (all registers except SR and K0 are unchanged).
  29910 
  29911 C(0Dh) - SetIrqAutoAck(irq,flag)
  29912 Specifies if the DefaultInterruptHandler shall automatically acknowledge IRQs.
  29913 The "irq" paramter is the number of the interrupt, ie. 00h..0Ah = IRQ0..IRQ10.
  29914 The "flag" value should be 0 to disable AutoAck, or non-zero to enable AutoAck.
  29915 By default, AutoAck is disabled for all IRQs.
  29916 Mind that the DefaultInterruptHandler is totally bugged. Especially the AutoAck
  29917 feature doesn't work very well: It may cause higher priority handlers to miss
  29918 their IRQ, and it may even cause the DefaultInterruptHandler to miss its own
  29919 IRQs.
  29920 
  29921 C(06h) - ExceptionHandler()
  29922 The C(06h) vector points to the exception handler, ie. to the function that is
  29923 invoked from the 4 opcodes at address 80000080h, that opcodes jump directly to
  29924 the exception handler, so patching the C(06h) vector has no effect.
  29925 Reading the C(06h) entry can be used to let a custom 80000080h handler pass
  29926 control back to the default handler (that, by a "direct" jump, not by the usual
  29927 "MOV R9,06h / CALL 0C0h" method, which would destroy main programs R9
  29928 register).
  29929 Also, reading C(06h) may be useful for patching the exception handler (which
  29930 contains a bunch of NOP opcodes, which seem to be intended to insert additional
  29931 opcodes, such like debugger exception handling) (Note: some of that NOPs are
  29932 reserved for Memory Card IRQ handling).
  29933 BUG: Early BIOS versions did try to examine a copy of cop0r13 in r2 register,
  29934 but did forgot cop0r13 to r2 (so they examined garbage), this was fixed in
  29935 newer BIOS versions, additionally, most commercial games still include patches
  29936 for compatibility with the old BIOS.
  29937 
  29938 B(17h) - ReturnFromException()
  29939 Restores the CPU registers (R1-R31,HI,LO,SR,PC) (except R26/K0) from the
  29940 current TCB. This function is usually executed automatically at the end of the
  29941 ExceptionHandler, however, functions in the exception chain may call
  29942 ReturnFromException to return immediately, without processing chain elements of
  29943 lower priority.
  29944 
  29945 C(00h) - EnqueueTimerAndVblankIrqs(priority) ;used with prio=1
  29946 C(01h) - EnqueueSyscallHandler(priority) ;used with prio=0
  29947 C(0Ch) - InitDefInt(priority) ;used with prio=3
  29948 Internally used to add some default IRQ and Exception handlers.
  29949 
  29950 No Nested Exceptions
  29951 The Kernel doesn't support nested exceptions, that would require a decreasing
  29952 exception stack, however, the kernel saves the incoming CPU registers in the
  29953 current TCB, and an exception stack with fixed start address for internal
  29954 push/pop during exception handling. So, nesting would overwrite these values.
  29955 Do not enable IRQs, and don't trap other exceptions (like break or syscall
  29956 opcodes, or memory or overlow errors) during exception handling.
  29957 Note: The execption stack has a fixed size of 1000h bytes (and is located
  29958 somewhere in the first 64Kbytes of memory).
  29959 
  29960 BIOS Event Functions
  29961 --------------------
  29962 
  29963 B(08h) - OpenEvent(class, spec, mode, func)
  29964 Adds an event structure to the event table.
  29965      class,spec - triggers if BOTH values match
  29966      mode - (1000h=execute function/stay busy, 2000h=no func/mark ready)
  29967      func - Address of callback function (0=None) (used only when mode=1000h)
  29968   out: R2 = Event descriptor (F1000000h and up), or FFFFFFFFh if failed
  29969 Opens an event, should be called within a critical section. The return value is
  29970 used to identify the event to the other event functions. A list of event
  29971 classes, specs and modes is at the end of this section. Initially, the event is
  29972 disabled.
  29973 Note: The desired max number of events can be specified in the SYSTEM.CNF boot
  29974 file (the default is "EVENT = 10" (which is a HEX number, ie. 16 decimal; of
  29975 which 5 events are internally used by the BIOS for CDROM functions, so, of the
  29976 16 events, only 11 events are available to the game). A bigger amount of events
  29977 will slowdown the DeliverEvent function (which always scans all EvCBs, even if
  29978 all events are disabled).
  29979 
  29980 B(09h) - CloseEvent(event) - releases event from the event table
  29981 Always returns 1 (even if the event handle is unused or invalid).
  29982 
  29983 B(0Ch) - EnableEvent(event) - Turns on event handling for specified event
  29984 Always returns 1 (even if the event handle is unused or invalid).
  29985 
  29986 B(0Dh) - DisableEvent(event) - Turns off event handling for specified event
  29987 Always returns 1 (even if the event handle is unused or invalid).
  29988 
  29989 B(0Ah) WaitEvent(event)
  29990 Returns 0 if the event is disabled. Otherwise hangs in a loop until the event
  29991 becomes ready, and returns 1 once when it is ready (and automatically switches
  29992 the event back to busy status). Callback events (mode=1000h) do never set the
  29993 ready flag (and thus WaitEvent would hang forever).
  29994 The main program simply hangs during the wait, so when using multiple threads,
  29995 it may be more recommended to create an own waitloop that checks TestEvent, and
  29996 to call ChangeThread when the event is busy.
  29997 BUG: The return value is unstable (sometimes accidently returns 0=disabled if
  29998 the event status changes from not-ready to ready shortly after the function
  29999 call).
  30000 
  30001 B(0Bh) TestEvent(event)
  30002 Returns 0 if the event is busy or disabled. Otherwise, when it is ready,
  30003 returns 1 (and automatically switches the event back to busy status). Callback
  30004 events (mode=1000h) do never set the ready flag.
  30005 
  30006 B(07h) DeliverEvent(class, spec)
  30007 This function is usually called by the kernel, it triggers all events that are
  30008 enabled/busy, and that have the specified class and spec values. Depending on
  30009 the mode, either the callback function is called (mode=1000h), or the event is
  30010 marked as enabled/ready (mode=2000h).
  30011 
  30012 B(20h) UnDeliverEvent(class, spec)
  30013 This function is usually called by the kernel, undelivers all events that are
  30014 enabled/ready, and that have mode=2000h, and that have the specified class and
  30015 spec values. Undeliver means that the events are marked as enabled/busy.
  30016 
  30017 C(04h) get_free_EvCB_slot()
  30018 A subfunction for OpenEvent.
  30019 
  30020 Event Classes
  30021 File Events:
  30022   0000000xh memory card (for file handle fd=x)
  30023 Hardware Events:
  30024   F0000001h IRQ0  VBLANK
  30025   F0000002h IRQ1  GPU
  30026   F0000003h IRQ2  CDROM Decoder
  30027   F0000004h IRQ3  DMA controller
  30028   F0000005h IRQ4  RTC0 (timer0)
  30029   F0000006h IRQ5/IRQ6 RTC1 (timer1 or timer2)
  30030   F0000007h N/A   Not used (this should be timer2)
  30031   F0000008h IRQ7  Controller (joypad/memcard)
  30032   F0000009h IRQ9  SPU
  30033   F000000Ah IRQ10 PIO ;uh, does the PIO have an IRQ signal? (IRQ10 is joypad)
  30034   F000000Bh IRQ8  SIO
  30035   F0000010h Exception ;CPU crashed (BRK,BadSyscall,Overflow,MemoryError, etc.)
  30036   F0000011h memory card (lower level BIOS functions)
  30037   F0000012h memory card (not used by BIOS; maybe used by Sony's devkit?)
  30038   F0000013h memory card (not used by BIOS; maybe used by Sony's devkit?)
  30039 Event Events:
  30040   F1xxxxxxh event (not used by BIOS; maybe used by Sony's devkit?)
  30041 Root Counter Events (Timers and Vblank):
  30042   F2000000h Root counter 0 (Dotclock)                    (hardware timer)
  30043   F2000001h Root counter 1 (horizontal retrace?)         (hardware timer)
  30044   F2000002h Root counter 2 (one-eighth of system clock)  (hardware timer)
  30045   F2000003h Root counter 3 (vertical retrace?) (this is a software timer)
  30046 User Events:
  30047   F3xxxxxxh user (not used by BIOS; maybe used by games and/or Sony's devkit?)
  30048 BIOS Events (including such that have nothing to do with BIOS):
  30049   F4000001h memory card (higher level BIOS functions)
  30050   F4000002h libmath (not used by BIOS; maybe used by Sony's devkit?)
  30051 Thread Events:
  30052   FFxxxxxxh thread (not used by BIOS; maybe used by Sony's devkit?)
  30053 
  30054 Event Specs
  30055   0001h counter becomes zero
  30056   0002h interrupted
  30057   0004h end of i/o
  30058   0008h file was closed
  30059   0010h command acknowledged
  30060   0020h command completed
  30061   0040h data ready
  30062   0080h data end
  30063   0100h time out
  30064   0200h unknown command
  30065   0400h end of read buffer
  30066   0800h end of write buffer
  30067   1000h general interrupt
  30068   2000h new device
  30069   4000h system call instruction ;SYS(04h..FFFFFFFFh)
  30070   8000h error happened
  30071   8001h previous write error happened
  30072   0301h domain error in libmath
  30073   0302h range error in libmath
  30074 
  30075 Event modes
  30076   1000h Execute callback function, and stay busy (do NOT mark event as ready)
  30077   2000h Do NOT execute callback function, and mark event as ready
  30078 
  30079 BIOS Event Summary
  30080 ------------------
  30081 
  30082 Below is a list of all events (class,spec values) that are delivered and/or
  30083 undelivered by the BIOS in one way or another. The BIOS does internally open
  30084 five events for cdrom (class=F0000003h with spec=10h,20h,40h,80h,8000h). The
  30085 various other class/spec's are only delivered by the BIOS (but not received by
  30086 the BIOS) (ie. a game may open/enable memory card events to receive
  30087 notifications from the BIOS).
  30088 
  30089 CDROM Events
  30090   F0000003h,10h  cdrom DMA finished (all sectors finished)
  30091   F0000003h,20h  cdrom ?
  30092   F0000003h,40h  cdrom dead feature (delivered only by unused functions)
  30093   F0000003h,80h  cdrom INT4 (reached end of disk)
  30094   F0000003h,100h         n/a ?  ;undelivered, but not opened, nor delivered
  30095   F0000003h,200h                ;undelivered, but not opened
  30096   F0000003h,8000h
  30097 
  30098 Memory Card - Higher Level File/Device Events
  30099   0000000xh,4     card file handle (x=fd) done okay
  30100   F4000001h,4     card done okay (len=0)
  30101   F4000001h,100h  card err busy  ;A(A9h)
  30102   F4000001h,2000h card err eject ;A(AAh) or unformatted (bad "MC" id)
  30103   F4000001h,8000h card err write ;A(A8h) or A(AEh) or general error
  30104 
  30105 Memory Card - Lower Level Hardware I/O Events
  30106   F0000011h,4      finished okay
  30107   F0000011h,100h   err busy
  30108   F0000011h,200h     n/a ?
  30109   F0000011h,2000h  err
  30110   F0000011h,8000h  err
  30111   F0000011h,8001h  err (this one is NOT undelivered!)
  30112 
  30113 Timer/Vblank Events
  30114   F2000000h,2   Timer0 (IRQ4)
  30115   F2000001h,2   Timer1 (IRQ5)
  30116   F2000002h,2   Timer2 (IRQ6)
  30117   F2000003h,2   Vblank (IRQ0) (unstable since IRQ0 is also used for joypad)
  30118 
  30119 Default IRQ Handler Events (very unstable, don't use)
  30120   F0000001h,1000h ;IRQ0  (VBLANK)
  30121   F0000002h,1000h ;IRQ1  (GPU)
  30122   F0000003h,1000h ;IRQ2  (CDROM)
  30123   F0000004h,1000h ;IRQ3  (DMA)
  30124   F0000005h,1000h ;IRQ4  (TMR0)
  30125   F0000006h,1000h ;IRQ5  (TMR1)
  30126   F0000006h,1000h ;IRQ6  (TMR2) (accidently uses same event as TMR1)
  30127   F0000008h,1000h ;IRQ7  (joypad/memcard)
  30128   F0000009h,1000h ;IRQ9  (SPU)
  30129   F000000Ah,1000h ;IRQ10 (Joypad and PIO)
  30130   F000000Bh,1000h ;IRQ8  (SIO)
  30131 
  30132 Unresolved Exception Events
  30133   F0000010h,1000h unknown exception ;neither IRQ nor SYSCALL
  30134   F0000010h,4000h unknown syscall   ;syscall(04h..FFFFFFFFh)
  30135 
  30136 BIOS Thread Functions
  30137 ---------------------
  30138 
  30139 B(0Eh) OpenThread(reg_PC,reg_SP_FP,reg_GP)
  30140 Searches a free TCB, marks it as used, and stores the inital program counter
  30141 (PC), global pointer (GP aka R28), stack pointer (SP aka R29), and frame
  30142 pointer (FP aka R30) (using the same value for SP and FP). All other registers
  30143 are left uninitialized (eg. may contain values from an older closed thread,
  30144 that includes the SR register, see note).
  30145 The return value is the new thread handle (in range FF000000h..FF000003h,
  30146 assuming that 4 TCBs are allocated) or FFFFFFFFh if there's no free TCB. The
  30147 function returns to the old current thread, use "ChangeThread" to switch to the
  30148 new thread.
  30149 Note: The desired max number of TCBs can be specified in the SYSTEM.CNF boot
  30150 file (the default is "TCB = 4", one initially used for the boot executable,
  30151 plus 3 free threads).
  30152 
  30153 BUG - Unitialized SR Register
  30154 OpenThread does NOT initialize the SR register (cop0r12) of the new thread.
  30155 Upon powerup, the bootcode zerofills the TCB memory (so, the SR of new threads
  30156 will be initially zero; ie. Kernel Mode, IRQ's disabled, and COP2 disabled).
  30157 However, when closing/reopening threads, the SR register will have the value of
  30158 the old closed thread (so it may get started with IRQs enabled, and, in worst
  30159 case, if the old thread should have switched to User Mode, even without access
  30160 to KSEG0, KSEG1 memory).
  30161 Or, ACTUALLY, the memory is NOT zerofilled on powerup... so SR is total random?
  30162 
  30163 B(0Fh) CloseThread(handle)
  30164 Marks the TCB for the specified thread as unused. The function can be used for
  30165 any threads, including for the current thread.
  30166 Closing the current thread doesn't terminate the current thread, so it may
  30167 cause problems once when opening a new thread, however, it should be stable to
  30168 execute the sequence "DisableInterrupts, CloseCurrentThread,
  30169 ChangeOtherThread".
  30170 The return value is always 1 (even if the handle was already closed).
  30171 
  30172 B(10h) ChangeThread(handle)
  30173 Pauses the current thread, and activates the selected new thread (or crashes if
  30174 the specified handle was unused or invalid).
  30175 The return value is always 1 (stored in the R2 entry of the TCB of the old
  30176 thread, so the return value will be received once when changing back to the old
  30177 thread).
  30178 Note: The BIOS doesn't automatically switch from one thread to another. So, all
  30179 other threads remain paused until the current thread uses ChangeThread to pass
  30180 control to another thread.
  30181 Each thread is having it's own CPU registers (R1..R31,HI,LO,SR,PC), the
  30182 registers are stored in the TCB of the old thread, and restored when switching
  30183 back to that thread. Mind that other registers (I/O Ports or GTE registers
  30184 aren't stored automatically, so, when needed, they need to be pushed/popped by
  30185 software before/after ChangeThread).
  30186 
  30187 C(05h) get_free_TCB_slot()
  30188 Subfunction for OpenThread, returns the number of the first free TCB (usually
  30189 in range 0..3) or FFFFFFFFh if there's no free TCB.
  30190 
  30191 SYS(03h) ChangeThreadSubFunction(addr) ;syscall with r4=03h, r5=addr
  30192 Subfunction for ChangeThread, R5 contains the address of the new TCB, just like
  30193 all exceptions, the syscall exception is saving the CPU registers in the
  30194 current TCB, but does then apply the new TCB as current TCB, and so, it does
  30195 then enter the new thread when returning from the exception.
  30196 
  30197 BIOS Timer Functions
  30198 --------------------
  30199 
  30200 Timers (aka Root Counters)
  30201 The three hardware timers aren't internally used by any BIOS functions, so they
  30202 can be freely used by the game, either via below functions, or via direct I/O
  30203 access.
  30204 
  30205 Vblank
  30206 Some of the below functions are allowing to use Vblank IRQs as a fourth
  30207 "timer". However, Vblank IRQs are internally used by the BIOS for handling
  30208 joypad and memory card accesses. One could theoretically use two separate
  30209 Vblank IRQ handlers, one for joypad, and one as "timer", but the BIOS is much
  30210 too unstable for such "shared" IRQ handling (it may occassionally miss one of
  30211 the two handlers).
  30212 So, although Vblank IRQs are most important for games, the PSX BIOS doesn't
  30213 actually allow to use them for purposes other than joypad access. A possible
  30214 workaround is to examine the status byte in one of the joypad buffers (ie. the
  30215 InitPad(buf1,22h,buf2,22h) buffers). Eg. a wait_for_vblank function could look
  30216 like so: set buf1[0]=55h, then wait until buf1[0]=00h or buf1[0]=FFh.
  30217 
  30218 B(02h) init_timer(t,reload,flags)
  30219 When t=0..2, resets the old timer mode by setting [1F801104h+t*16]=0000h,
  30220 applies the reload value by [1F801108h+t*16]=reload, computes the new mode:
  30221   if flags.bit4=0 then mode=0048h else mode=0049h
  30222   if flags.bit0=0 then mode=mode OR 100h
  30223   if flags.bit12=1 then mode=mode OR 10h
  30224 and applies it by setting [1F801104h+t*16]=mode, and returns 1. Does nothing
  30225 and returns zero for t>2.
  30226 
  30227 B(03h) get_timer(t)
  30228 Reads the current timer value: Returns halfword[1F801100h+t*16] for t=0..2.
  30229 Does nothing and returns zero for t>2.
  30230 
  30231 B(04h) enable_timer_irq(t)
  30232 B(05h) disable_timer_irq(t)
  30233 Enables/disables timer or vblank interrupt enable bits in [1F801074h], bit4,5,6
  30234 for t=0,1,2, or bit0 for t=3, or random/garbage bits for t>3. The enable
  30235 function returns 1 for t=0..2, and 0 for t=3. The disable function returns
  30236 always 1.
  30237 
  30238 B(06h) restart_timer(t)
  30239 Sets the current timer value to zero: Sets [1F801100h+t*16]=0000h and returns 1
  30240 for t=0..2. Does nothing and returns zero for t>2.
  30241 
  30242 C(0Ah) - ChangeClearRCnt(t,flag) ;root counter (aka timer)
  30243 Selects what the kernel's timer/vblank IRQ handlers shall do after they have
  30244 processed an IRQ (t=0..2: timer 0..2, or t=3: vblank) (flag=0: do nothing; or
  30245 flag=1: automatically acknowledge the IRQ and immediately return from
  30246 exception). The function returns the old (previous) flag value.
  30247 
  30248 BIOS Joypad Functions
  30249 ---------------------
  30250 
  30251 Pad Input
  30252 Joypads should be initialized via InitPad(buf1,22h,buf2,22h), and StartPad().
  30253 The main program can read the pad data from the buf1/buf2 addresses (including
  30254 Status, ID1, button states, and any kind of analogue inputs). For more info on
  30255 ID1, Buttons and analogue inputs, see
  30256 --> Controllers and Memory Cards
  30257 Note: The BIOS doesn't include any functions for sending custom data to the
  30258 pads (such like for controlling rumble motors).
  30259 
  30260 B(12h) - InitPad(buf1, siz1, buf2, siz2)
  30261 Memorizes the desired buf1/buf2 addresses, zerofills the buffers by using the
  30262 siz1/siz2 buffer size values (which should be 22h bytes each). And does some
  30263 initialization on the PadCardIrq element (but doesn't enqueue it, that must be
  30264 done by a following call to StartPad), and does set the "pad_enable_flag", that
  30265 flag can be also set/cleared via InitCard(pad_enable), where it selects if the
  30266 Pads are kept handled together with Memory Cards. buf1/buf2 are having the
  30267 following format:
  30268   00h      Status (00h=okay, FFh=timeout/wrong ID2)
  30269   01h      ID1    (eg. 41h=digital_pad, 73h=analogue_pad, 12h=mouse, etc.)
  30270   02h..21h Data   (max 16 halfwords, depending on lower 4bit of ID1)
  30271 Note: InitPad does initially zerofill the buffers, so, until the first IRQ is
  30272 processed, the initial status is 00h=okay, with buttons=0000h (all buttons
  30273 pressed), to fix that situation, change the two status bytes to FFh after
  30274 calling InitPad (or alternately, reject ID1=00h).
  30275 Once when the PadCardIrq is enqueued via StartPad, and while "pad_enable_flag"
  30276 is set, the data for (both) Pad1 and Pad2 is read on Vblank interrupts, and
  30277 stored in the buffers, the IRQ handler stores up to 22h bytes in the buffer
  30278 (regardless of the siz1/siz2 values) (eg. a Multitap adaptor uses all 22h
  30279 bytes).
  30280 
  30281 B(13h) - StartPad()
  30282 Should be used after InitPad. Enqueues the PadCardIrq handler, and does
  30283 additionally initialize some flags.
  30284 
  30285 B(14h) - StopPad()
  30286 Dequeues the PadCardIrq handler. Note that this handler is also used for memory
  30287 cards, so it'll "stop" cards, too.
  30288 
  30289 B(15h) - OutdatedPadInitAndStart(type, button_dest, unused, unused)
  30290 This is an extremely bizarre and restrictive function - don't use! The function
  30291 fails unless type is 20000000h or 20000001h (the type value has no other
  30292 function). The function uses "buf1/buf2" addresses that are located somewhere
  30293 "hidden" within the BIOS variables region, the only way to read from that
  30294 internal buffers is to use the ugly "OutdatedPadGetButtons()" function. For
  30295 some strange reason it FFh-fills buf1/buf2, and does then call
  30296 InitPad(buf1,22h,buf2,22) (which does immediately 00h-fill the previously
  30297 FFh-filled buffers), and does then call StartPad().
  30298 Finally, it does memorize the "button_dest" address (see
  30299 OutdatedPadGetButtons() for details on that value). The two unused parameters
  30300 have no function, however, they are internally written back to the stack
  30301 locations reserved for parameter 2 and 3, ie. at [SP+08h] and [SP+0Ch] on the
  30302 caller's stack, so the function MUST be called with all four parameters
  30303 allocated on stack. Return value is 2 (or 0 if type was disliked).
  30304 
  30305 B(16h) - OutdatedPadGetButtons()
  30306 This is a very ugly function, using the internal "buf1/buf2" values from
  30307 "OutdatedPadInitAndStart" and the "button_dest" value that was passed to that
  30308 function.
  30309 If "button_dest" is non-zero, then this function is automatically called by the
  30310 PadCardIrq handler, and stores it's return value at [button_dest] (where it may
  30311 be read by the main program). If "button_dest" is zero, then it isn't called
  30312 automatically, and it <can> be called manually (with return value in R2),
  30313 however, it does additionally write the return value to [button_dest], ie. to
  30314 [00000000h] in this case, destroying that memory location.
  30315 The return value itself is useless garbage: The lower 16bit contain the pad1
  30316 buttons, the upper 16bit the pad2 buttons, of which, both values have reversed
  30317 byte-order (ie. the first button byte in upper 8bit). The function works only
  30318 with controller IDs 41h (digital joypad) and 23h (nonstandard device). For
  30319 ID=23h, the halfword is ORed with 07C7h, and bit6,7 are then cleared if the
  30320 analogue inputs are greater than 10h. For ID=41h the data is left intact. Any
  30321 other ID values, or disconnected joypads, cause the halfword to be set to FFFFh
  30322 (same as when no buttons are pressed), that includes newer analogue pads
  30323 (unless they are switched to "digital" mode).
  30324 
  30325 BIOS GPU Functions
  30326 ------------------
  30327 
  30328 A(48h) - SendGP1Command(gp1cmd)
  30329 Writes [1F801814h]=gp1cmd. There's no return value (r2 is left unchanged).
  30330 
  30331 A(49h) - GPU_cw(gp0cmd)      ;send GP0 command word
  30332 Calls gpu_sync(), and does then write [1F801810h]=gp0cmd. Returns the return
  30333 value from the gpu_sync() call.
  30334 
  30335 A(4Ah) - GPU_cwp(src,num) ;send GP0 command word and parameter words
  30336 Calls gpu_sync(), and does then copy "num" words from [src and up] to
  30337 [1F801810h], src should usually point to a command word, followed by num-1
  30338 parameter words. Transfer is done by software (without DMA). Always returns 0.
  30339 
  30340 A(4Bh) - send_gpu_linked_list(src)
  30341 Transfer an OT via DMA. Calls gpu_sync(), and does then write
  30342 [1F801814h]=4000002h, [1F8010F4h]=0, [1F8010F0h]=[1F8010F0h] OR 800h,
  30343 [1F8010A0h]=src, [1F8010A4h]=0, [1F8010A8h]=1000401h. The function does
  30344 additionally output a bunch of TTY status messages via printf. The function
  30345 doesn't wait until the DMA is completed. There's no return value.
  30346 
  30347 A(4Ch) - gpu_abort_dma()
  30348 Writes [1F8010A8h]=401h, [1F801814h]=4000000h, [1F801814h]=2000000h,
  30349 [1F801814h]=1000000h. Ie. stops GPU DMA, and issues GP1(4), GP1(2), GP1(1).
  30350 Returns 1F801814h, ie. the I/O address.
  30351 
  30352 A(4Dh) - GetGPUStatus()
  30353 Reads [1F801814h] and returns that value.
  30354 
  30355 A(46h) - GPU_dw(Xdst,Ydst,Xsiz,Ysiz,src)
  30356 Waits until GPUSTAT.Bit26 is set (unlike gpu_sync, which waits for Bit28), and
  30357 does then [1F801810h]=A0000000h, [1F801810h]=YdstXdst, [1F801810h]=YsizXsiz,
  30358 and finally transfers "N" words from [src and up] to [1F801810h], where "N" is
  30359 "Xsiz*Ysiz/2". The data is transferred by software (without DMA) (by code
  30360 executed in the uncached BIOS region with high waitstates, so the data transfer
  30361 is very SLOW).
  30362 Caution: If "Xsiz*Ysiz" is odd, then the last halfword is NOT transferred, so
  30363 the GPU stays waiting for the last data value.
  30364 Returns [SP+04h]=Ydst, [SP+08h]=Xsiz, [SP+0Ch]=Ysiz, [SP+10h]=src+N*4, and
  30365 R2=src=N*4.
  30366 
  30367 A(47h) - gpu_send_dma(Xdst,Ydst,Xsiz,Ysiz,src)
  30368 Calls gpu_sync(), writes [1F801810h]=A0000000h, [1F801814h]=4000002h,
  30369 [1F8010F0h]=[1F8010F0h] OR 800h, [1F8010A0h]=src, [1F8010A4h]=N*10000h+10h
  30370 (where N="Xsiz*Ysiz/32"), [1F8010A8h]=1000201h.
  30371 Caution: If "Xsiz*Ysiz" is not a multiple of 32, then the last halfword(s) are
  30372 NOT transferred, so the GPU stays waiting for that values.
  30373 Returns R2=1F801810h, and [SP+04h]=Ydst, [SP+08h]=Xsiz, [SP+0Ch]=Ysiz.
  30374 
  30375 A(4Eh) - gpu_sync()
  30376 If DMA is off (when GPUSTAT.Bit29-30 are zero): Waits until GPUSTAT.Bit28=1 (or
  30377 until timeout).
  30378 If DMA is on: Waits until D2_CHCR.Bit24=0 (or until timeout), and does then
  30379 wait until GPUSTAT.Bit28=1 (without timeout, ie. may hang forever), and does
  30380 then turn off DMA via GP1(04h).
  30381 Returns 0 (or -1 in case of timeout, however, the timeout values are very big,
  30382 so it may take a LOT of seconds before it returns).
  30383 
  30384 BIOS Memory Allocation
  30385 ----------------------
  30386 
  30387 A(33h) - malloc(size)
  30388 Allocates size bytes on the heap, and returns the memory handle (aka the
  30389 address of the allocated memory block). The address of the block is guaranteed
  30390 to by aligned to 4-byte memory boundaries. Size is rounded up to a multiple of
  30391 4 bytes. The address may be in KUSEG, KSEG0, or KSEG1, depending on the address
  30392 passed to InitHeap.
  30393 Caution: The BIOS (tries to) initialize the heap size to 0 bytes (actually it
  30394 accidently overwrites that initial setting by garbage during relocation), so
  30395 any call to malloc will fail, unless InitHeap has been used to initialize the
  30396 address/size of the heap.
  30397 
  30398 A(34h) - free(buf)
  30399 Deallocates the memory block. There's no return value, and no error checking.
  30400 The function simply sets [buf-4]=[buf-4] OR 00000001h, so if buf is an invalid
  30401 handle it may destroy memory at [buf-4], or trigger a memory exception (for
  30402 example, when buf=0).
  30403 
  30404 A(37h) - calloc(sizx, sizy)     ;SLOW!
  30405 Allocates xsiz*ysiz bytes by calling malloc(xsiz*ysiz), and, unlike malloc, it
  30406 does additionally zerofill the memory via SLOW "bzero" function. Returns the
  30407 address of the memory block (or zero if failed).
  30408 
  30409 A(38h) - realloc(old_buf, new_size)   ;SLOW!
  30410 If "old_buf" is zero, executes malloc(new_size), and returns r2=new_buf (or
  30411 0=failed). Else, if "new_size" is zero, executes free(old_buf), and returns
  30412 r2=garbage. Else, executes malloc(new_size), bcopy(old_buf,new_buf,new_size),
  30413 and free(old_buf), and returns r2=new_buf (or 0=failed).
  30414 Caution: The bcopy function is SLOW, and realloc does accidently copy
  30415 "new_size" bytes from old_buf, so, if the old_size was smaller than new_size
  30416 then it'll copy whatever garbage data - in worst case, if it exceeds the top of
  30417 the 2MB RAM region, it may crash with a locked memory exception, although
  30418 that'd happen only if SetMemSize(2) was used to restrict RAM to 2MBs.
  30419 
  30420 A(39h) - InitHeap(addr, size)
  30421 Initializes the address and size of the heap - the BIOS does not automatically
  30422 do this, so, before using the heap, InitHeap must be called by software.
  30423 Usually, the heap would be memory region between the end of the boot
  30424 executable, and the bottom of the executable's stack. InitHeap can be also used
  30425 to deallocate all memory handles (eg. when a new exe file has been loaded, it
  30426 may use it to deallocate all old memory).
  30427 The heap is used only by malloc/realloc/calloc/free, and by the "qsort"
  30428 function.
  30429 
  30430 B(00h) alloc_kernel_memory(size)
  30431 B(01h) free_kernel_memory(buf)
  30432 Same as malloc/free, but, instead of the heap, manages the 8kbyte control block
  30433 memory at A000E000h..A000FFFFh. This region is used by the kernel to allocate
  30434 ExCBs (4x08h bytes), EvCBs (N*1Ch bytes), TCBs (N*0C0h bytes), and the process
  30435 control block (1x04h bytes). Unlike the heap, the BIOS does automatically
  30436 initialize this memory region via SysInitMemory(addr,size), and does
  30437 autimatically allocate the above data (where the number of EvCBs and TCBs is as
  30438 specified in the SYSTEM.CNF file). Note: FCBs and DCBs are located elsewhere,
  30439 at fixed locations in the kernel variables area.
  30440 
  30441 Scratchpad Note
  30442 The kernel doesn't include any allocation functions for the scratchpad (nor do
  30443 any kernel functions use that memory area), so the executable can freely use
  30444 the "fast" memory at 1F800000h..1F8003FFh.
  30445 
  30446 A(9Fh) - SetMemSize(megabytes)
  30447 Changes the effective RAM size (2 or 8 megabytes) by manipulating port
  30448 1F801060h, and additionally stores the size in megabytes in RAM at [00000060h].
  30449 Note: The BIOS bootcode accidently sets the RAM value to 2MB (which is the
  30450 correct physical memory size), but initializes the I/O port to 8MB (which
  30451 mirrors the physical 2MB within that 8MB region), so the initial values don't
  30452 match up with each other.
  30453 Caution: Applying the correct size of 2MB may cause the "realloc" function to
  30454 crash (that function may accidently access memory above 2MB).
  30455 
  30456 BIOS Memory Fill/Copy/Compare (SLOW)
  30457 ------------------------------------
  30458 
  30459 Like most A(NNh) functions, below functions are executed in uncached BIOS ROM,
  30460 the ROM has very high waitstates, and the 32bit opcodes are squeezed through an
  30461 8bit bus. Moreover, below functions are restricted to process the data
  30462 byte-by-byte. So, they are very-very-very slow, don't even think about using
  30463 them.
  30464 Of course, that applies also for most other BIOS functions. But it's becoming
  30465 most obvious for these small functions; memcpy takes circa 160 cycles per byte
  30466 (reasonable would be less than 4 cycles), and bzero takes circa 105 cycles per
  30467 byte (reasonable would be less than 1 cycles).
  30468 
  30469 A(2Ah) - memcpy(dst, src, len)
  30470 Copies len bytes from [src..src+len-1] to [dst..dst+len-1]. Refuses to copy any
  30471 data when dst=00000000h or when len>7FFFFFFFh. The return value is always the
  30472 incoming "dst" value.
  30473 
  30474 A(2Bh) - memset(dst, fillbyte, len)
  30475 Fills len bytes at [dst..dst+len-1] with the fillbyte value. Refuses to fill
  30476 memory when dst=00000000h or when len>7FFFFFFFh. The return value is the
  30477 incoming "dst" value (or zero, when len=0 or len>7FFFFFFFh).
  30478 
  30479 A(2Ch) - memmove(dst, src, len) - bugged
  30480 Same as memcpy, but (attempts) to support overlapping src/dst regions, by using
  30481 a backwards transfer when src<dst (and, for some reason, only when
  30482 dst>=src+len).
  30483 BUG: The backwards variant accidently transfers len+1 bytes from [src+len..src]
  30484 down to [dst+len..dst].
  30485 
  30486 A(2Dh) - memcmp(src1, src2, len) - bugged
  30487 Compares len bytes at [src1..src1+len-1] with [src2..src2+len-1], and
  30488 (attempts) to return the difference between the first mismatching bytes, ie.
  30489 [src1+N]-[src2+N], or 0 if there are no mismatches. Refuses to compare data
  30490 when src1 or src2 is 00000000h, and returns 0 in that case.
  30491 BUG: Accidently returns the difference between the bytes AFTER the first
  30492 mismatching bytes, ie. [src1+N+1]-[src2+N+1].
  30493 That means that a return value of 0 can mean absolutely anything: That the
  30494 memory blocks are identical, or that a mismatch has been found (but that the
  30495 NEXT byte after the mismatch does match), or that the function has failed (due
  30496 to src1 or src2 being 00000000h).
  30497 
  30498 A(2Eh) - memchr(src, scanbyte, len)
  30499 Scans [src..src+len-1] for the first occurence of scanbyte. Refuses to scan any
  30500 data when src=00000000h or when len>7FFFFFFFh. Returns the address of that
  30501 first occurence, or 0 if the scanbyte wasn't found.
  30502 
  30503 A(27h) - bcopy(src, dst, len)
  30504 Same as "memcpy", but with "src" and "dst" exchanged. That is, the first
  30505 parameter is "src", the refuse occurs when "src" is 00000000h, and, returns the
  30506 incoming "src" value (whilst "memcpy" uses "dst" in that places).
  30507 
  30508 A(28h) - bzero(dst, len)
  30509 Same as memset, but uses 00h as fixed fillbyte value.
  30510 
  30511 A(29h) - bcmp(ptr1, ptr2, len) - bugged
  30512 Same as "memcmp", with exactly the same bugs.
  30513 
  30514 BIOS String Functions
  30515 ---------------------
  30516 
  30517 A(15h) - strcat(dst, src)
  30518 Appends src to the end of dst. Searches the ending 00h byte in dst, and copies
  30519 src to that address, up to including the ending 00h byte in src. Returns the
  30520 incoming dst value. Refuses to do anything if src or dst is 00000000h (and
  30521 returns 0 in that case).
  30522 
  30523 A(16h) - strncat(dst, src, maxlen)
  30524 Same as "strcat", but clipped to "MaxSrc=(min(0,maxlen)+1)" characters, ie. the
  30525 total length is max "length(dst)+min(0,maxlen)+1". If src is longer or equal to
  30526 "MaxSrc", then only the first "MaxSrc" chars are copied (with the last byte
  30527 being replaced by 00h). If src is shorter, then everything up to the ending 00h
  30528 byte gets copied, but without additional padding (unlike as in "strncpy").
  30529 
  30530 A(17h) - strcmp(str1, str2)
  30531 Compares the strings up to including ending 00h byte. Returns 0 if they are
  30532 identical, or otherwise [str1+N]-[str2+N], where N is the location of the first
  30533 mismatch, the two bytes are sign-expanded to 32bits before doing the
  30534 subtraction. The function rejects str1/str2 values of 00000000h (and returns
  30535 0=both are zero, -1=only str1 is zero, and +1=only str2 is zero).
  30536 
  30537 A(18h) - strncmp(str1, str2, maxlen)
  30538 Same as "strcmp" but stops after comparing "maxlen" characters (and returns 0
  30539 if they did match). If the strings are shorter, then comparision stops at the
  30540 ending 00h byte (exactly as for strcmp).
  30541 
  30542 A(19h) - strcpy(dst, src)
  30543 Copies data from src to dst, up to including the ending 00h byte. Refuses to
  30544 copy anything if src or dst is 00000000h. Returns the incoming dst address (or
  30545 0 if copy was refused).
  30546 
  30547 A(1Ah) - strncpy(dst, src, maxlen)
  30548 Same as "strcpy", but clipped to "maxlen" characters. If src is longer or equal
  30549 to maxlen, then only the first "maxlen" chars are copied (but without appending
  30550 an ending 00h byte to dst). If src is shorter, then the remaining bytes in dst
  30551 are padded with 00h bytes.
  30552 
  30553 A(1Bh) - strlen(src)
  30554 Returns the length of the string up to excluding the ending 00h byte (or 0 when
  30555 src is 00000000h).
  30556 
  30557 A(1Ch) - index(src, char)
  30558 A(1Dh) - rindex(src, char)
  30559 A(1Eh) - strchr(src, char)  ;exactly the same as "index"
  30560 A(1Fh) - strrchr(src, char) ;exactly the same as "rindex"
  30561 Scans for the first (index) or last (rindex) occurence of char in the string.
  30562 Returns the memory address of that occurence (or 0 if there's no occurence, or
  30563 if src is 00000000h). Char may be 00h (returns the end address of the string).
  30564 Note that, despite of the function names, the return value is always a memory
  30565 address, NOT an index value relative to src.
  30566 
  30567 A(20h) - strpbrk(src, list)
  30568 Scans for the first occurence of a character that is contained in the list. The
  30569 list contains whatever desired characters, terminated by 00h.
  30570 Returns the address of that occurence, or 0 if there was none. BUG: If there
  30571 was no occurence, it returns 0 only if src[0]=00h, and otherwise returns the
  30572 incoming "src" value (which is the SAME return value as when a occurence did
  30573 occur on 1st character).
  30574 
  30575 A(21h) - strspn(src, list)
  30576 A(22h) - strcspn(src, list)
  30577 Scans for the first occurence of a character that is (strspn), or that isn't
  30578 (strcspn) contained in the list. The list contains whatever desired characters,
  30579 terminated by 00h.
  30580 Returns the index (relative to src) of that occurence. If there was no
  30581 occurence, then it returns the length of src. That silly return values do not
  30582 actually indicate if an occurence has been found or not (unless one checks for
  30583 [src+index]=00h or so).
  30584 ***
  30585 "The strcspn() function shall compute the length (in bytes) of the maximum
  30586 initial segment of the string pointed to by s1 which consists entirely of bytes
  30587 not from the string pointed to by s2."
  30588 "The strspn() function shall compute the length (in bytes) of the maximum
  30589 initial segment of the string pointed to by s1 which consists entirely of bytes
  30590 from the string pointed to by s2."
  30591 ***
  30592 Hmmmm, that'd be vice-versa?
  30593 
  30594 A(23h) - strtok(src, list) ;first call
  30595 A(23h) - strtok(0, list) ;further call(s)
  30596 Used to split a string into fragments, list contains a list of characters that
  30597 are to be treated as separators, terminated by 00h.
  30598 The first call copies the incoming string to a buffer in the BIOS variables
  30599 area (the buffer size is 100h bytes, so the string should be max 255 bytes
  30600 long, plus the ending 00h byte, otherwise the function destroys other BIOS
  30601 variables), it does then search the first fragment, starting at the begin of
  30602 the buffer. Further calls (with src=00000000h) are searching further fragments,
  30603 starting at the buffer address from the previous call. The internal buffer is
  30604 used only for strtok, so its contents (and the returned string fragments)
  30605 remain intact until a new first call to strtok takes place.
  30606 The separate fragments are processed by searching the first separator, starting
  30607 at the current buffer address, the separator is then replaced by a 00h byte,
  30608 and the old buffer address is returned to the caller. Moreover, the function
  30609 tries to skip all continously following separators, until reaching a
  30610 non-separator, and does memorize that address for the next call (due to that
  30611 skipping further calls won't return empty fragments, the first call may do so
  30612 though). That skipping seems to be bugged, if list contains two or more
  30613 different characters, then additional separators aren't skipped.
  30614   ",,TEXT,,,END" with list=","  returns "", "TEXT", "END"
  30615   ",,TEXT,,,END" with list=",." returns "", "", "TEXT", "", "", "END"
  30616 Once when there are no more fragments, then 00000000h is returned.
  30617 
  30618 A(24h) - strstr(str, substr) - buggy
  30619 Scans for the first occurence of substr in the string. Returns the memory
  30620 address of that occurence (or 0 if it was unable to find an occurence).
  30621 BUG: After rejecting incomplete matches, the function doesn't fallback to the
  30622 old str address plus 1, but does rather continue at the current str address.
  30623 Eg. it doesn't find substr="aab" in str="aaab" (in that example, it does merely
  30624 realize that "aab"<>"aaa" and then that "aab"<>"b").
  30625 
  30626 BIOS Number/String/Character Conversion
  30627 ---------------------------------------
  30628 
  30629 A(0Eh) - abs(val)
  30630 A(0Fh) - labs(val)  ;exactly same as "abs"
  30631 Returns the absolute value (if val<0 then R2=-val, else R2=val).
  30632 
  30633 A(0Ah) - todigit(char)
  30634 Takes the incoming character, ANDed with FFh, and returns 0..9 for characters
  30635 "0..9" and 10..35 for "A..Z" or "a..z", or 0098967Fh (9,999,999 decimal) for
  30636 any other 7bit characters, or garbage for characters 80h..FFh.
  30637 
  30638 A(25h) - toupper(char)
  30639 A(26h) - tolower(char)
  30640 Returns the incoming character, ANDed with FFh, with letters "A..Z" converted
  30641 to uppercase/lowercase format accordingly. Works only for char 00h..7Fh (some
  30642 characters in range 80h..FFh are left unchanged, others are randomly "adjusted"
  30643 by adding/subtracting 20h, and by sign-expanding the result to 32bits).
  30644 
  30645 A(0Dh) - strtol(src, src_end, base)
  30646 Converts a string to a number. The function skips any leading "blank"
  30647 characters (that are, 09h..0Dh, and 20h) (ie. TAB, CR, LF, SPC, and some
  30648 others) (some characters in range 80h..FFh are accidently treated as "blank",
  30649 too).
  30650 The incoming base value should be in range 2..11, although the function does
  30651 also accept the buggy values in range of 12..36 (for values other than 2..36 it
  30652 defaults to decimal/base10). The used numeric digits are "0..9" and "A..Z" (or
  30653 less when base is smaller than 36).
  30654 The string may have a negative sign prefix "-" (negates the result) (a "+" is
  30655 NOT recognized; and will be treated as the end of the string). Additionally,
  30656 the string may contain prefixes "0b" (binary/base2), "0x" (hex/base16), or "o"
  30657 (octal/base8) (only "o", not "0o"), allowing to override the incoming "base"
  30658 value.
  30659 BUG: Incoming base values greater than 11 don't work due to the prefix feature
  30660 (eg. base=16 with string "0b11" will be treated as 11 binary, and base=36 with
  30661 string "o55" will be treated as 55 octal) (the only workaround would be to
  30662 add/remove leading "0" characters, ie. "b11" or "00b11" or "0o55" would work
  30663 okay).
  30664 Finally, the function initializes result=0, and does then process the digits as
  30665 "result=result*base+digit" (without any overflow checks) unless/until it
  30666 reaches an unknown digit (or when digit>=base) (ie. the string may end with
  30667 00h, or with any other unexpected characters).
  30668 The function accepts both uppercase and lowercase characters (both as prefixes,
  30669 and as numeric digits). The function returns R2=result, and
  30670 [src_end]=end_address (ie. usually the address of the ending 00h byte; or of
  30671 any other unexpected end-byte). If src points to 00000000h, then the function
  30672 returns r2=0, and leaves [src_end] unchanged.
  30673 
  30674 A(0Ch) - strtoul(src, src_end, base)
  30675 Same as "strtol" except that it doesn't recognize the "-" sign prefix (ie.
  30676 works only for unsigned numbers).
  30677 
  30678 A(10h) - atoi(src)
  30679 A(11h) - atol(src)  ;exactly same as "atoi" (but slightly slower)
  30680 Same as "strtol", except that it doesn't return the string end address in
  30681 [src_end], and except that it defaults to base=10, but still supports prefixes,
  30682 allowing to use base2,8,16. CAUTION: For some super bizarre reason, this
  30683 function treats "0" (a leading ZERO digit) as OCTAL prefix (unlike strtol,
  30684 which uses the "o" letter as octal prefix) (the "0x" and "0b" prefixes are
  30685 working as usually).
  30686 
  30687 A(12h) - atob(src, num_dst)
  30688 Calls "strtol(str,src_end,10)", and does then exchange the two return values
  30689 (ie. sets R2=[src_end], and [num_dst]=value_32bit).
  30690 
  30691 A(0Bh) - atof(src) ;USES (ABSENT) COP1 FPU !!!
  30692 A(32h) - strtod(src, src_end) ;USES (ABSENT) COP1 FPU !!!
  30693 These functions are intended to convert strings to floating point numbers,
  30694 however, the functions are accidently compiled for MIPS processors with COP1
  30695 floating point unit (which is not installed in the PSX, nor does the BIOS
  30696 support a COP1 software emulation), so calling these functions will produce a
  30697 coprocessor exception, causing the PSX to lockup via A(40h)
  30698 SystemErrorUnresolvedException.
  30699 
  30700 Note
  30701 On other systems (eg. 8bit computers), "abs/atoi" (integer) and "labs/atol"
  30702 (long) may act differently. However, on the Playstation, both use signed 32bit
  30703 values.
  30704 
  30705 BIOS Misc Functions
  30706 -------------------
  30707 
  30708 A(2Fh) - rand()
  30709 Advances the random generator as "x=x*41C64E6Dh+3039h" (aka plus 12345
  30710 decimal), and returns a 15bit random value "R2=(x/10000h) AND 7FFFh".
  30711 
  30712 A(30h) - srand(seed)
  30713 Changes the current 32bit value of the random generator.
  30714 
  30715 A(B4h) - GetSystemInfo(index)  ;not supported by old CEX-1000 version
  30716 Returns a word, halfword, or string, depending on the selected index value:
  30717   00h      Get Kernel BCD Date       (eg. 19951204h) (YYYYMMDDh)
  30718   01h      Get Kernel Flags or so    (usually/always 000000003h)
  30719   02h      Get Kernel Version String (eg. "CEX-3000/1001/1002 by K.S.",0)
  30720   03h      Get whatever halfword     (usually 0)    ;PS2: returns cop0r15
  30721   04h      Get whatever halfword     (usually 0)
  30722   05h      Get RAM Size in kilobytes (usually 2048) ;=[00000060h] SHL 10
  30723   06h..0Eh Get whatever halfwords    (usually 0,400h,0,200h,0,0,1,1,1)
  30724   0Fh      N/A (returns zero) ;PS2: returns 0000h (effectively = same as zero)
  30725   10h..FFFFFFFFh Not used (returns zero)
  30726 Note: The Date/Version are referring to the Kernel (in the first half of the
  30727 BIOS). The Intro and Bootmenu (in the second half of the BIOS) may have a
  30728 different version, there's no function to retrieve info on that portion,
  30729 however, a version string for it can be usually found at BFC7FF32h (eg. "System
  30730 ROM Version 4.5 05/25/00 E",0) (in many bios versions, the last letter of that
  30731 string indicates the region, but not in all versions) (the old SCPH1000 does
  30732 not include that version string at all).
  30733 
  30734 B(56h) GetC0Table()
  30735 B(57h) GetB0Table()
  30736 Retrieves the address of the jump lists for B(NNh) and C(NNh) functions,
  30737 allowing to patch entries in that lists (however, the BIOS does often jump
  30738 directly to the function addresses, rather than indirectly via the list, so
  30739 patching may have little effect in such cases). Note: There's no function to
  30740 retrieve the address of the A(NNh) jump list, however, that list is
  30741 usually/always at 00000200h.
  30742 
  30743 A(31h) - qsort(base, nel, width, callback)
  30744 Sorts an array, using a super-slow implementation of the "quick sort"
  30745 algorithm. base is the address of the array, nel is the number of elements in
  30746 the array, width is the size in bytes of each element, callback is a function
  30747 that receives pointers to two elements which need to be compared; callback
  30748 should return return zero if the elements are identical, or a positive/negative
  30749 number to indicate which element is bigger.
  30750 The qsort function rearranges the contents of the array, ie. depending on the
  30751 callback result, it may swap the contents of the two elements, for some bizarre
  30752 reason it doesn't swap them directly, but rather stores one of the elements
  30753 temporarily on the heap (that means, qsort works only if the heap was
  30754 initialized with InitHeap, and only if "width" bytes are free). There's no
  30755 return value.
  30756 
  30757 A(35h) - lsearch(key, base, nel, width, callback)
  30758 A(36h) - bsearch(key, base, nel, width, callback)
  30759 Searches an element in an array (key is the pointer to the searched element,
  30760 the other parameters are same as for "qsort"). "lsearch" performs a slow linear
  30761 search in an unsorted array, by simply comparing one array element after each
  30762 other. "bsearch" assumes that the array contains sorted elements (eg. via
  30763 qsort), which is allowing to skip some elements, and to jump back and forth in
  30764 the array, until it has found the desired element (or the location where it'd
  30765 be, if it'd be in the array). Both functions return the address of the element
  30766 (or 0 if it wasn't found).
  30767 
  30768 C(19h) - ioabort(txt1,txt2)
  30769 Displays the two strings on the TTY (in some cases the BIOS does accidently
  30770 pass garbage instead of the 2nd string though). And does then execute
  30771 ioabort_raw(1), see there for more details.
  30772 
  30773 A(B2h) - ioabort_raw(param)  ;not supported by old CEX-1000 version
  30774 Executes "RestoreState(ioabortbuffer,param)". Internally used to recover from
  30775 failed I/O operations, param should be nonzero to notify the SaveState caller
  30776 that the abort has occurred.
  30777 
  30778 A(13h) - SaveState(buf)
  30779 Stores some (not all) CPU registers in the specified buffer (30h bytes):
  30780   00h 4    r31 (ra) (aka caller's pc)
  30781   04h 4    r29 (sp)
  30782   08h 4    r30 (fp)
  30783   0Ch 4x8  r16..r23
  30784   2Ch 4    r28 (gp)
  30785 That type of buffer can be used with "ioabort", "RestoreState", and also
  30786 "SetCustomExitFromException(addr)".
  30787 The "SaveState" function (initially) returns 0, however, it may return again -
  30788 to the same return address - with another return value (which should be usually
  30789 non-zero, to indicate that the state has been restored (eg. ioabort passes 1 as
  30790 return value).
  30791 
  30792 A(14h) - RestoreState(buf, param)
  30793 Restores the R16-R23,GP,SP,FP,RA registers from a previously recorded SaveState
  30794 buffer, and "returns" to that new RA address (rather than to the caller of the
  30795 RestoreState function), the "param" value is passed as "return value" to the
  30796 code at RA, ie. usually to the caller of the original SaveState call) (since
  30797 SaveState returns 0, "param" should be usually 1, or another non-zero value to
  30798 inidicate that RestoreState has occurred). See SaveState for further details.
  30799 
  30800 A(53h) - set_ioabort_handler(src)  ;PS2 only  ;PSX: SystemError
  30801 Normally the ioabort handler is changed only internally during booting, with
  30802 this new function, games can install their own ioabort handler. src is pointer
  30803 to a 30h-byte "savestate" structure, which will be copied to the actual ioabort
  30804 structure.
  30805 
  30806 A(06h) or B(38h) - exit(exitcode)
  30807 Terminates the program and returns control to the BIOS; which does then lockup
  30808 itself via A(3Ah) SystemErrorExit.
  30809 
  30810 A(A0h) - WarmBoot()
  30811 Performs a warmboot (resets the kernel and reboots from CDROM). Unlike the
  30812 normal coldboot procedure, it doesn't display the "<S>" and "PS" intro screens
  30813 (and doesn't verify the "PS" logo in the ISO System Area), and, doesn't enter
  30814 the bootmenu (even if the disk drive is empty, or if it contains an Audio
  30815 disk). And, it doesn't reload the SYSTEM.CNF file, so the function works only
  30816 if the same disk is still inserted (or another disk with identical SYSTEM.CNF,
  30817 such like Disk 2 of the same game).
  30818 
  30819 A(B5h..BFh) B(11h,24h..29h,2Ch..31h,5Eh..FFh) C(1Eh..7Fh) - N/A - Jump 0
  30820 These functions jump to address 00000000h. For whatever reason, that address
  30821 does usually contain a copy of the exception handler (ie. same as at address
  30822 80000080h). However, since there's no return address stored in EPC register,
  30823 the functions will likely crash when returning from the exception handler.
  30824 
  30825 A(57h..5Ah,73h..77h,79h..7Bh,7Dh,7Fh..80h,82h..8Fh,B0h..B1h,B3h), and
  30826 C(0Eh..11h,14h) - N/A - Returns 0
  30827 No function. Simply returns with r2=00000000h.
  30828 Reportedly, A(85h) is CdStop, but that seems to be nonsense?
  30829 
  30830 SYS(00h) - NoFunction()
  30831 No function. Simply returns without changing any registers or memory locations
  30832 (except that, of course, the exception handler destroys k0).
  30833 
  30834 SYS(04h..FFFFFFFFh) - calls DeliverEvent(F0000010h,4000h)
  30835 These are syscalls with invalid function number in R4. For whatever reason that
  30836 is handled by issuing DeliverEvent(F0000010h,4000h). Thereafter, the syscall
  30837 returns to the main program (ie. it doesn't cause a SystemError).
  30838 
  30839 A(3Ah) - SystemErrorExit(exitcode)
  30840 A(40h) - SystemErrorUnresolvedException()
  30841 A(A1h) - SystemErrorBootOrDiskFailure(type,errorcode) ;type "B"=Boot,"D"=Disk
  30842 These are used "SystemError" functions. The functions are repeatedly jumping to
  30843 themselves, causing the system to hang. Possibly useful for debugging software
  30844 which may hook that functions.
  30845 
  30846 A(4Fh,50h,52h,53h,9Ah,9Bh) B(1Ah..1Fh,21h..23h,2Ah,2Bh,52h,5Ah) C(0Bh) - N/A
  30847 These are additional "SystemError" functions, but they are never used. The
  30848 functions are repeatedly jumping to themselves, causing the system to hang.
  30849 Note: A(52h) is reportedly "GetSysSp()", but that seems to be nonsense?
  30850 
  30851 BRK(1C00h) - Division by zero (commonly checked/invoked by software)
  30852 BRK(1800h) - Division overflow (-80000000h/-1, sometimes checked by software)
  30853 The CPU does not generate any exceptions upon divide overflows, because of
  30854 that, the Kernel code and many games are commonly checking if the divider is
  30855 zero (by software), and, if so, execute a BRK 1C00h opcode. The default BIOS
  30856 exception handler doesn't handle BRK exceptions, and does simply redirect them
  30857 to SystemErrorUnresolvedException().
  30858 
  30859 BIOS Internal Boot Functions
  30860 ----------------------------
  30861 
  30862 A(45h) - init_a0_b0_c0_vectors
  30863 Copies the three default four-opcode handlers for the A(NNh),B(NNh),C(NNh)
  30864 functions to A00000A0h..A00000CFh.
  30865 
  30866 C(07h) - InstallExceptionHandlers()  ;destroys/uses k0/k1
  30867 Copies the default four-opcode exception handler to the exception vector at
  30868 80000080h..8000008Fh, and, for whatever reason, also copies the same opcodes to
  30869 80000000h..8000000Fh.
  30870 
  30871 C(08h) - SysInitMemory(addr,size)
  30872 Initializes the address (A000E000h) and size (2000h) of the allocate-able
  30873 Kernel Memory region, and, seems to deallocate any memory handles which may
  30874 have been allocated via B(00h).
  30875 
  30876 C(09h) - SysInitKernelVariables()
  30877 Zerofills all Kernel variables; which are usually at [00007460h..0000891Fh].
  30878 Note: During the boot process, the BIOS accidently overwrites the first opcode
  30879 of this function (by the last word of the A0h table), so, thereafter, this
  30880 function won't work anymore (nor would it be of any use).
  30881 
  30882 C(12h) - InstallDevices(ttyflag)
  30883 Initializes the size and address of the File and Device Control Blocks (FCBs
  30884 and DCBs). Adds the TTY device by calling "KernelRedirect(ttyflag)", and the
  30885 CDROM and Memory Card devices by calling "AddCDROMDevice()" and
  30886 "AddMemCardDevice()".
  30887 
  30888 C(1Ch) - AdjustA0Table()
  30889 Copies the B(32h..3Bh) and B(3Ch..3Fh) function addresses to A(00h..09h) and
  30890 A(3Bh..3Eh). Apparently Sony's compiler/linker can't insert the addresses in
  30891 the A0h table directly at compilation time, so this function is used to insert
  30892 them during execution of the boot code.
  30893 
  30894 BIOS More Internal Functions
  30895 ----------------------------
  30896 
  30897 Below are mainly internally used device related subfunctions.
  30898 
  30899 Internal Device Stuff
  30900   A(5Bh) dev_tty_init()                                      ;PS2: SystemError
  30901   A(5Ch) dev_tty_open(fcb,and unused:"path\name",accessmode) ;PS2: SystemError
  30902   A(5Dh) dev_tty_in_out(fcb,cmd)                             ;PS2: SystemError
  30903   A(5Eh) dev_tty_ioctl(fcb,cmd,arg)                          ;PS2: SystemError
  30904   A(5Fh) dev_cd_open(fcb,"path\name",accessmode)
  30905   A(60h) dev_cd_read(fcb,dst,len)
  30906   A(61h) dev_cd_close(fcb)
  30907   A(62h) dev_cd_firstfile(fcb,"path\name",direntry)
  30908   A(63h) dev_cd_nextfile(fcb,direntry)
  30909   A(64h) dev_cd_chdir(fcb,"path")
  30910   A(65h) dev_card_open(fcb,"path\name",accessmode)
  30911   A(66h) dev_card_read(fcb,dst,len)
  30912   A(67h) dev_card_write(fcb,src,len)
  30913   A(68h) dev_card_close(fcb)
  30914   A(69h) dev_card_firstfile(fcb,"path\name",direntry)
  30915   A(6Ah) dev_card_nextfile(fcb,direntry)
  30916   A(6Bh) dev_card_erase(fcb,"path\name")
  30917   A(6Ch) dev_card_undelete(fcb,"path\name")
  30918   A(6Dh) dev_card_format(fcb)
  30919   A(6Eh) dev_card_rename(fcb1,"path\name1",fcb2,"path\name2")
  30920   A(6Fh) ?   ;card ;[r4+18h]=00000000h  ;card_clear_error(fcb) or so
  30921   A(96h) AddCDROMDevice()
  30922   A(97h) AddMemCardDevice()
  30923   A(98h) AddDuartTtyDevice()   ;PS2: SystemError
  30924   A(99h) AddDummyTtyDevice()
  30925   B(47h) AddDevice(device_info)  ;subfunction for AddXxxDevice functions
  30926   B(48h) RemoveDevice(device_name_lowercase)
  30927   B(5Bh) ChangeClearPad(int)   ;pad AND card (ie. used also for Card)
  30928   C(15h) tty_cdevinput(circ,char)
  30929   C(16h) tty_cdevscan()
  30930   C(17h) tty_circgetc(circ)    ;uses r5 as garbage txt for ioabort
  30931   C(18h) tty_circputc(char,circ)
  30932 
  30933 Device Names
  30934 Device Names are case-sensitive (usually lowercase, eg. "bu" for memory cards).
  30935 In filenames, the device name may be followed by a hexadecimal 32bit
  30936 non-case-sensitive port number (eg. "bu00:" for selecting the first memory card
  30937 slot). Accordingly, the device name should not end with a hexdigit (eg. "usb:"
  30938 would be treated as device "us" with port number 0Bh).
  30939 Standard device names are "cdrom:", "bu00:", "bu10:", "tty00:". Other,
  30940 nonstandard devices are:
  30941   Castlevania is trying to access an unknown device named "sim:".
  30942   Caetla (a firmware replacement for Cheat Devices) supports "pcdrv:" device.
  30943 
  30944 BIOS PC File Server
  30945 -------------------
  30946 
  30947 DTL-H2000
  30948 Below BRK's are internally used in DTL-H2000 BIOS for two devices: "mwin:"
  30949 (Message Window) and "sim:" (CDROM Sim).
  30950 
  30951 Caetla Blurb
  30952 Caetla (a firmware replacement for Cheat Devices) supports "pcdrv:" device, the
  30953 SN systems (=what?) device extension to access files on the drive of the pc.
  30954 This fileserver can be accessed by using the kernel functions, with the
  30955 "pcdrv:" device name prefix to the filenames or using the SN system calls.
  30956 The following SN system calls for the fileserver are provided. Accessed by
  30957 setting the registers and using the break command with the specified field.
  30958 The break functions have argument(s) in A1,A2,A3 (ie. unlike normal BIOS
  30959 functions not in A0,A1,A2), and TWO return values (in V0, and V1).
  30960 
  30961 Detection
  30962 WCW Mayhem (MagDemo28) examines the exception vector opcodes to determine
  30963 whether to initialize debug stuff, the opcodes are usually:
  30964   80000080h = LUI+ADDIU+JMP+NOP         ;normal sony bios
  30965   80000080h = LUI+ORI+JMP+NOP           ;whatever debug bios (caetla or so?)
  30966 Namely, WCW Mayhem is doing "IF [86h]=375Ah=ORI then BRK(101h)". To avoid
  30967 crashing on that BRK, normal BIOSes must not use ORI in that place.
  30968 
  30969 BRK(101h) - PCInit() - Inits the fileserver
  30970 No parameters.
  30971 
  30972 BRK(102h) - PCCreat(filename, fileattributes) - Creates a new file on PC
  30973   out: V0  0 = success, -1 = failure
  30974        V1  file handle or error code if V0 is negative
  30975 Attributes Bits (standard MSDOS-style):
  30976   bit0     Read only file (R)
  30977   bit1     Hidden file    (H)
  30978   bit2     System file    (S)
  30979   bit3     Not used       (zero)
  30980   bit4     Directory      (D)
  30981   bit5     Archive file   (A)
  30982   bit6-31  Not used       (zero)
  30983 
  30984 BRK(103h) - PCOpen(filename, accessmode) - Opens a file on the PC
  30985   out: V0  0 = success, -1 = failure
  30986        V1  file handle or error code if V0 is negative
  30987 
  30988 BRK(104h) - PCClose(filehandle) - Closes a file on the PC
  30989   out: V0  0 = success, -1 = failure
  30990        V1  0 = success, error code if V0 is negative
  30991 
  30992 BRK(105h) - PCRead(filehandle, length, memory_destination_address)
  30993   out: V0  0 = success, -1 = failure
  30994        V1  number of read bytes or error code if V0 is negative.
  30995 Note: PCRead does not stop at EOF, so if you set more bytes to read than the
  30996 filelength, the fileserver will pad with zero bytes. If you are not sure of the
  30997 filelength obtain the filelength by PClSeek (A2=0, A3=2, V1 will return the
  30998 length of the file, don't forget to reset the file pointer to the start before
  30999 calling PCread!)
  31000 
  31001 BRK(106h) - PCWrite(filehandle, length, memory_source_address)
  31002   out: V0  0 = success, -1 = failure
  31003        V1  number of written bytes or error code if V0 is negative.
  31004 
  31005 BRK(107h) - PClSeek(filehandle, file_offset, seekmode) - Change Filepos
  31006 seekmode may be from 0=Begin of file, 1=Current fpos, or 2=End of file.
  31007   out: V0  0 = success, -1 = failure
  31008        V1  file pointer
  31009 
  31010 BIOS TTY Console (std_io)
  31011 -------------------------
  31012 
  31013 A(3Fh) - Printf(txt,param1,param2,etc.) - Print string to console
  31014   in:  A0                     Pointer to 0 terminated string
  31015        A1,A2,A3,[SP+10h..]    Argument(s)
  31016 Prints the specified string to the TTY console. Printf does internally use
  31017 "std_out_putchar" to output the separate characters (and expands char 09h and
  31018 0Ah accordingly).
  31019 The string can contain C-style escape codes (prefixed by "%" each):
  31020   c         display ASCII character
  31021   s         display ASCII string
  31022   i,d,D     display signed Decimal number (d/i=default32bit, D=force32bit)
  31023   u,U       display unsigned Decimal number (u=default32bit, U=force32bit)
  31024   o,O       display unsigned Octal number (o=default32bit, O=force32bit)
  31025   p,x,X     display unsigned Hex number (p=lower/force32bit, x=lower, X=upper)
  31026   n         write 32bit/16bit string length to [parameter] (default32bit)
  31027 Additionally, following prefixes (inserted between "%" and escape code):
  31028   + or SPC  show leading plus or space character in positive signed numbers
  31029   NNN       fixed width (for padding or so) (first digit must be 1..9) (not 0)
  31030   .NNN      fixed width (for clipping or so)
  31031   *         variable width (using one of the parameters) (negative=ending_spc)
  31032   .*        variable width
  31033   -         force ending space padding (in case of width being specified)
  31034   #         show leading "0x" or "0X" (hex), or ensure 1 leading zero (octal)
  31035   0         show leading zero's
  31036   L         unknown/no effect?
  31037   h,l       force 16bit (h=halfword), or 32bit (l=long/word)
  31038 The force32bit codes (D,U,O,p,l) are kinda useless since the PSX defaults to
  31039 32bit parameters anyways. The force16bit code (h) may be useful as "%hn"
  31040 (writeback 16bit value), otherwise it's rather useless, unless signed 16bit
  31041 parameters have garbage in upper 16bit, for unsigned 16bit parameters it
  31042 doesn't work at all (accidently sign-expands 16bit to 32bit, and then displays
  31043 that signed 32bit value as giant unsigned value). Printf supports only octal,
  31044 decimal, and hex (but not binary).
  31045 
  31046 A(3Eh) or B(3Fh) std_out_puts(src) - Write string to TTY
  31047   in: R4=address of string (terminated by 00h)
  31048 Like "printf", but doesn't resolve any "%" operands. Empty strings are handled
  31049 in a special way: If R4 points to a 00h character then nothing is output (as
  31050 one would expect it), but, if R4 is 00000000h then "<NULL>" is output (only
  31051 that six letters; without appending any CR or LF).
  31052 
  31053 A(3Dh) or B(3Eh) std_in_gets(dst) - Read string from TTY (keyboard input)
  31054   in: r4=dst (pointer to a 128-byte buffer) - out: r2=dst (same is incoming r4)
  31055 Internally uses "std_in_getchar" to receive the separate characters (which are
  31056 thus masked by 7Fh). The received characters are stored in the buffer, and are
  31057 additionally sent back as echo to the TTY via std_out_putc.
  31058 The following characters are handled in a special way: 09h (TAB) is replaced by
  31059 a single SPC. 08h or 7FH (BS or DEL) are removing the last character from the
  31060 buffer (unless it is empty) and send 08h,20h,08h (BS,SPC,BS) to the TTY. 0Dh or
  31061 0Ah (CR or LF) do terminate the input (append 00h to the buffer, send 0Ah to
  31062 the TTY, which is expanded to 0Dh,0Ah by the std_out_putc function, and do then
  31063 return from the std_in_gets function).
  31064 The sequence 16h,NNh forces NNh to be stored in the buffer (even if NNh is a
  31065 special character like 00h..1Fh or 7Fh). If the buffer is full (circa max 125
  31066 chars, plus one extra byte for the ending 00h), or if an unknown control code
  31067 in range of 00h..1Fh is received without the 16h prefix, then 07h (BELL) is
  31068 sent to the TTY.
  31069 
  31070 A(3Bh) or B(3Ch) std_in_getchar() - Read character from TTY
  31071 Reads one character from the TTY console, by internally redirecting to
  31072 "FileRead(0,tempbuf,1)". The returned character is ANDed by 7Fh (so, to read a
  31073 fully intact 8bit character, "FileRead(0,tempbuf,1)" must be used instead of
  31074 this function).
  31075 
  31076 A(3Ch) or B(3Dh) std_out_putchar(char) - Write character to TTY
  31077 Writes the character to the TTY console, by internally redirecting to
  31078 "FileWrite(1,tempbuf,1)". Char 09h (TAB) is expanded to one or more SPC
  31079 characters, until reaching the next tabulation boundary (every 8 characters).
  31080 Char 0Ah (LF) is expanded to 0Dh,0Ah (CR,LF). Other special characters (which
  31081 should be handled at the remote terminal side) are 08h (BS, backspace, move
  31082 cursor one position to the left), and 07h (BELL, produce a short beep sound).
  31083 
  31084 C(13h) FlushStdInOutPut()
  31085 Closes and re-opens the std_in (fd=0) and std_out (fd=1) file handles.
  31086 
  31087 C(1Bh) KernelRedirect(ttyflag)  ;PS2: ttyflag=1 causes SystemError
  31088 Removes, re-mounts, and flushes the TTY device, the parameter selects whether
  31089 to mount the real DUART-TTY device (r4=1), or a Dummy-TTY device (r4=0), the
  31090 latter one sends any std_out to nowhere. Values other than r4=0 or r4=1 do
  31091 remove the device, but do not re-mount it (which might result in problems).
  31092 Caution: Trying to use r4=1 on a PSX that does not has the DUART hardware
  31093 installed causes the BIOS to hang (so one should first detect the DUART
  31094 hardware, eg. by writing two different bytes to Port 1F802020h.1st/2nd access,
  31095 and the read and verify that two bytes).
  31096 
  31097 Activating std_io
  31098 The std_io functions can be enabled via C(1Bh) KernelRedirect(ttyflag), the
  31099 BIOS is unable to detect the presence of the TTY hardware, by default the BIOS
  31100 bootcode disables std_io by setting the initial KernelRedirect value at
  31101 [A000B9B0h] to zero, this is hardcoded shortly after the POST(E) output:
  31102   call    output_post_r4        ;\output POST(E)
  31103   +mov    r4,0Eh                ;/
  31104   mov     r1,0A0010000h         ;\set [0A000B9B0h]=0 ;TTY=dummy/off
  31105   call    reset_cont_d_3        ; and call reset_cont_d_3
  31106   +mov    [r1-4650h],0          ;/
  31107 assuming that R28=A0010FF0h, the last 3 opcodes of above code can be replaced
  31108 by:
  31109   mov     r1,1h                 ;\set [0A000B9B0h]=1 ;TTY=duart/on
  31110   call    reset_cont_d_3        ; and call reset_cont_d_3
  31111   +mov    [r28-4650h-0ff0h],r1  ;/
  31112 with that patch, the BIOS bootcode (and many games) are sending debug messages
  31113 to the debug terminal, via expansion port, see:
  31114 --> EXP2 Dual Serial Port (for TTY Debug Terminal)
  31115 Note: The nocash BIOS automatically detects the DUART hardware, and activates
  31116 TTY if it is present.
  31117 
  31118 B(49h) PrintInstalledDevices()
  31119 Uses printf to display the long and short names from the DCB of the currently
  31120 installed devices. Doesn't do anything else. There's no return value.
  31121 
  31122 Note
  31123 Several BIOS functions are internally using printf to output status
  31124 information, timeout, and error messages, etc. So, trying to close the TTY file
  31125 handles (fd=0 and fd=1) would cause such functions to work unstable.
  31126 
  31127 BIOS Character Sets
  31128 -------------------
  31129 
  31130 B(51h) Krom2RawAdd(shiftjis_code)
  31131   In: r4  = 16bit Shift-JIS character code
  31132   Out: r2 = address in BIOS ROM of the desired character (or -1 = error)
  31133 r4 should be 8140h..84BEh (charset 2), or 889Fh..9872h (charset 3).
  31134 
  31135 B(53h) Krom2Offset(shiftjis_code)
  31136   In: r4  = 16bit Shift-JIS character code
  31137   Out: r2 = offset within charset (without charset base address)
  31138 This is a subfunction for B(51h) Krom2RawAdd(shiftjis_code).
  31139 
  31140 Character Sets in ROM (112Kbytes)
  31141 The character sets are located at BFC64000h and up, intermixed with some other
  31142 stuff:
  31143   BFC64000h  Charset 1 (16x15 pix, letters with accent marks)    (NOT in JAPAN)
  31144   BFC65CB6h  Garbage   (four-and-a-half reverb tables, ioports, printf strings)
  31145   BFC66000h  Charset 2 (16x15 pix, various alphabets, english, greek, etc.)
  31146   BFC69D68h  Charset 3 (16x15 pix, japanese or chinese symbols or so)
  31147   BFC7F8DEh  Charset 4 (8x15 pix, mainly ASCII letters)
  31148   BFC7FE6Fh  Charset 5 (8x15 pix, additional punctuation marks)    (NOT in PS2)
  31149   BFC7FF32h  Version   (Version and Copyright strings)        (NOT in SCPH1000)
  31150   BFC7FF8Ch  Charset 6 (8x15 pix, seven-and-a-half japanese chars) (NOT in PS2)
  31151   BFC80000h  End       (End of 512kBYTE BIOS ROM)
  31152 Charset 1 (and Garbage) is NOT included in japanese BIOSes (in the SCPH1000
  31153 version that region contains uncompressed program code, in newer japanese
  31154 BIOSes that regions are zerofilled)
  31155 Charset 1 symbols are as defined in JIS-X-0212 char(2661h..2B77h), and EUC-JP
  31156 char(8FA6E0h..8FABF7h).
  31157 Version (and Copyright) string is NOT included in SCPH1000 version (that BIOS
  31158 includes further japanese 8x15 pix chars in that region).
  31159 For charset 2 and 3 it may be recommended to use the B(51h)
  31160 Krom2RawAdd(shiftjis_code) to obtain the character addresses. There is no BIOS
  31161 function to retrieve charset 1, 4, 5, and 6 addresses.
  31162 
  31163 BIOS Control Blocks
  31164 -------------------
  31165 
  31166 Exception Control Blocks (ExCB) (4 blocks of 8 bytes each)
  31167   00h 4   ptr to first element of exception chain
  31168   04h 4   not used (zero)
  31169 
  31170 Event Control Blocks (EvCB) (usually 16 blocks of 1Ch bytes each)
  31171   00h 4   class  (events are triggered when class and spec match)
  31172   04h 4   status (0=free,1000h=disabled,2000h=enabled/busy,4000h=enabled/ready)
  31173   08h 4   spec   (events are triggered when class and spec match)
  31174   0Ch 4   mode   (1000h=execute function/stay busy, 2000h=no func/mark ready)
  31175   10h 4   ptr to function to be executed when ready (or 0=none)
  31176   14h 8   not used (uninitialized)
  31177 
  31178 Thread Control Blocks (TCB) (usually 4 blocks of 0C0h bytes each)
  31179   00h 4   status        (1000h=Free TCB, 4000h=Used TCB)
  31180   04h 4   not used      (set to 1000h by OpenThread) (not for boot executable?)
  31181   08h 80h r0..r31       (entries for r0/zero and r26/k0 are unused)
  31182   88h 4   cop0r14/epc   (aka r26/k0 and pc when returning from exception)
  31183   8Ch 8   hi,lo         (the mul/div registers)
  31184   94h 4   cop0r12/sr    (stored/restored by exception, NOT init by OpenThread)
  31185   98h 4   cop0r13/cause (stored when entering exception, NOT restored on exit)
  31186   9Ch 24h not used      (uninitialized)
  31187 
  31188 Process Control Block (1 block of 4 bytes)
  31189   00h 4   ptr to TCB of current thread
  31190 The PSX supports only one process, and thus only one Process Control Block.
  31191 
  31192 File Control Blocks (FCB) (16 blocks of 2Ch bytes each)
  31193   00h 4  status (0=Free FCB) (nonzero=accessmode)
  31194   04h 4  cdrom: disk_id (checksum across path table of the corresponding disk),
  31195          memory card: port number (00h=slot1, 10h=slot2)
  31196   08h 4  transfer address (for dev_in_out function)
  31197   0Ch 4  transfer length  (for dev_in_out function)
  31198   10h 4  current file position
  31199   14h 4  device flags (copy of DCB[04h])
  31200   18h 4  error  ;used by B(55h) - GetLastFileError(fd)
  31201   1Ch 4  Pointer to DCB for the file
  31202   20h 4  filesize
  31203   24h 4  logical block number (start of file) (for cdrom: at least)
  31204   28h 4  file control block number (simply 0..15 for FCB number 0..15)
  31205 
  31206 Device Control Blocks (DCB) (10 blocks of 50h bytes each)
  31207   00h 4   ptr to lower-case short name ("cdrom", "bu", "tty") (or 0=Free DCB)
  31208   04h 4   device flags (cdrom=14h, bu=14h, tty/dummy=1, tty/duart=3)
  31209   08h 4   sector size  (cdrom=800h, bu=80h, tty=1)
  31210   0Ch 4   ptr to upper-case long name  ("CD-ROM", "MEMORY CARD", "CONSOLE")
  31211   10h 4   ptr to init()                                         (TTY only)
  31212   14h 4   ptr to open(fcb,"path\name",accessmode)
  31213   18h 4   ptr to in_out(fcb,cmd)                                (TTY only)
  31214   1Ch 4   ptr to close(fcb)
  31215   20h 4   ptr to ioctl(fcb,cmd,arg)                             (TTY only)
  31216   24h 4   ptr to read(fcb,dst,len)
  31217   28h 4   ptr to write(fcb,src,len)
  31218   2Ch 4   ptr to erase(fcb,"path\name")
  31219   30h 4   ptr to undelete(fcb,"path\name")
  31220   34h 4   ptr to firstfile(fcb,"path\name",direntry)
  31221   38h 4   ptr to nextfile(fcb,direntry)
  31222   3Ch 4   ptr to format(fcb)
  31223   40h 4   ptr to chdir(fcb,"path")                            (CDROM only)
  31224   44h 4   ptr to rename(fcb1,"path\name1",fcb2,"path\name2")
  31225   48h 4   ptr to remove()
  31226   4Ch 4   ptr to testdevice(fcb,"path\name")
  31227 
  31228 BIOS Boot State
  31229 ---------------
  31230 
  31231 The BIOS/Kernel is doing little hardware initialization, however, most of the
  31232 GPU/GTE/SPU registers contain leftovers from the BIOS/GUI, namely from the
  31233 "PS"-intro. Though there are some special cases:
  31234  - GUI 1.0j displays "PS"-intro only for japanese discs (but does allow to
  31235    boot non-japanese discs, but without showing the "PS"-intro; so GPU/SPU
  31236    leftovers are then from "<S>"-intro, and GTE is left uninitialized).
  31237  - Some registers may differ when inserting a CDROM while in boot menu.
  31238  - There may be small differences depending on CDROM loading time.
  31239  - Expansion ROMs or Kernel Clones may initialize some things differently.
  31240  - Different Kernel versions may differ (especially on initial CPU registers).
  31241 Values below were recorded in no$psx, some values might differ on real
  31242 hardware.
  31243 
  31244 Games
  31245 Most games are initializing all required hardware registers, but some do rely
  31246 on GUI leftovers:
  31247  - Saga Frontier requires GPU display enable via GP1(03h)=0
  31248 
  31249 CPU Registers
  31250   pc     = <ExeEntrypoint>              r16/s0 = 0a000b870h    ;kernel ram
  31251   r1/at  = 000000005h                   r17/s1 = 0
  31252   r2/v0  = 000000001h                   r18/s2 = 0
  31253   r3/v1  = 000000004h  ;can be 1 or 4   r19/s3 = 0
  31254   r4/a0  = 000000001h  ;boot param1=1   r20/s4 = 0
  31255   r5/a1  = 0           ;boot param2=0   r21/s5 = 0
  31256   r6/a2  = 0                            r22/s6 = 0
  31257   r7/a3  = 00000002Ah                   r23/s7 = 0bfc0702ch    ;kernel rom
  31258   r8/t0  = <SystemCnfSp> ;from do_exec  r24/t8 = 00000001fh
  31259   r9/t1  = 0             ;from do_exec  r25/t9 = 01f801802h    ;I/O addr
  31260   r10/t2 = 00000002dh                   r26/k0 = 0bfc0d968h    ;kernel rom
  31261   r11/t3 = <ExeEntrypoint>              r27/k1 = 000000f1ch
  31262   r12/t4 = 000000023h                   r28/gp = 0
  31263   r13/t5 = 00000002bh                   r29/sp = <SystemCnfSp> ;sp
  31264   r14/t6 = 000000001h                   r30/fp = <SystemCnfSp> ;same as sp
  31265   r15/t7 = 01f801800h    ;I/O addr      r31/ra = <RetadrToKernel>
  31266   lo     = 000000001h                   hi     = 0
  31267 
  31268 COP0 Registers (System)
  31269   cop0r6/jumpdest = <varies>         cop0r3/bpc   = 0
  31270   cop0r8/badvaddr = FFFFFFFFh        cop0r5/bda   = 0
  31271   cop0r12/sr      = 40000000h        cop0r7/dcic  = 0
  31272   cop0r13/cause   = 00000020h        cop0r9/bdam  = 0
  31273   cop0r14/epc     = <RetadrFromIrq>  cop0r11/bpcm = 0
  31274   cop0r15/prid    = 00000002h, or 1
  31275 
  31276 COP2 Registers (GTE)
  31277   cop2r0  = 000000b50h ;\vector0     cop2r32 = 000000ffbh ;\
  31278   cop2r1  = 000000b50h ;/            cop2r33 = 0ffb7ff44h ; rotation
  31279   cop2r2  = 0fdabff8dh ;\vector1     cop2r34 = 0f9ca0ebch ; matrix
  31280   cop2r3  = 0fffffe51h ;/            cop2r35 = 0063700adh ;
  31281   cop2r4  = 0fdab000ah ;\vector2     cop2r36 = 000000eb7h ;/
  31282   cop2r5  = 0fffffdd4h ;/            cop2r37 = 0          ;\translation
  31283   cop2r6  = 0200808ffh ;-rgbc        cop2r38 = 0fffffeach ; vector
  31284   cop2r7  = 000000509h ;-otz         cop2r39 = 000001700h ;/
  31285   cop2r8  = 0000000a4h ;-ir0         cop2r40 = 0          ;\
  31286   cop2r9  = 00000104ah ;\            cop2r41 = 000000fa0h ; light source
  31287   cop2r10 = 000000082h ; ir1-3       cop2r42 = 00000f060h ; matrix
  31288   cop2r11 = 000000082h ;/            cop2r43 = 00000f060h ;
  31289   cop2r12 = 00041012dh ;\            cop2r44 = 0          ;/
  31290   cop2r13 = 00063012dh ; screen      cop2r45 = 000000640h ;\background
  31291   cop2r14 = 000690146h ; xy fifo     cop2r46 = 000000640h ; color
  31292   cop2r15 = 000690146h ;/            cop2r47 = 000000640h ;/
  31293   cop2r16 = 000001441h ;\            cop2r48 = 00bb80fa0h ;\
  31294   cop2r17 = 000001441h ; screen      cop2r49 = 00fa00fa0h ; light color
  31295   cop2r18 = 000001486h ; z fifo      cop2r50 = 00fa00bb8h ; matrix source
  31296   cop2r19 = 000001419h ;/            cop2r51 = 00bb80fa0h ;
  31297   cop2r20 = 0200808ffh ;\color       cop2r52 = 000000fa0h ;/
  31298   cop2r21 = 0200808ffh ; rgb fifo    cop2r53 = 0          ;\
  31299   cop2r22 = 0200808ffh ;/            cop2r54 = 0          ; far color
  31300   cop2r23 = 0          ;-reserved    cop2r55 = 0          ;/
  31301   cop2r24 = 0fffffcaeh ;-mac0        cop2r56 = 001400000h ;\screen offset
  31302   cop2r25 = 00000104ah ;\            cop2r57 = 000f00000h ;/
  31303   cop2r26 = 000000082h ; mac1-3      cop2r58 = 000000400h ;-h
  31304   cop2r27 = 000000082h ;/            cop2r59 = 0fffff9e9h ;-dqa
  31305   cop2r28 = 00000043fh ;-irgb        cop2r60 = 001400000h ;-dqb
  31306   cop2r29 = 00000043fh ;-orgb        cop2r61 = 000000155h ;\average z scale
  31307   cop2r30 = 0          ;-lzcs        cop2r62 = 000000100h ;/
  31308   cop2r31 = 000000020h ;-lzcr        cop2r63 = 000600000h ;-flag
  31309 
  31310 GPU/MDEC Registers
  31311   GP1(03h)=000000h                  display_disable (0=on)
  31312   GP1(04h)=000000h                  dma_direction
  31313   GP1(05h)=000800h                  display_address
  31314   GP1(06h)=c7e27eh                  display_x_range
  31315   GP1(07h)=04682bh                  display_y_range
  31316   GP1(08h)=000027h+bit3             display_mode (bit3=pal)
  31317   GP1(09h)=000000h                  tex_disable
  31318   GP0(E1h)=00300Dh                  tex_page
  31319   GP0(E2h)=000000h=GP1(10h:2)       tex_window
  31320   GP0(E3h)=000800h=GP1(10h:3)       draw_x1y1
  31321   GP0(E4h)=077e7fh=GP1(10h:4)       draw_x2y2
  31322   GP0(E5h)=001000h=GP1(10h:5)       draw_offset
  31323   GP0(E6h)=000000h                  mask_setting
  31324   GP1(10h:7)=000002h (if any)       gpu_version
  31325   GP1(10h:8)=000000h (if any)       unknown
  31326   [1f801814h]=144e200dh+bit31+bit20 gpu_stat (bit31=even/odd, bit20=pal)
  31327   [1f801824h]=80040000h             mdec_stat
  31328 VRAM isn't cleared when starting the EXE (it does usually contain the
  31329 640x480pix bootscreen with the PS logo, and some related textures).
  31330 MDEC quant/scale tables are uninitialized (unknown if /RESET sets them to some
  31331 default values, or zeroes, or random).
  31332 
  31333 CDROM Registers
  31334   stat=02h, mode=20h, file=00h, channel=00h
  31335   [1f801800h.read]=39h    ;index
  31336   [1f801803h.read.0]=FFh  ;irq.enable
  31337   [1f801803h.read.1]=E0h  ;irq.flag
  31338 
  31339 Misc Registers
  31340   exp1_base [1f801000h]=1f000000h      ;\
  31341   exp2_base [1f801004h]=1f802000h      ;
  31342   exp1_siz  [1f801008h]=0013243fh      ;
  31343   exp3_siz  [1f80100ch]=00003022h      ; memory control 1
  31344   bios_siz  [1f801010h]=0013243fh      ;
  31345   spu_siz   [1f801014h]=200931e1h      ;
  31346   cdrom_siz [1f801018h]=00020943h      ;
  31347   exp2_siz  [1f80101ch]=00070777h      ;
  31348   com_delay [1f801020h]=0000132ch      ;/
  31349   ram_siz   [1f801060h]=00000b80h+bit3 ;-memory control 2 (bit3=newtype)
  31350   cache_cnt [fffe0130h]=0001e988h      ;-cache control
  31351   post      [1f802041h]=09h            ;-post (write-only, if any)
  31352   joy_data  [1f801040h]=00000000h      ;\
  31353   joy_stat  [1f801044h]=00000805h      ;
  31354   joy_mode  [1f801048h]=0000h          ; joypad
  31355   joy_ctrl  [1f80104ah]=0000h          ;
  31356   joy_baud  [1f80104eh]=0000h          ;/
  31357   sio_data  [1f801050h]=00000000h      ;\
  31358   sio_stat  [1f801054h]=00000805h      ;
  31359   sio_mode  [1f801058h]=0000h          ; sio
  31360   sio_ctrl  [1f80105ah]=0000h          ;
  31361   sio_misc  [1f80105ch]=0000h          ;
  31362   sio_baud  [1f80105eh]=0000h          ;/
  31363   irq_stat  [1f801070h]=00000001h      ;\interrupt control
  31364   irq_mask  [1f801074h]=0000000ch      ;/
  31365 
  31366 DMA Registers (addr,len,cnt)
  31367   [1f801080h]=<random> ,<random> ,00000000h ;dma0 mdec.in
  31368   [1f801090h]=<random> ,<random> ,00000000h ;dma1 mdec.out
  31369   [1f8010a0h]=00ffffffh,00000000h,00000401h ;dma2 gpu
  31370   [1f8010b0h]=<ExeLast>,00010200h,00000000h ;dma3 cdrom
  31371   [1f8010c0h]=<random> ,<random> ,00000000h ;dma4 spu
  31372   [1f8010d0h]=<random> ,<random> ,00000000h ;dma5 pio
  31373   [1f8010e0h]=00129834h,00000400h,00000002h ;dma6 otc
  31374   [1f8010f0h]=00009099h ;dma_cnt
  31375   [1f8010f4h]=848c0000h ;dma_irq
  31376   [1f8010f8h]=0BFAC688h ;dma_unk1
  31377   [1f8010fch]=00000000h ;dma_unk2
  31378 DMA3 has ExeLast=(ExeEnd-800h) and 00ffffffh.
  31379 
  31380 Timer Registers (val,mode,dest)
  31381   [1f801100h,04h,08h]=<T+009Ch>,1c00h,0000h  ;timer0
  31382   [1f801110h,04h,08h]=<T+004Eh>,1c00h,0000h  ;timer1
  31383   [1f801120h,04h,08h]=<T+0000h>,1c00h,0000h  ;timer2
  31384 The timers are running in SysClk mode, and they are started almost
  31385 simultaneously, and do thus contain almost the same value (about 4Eh cycles
  31386 apart).
  31387 
  31388 SPU Control
  31389   [1f801d80h]=37ef3fffh ;spu_main_vol   ;[1f801da0h]=<random>    ;spu_unk1
  31390   [1f801d84h]=5ebc5ebch ;spu_echo_vol    [1f801da2h]=e128h       ;spu_echo_base
  31391   [1f801d88h]=00000000h ;spu_key_on      [1f801da4h]=0000h       ;spu_irq_addr
  31392   [1f801d8ch]=00000c00h ;spu_key_off     [1f801da6h]=0200h       ;spu_xfer_addr
  31393   [1f801d90h]=00000000h ;spu_freqmod    ;[1f801da8h]=0000h       ;spu_xfer_fifo
  31394   [1f801d94h]=00000000h ;spu_noise       [1f801daah]=c085h       ;spu_cnt
  31395   [1f801d98h]=00ffffffh ;spu_reverb      [1f801dach]=0004h       ;spu_xfer_ctrl
  31396   [1f801d9ch]=00ffffcfh ;spu_on_off      [1f801daeh]=0005h+bit11 ;spu_stat
  31397   [1f801db8h]=6fde7ffeh ;spu_curr_vol    [1f801db0h]=0000h       ;spu_cd_vol
  31398  ;[1f801dbch]=<random>  ;spu_unk2        [1f801db4h]=0000h       ;spu_aux_vol
  31399  ;[1f801e60h..7Fh]=<random>  ;spu_unk3
  31400 
  31401 SPU Reverb (Echo)
  31402   [1f801dd4h]=1a311ed6h ;echo_m_same     [1f801dc0h]=033dh ;echo_d_appf1
  31403   [1f801dd8h]=183b1d14h ;echo_m_comb1    [1f801dc2h]=0231h ;echo_d_appf2
  31404   [1f801ddch]=16b21bc2h ;echo_m_comb2    [1f801dc4h]=7e00h ;echo_v_iir
  31405   [1f801de0h]=15ef1a32h ;echo_d_same     [1f801dc6h]=5000h ;echo_v_comb1
  31406   [1f801de4h]=105515eeh ;echo_m_diff     [1f801dc8h]=b400h ;echo_v_comb2
  31407   [1f801de8h]=0f2d1334h ;echo_m_comb3    [1f801dcah]=b000h ;echo_v_comb3
  31408   [1f801dech]=0c5d11f6h ;echo_m_comb4    [1f801dcch]=4c00h ;echo_v_comb4
  31409   [1f801df0h]=0ae11056h ;echo_d_diff     [1f801dceh]=b000h ;echo_v_wall
  31410   [1f801df4h]=07a20ae0h ;echo_m_apf1     [1f801dd0h]=6000h ;echo_v_apf1
  31411   [1f801df8h]=02320464h ;echo_m_apf2     [1f801dd2h]=5400h ;echo_v_apf2
  31412   [1f801dfch]=80008000h ;echo_v_in
  31413 
  31414 SPU Voice 0..23 (vol,rateaddr,adsr,stat, and currvol)
  31415 Below are leftovers from PS-logo. Observe that some voices and ADSR generators
  31416 are still running at time when starting the EXE file (some of that may depend
  31417 on CDROM seek time and EXE file size).
  31418   [1f801c00h]=00000e7fh,02000bfch,dfed8c7ah,034c0000h  [1f801e00h]=00001cfeh
  31419   [1f801c10h]=00000d0ch,02000aadh,dfed8c7ah,034c0000h  [1f801e04h]=00001a18h
  31420   [1f801c20h]=0b740000h,02000c12h,dfed8c7ah,034c0000h  [1f801e08h]=16e80000h
  31421   [1f801c30h]=05420000h,02000ac1h,dfed8c7ah,034c0000h  [1f801e0ch]=0a840000h
  31422   [1f801c40h]=00001548h,0200017fh,cfaeb8ffh,034c4c41h  [1f801e10h]=00002a90h
  31423   [1f801c50h]=16ab0000h,02000182h,cfaeb8ffh,034c4c41h  [1f801e14h]=2d560000h
  31424   [1f801c60h]=00003e03h,0c2802abh,dff18088h,14c40faeh  [1f801e18h]=00007c06h
  31425   [1f801c70h]=0000089eh,02001000h,dfed8c7ah,034c0000h  [1f801e1ch]=0000113ch
  31426   [1f801c80h]=000005f4h,02000400h,dfed8c7ah,034c0000h  [1f801e20h]=00000be8h
  31427   [1f801c90h]=02660000h,02000407h,dfed8c7ah,034c0000h  [1f801e24h]=04cc0000h
  31428   [1f801ca0h]=00000bf7h,02000200h,cfaeb8ffh,034c0000h  [1f801e28h]=000017eeh
  31429   [1f801cb0h]=0cc00000h,02000203h,cfaeb8ffh,034c0000h  [1f801e2ch]=19800000h
  31430   [1f801cc0h]=00000735h,02000720h,dfed8c7ah,034c0000h  [1f801e30h]=00000e6ah
  31431   [1f801cd0h]=05b10000h,0200072dh,dfed8c7ah,034c0000h  [1f801e34h]=0b620000h
  31432   [1f801ce0h]=0000076fh,02000983h,dfed8c7ah,034c0000h  [1f801e38h]=00000edeh
  31433   [1f801cf0h]=0a640000h,02000995h,dfed8c7ah,034c0000h  [1f801e3ch]=14c80000h
  31434   [1f801d00h]=00000455h,02000aadh,dfed8c7ah,034c0000h  [1f801e40h]=000008aah
  31435   [1f801d10h]=0c0d0000h,02000ac1h,dfed8c7ah,034c0000h  [1f801e44h]=181a0000h
  31436   [1f801d20h]=00002171h,0c280556h,dff18088h,14c40fb8h  [1f801e48h]=000042e2h
  31437   [1f801d30h]=0c0d0000h,0200101dh,dfed8c7ah,034c0000h  [1f801e4ch]=181a0000h
  31438   [1f801d40h]=00000b43h,02000e41h,dfed8c7ah,034c0000h  [1f801e50h]=00001686h
  31439   [1f801d50h]=0fbd0000h,02000e5bh,dfed8c7ah,034c0000h  [1f801e54h]=1f7a0000h
  31440   [1f801d60h]=00000893h,02000800h,dfed8c7ah,034c0000h  [1f801e58h]=00001126h
  31441   [1f801d70h]=06c70000h,0200080eh,dfed8c7ah,034c0000h  [1f801e5ch]=0d8e0000h
  31442 
  31443 BIOS Versions
  31444 -------------
  31445 
  31446 Kernel Versions
  31447 For the actual kernel, there seem to be only a few different versions. Most
  31448 PSX/PSone's are containing the version from 1995 (which is kept 1:1 the same in
  31449 all consoles; without any PAL/NTSC related customizations).
  31450   28-Jul-1994  "DTL-H2000"                   ;v0.x (pre-retail devboard)
  31451   22-Sep-1994  "CEX-1000 KT-3  by S.O."      ;v1.0 through v2.0
  31452   no-new-date  "CEX-3000 KT-3  by K.S."      ;v2.1 only (old Port 1F801060h)
  31453   04-Dec-1995  "CEX-3000/1001/1002 by K.S."  ;v2.2 through v4.5 (except v4.0)
  31454   29-May-1997  "CEX-7000/-7001 by K.S.    "  ;v4.0 only (new Port 1F801010h)
  31455   17-Jan-2000  "PS compatible mode by M.T."  ;v5.0 (Playstation 2)
  31456 The date and version string can be retrieved via GetSystemInfo(index).
  31457 The "CEX-7000/-7001" version was only "temporarily" used (when the kernel/gui
  31458 grew too large they changed the ROM size from 512K to 1024K; but did then
  31459 figure out that they could use a self-decompressing GUI to squeeze everything
  31460 into 512K; but they did accidentally still use the 1024K setting) (newer
  31461 consoles fixed that and switched back to the old version from 1995) (aside from
  31462 the different date/version string, the only changed thing is the opcode at
  31463 BFC00000h, which initializes port 1F801010h to BIOS ROM size of 1MB, instead of
  31464 512KB; no idea if that BIOS does actually contain additional data?).
  31465 The "CEX-3000 KT-3" version is already almost same as "CEX-3000/1001/1002",
  31466 aside from version/date, the only differences are at offset BFC00014h..1Fh, and
  31467 BFC003E0h (both related to Port 1F801060h).
  31468 
  31469 Bootmenu/Intro Versions
  31470 This portion was updated more often. It's customized for PAL/NTSC displays,
  31471 japanese/english language, and (maybe?) region/licence string checks. The
  31472 SCPH1000 uses uncompressed Bootmenu/Intro code with "<S>" intro and "PS" intro
  31473 (although "PS" is shown only on region matches), newer versions are using
  31474 selfdecompressing code. The GUI in older PSX models looks like a drawing
  31475 program for children, the GUI in newer PSX models and in PSone's looks more
  31476 like a modernized bathroom furniture, unknown how the PS2 GUI looks like?
  31477 Games are communicating only with the Kernel, so the differences in the
  31478 Bootmenu/Intro part should have little or effect on compatibility (although
  31479 some I/O ports might be initialized differently, and although some games might
  31480 (accidently) read different (garbage) values from the ROM).
  31481   Ver  CRC32    Used in                      System ROM Version  Kernel
  31482   0.xj 18D0F7D8 DTL-H2000                    (no version string) dtlh2000
  31483   1.0j 3B601FC8 SCPH-1000 and DTL-H1000      (no version string) cex1000
  31484   1.1j 3539DEF6 SCPH-3000 and DTL-H1000H     "1.1 01/22/95"      ""
  31485   2.0a 55847D8C DTL-H1001                    "2.0 05/07/95 A"    ""
  31486   2.0e 9BB87C4B SCPH-1002 and DTL-H1002      "2.0 05/10/95 E"    ""
  31487   2.1j BC190209 SCPH-3500                    "2.1 07/17/95 J"    cex3000
  31488   2.1a AFF00F2F SCPH-1001 and DTL-H1101      "2.1 07/17/95 A"    ""
  31489   2.1e 86C30531 SCPH-1002 and DTL-H1102      "2.1 07/17/95 E"    ""
  31490   2.2j 24FC7E17 SCPH-5000 and DTL-H1200      "2.2 12/04/95 J"    cex3000/100x
  31491   2.2a 37157331 SCPH-1001 and DTL-H1201/3001 "2.2 12/04/95 A"    ""
  31492   2.2e 1E26792F SCPH-1002 and DTL-H1202/3002 "2.2 12/04/95 E"    ""
  31493   2.2v 446EC5B2 SCPH-5903 (VCD, 1Mbyte)      "2.2 12/04/95 J"    ""
  31494   2.2d DECB22F5 DTL-H1100                    "2.2 03/06/96 D"    ""
  31495   3.0j FF3EEB8C SCPH-5500                    "3.0 09/09/96 J"    ""
  31496   3.0a 8D8CB7E4 SCPH-5501/7003               "3.0 11/18/96 A"    ""
  31497   3.0e D786F0B9 SCPH-5502/5552               "3.0 01/06/97 E"    ""
  31498   4.0j EC541CD0 SCPH-7000/9000               "4.0 08/18/97 J"    cex7000
  31499   4.1w B7C43DAD SCPH-7000W                       ...XXX...
  31500   4.1a 502224B6 SCPH-7001/7501/7503/9001     "4.1 12/16/97 A"    cex3000/100x
  31501   4.1e 318178BF SCPH-7002/7502/9002          "4.1 12/16/97 E"    ""
  31502   4.3j F2AF798B SCPH-100  (PSone)            "4.3 03/11/00 J"    ""
  31503   4.4a 6A0E22A0 SCPH-101  (PSone)            "4.4 03/24/00 ..XXX..
  31504   4.4e 0BAD7EA9 SCPH-102  (PSone)            "4.4 03/24/00 E"    ""
  31505   4.5a 171BDCEC SCPH-101  (PSone)            "4.5 05/25/00 A"    ""
  31506   4.5e 76B880E5 SCPH-102  (PSone)            "4.5 05/25/00 E"    ""
  31507   5.0t B7EF81A9 SCPH10000 (Playstation 2)    "5.0 01/17/00 T"    PS compatible
  31508 The System ROM Version string can be found at BFC7FF32h (except in v1.0).
  31509 
  31510 v2.2j/a/e use exactly the same GUI as v2.1 (only the kernel was changed). v2.2d
  31511 is almost same as v2.2j (but with some GUI patches or so).
  31512 v4.1 and v4.5 use exactly the same GUI code for "A" and "E" regions (the only
  31513 difference is the last byte of the version string; which does specify whether
  31514 the GUI shall use PAL or NTSC).
  31515 v5.0 is playstation 2 bios (4MB) with more or less backwards compatible kernel.
  31516 
  31517 Character Set Versions
  31518 The 16x15 pixel charsets at BFC66000h and BFC69D68h are included in all BIOSes,
  31519 however, the 16x15 portion for letters with accent marks at BFC64000h is
  31520 included only in non-japanese BIOSes, and in some newer japanese BIOSes (not
  31521 included in v4.0j, but they are included in v4.3j).
  31522 The 8x15 pixel charset with characters 21h..7Fh is included in all BIOSes. In
  31523 the SCPH1000, this region is followed by additional 8x15 punctuation marks at
  31524 char 80h and up, however, this region is missing in PS2 BIOS. Moreover, some
  31525 BIOSes include an incomplete 8x15 japanese character set (which ends abruptly
  31526 at BF7FFFFFh), in newer BIOSes, some of theses chars are replaced by the
  31527 version string at BFC7FF32h, and, the remaining 8x15 japanese chars were
  31528 removed in the PS2 BIOS version.
  31529 
  31530 BIOS Patches
  31531 ------------
  31532 
  31533 The original PSX Kernel mainly consists of messy and unstable compiler
  31534 generated code, and, to the worst, the <same> author seems to have attempted to
  31535 use assembler code in some places. In result, most commercial games are causing
  31536 a greater mess by inserting patches in the kernel code...
  31537 Which has been a nasty surprise when making the nocash PSX bios; which
  31538 obviously wasn't compatible with these patches. The only solutions would have
  31539 been to insert hundreds of NOPs to make my bios <exactly> as bloated as the
  31540 original bios (which I really didn't want to do), or to create
  31541 anti-patch-patches.
  31542 
  31543 Patches and Anti-Patch-Patches
  31544 As shown below, all known patches are invoked by a B(56h) or B(57h) function
  31545 call. In the nocash PSX bios, these two functions are examining the following
  31546 opcodes, if the opcodes are a known patch, then the BIOS reproduces the desired
  31547 behaviour, and does then continue normal execution after those opcodes. If the
  31548 opcodes are unknown, then the BIOS simply locks up; and shows an error message
  31549 with the address of that opcodes in the TTY window; info about any such unknown
  31550 opcodes would be welcome!
  31551 
  31552 Compatibility
  31553 If you want to (or need to) use patches, please use byte-identical opcodes as
  31554 commercial games do (as shown below; only the "xxxx" address digits are don't
  31555 care), so the nocash PSX bios (or other homebrewn BIOSes) can detect and
  31556 reproduce them. Or alternately, don't use the BIOS, and access I/O ports
  31557 directly, which is much better and faster anyways.
  31558 
  31559 patch_missing_cop0r13_in_exception_handler:
  31560 In newer Kernel version, the exception handler reads cop0r13/cause to r2,
  31561 examines the Excode value in r2, and if the exception was caused by an
  31562 interrupt, and if the next opcode (at EPC) is a GTE/COP2 command, then it does
  31563 increment EPC by 4. The GTE commands are executed even if an interrupt occurs
  31564 simultaneously, so, without adjusting EPC, the command would be executed twice.
  31565 With some commands that'd just waste some clock cycles, with other commands it
  31566 may cause data to be written twice to the GTE FIFOs, or may re-use the result
  31567 from the 1st command execution as input to the 2nd execution.
  31568 The old "CEX-1000 KT-3" Kernel version did examine r2, but it "forgot" to
  31569 previously load cop0r13 to r2, so it did randomly examine a garbage value. The
  31570 patch inserts the missing opcode, used in elo2 at 80033740h, and in Pandemonium
  31571 II at 8007F3FCh:
  31572   240A00B0 mov  r10,0B0h                      ;\   00000000 nop
  31573   0140F809 call r10                           ;    00000000 nop
  31574   24090056 +mov  r9,56h                       ;/   241A0100 mov k0,100h
  31575   3C0Axxxx mov  r10,xxxx0000h                 ;\   8F5A0008 mov k0,[k0+8h]
  31576   3C09xxxx mov  r9,xxxx0000h                  ;    00000000 nop
  31577   8C420018 mov  r2,[r2+06h*4] ;=C(06h)        ;    8F5A0000 mov k0,[k0]
  31578   254Axxxx add  r10,xxxxh ;=@@new_data        ;    00000000 nop
  31579   2529xxxx add  r9,xxxxh  ;=@@new_data_end    ;/   235A0008 addt k0,8h
  31580           @@copy_lop:                         ;\   AF410004 mov [k0+4h],r1
  31581   8D430000 mov  r3,[r10]                      ;    AF420008 mov [k0+8h],r2
  31582   254A0004 add  r10,4h                        ;    AF43000C mov [k0+0Ch],r3
  31583   24420004 add  r2,4h                         ;    AF5F007C mov [k0+7Ch],ra
  31584   1549FFFC jne  r10,r9,@@copy_lop             ;    40026800 mov r2,cop0r13
  31585   AC43FFFC +mov [r2-4h],r3                    ;/   00000000 nop
  31586 Alternately, same as above, but using k0/k1 instead of r10/r9, used in Ridge
  31587 Racer at 80047B14h:
  31588   240A00B0 mov  r10,0B0h                      ;\     00000000 nop
  31589   0140F809 call r10                           ;      00000000 nop
  31590   24090056 +mov r9,56h                        ;/     241A0100 mov  k0,100h
  31591   3C1Axxxx mov  k0,xxxx0000h                  ;\     8F5A0008 mov  k0,[k0+8h]
  31592   3C1Bxxxx mov  k1,xxxx0000h                  ;      00000000 nop
  31593   8C420018 mov  r2,[r2+06h*4] ;=C(06h)        ;      8F5A0000 mov  k0,[k0]
  31594   275Axxxx add  k0,xxxxh  ;=@@new_data        ;      00000000 nop
  31595   277Bxxxx add  k1,xxxxh  ;=@@new_data_end    ;/     235A0008 addt k0,8h
  31596           @@copy_lop:                         ;\     AF410004 mov  [k0+4h],r1
  31597   8F430000 mov  r3,[k0]                       ;      AF420008 mov  [k0+8h],r2
  31598   275A0004 add  k0,4h                         ;      AF43000C mov  [k0+0Ch],r3
  31599   24420004 add  r2,4h                         ;      AF5F007C mov  [k0+7Ch],ra
  31600   175BFFFC jne  k0,k1,@@copy_lop              ;      40026800 mov  r2,cop0r13
  31601   AC43FFFC +mov [r2-4h],r3                    ;/     00000000 nop
  31602 Alternately, slightly different code used in metal_gear_solid at 80095CC0h, and
  31603 in alone1 at 800A3ECCh:
  31604   24090056 mov  r9,56h                        ;\
  31605   240A00B0 mov  r10,0B0h                      ; B(56h) GetC0Table
  31606   0140F809 call r10                           ;
  31607   00000000 +nop                               ;/
  31608   8C420018 mov  r2,[r2+06h*4] ;=00000C80h = exception_handler = C(06h)
  31609   00000000 nop
  31610   24420028 add  r2,28h
  31611   00407821 mov  r15,r2
  31612   3C0Axxxx lui  r10,xxxxh ;\@@ori_data        ;\
  31613   254Axxxx add  r10,xxxxh ;/                  ;
  31614   3C09xxxx lui  r9,xxxxh  ;\@@ori_data_end    ; @@ori_data:
  31615   2529xxxx add  r9,xxxxh  ;/                  ;  AF410004 mov [k0+4h],r1
  31616           @@verify_lop:                       ;  AF420008 mov [k0+8h],r2
  31617   8D430000 mov  r3,[r10]                      ;  AF43000C mov [k0+0Ch],r3
  31618   8C4B0000 mov  r11,[r2]                      ;  AF5F007C mov [k0+7Ch],ra
  31619   254A0004 add  r10,4h                        ;  40037000 mov r3,cop0r14
  31620   146B000E jne  r3,r11,@@verify_mismatch      ;  00000000 nop
  31621   24420004 +add r2,4h                         ;
  31622   1549FFFA jne  r10,r9,@@verify_lop           ;
  31623   00000000 +nop                               ;/
  31624   01E01021 mov  r2,r15
  31625   3C0Axxxx lui  r10,xxxxh ;\@@new_data        ;\
  31626   254Axxxx add  r10,xxxxh ;/                  ;
  31627   3C09xxxx lui  r9,xxxxh  ;\@@new_data_end    ; @@new_data:
  31628   2529xxxx add  r9,xxxxh  ;/                  ;  AF410004 mov [k0+4h],r1
  31629           @@copy_lop:                         ;  AF420008 mov [k0+8h],r2
  31630   8D430000 mov  r3,[r10]                      ;  40026800 mov r2,cop0r13
  31631   00000000 nop                                ;  AF43000C mov [k0+0Ch],r3
  31632   AC430000 mov  [r2],r3                       ;  40037000 mov r3,cop0r14
  31633   254A0004 add  r10,4h                        ;  AF5F007C mov [k0+7Ch],ra
  31634   1549FFFB jne  r10,r9,@@copy_lop             ;
  31635   24420004 +add r2,4h                         ;/
  31636           @@verify_mismatch:
  31637 Alternately, a bugged/nonfunctional homebrew variant (used by Hitmen's
  31638 "minimum" demo):
  31639   ;BUG1: 8bit "movb r6" should be 32bit "mov r6"
  31640   ;BUG2: @@copy_lop should transfer 6 words (not 7 words)
  31641   ;BUG3: and, asides, the minimum demo works only with PAL BIOS (not NTSC)
  31642   0xxxxxxx call xxxxxxxxh               ;\B(56h) GetC0Table
  31643   00000000 +nop                         ;/(mov r8,0B0h, jmp r8, +mov r9,56h)
  31644   3C04xxxx mov  r4,xxxx0000h  ;\@@ori_data
  31645   2484xxxx add  r4,xxxxh      ;/
  31646   90460018 movb r6,[r2+06h*4] ;BUG1 ;exception_handler = C(06h)
  31647   24870018 add  r7,r4,18h ;@@ori_end     ;\
  31648   24C50028 add  r5,r6,28h ;C(06h)+28h    ;
  31649   00A03021 mov  r6,r5                    ;                   @@ori_data:
  31650           @@verify_lop:                  ;  80086520 AF410004 mov [k0+4h],r1
  31651   8CA30000 mov  r3,[r5]                  ;  80086524 AF420008 mov [k0+8h],r2
  31652   8C820000 mov  r2,[r4]                  ;  80086528 AF43000C mov [k0+0Ch],r3
  31653   00000000 nop                           ;  8008652C AF5F007C mov [k0+7Ch],ra
  31654   1462000C jne  r3,r2,@@verify_mismatch  ;  80086530 40037000 mov r3,cop0r14
  31655   24840004 +add r4,4h                    ;  80086534 00000000 nop
  31656   1487FFFA jne  r4,r7,@@verify_lop       ;                   @@ori_end:
  31657   24A50004 +add r5,4h                    ;/
  31658   00C02821 mov  r5,r6                    ;\                  @@new_data:
  31659   3C04xxxx mov  r4,xxxx0000h ;\@@new_data;  80086538 AF410004 mov [k0+4h],r1
  31660   2484xxxx add  r4,xxxxh     ;/          ;  8008653C AF420008 mov [k0+8h],r2
  31661   2483001C add  r3,r4,1Ch ;@@bugged_end  ;  80086540 40026800 mov r2,cop0r13
  31662           @@copy_lop:                    ;  80086544 AF43000C mov [k0+0Ch],r3
  31663   8C820000 mov  r2,[r4]                  ;  80086548 40037000 mov r3,cop0r14
  31664   24840004 add  r4,4h                    ;  8008654C AF5F007C mov [k0+7Ch],ra
  31665   ACA20000 mov  [r5],r2                  ;                   @@new_end:
  31666   1483FFFC jne  r4,r3,@@copy_lop         ;  80086550 00000000 nop  ;BUG2
  31667   24A50004 +add r5,4h                    ;/                  @@bugged_end:
  31668           @@verify_mismatch:
  31669 
  31670 early_card_irq_patch:
  31671 Because of a hardware glitch the card IRQ cannot be acknowledged while the
  31672 external IRQ signal is still LOW, making it neccessary to insert a delay that
  31673 waits until the signal gets HIGH before acknowledging the IRQ.
  31674 The original BIOS is so inefficient that it takes hundreds of clock cycles
  31675 between the interrupt request and the IRQ acknowledge, so, normally, it doesn't
  31676 require an additional delay.
  31677 However, the central mistake in the IRQ handler is that it doesn't memorize
  31678 which IRQ has originally triggered the interrupt. For example, it may get
  31679 triggered by a timer IRQ, but a newer card IRQ may occur during IRQ handling,
  31680 in that case, the card IRQ may get processed and acknowledged without the
  31681 required delay.
  31682 Used in Metal Gear Solid at 8009AA5Ch, and in alone1 at 800AE2F8h:
  31683   24090056 mov  r9,56h    ;\                  ;        @@new_data:
  31684   240A00B0 mov  r10,0B0h  ; B(56h) GetC0Table ;3C02A001 lui  r2,0A001h
  31685   0140F809 call r10       ;                   ;2442DFAC sub  r2,2054h
  31686   00000000 +nop           ;/                  ;00400008 jmp  r2 ;=@@new_cont_d
  31687   8C420018 mov  r2,[r2+06h*4] ;\get C(06h)    ;00000000 +nop    ;=A000DFACh
  31688   00000000 nop                ;/              ;00000000 nop
  31689   8C430070 mov  r3,[r2+70h]   ;\              ;        @@new_data_end:
  31690   00000000 nop                ; get           ;        @@new_cont_d:
  31691   3069FFFF and  r9,r3,0FFFFh  ; early_card    ;8C621074 mov  r2,[r3+1074h]
  31692   00094C00 shl  r9,10h        ; irq_handler   ;00000000 nop
  31693   8C430074 mov  r3,[r2+74h]   ;               ;30420080 and  r2,80h ;I_STAT.7
  31694   00000000 nop                ;               ;1040000B jz   r2,@@ret
  31695   306AFFFF and  r10,r3,0FFFFh ;/              ;00000000 +nop
  31696   012A1821 add  r3,r9,r10                     ;        @@wait_lop:
  31697   24620028 add  r2,r3,28h ;=early+28h         ;8C621044 mov  r2,[r3+1044h]
  31698   3C0Axxxx lui  r10,xxxxh ;\@@new_data        ;00000000 nop
  31699   254Axxxx sub  r10,xxxxh ;/                  ;30420080 and  r2,80h ;JOY_STAT.7
  31700   3C09xxxx lui  r9,xxxxh  ;\@@new_data_end    ;1440FFFC jnz  r2,@@wait_lop
  31701   2529xxxx sub  r9,xxxxh  ;/                  ;00000000 +nop
  31702           @@copy_lop:                         ;3C020001 lui  r2,0001h
  31703   8D430000 mov  r3,[r10]                      ;8C42DFFC mov  r2,[r2-2004h]
  31704   00000000 nop                                ;00000000 nop
  31705   AC430000 mov  [r2],r3                       ;00400008 jmp  r2 ;=[0000DFFCh]
  31706   254A0004 add  r10,4h                        ;00000000 +nop
  31707   1549FFFB jne  r10,r9,@@copy_lop             ;        @@ret:
  31708   24420004 +add r2,4h                         ;03E00008 ret
  31709   3C010001 lui  r1,0001h      ;\[DFFCh]=r2    ;00000000 +nop
  31710   0xxxxxxx call xxxxxxxxh     ; and call ...  ;
  31711   AC22DFFC +mov [r1-2004h],r2 ;/              ;
  31712 Alternately, elo2 uses slightly different code at 8003961Ch:
  31713   240A00B0 mov  r10,0B0h  ;\                  ;        @@new_data:
  31714   0140F809 call r10       ; B(56h) GetC0Table ;3C02xxxx lui  r2,8xxxh
  31715   24090056 +mov r9,56h    ;/                  ;2442xxxx sub  r2,xxxxh
  31716   8C420018 mov  r2,[r2+06h*4] ;\get C(06h)    ;00400008 jmp  r2 ;=@@new_cont_d
  31717   00000000 nop                ;/              ;00000000 +nop    ;=8xxxxxxxh
  31718   8C430070 mov  r3,[r2+70h]   ;\              ;00000000 nop
  31719   00000000 nop                ; get           ;        @@new_data_end:
  31720   3069FFFF and  r9,r3,0FFFFh  ; early_card    ;        @@new_cont_d:
  31721   8C430074 mov  r3,[r2+74h]   ; irq_handler   ;8C621074 mov  r2,[r3+1074h]
  31722   00094C00 shl  r9,10h        ;               ;00000000 nop
  31723   306AFFFF and  r10,r3,0FFFFh ;               ;30420080 and  r2,80h ;I_STAT.7
  31724   012A1821 add  r3,r9,r10     ;/              ;1040000B jz   r2,@@ret
  31725   3C0Axxxx mov  r10,xxxx0000h                 ;00000000 +nop
  31726   3C09xxxx mov  r9,xxxx0000h                  ;        @@wait_lop:
  31727   24620028 add  r2,r3,28h ;=early+28h         ;8C621044 mov  r2,[r3+1044h]
  31728   254Axxxx sub  r10,xxxxh ;=@@new_data        ;00000000 nop
  31729   2529xxxx sub  r9,xxxxh  ;=@@new_data_end    ;30420080 and  r2,80h ;JOY_STAT.7
  31730           @@copy_lop:                         ;1440FFFC jnz  r2,@@wait_lop
  31731   8D430000 mov  r3,[r10]                      ;00000000 +nop
  31732   254A0004 add  r10,4h                        ;3C02xxxx lui  r2,8xxxh
  31733   24420004 add  r2,4h                         ;8C42xxxx mov  r2,[r2-xxxxh]
  31734   1549FFFC jne  r10,r9,@@copy_lop             ;00000000 nop
  31735   AC43FFFC +mov [r2-4h],r3                    ;00400008 jmp  r2 ;=[8xxxxxxxh]
  31736   3C018xxx mov  r1,8xxx0000h  ;\[...]=r2,     ;00000000 +nop
  31737   0xxxxxxx call xxxxxxxxh     ; and call ...  ;        @@ret:
  31738   AC22xxxx +mov [r1+xxxxh],r2 ;/              ;03E00008 ret
  31739            ...                                ;00000000 +nop
  31740 Note: The above @@wait_lop's should be more preferably done with timeouts (else
  31741 they may hang endless if a Sony Mouse is newly connected; the mouse does have
  31742 /ACK stuck LOW on power-up).
  31743 
  31744 patch_uninstall_early_card_irq_handler:
  31745 Used to uninstall the "early_card_irq_vector" (the BIOS installs that vector
  31746 from inside of B(4Ah) InitCard(pad_enable), and, without patches, the BIOS
  31747 doesn't allow to uninstall it thereafter).
  31748 Used in Breath of Fire III (SLES-01304) at 8017E790, and also in Ace Combat 2
  31749 (SLUS-00404) at 801D23F4:
  31750   240A00B0 mov  r10,0B0h          ;\
  31751   0140F809 call r10               ; B(56h) GetC0Table
  31752   24090056 +mov r9,56h            ;/
  31753   3C0Axxxx mov  r10,xxxx0000h
  31754   3C09xxxx mov  r9,xxxx0000h
  31755   8C420018 mov  r2,[r2+06h*4] ;=00000C80h = exception_handler = C(06h)
  31756   254Axxxx add  r10,xxxxh ;@@new_data
  31757   2529xxxx add  r9,xxxxh  ;@@new_data_end
  31758           @@copy_lop:             ;\  @@new_data:
  31759   8D430000 mov  r3,[r10]          ;    00000000 nop
  31760   254A0004 add  r10,4h            ;    00000000 nop
  31761   24420004 add  r2,4h             ;    00000000 nop
  31762   1549FFFC jne  r10,r9,@@copy_lop ;   @@new_data_end:
  31763   AC43006C +mov [r2+70h-4],r3     ;/
  31764 Alternately, more inefficient, used in Blaster Master-Blasting Again
  31765 (SLUS-01031) at 80063FF4h, and Raiden DX at 80029694h:
  31766   24090056 mov  r9,56h            ;\
  31767   240A00B0 mov  r10,0B0h          ; B(56h) GetC0Table
  31768   0140F809 call r10               ;
  31769   00000000 +nop                   ;/
  31770   8C420018 mov  r2,[r2+06h*4] ;=00000C80h = exception_handler = C(06h)
  31771   3C0Axxxx mov  r10,xxxx0000h ;\@@new_data
  31772   254Axxxx add  r10,xxxxh     ;/
  31773   3C09xxxx mov  r9,xxxx0000h  ;\@@new_data_end
  31774   2529xxxx add  r9,xxxxh      ;/
  31775           @@copy_lop:             ;\
  31776   8D430000 mov  r3,[r10]          ;   @@new_data:
  31777   00000000 nop                    ;    00000000 nop
  31778   AC430070 mov  [r2+70h],r3       ;    00000000 nop
  31779   254A0004 add  r10,4h  ;src      ;    00000000 nop
  31780   1549FFFB jne  r10,r9,@@copy_lop ;   @@new_data_end:
  31781   24420004 +add r2,4h   ;dst      ;/
  31782 Note: the above code is same as "patch_install_lightgun_irq_handler", except
  31783 that it writes to r2+70h, instead of r2+80h.
  31784 
  31785 patch_card_specific_delay:
  31786 Same purpose as the "early_card_irq_patch" (but for the command/status bytes
  31787 rather than for the data bytes). The patch looks buggy since it inserts the
  31788 delay AFTER the acknowledge, but it DOES work (the BIOS accidently acknowledges
  31789 the IRQ twice; and the delay occurs PRIOR to 2nd acknowledge).
  31790 Used in Metal Gear Solid at 8009AAF0h, and in Legacy of Kain at 801A56D8h, and
  31791 in alone1 at 800AE38Ch:
  31792   24090057 mov  r9,57h   ;\                   ;         @@new_data:
  31793   240A00B0 mov  r10,0B0h ; B(57h) GetB0Table  ; 3C08A001 lui  r8,0A001h
  31794   0140F809 call r10      ;/                   ; 2508DF80 sub  r8,2080h
  31795   00000000 +nop                               ; 0100F809 call r8 ;=A000DF80h
  31796   8C42016C mov  r2,[r2+5Bh*4] ;B(5Bh)         ; 00000000 +nop
  31797   00000000 nop                                ; 00000000 nop
  31798   8C4309C8 mov  r3,[r2+9C8h]  ;blah           ;         @@new_data_end:
  31799   3C0Axxxx lui  r10,xxxxh ;\@@new_data        ; 946F000A movh r15,[r3+0Ah]
  31800   254Axxxx sub  r10,xxxxh ;/                  ; 3C080000 mov  r8,0h
  31801   3C09xxxx lui  r9,xxxxh  ;\@@new_data_end    ; 01E2C025 or   r24,r15,r2
  31802   2529xxxx sub  r9,xxxxh  ;/                  ; 37190012 or   r25,r24,12h
  31803           @@copy_lop:                         ; A479000A movh [r3+0Ah],r25
  31804   8D480000 mov  r8,[r10]                      ; 24080028 mov  r8,28h
  31805   00000000 nop                                ;         @@wait_lop:
  31806   AC4809C8 mov  [r2+9C8h],r8   ;B(5Bh)+9C8h.. ; 2508FFFF sub  r8,1h
  31807   254A0004 add  r10,4h                        ; 1500FFFE jnz  r8,@@wait_lop
  31808   1549FFFB jne  r10,r9,@@copy_lop             ; 00000000 +nop
  31809   24420004 +add r2,4h                         ; 03E00008 ret  ;above delay is
  31810            ...                                ; 00000000 +nop ;in UNCACHED RAM
  31811 Alternately, slightly different code used in elo2 at800396D4h, and in Resident
  31812 Evil 2 at 800910E4h:
  31813   240A00B0 mov  r10,0B0h ;\                   ;         @@swap_begin:
  31814   0140F809 call r10      ; B(57h) GetB0Table  ; 3C088xxx lui  r8,8xxxh
  31815   24090057 +mov r9,57h   ;/                   ; 2508xxxx sub  r8,xxxxh
  31816   8C42016C mov  r2,[r2+5Bh*4] ;B(5Bh)         ; 0100F809 call r8 ;=8xxxxxxxh
  31817   3C0Axxxx mov  r10,xxxx0000h                 ; 00000000 +nop
  31818   3C09xxxx mov  r9,xxxx0000h                  ; 00000000 nop
  31819   8C4309C8 mov  r3,[r2+9C8h] ;blah            ;         @@swap_end:
  31820   254Axxxx sub  r10,xxxxh  ;=@@swap_begin     ;         ;- -  -
  31821   2529xxxx sub  r9,xxxxh   ;=@@swap_end       ; 00000000 nop
  31822           @@swap_lop:                         ; 240800C8 mov  r8,0C8h
  31823   8C4309C8 mov  r3,[r2+9C8h] ;B(5Bh)+9C8h..   ;         @@wait_lop:
  31824   8D480000 mov  r8,[r10]                      ; 2508FFFF sub  r8,1h
  31825   254A0004 add  r10,4h                        ; 1500FFFE jnz  r8,@@wait_lop
  31826   AD43FFFC mov  [r10-4h],r3                   ; 00000000 +nop
  31827   24420004 add  r2,4h                         ; 03E00008 ret  ;above delay is
  31828   1549FFFA jne  r10,r9,@@swap_lop             ; 00000000 +nop ;in CACHED RAM
  31829   AC4809C4 +mov [r2+9C4h],r8                  ;
  31830 
  31831 patch_card_info_step4:
  31832 The "card_info" function sends an incomplete read command to the card; in order
  31833 to receive status information. After receiving the last byte, the function does
  31834 accidently send a further byte to the card, so the card responds by another
  31835 byte (and another IRQ7), which is not processed nor acknowledged by the BIOS.
  31836 This patch kills the opcode that sends the extra byte.
  31837 Used in alone1 at 800AE214h:
  31838   24090057 mov  r9,57h                        ;\
  31839   240A00B0 mov  r10,0B0h                      ; B(57h) GetB0Table
  31840   0140F809 call r10                           ;
  31841   00000000 +nop                               ;/
  31842   240A0009 mov  r10,9h        ;=blah
  31843   8C42016C mov  r2,[r2+5Bh*4] ;=B(5Bh)
  31844   00000000 nop
  31845   20431988 addt r3,r2,1988h   ;=B(5Bh)+1988h  ;\store a NOP,
  31846   0xxxxxxx call xxxxxxxxh                     ; and call ...
  31847   AC600000 +mov [r3],0        ;=nop           ;/
  31848 
  31849 patch_pad_error_handling_and_get_pad_enable_functions:
  31850 If a transmission error occurs (or if there's no controller connected), then
  31851 the Pad handler handler does usually issue a strange chip select signal to the
  31852 OTHER controller slot, and does then execute the bizarre_pad_delay function.
  31853 The patch below overwrites that behaviour by NOPs. Purpose of the original (and
  31854 patched) behaviour is unknown.
  31855 Used by Perfect Assassin at 800519D4h:
  31856   240A00B0 mov  r10,0B0h                      ;\
  31857   0140F809 call r10                           ; B(57h) GetB0Table
  31858   24090057 +mov r9,57h                        ;/
  31859   8C42016C mov  r2,[r2+5Bh*4] ;=B(5Bh)
  31860   3C01xxxx mov  r1,xxxx0000h
  31861   20430884 addt r3,r2,884h    ;B(5Bh)+884h
  31862   AC23xxxx mov  [r1+xxxxh],r3 ;<--- SetPadEnableFlag()
  31863   3C01xxxx mov  r1,xxxx0000h
  31864   20430894 addt r3,r2,894h    ;B(5Bh)+894h
  31865   2409000B mov  r9,0Bh        ;len
  31866   AC23xxxx mov  [r1+xxxxh],r3 ;<--- ClearPadEnableFlag()
  31867           @@fill_lop:                         ;\
  31868   2529FFFF sub  r9,1h                         ;
  31869   AC400594 mov  [r2+594h],0   ;B(5Bh)+594h..  ; erase error handling
  31870   1520FFFD jnz  r9,@@fill_lop                 ;
  31871   24420004 +add r2,4h                         ;/
  31872 Alternately, same as above, but with inefficient nops, used by Sporting Clays
  31873 at 8001B4B4h:
  31874   24090057 mov  r9,57h       ;\
  31875   240A00B0 mov  r10,0B0h     ; B(57h) GetB0Table
  31876   0140F809 call r10          ;
  31877   00000000 +nop              ;/
  31878   8C42016C mov  r2,[r2+5Bh*4]
  31879   2409000B mov  r9,0Bh ;len
  31880   20430884 addt r3,r2,884h
  31881   3C01xxxx mov  r1,xxxx0000h
  31882   AC23xxxx mov  [r1+xxxxh],r3 ;<--- SetPadEnableFlag()
  31883   20430894 addt r3,r2,894h
  31884   3C01xxxx mov  r1,xxxx0000h
  31885   AC23xxxx mov  [r1+xxxxh],r3 ;<--- ClearPadEnableFlag()
  31886           @@fill_lop:         ;\
  31887   AC400594 mov  [r2+594h],0   ;
  31888   24420004 add  r2,4h         ; erase error handling
  31889   2529FFFF sub  r9,1h         ;
  31890   1520FFFC jnz  r9,@@fill_lop ;
  31891   00000000 +nop               ;/
  31892 Alternately, same as above, but without getting PadEnable functions, used in
  31893 Pandemonium II (at 80083C94h and at 8010B77Ch):
  31894   240A00B0 mov  r10,0B0h              ;\
  31895   0140F809 call r10                   ; B(57h) GetB0Table
  31896   24090057 +mov r9,57h                ;/
  31897   8C42016C mov  r2,[r2+5Bh*4] ;=B(5Bh)
  31898   2409000B mov  r9,0Bh        ;len            ;\
  31899           @@fill_lop:                         ;
  31900   2529FFFF sub  r9,1h                         ; erase error handling
  31901   AC400594 mov  [r2+594h],0   ;B(5Bh)+594h..  ;
  31902   1520FFFD jnz  r9,@@fill_lop                 ;
  31903   24420004 +add r2,4h                         ;/
  31904 
  31905 patch_optional_pad_output:
  31906 The normal BIOS functions are only allowing to READ from the controllers, but
  31907 not to SEND data to them (which would be required to control Rumble motors, and
  31908 to auto-activate Analog mode without needing the user to press the Analog
  31909 button). Internally, the BIOS does include some code for sending data to the
  31910 controller, but it doesn't offer a function vector for setting up the data
  31911 source address, and, even if that would be supported, it clips the data bytes
  31912 to 00h or 01h. The patch below retrieves the required SetPadOutput function
  31913 address (in which only the src1/src2 addresses are relevant, the blah1/blah2
  31914 values aren't used), and suppresses clipping (ie. allows to send any bytes in
  31915 range 00h..FFh).
  31916 Used in Resident Evil 2 at 80091914h:
  31917   240A00B0 mov  r10,0B0h                      ;\
  31918   0140F809 call r10                           ; B(57h) GetB0Table
  31919   24090057 +mov r9,57h                        ;/
  31920   8C42016C mov  r2,[r2+5Bh*4] ;B(5Bh)
  31921   3C0Axxxx mov  r10,xxxx0000h
  31922   3C09xxxx mov  r9,xxxx0000h
  31923   3C01xxxx mov  r1,xxxx0000h
  31924   204307A0 addt r3,r2,7A0h    ;B(5Bh)+7A0h
  31925   254Axxxx add  r10,xxxxh  ;=@@new_data
  31926   2529xxxx add  r9,xxxxh   ;=@@new_data_end
  31927   AC23xxxx mov  [r1-xxxxh],r3 ;<--- SetPadOutput(src1,blah1,src2,blah2)
  31928           @@double_copy_lop:                  ;\
  31929   8D430000 mov  r3,[r10]                      ;           @@new_data:
  31930   254A0004 add  r10,4h                        ;   00551024 and     r2,r21
  31931   AC4303D8 mov  [r2+3D8h],r3  ;<--- here      ;   00000000 nop
  31932   24420004 add  r2,4h                         ;   00000000 nop
  31933   1549FFFB jne  r10,r9,@@double_copy_lop      ;   00000000 nop
  31934   AC4304DC +mov [r2+4DCh],r3  ;<--- here      ;/          @@new_data_end:
  31935 Alternately, more inefficient (with NOPs), used in Lemmings at 80036618h:
  31936   24090057 mov  r9,57h                        ;\
  31937   240A00B0 mov  r10,0B0h                      ; B(57h) GetB0Table
  31938   0140F809 call r10                           ;
  31939   00000000 +nop                               ;/
  31940   3C0Axxxx mov  r10,xxxx0000h
  31941   254Axxxx add  r10,xxxxh    ;=@@new_data
  31942   3C09xxxx movp r9,xxxx0000h
  31943   2529xxxx add  r9,xxxxh     ;=@@new_data_end
  31944   8C42016C mov  r2,[r2+5Bh*4] ;B(5Bh)
  31945   00000000 nop
  31946   204307A0 addt r3,r2,7A0h    ;B(5Bh)+7A0h
  31947   3C01xxxx mov  r1,xxxx0000h
  31948   AC23xxxx mov  [r1+xxxxh],r3 ;<--- SetPadOutput(src1,blah1,src2,blah2)
  31949           @@double_copy_lop:                  ;\
  31950   8D430000 mov  r3,[r10]                      ;           @@new_data:
  31951   00000000 nop                                ;   00551024 and     r2,r21
  31952   AC4303D8 mov  [r2+3D8h],r3                  ;   00000000 nop
  31953   AC4304E0 mov  [r2+4E0h],r3                  ;   00000000 nop
  31954   24420004 add  r2,4h                         ;   00000000 nop
  31955   254A0004 add  r10,4h                        ;           @@new_data_end:
  31956   1549FFF9 jne  r10,r9,@@double_copy_lop      ;
  31957   00000000 +nop                               ;/
  31958 
  31959 patch_no_pad_card_auto_ack:
  31960 This patch suppresses automatic IRQ0 (vblank) acknowleding in the Pad/Card IRQ
  31961 handler, that, even if auto-ack is enabled. Obviously, one could as well
  31962 disable auto-ack via B(5Bh) ChangeClearPad(int), so this patch is total
  31963 nonsense. Used in Resident Evil 2 at 800919ACh:
  31964   240A00B0 mov   r10,0B0h                      ;\
  31965   0140F809 call  r10                           ; B(57h) GetB0Table
  31966   24090057 +mov  r9,57h                        ;/
  31967   8C42016C mov   r2,[r2+5Bh*4] ;=B(5Bh)
  31968   240A0009 mov   r10,9h        ;len            ;\
  31969   2043062C addt  r3,r2,62Ch    ;=B(5Bh)+62Ch   ;
  31970           @@fill_lop:                          ;
  31971   254AFFFF sub   r10,1h                        ;
  31972   AC600000 mov   [r3],0                        ;
  31973   1540FFFD jnz   r10,@@fill_lop                ;
  31974   24630004 +add  r3,4h                         ;/
  31975 Alternately, same as above, but more inefficient, used in Sporting Clays at
  31976 8001B53Ch:
  31977   24090057 mov   r9,57h                        ;\
  31978   240A00B0 mov   r10,0B0h                      ; B(57h) GetB0Table
  31979   0140F809 call  r10                           ;
  31980   00000000 +nop                                ;/
  31981   240A0009 mov   r10,9h    ;len
  31982   8C42016C mov   r2,[r2+5Bh*4]
  31983   00000000 nop
  31984   2043062C addt  r3,r2,62Ch
  31985           @@fill_lop:                          ;\
  31986   AC600000 mov   [r3],0                        ;
  31987   24630004 add   r3,4h                         ;
  31988   254AFFFF sub   r10,1h                        ;
  31989   1540FFFC jnz   r10,@@fill_lop                ;
  31990   00000000 +nop                                ;/
  31991 Either way, no matter if using the patch or if using ChangeClearPad(int),
  31992 having auto-ack disabled allows to install a custom vblank IRQ0 handler, which
  31993 is probably desired for most games, however, mind that the PSX BIOS doesn't
  31994 actually support the same IRQ to be processed by two different IRQ handlers,
  31995 eg. the custom handler may acknowledge the IRQ even when the Pad/Card handler
  31996 didn't process it, so pad input may become bumpy.
  31997 
  31998 patch_install_lightgun_irq_handler:
  31999 Used in Sporting Clays at 80027D68h (when Konami Lightgun connected):
  32000   240A00B0 mov  r10,0B0h      ;\
  32001   0140F809 call r10           ; B(56h) GetC0Table
  32002   24090056 +mov r9,56h        ;/
  32003   3C0Axxxx mov  r10,xxxx0000h ;src
  32004   3C09xxxx mov  r9,xxxx0000h  ;src.end
  32005   8C420018 mov  r2,[r2+06h*4] ;C(06h) ;=00000C80h = exception_handler
  32006   254Axxxx add  r10,xxxxh     ;src
  32007   2529xxxx add  r9,xxxxh      ;src.end (=src+10h)
  32008           @@copy_lop:              ;\    ;        @@src:
  32009   8D430000 mov  r3,[r10]           ;     ;3C02xxxx mov  r2,xxxx0000h
  32010   254A0004 add  r10,4h             ;     ;2442xxxx add  r2,xxxxh
  32011   24420004 add  r2,4h              ;     ;0040F809 call r2  ;lightgun_proc
  32012   1549FFFC jne  r10,r9,@@copy_lop  ;     ;00000000 +nop
  32013   AC43007C +mov [r2+80h-4],r3      ;/             @@src_end:
  32014 Alternately, same as above, using k0/k1, used in Star Wars Rebel Assault II
  32015 (The Hidden Empire) at 800942B0h (install) and 80094308h (uninstall):
  32016   240A00B0 mov  r10,0B0h      ;\
  32017   0140F809 call r10           ; B(56h) GetC0Table
  32018   24090056 +mov r9,56h        ;/
  32019   3C1Axxxx mov  k0,xxxx0000h  ;src
  32020   3C1Bxxxx mov  k1,xxxx0000h  ;src.end (=src+10h)
  32021   8C420018 mov  r2,[r2+06h*4] ;C(06h) ;=00000C80h = exception_handler
  32022   275Axxxx add  k0,xxxxh      ;src      ;=8009438Ch
  32023   277Bxxxx add  k1,xxxxh      ;src.end
  32024           @@copy_lop:             ;\@@new_data: ;for (un-)install...
  32025   8F430000 mov  r3,[k0]           ; 00000000 nop / 3C02xxxx mov r2,xxxx0000h
  32026   275A0004 add  k0,4h             ; 00000000 nop / 2442xxxx add r2,-xxxxh
  32027   24420004 add  r2,4h             ; 00000000 nop / 0040F809 call r2  ;proc
  32028   175BFFFC jne  k0,k1,@@copy_lop  ; 00000000 nop / 00000000 +nop
  32029   AC43007C +mov [r2+80h-4],r3     ;/@@new_data_end:
  32030 Alternately, same as above, but more inefficient, used in DQM (Dragon Quest
  32031 Monsters 1&2) at 80089390h (install) and 800893F8h (uninstall):
  32032   24090056 mov  r9,56h        ;\
  32033   240A00B0 mov  r10,0B0h      ; B(56h) GetC0Table
  32034   0140F809 call r10           ;
  32035   00000000 +nop               ;/
  32036   8C420018 mov  r2,[r2+06h*4] ;C(06h) ;=00000C80h = exception_handler
  32037   3C0Axxxx mov  r10,xxxx0000h ;\@@new_data (3xNOP)
  32038   254Axxxx add  r10,-xxxxh    ;/
  32039   3C09xxxx mov  r9,xxxx0000h  ;\@@new_data_end
  32040   2529xxxx add  r9,-xxxxh     ;/
  32041           @@copy_lop:             ;\
  32042   8D430000 mov  r3,[r10]          ; @@new_data: ;for (un-)install...
  32043   00000000 nop                    ; 00000000 nop / 3C02xxxx mov r2,xxxx0000h
  32044   AC430080 mov  [r2+80h],r3       ; 00000000 nop / 2442xxxx add r2,-xxxxh
  32045   254A0004 add  r10,4h            ; 00000000 nop / 0040F809 call r2  ;proc
  32046   1549FFFB jne  r10,r9,@@copy_lop ; @@new_data_end:
  32047   24420004 +add r2,4h             ;/
  32048 Some lightgun games (eg. Project Horned Owl) do (additionally to above stuff)
  32049 hook the exception vector at 00000080h (aka 80000080h), the hook copies the
  32050 horizontal coordinate (timer0) to a variable in RAM, thus getting the timer0
  32051 value "closest" to the actual IRQ execution. Doing that may eliminate some
  32052 unpredictable timing offsets that could be caused by cache hits/misses during
  32053 later IRQ handling (and may also eliminate a rather irrelevant 1-cycle
  32054 inaccuracy depending on whether EPC was pointing to a GTE opcode, and also
  32055 eliminates constant cycle offsets depending on whether early_card_irq_handler
  32056 was installed and enabled, and might eliminate timing differences for different
  32057 BIOS versions).
  32058 
  32059 set_conf_without_realloc:
  32060 Used in Spec Ops Airborne Commando at 80070AE8h, and also in the homebrew game
  32061 Roll Boss Rush at 80010B68h and 8001B85Ch. Purpose is unknown (maybe to
  32062 override improperly defined .EXE headers).
  32063   8C030474 mov   r3,[200h+(9Dh*4)]      ;\get ptr to A(9Dh) GetConf (done so,
  32064   00000000 nop                          ;/as there's no "GetA0Table" funtion)
  32065   94620000 movh  r2,[r3+0h] ;lui msw    ;\
  32066   84630004 movhs r3,[r3+4h] ;lw lsw+8   ; extract ptr to "boot_cnf_values"
  32067   00021400 shl   r2,10h     ;msw*10000h ; (from first 2 opcodes of GetConf)
  32068   2442FFF8 sub   r2,8h      ;undo +8    ;
  32069   00431021 add   r2,r3      ;lsw        ;/
  32070   AC450000 mov   [r2+0h],r5 ;num_TCB    ;\set num_EvCB,num_TCB,stacktop
  32071   AC440004 mov   [r2+4h],r4 ;num_EvCB   ; (unlike A(9Ch) SetConf, without
  32072   03E00008 ret                          ; actually reallocting anything)
  32073   AC460008 +mov  [r2+8h],r6 ;stacktop   ;/
  32074 
  32075 Cheat Devices
  32076 CAETLA detects the PSX BIOS version by checksumming BFC06000h..BFC07FFFh and
  32077 does then use some hardcoded BIOS addresses based on that checksum. The reason
  32078 for doing that is probably that the Pre-Boot Expansion ROM vector is called
  32079 with the normal A0h/B0h/C0h vectors being still uninitialized.
  32080 Problems are that the hardcoded addresses won't work with all BIOSes (eg. not
  32081 with the no$psx bios clone, probably also not with the newer PS2 BIOS),
  32082 moreover, the checksumming can fail with patched original BIOSes (eg. no$psx
  32083 allows to enable TTY debug messages and to skip the BIOS intro).
  32084 The Cheat Firmwares are probably also hooking the Vblank handler, and maybe
  32085 also some other functions.
  32086 ACTION REPLAY (at least later versions like 2.81) uses the Pre-Boot handler to
  32087 set a COP0 hardware breakpoint at 80030000h and does then resume normal BIOS
  32088 booting (which will then initialize important things like A0h/B0h/C0h tables,
  32089 and will then break when starting the GUI code at 80030000h).
  32090 XPLORER searches opcode 24040385h at BFC06000h and up, and does then place a
  32091 COP0 opcode fetch breakpoint at the opcode address+10h (note: this is within a
  32092 branch delay slot, which makes COP0 emulation twice as complicated). XPLORER
  32093 does also require space in unused BIOS RAM addresses (eg. Xplorer v3.20: addr
  32094 7880h at 1F002280h, addr 017Fh at 1F006A58h).
  32095 
  32096 Note
  32097 Most games include two or three patches. The only game that I've seen so far
  32098 that does NOT use any patches is Wipeout 2097.
  32099 
  32100 Arcade Cabinets
  32101 ---------------
  32102 
  32103 PSX-Based Arcade Boards
  32104   Namco System 11, System 12 (and System 10?)
  32105   Capcom/Sony ZN-1, ZN-2
  32106   Konami GV, Konami GQ
  32107   Taito FX-1A, Taito FX-1B
  32108   Atlus PSX, PS Arcade 95, Tecmo TPS
  32109 
  32110 CPU
  32111 Same as in PSX. Except, one board is said to be having the CPU clocked at
  32112 48MHz, instead of 33MHz???
  32113 
  32114 GPU
  32115 Same as in PSX. Except, most or all boards are said to have 2MB VRAM instead of
  32116 1MB. Unknown how the extra VRAM is accessed... maybe as Y=512..1023... (though
  32117 the PSX VRAM transfer commands are limited to 9bit Ysiz values, but maybe Y
  32118 coordinates can be 10bit wide).
  32119 
  32120 ROM vs CDROM
  32121 Arcade games are stored on ROM (or FLASH) instead of using CDROM drives.
  32122 
  32123 SPU
  32124 Most PSX-based arcade boards are having the PSX-SPU replaced by a different
  32125 sound chip (with each arcade manufacturer using their own custom sound chip,
  32126 often controlled by a separate sound CPU).
  32127 
  32128 Controls
  32129 Arcade boards are typically having digital joysticks instead of joypads, with
  32130 differently named buttons (instead of /\,[],(),><), probably accessed via
  32131 custom I/O ports (instead of serial transmission)? Plus additional coin inputs
  32132 and DIP switches.
  32133 
  32134 Note: There's no documentation for those arcade boards yet, however, it might
  32135 be possible to extract that info from MAME source code.
  32136 
  32137 Cheat Devices
  32138 -------------
  32139 
  32140 Action Replay, GameShark, Gamebuster, GoldFinger, Equalizer (Datel/clones)
  32141 The Datel devices exist in various official/cloned hardware revisions, the DB25
  32142 connector requires a special Comms Link ISA card (or a "FiveWire" mod for
  32143 making it compatible with normal PC parallel ports). Later "PAR3" models are
  32144 said to not require Comms Link, and do thus probably work directly with normal
  32145 parallel ports).
  32146 --> Cheat Devices - Datel I/O
  32147 --> Cheat Devices - Datel DB25 Comms Link Protocol
  32148 --> Cheat Devices - Datel Chipset Pinouts
  32149 --> Cheat Devices - Datel Cheat Code Format
  32150 
  32151 Xplorer/Xploder/X-Terminator (FCD/Blaze)
  32152 The FCD/Blaze devices are all same hardware-wise (with some cosmetic PCB
  32153 revisions, and with extra SRAM and bigger FLASH installed in some carts). The
  32154 DB25 connector can be directly connected to a PC parallel port.
  32155 --> Cheat Devices - Xplorer Memory and I/O Map
  32156 --> Cheat Devices - Xplorer DB25 Parallel Port Function Summary
  32157 --> Cheat Devices - Xplorer DB25 Parallel Port Command Handler
  32158 --> Cheat Devices - Xplorer DB25 Parallel Port Low Level Transfer Protocol
  32159 --> Cheat Devices - Xplorer Versions
  32160 --> Cheat Devices - Xplorer Chipset Pinouts
  32161 --> Cheat Devices - Xplorer Cheat Code Format
  32162 --> Cheat Devices - Xplorer Cheat Code and ROM-Image Decryption
  32163 
  32164 FLASH Chips (for both Xplorer and Datel)
  32165 --> Cheat Devices - FLASH/EEPROMs
  32166 
  32167 http://gamehacking.org/faqs/hackv500c.html - cheat code formats
  32168 http://doc.kodewerx.org/hacking_psx.html - cheat code formats
  32169 http://xianaix.net/museum.htm - around 64 bios versions
  32170 http://www.murraymoffatt.com/playstation-xplorer.html - xplorer bioses
  32171 
  32172 Separating between Gameshark and Xplorer Codes
  32173   First Digit  Usage
  32174   3,8          Same for Gameshark & Xplorer (for Xplorer: can be encrypted)
  32175   1,2,C,D,E    Gameshark
  32176   4,6,7,9,B,F  Xplorer
  32177   0,5          Meaning differs for Gameshark & Xplorer
  32178   A            Unused
  32179 
  32180 Codebreaker
  32181 Megacom Power Replay III Game Enhancer
  32182 
  32183 Cheat Devices - Datel I/O
  32184 -------------------------
  32185 
  32186 Datel Memory and I/O Map (for PAR2 or so)
  32187   1F000000h-1F01FFFFh R/W Flash (first 128K)
  32188   1F020010h           R   Comms Link STB pin state (bit0)
  32189   1F020018h           R   Switch Setting (bit0: 0=Off, 1=On)
  32190   1F040000h-1F05FFFFh R/W Flash (second 128K) + feedback area (see below)
  32191   1F060000h           R   Comms Link data in (byte)
  32192   1F060008h           W   Comms Link data out (byte, pulses ACK to Comms Link)
  32193 
  32194 Datel PAR1
  32195 Original PAR1 might have supported only 128K FLASH (?) if so, the I/O ports are
  32196 probably same as above, but without the "second 128K" FLASH area.
  32197 
  32198 Datel PAR3
  32199 The PAR3 version is said to work with parallel ports (not needing the Comms
  32200 Link ISA card), and said to support more FLASH with bankswitching, so the I/O
  32201 ports must work somehow entirely different as described above.
  32202 Some notes from a (poorly translated) japanese document:
  32203 PAR3 Memory:
  32204   1f000000-1f01ffff ROM. Change in bank switching.
  32205   1f020000-1f03ffff ROM. Change in bank switching.
  32206   1f040000-1f05ffff whopping RAM. It is able to use.
  32207   1f060000-1f06003f I/O. Intently mirror to the subsequent 1f07ffff.
  32208 PAR3 I/O:
  32209   1f060000 for reception. (1f060000 use only.) All bytes same treatment like.
  32210              It is 01h in the state that does not connected anything.
  32211   1f060008 for transmission. (1f060008 use only.) This is ffh in the state
  32212              that does not connected anything.
  32213   1f060010 during data reception it will stand the least significant bit.
  32214              Usually is fe.
  32215   1f060018 state of the push button. In not pressed and fefefefefefefefe,
  32216              it will Ost ffffffffffffffff.
  32217   1f060020 I think 1f060020 unused. It is ffffffffffffffff.
  32218   1f060028 I think 1f060028 unused. It is ffffffffffffffff.
  32219   1f060030 bank switching. 1 put and run-time of the ROM, and changes to the
  32220              3's and the start-up of the ROM.
  32221   1f060038 would be what? It is lbu. Like there is a meaning bits 0 and 1.
  32222              It was fcfcfcfcfcfcfcfc. I think that it is bank cult.
  32223 
  32224 Cheat Devices - Datel DB25 Comms Link Protocol
  32225 ----------------------------------------------
  32226 
  32227 Boot Command Handler
  32228 The Boot Command Handler is executed once at Pre-Boot, and also (at least in
  32229 some firmware versions) once before displaying the GUI. Following command(s)
  32230 can be sent from PC side:
  32231   Repeatedly send 8bit "W", until receiving "R"
  32232   Repeatedly send 8bit "B", until receiving "W"
  32233   Send 8bit command "X" (upload/exec) or "U" (upload/flash), and receive ECHO
  32234   Send 32bit ADDRESS,  and receive ECHO or "BX" (bad command)
  32235   Send 32bit LENGTH,   and receive ECHO
  32236   Send DATA[LENGTH],   and receive ECHO
  32237   Send 16bit CHECKSUM, and receive ECHO
  32238   (for upload/flash and if checksum was good, PSX will now BURN ADDR,LENGTH)
  32239   Send 16bit DUMMY, and receive "OK"/"BC"/"BF" (okay, bad chksum, bad flash)
  32240   (for upload/exec and if checksum was good, PSX will now CALL ADDR)
  32241   (thereafter, PAR2.0 and up will reboot via jmp BFC00000h)
  32242 Data is always transferred as byte-pair (send one byte, receive one byte),
  32243 16bit/32bit values are transferred MSB first (with ECHO after each byte).
  32244 The upload/exec command is supported by both Datel and Caetla, the upload/flash
  32245 command is supported by Datel only (but it's totally bugged in PAR1.99, and
  32246 might also have upwards compatiblity issues in later versions, so it's better
  32247 to upload a custom flash function via upload/exec instead of using
  32248 upload/flash).
  32249 The 16bit checksum is all DATA[len] bytes added together, and then ANDed with
  32250 0FFFh (ie. actually only 12bit wide).
  32251 
  32252 Menu/Game Command Handler
  32253 There must be some further command handler(s) after the Boot Command Handler,
  32254 with support for additional cheat related commands, and (at least in Caetla)
  32255 with support for uploading EXE files with Kernel functions installed (the Boot
  32256 Command Handler at Pre-Boot time can also upload EXE code, but doesn't have
  32257 Kernel installed).
  32258 Original Datel commands for Menu/Game mode are unknown. The Caetla commands are
  32259 documented in japanese, and there are also two english translations:
  32260 http://www.psxdev.net/forum/viewtopic.php?f=49&t=370 - good (though incomplete)
  32261 http://www.psxdev.net/forum/viewtopic.php?f=53&t=462#p6849 - very bad (beware)
  32262 
  32263 Cheat Devices - Datel Chipset Pinouts
  32264 -------------------------------------
  32265 
  32266 There appear to be numerous Datel hardware revisions (and possibly numerous
  32267 Datel clones). So this chapter is unlikely to cover all hardware revisions.
  32268  PSX Expansion cards:
  32269   PCB              Controller         FLASH      DB25  spotted by
  32270   DATEL REF 1215   GAL + 74HC245      128K+128K  yes   Type79
  32271   DATEL REF 1288   DATEL ASIC1        256K       yes   nocash
  32272   DATEL xxx?       GAL + PIC + HC245  128K       yes   CharlesMacD
  32273   noname?          GAL + 74HC245      256K+0K    yes   Type79
  32274   DATEL REF 1324   lots of chips?     lots?      no    CyrusDevX
  32275   DATEL REF 1326   lots of chips?     lots?      yes   Type79
  32276   PS-121 ZISAN     GAL + PIC? + HC245 128K       yes   Kryptonick
  32277   JSZ-02           GAL (+HC245?)      128K       (yes) nocash
  32278  Comms Link ISA cards:
  32279   PCB                              Chipset                     spotted by
  32280   DATEL COMMS LINK, XXX?           blurry SMD chipset?         lowres photo
  32281   DATEL REF 1113, IBM SATURN LINK  1x74HC74, 2x74HC373, 1xXXX? Type79
  32282   EMS, PCCOM                       1x74HC74, 2x74HC373, 1xXXX? jokergameth
  32283  DIY Alternatives to Comms Link
  32284   FiveWire    ;simple hardware mod for use with parallel ports, for SPP/EPP
  32285   FreeWing    ;parallel port adaptor, lots of 74xxx TTL chips, for SPP/EPP
  32286   ExStand     ;parallel port adaptor, lots of 74xxx TTL chips, for EPP
  32287   CommLinkUSB ;USB adaptor, Buy-and-Diy technology (adafruit/teensy based)
  32288 
  32289 DATEL REF1288 board (with DATEL ASIC1 chip)
  32290 The ASIC1 chip is found in this hardware:
  32291   Label: "EQUALIZER, EVEN THE ODDS" (sticker on outside of case)
  32292   Case:  "DATEL ENGLAND" (printed inside of case)
  32293   PCB:   "DATEL REF1288 SONY SONYPSX2meg"
  32294   U:  44pin "DATEL, ASIC1, A8B1944A, 9832"       ;custom logic chip
  32295   U:  32pin "SST, 29EE020, 150-4C-NH, 981918-D"  ;256Kx8 EEPROM
  32296   U:  8pin  "83BA, LM78L, 05ACM"                 ;5V voltage regulator
  32297   CN: 25pin DB25 connector (for Comms Link ISA card)
  32298   CN: 68pin PSX expansion port connector
  32299   SW: 3pin  Switch
  32300 The ASIC1 is basically same as the PAL/GAL on other boards, with the 74HC245
  32301 transceiver intergrated; the ASIC1 is using a 44pin PLCC package, with pin1
  32302 being upper-middle, and pin7 being upper-left. Pinouts are:
  32303   7  D0           18 DB25.2.DATA0    29 D0 (same as pin7)    40 A3
  32304   8  D1           19 DB25.3.DATA1    30 EERPROM./WE          41 A4
  32305   9  D2           20 DB25.4.DATA2    31 /WR                  42 /EXP
  32306   10 GND          21 GND             32 GND                  43 GND
  32307   11 D3           22 DB25.5.DATA3    33 /RD                  44 A17
  32308   12 D4           23 DB25.6.DATA4    34 /MODE ("jumper")     1  A18
  32309   13 D5           24 DB25.7.DATA5    35 VCC                  2  GND
  32310   14 VCC          25 VCC             36 DB25.11.ACK          3  VCC
  32311   15 D6           26 DB25.8.DATA6    37 ?                    4  EEPROM./OE
  32312   16 VCC          27 DB25.9.DATA7    38 VCC                  5  DB25.10.STB
  32313   17 D7           28 EEPROM./CS      39 ?                    6  SWITCH
  32314 D0 is wired to both pin7 and pin29. The /MODE pin is NC (but could be GNDed via
  32315 the two solder points in middle of the PCB). The SWITCH has 10K pullup (can can
  32316 get GNDed depending on switch setting).
  32317 
  32318 Power Replay III Game Enhancer?
  32319   PCB: "JSZ-02"
  32320   U1 32pin  AMD AM29F010 (128Kx8 FLASH)
  32321   U2 20pin  PALCE, 16V8H-25JC/4, 0018BZ2 (sticker "(C)DEC95, H00028, 340Y3")
  32322   U3 20pin  Optional 74xxx?         (not installed)
  32323   J1 68pin  PSX expansion port connector
  32324   J2 25pin  Optional DB25 connector (not installed)
  32325   K1  3pin  Switch
  32326   resistor/z-diode for 5.1V supply (or optionally 2x1N4148 for about 6V)
  32327 
  32328 PALCE20V8 Cuthbert Action Replay schematic (from hitmen webpage)
  32329   1-NC         8-NC         15-NC                    22-NC
  32330   2-FBIN       9-CPU.A4     16-GNDed                 23-FLASH./WE
  32331   3-CPU.A17    10-CPU./EXP  17-DB25.pin10 (PAR.STB)  24-FBOUT
  32332   4-CPU./WR    11-CPU.A3    18-FLASH./CS             25-FLASH./OE (and BUF.DIR)
  32333   5-CPU./RD    12-CPU.A5    19-DB25.pin11 (PAR.ACK)  26-BUF./EN
  32334   6-CPU.A18    13-SWITCH    20-CPU.D0                27-unused
  32335   7-CPU.A20    14-GND       21-FLASH.A17             28-VCC
  32336 
  32337 Charles MacDonald Game Shark schematic
  32338   1-FBIN       7-CPU.A4.NC?    13-GNDed       19-FLASH./WE
  32339   2-PIC.RC1    8-CPU./EXP.NC?  14-PAR.STB     20-FBOUT
  32340   3-CPU./WR    9-CPU.A3        15-PIC.RA0     21-BUF.DIR
  32341   4-CPU./RD    10-CPU.A2       16-PAR.ACK     22-BUF./OE
  32342   5-CPU.A18    11-SWITCH       17-CPU.D0      23-PIC.RC0
  32343   6-CPU.A17    12-GND          18-FLASH./OE   24-VCC
  32344 Uhm, schematic shows "PAR.ACK" instead of "BUF.DIR" as transceiver direction?
  32345 The 24pin PAL in Charles schematic does actually seem to be a 28pin PLCC GAL in
  32346 actual hardware (which has four NC pins, hence the 24pin notation in the
  32347 schematic).
  32348 The three PIC pins connect to a 28pin PIC16C55 microprocessor (unknown
  32349 purpose). Most of the PIC pins are NC (apart from the above three signals, plus
  32350 supply, plus OSC ... derived from some oscillator located "behind" the DB25
  32351 connector?).
  32352 
  32353 Charles MacDonald Gold Finger schematic
  32354   1-FBIN       6-CPU.A17       11-CPU.A2     16-FBOUT
  32355   2-SWITCH     7-CPU.A4.NC?    12-PAR.ACK    17-CPU.A20
  32356   3-CPU./WR    8-CPU./EXP.NC?  13-CPU.D0     18-PAR.STB
  32357   4-CPU./RD    9-CPU.A3        14-FLASH./OE  19-BUF./OE
  32358   5-CPU.A18    10-GND          15-FLASH./WE  20-VCC
  32359 Note: This is a datel clone, without "BUF.DIR" signal (instead, the transceiver
  32360 DIR pin is wired to "PAR.ACK"; it's probably functionally same as real datel
  32361 hardware, assuming that "PAR.ACK" is only a short pulse during writing; then
  32362 reading should be possible anytime else).
  32363 
  32364 Charles MacDonald Comms Link schematic
  32365 PAL
  32366   1-/STATUS    7-ISA.A6        13-JP2        19-NC
  32367   2-ISA.A1     8-ISA.A7        14-ISA.A9     20-PCWR
  32368   3-ISA.A2     9-ISA.A8        15-NC         21-/PCRD
  32369   4-ISA.A3     10-ISA.AEN      16-ISA./IOW   22-NC
  32370   5-ISA.A4     11-JP1          17-/IRQ       23-ISA./IOR
  32371   6-ISA.A5     12-GND          18-ISA.D0     24-VCC
  32372 The JP1/JP2 pins allow to select Port 300h,310h,320h,330h via two jumpers. The
  32373 /IRQ pin could be forward to ISA./IRQ2..7 via six jumpers (but the feature is
  32374 ununsed and the six jumpers aren't installed at all).
  32375 
  32376 DB25 Connector
  32377   Pin  Parallel Port   CommsLink (PC)        cable         PAR (PSX)
  32378   1    /STB    ---->   "strobe" ----.---o-------------o--    -- NC
  32379   2-9  DATA <-/---->   DATA     <-- | --o-------------o-------> DATA
  32380   10   /ACK    <----   "strobe" ----'---o-------------o-------> "strobe"
  32381   11   BUSY    <----   "ack"    <-------o-------------o-------- "ack"
  32382   12   PE      <----   NC       --    --o-------------o--    -- NC
  32383   13   SLCT    <----   NC       --    --o-------------o--    -- NC
  32384   14   /AUTOLF ---->   NC       --    --o-------------o--.  .-- GNDed
  32385   15   /ERROR  <----   NC       --    --o-------------o--.  .-- GNDed
  32386   16   /INIT   ---->   NC       --    --o-------------o--.  .-- GNDed
  32387   17   /SELECT ---->   GNDed    --.  .--o-------------o--.  .-- GNDed
  32388   18-25 GND    -----   GND      --'--'--o-------------o--'--'-- GND
  32389 
  32390 nocash FiveWire mod (for connecting datel expansion cart to parallel port)
  32391   disconnect DB25.pin14,15,16,17 from GND (may require to desolder the DB25)
  32392   repair any GND connections that were "routed through" above pins
  32393   wire DB25.pin1./STB    to DB25.pin10./ACK
  32394   wire DB25.pin16./INIT  to PSX.EXPANSION.pin2./RESET
  32395   wire DB25.pin15./ERROR to PSX.EXPANSION.pin28.A20
  32396   wire DB25.pin13.SLCT   to PSX.EXPANSION.pin62.A21
  32397   wire DB25.pin12.PE     to PSX.EXPANSION.pin29.A22
  32398 
  32399 Cheat Devices - Datel Cheat Code Format
  32400 ---------------------------------------
  32401 
  32402 PSX Gameshark Code Format
  32403   30aaaaaa 00dd   ;-8bit Write  [aaaaaa]=dd
  32404   80aaaaaa dddd   ;-16bit Write [aaaaaa]=dddd
  32405 Below for v2.2 and up only
  32406   D0aaaaaa dddd   ;-16bit/Equal     If dddd=[aaaaaa] then (exec next code)
  32407   D1aaaaaa dddd   ;-16bit/NotEqual  If dddd<>[aaaaaa] then (exec next code)
  32408   D2aaaaaa dddd   ;-16bit/Less      If dddd<[aaaaaa] then (exec next code)
  32409   D3aaaaaa dddd   ;-16bit/Greater   If dddd>[aaaaaa] then (exec next code)
  32410   E0aaaaaa 00dd   ;-8bit/Equal      If dd=[aaaaaa] then (exec next code)
  32411   E1aaaaaa 00dd   ;-8bit/NotEqual   If dd<>[aaaaaa] then (exec next code)
  32412   E2aaaaaa 00dd   ;-8bit/Less       If dd<[aaaaaa] then (exec next code)
  32413   E3aaaaaa 00dd   ;-8bit/Greater    If dd>[aaaaaa] then (exec next code)
  32414   10aaaaaa dddd   ;-16bit Increment [aaaaaa]=[aaaaaa]+dddd
  32415   11aaaaaa dddd   ;-16bit Decrement [aaaaaa]=[aaaaaa]-dddd
  32416   20aaaaaa 00dd   ;-8bit Increment  [aaaaaa]=[aaaaaa]+dd
  32417   21aaaaaa 00dd   ;-8bit Decrement  [aaaaaa]=[aaaaaa]-dd
  32418 Below for v2.41 and up only
  32419   D4000000 dddd   ;-Buttons/If  If dddd=JoypadButtons then (exec next code)
  32420   D5000000 dddd   ;-Buttons/On  If dddd=JoypadButtons then (turn on all codes)
  32421   D6000000 dddd   ;-Buttons/Off If dddd=JoypadButtons then (turn off all codes)
  32422   C0aaaaaa dddd   ;-If/On       If dddd=[aaaaaa] (turn on all codes)
  32423 Below probably v2.41, too (though other doc claims for v2.2)
  32424   5000nnbb dddd   ;\Slide Code aka Patch Code aka Serial Repeater
  32425   aaaaaaaa ??ee   ;/for i=0 to nn-1, [aaaaaaaa+(i*bb)]=dddd+(i*??ee), next i
  32426   00000000 0000   ;-Dummy (do nothing?) needed between slides (CD version only)
  32427 Below probably v2.41, too (though other doc claims for ALL versions)
  32428   C1000000 nnnn   ;-Delays activation of codes by nnnn (4000-5000 = 20-30 sec)
  32429   C2ssssss nnnn   ;\Copy ssss bytes from 80ssssss to 80tttttt
  32430   80tttttt 0000   ;/
  32431 Below from Caetla .341 release notes
  32432 These are probably caetla-specific, not official Datel-codes. In fact, Caetla
  32433 .341 itself might be an inofficial hacked version of Caetla .34 (?) so below
  32434 might be totally inofficial stuff:
  32435   C3aaaaaa 0000     ;\Indirect 8bit Write  [[aaaaaa]+bbbb]=dd
  32436   9100bbbb 000000dd ;/
  32437   C3aaaaaa 0001     ;\Indirect 16bit Write [[aaaaaa]+bbbb]=dddd (Tomb Raider 2)
  32438   9100bbbb 0000dddd ;/
  32439   C3aaaaaa 0002     ;\Indirect 32bit Write [[aaaaaa]+bbbb]=dddddddd
  32440   9100bbbb dddddddd ;/
  32441   FFFFFFFF 0001     ;-Optional prefix for GameShark 2.2 codes(force non-caetla)
  32442   12aaaaaa dddddddd ;-32bit Increment [aaaaaa]=[aaaaaa]+dddddddd
  32443   22aaaaaa dddddddd ;-32bit Decrement [aaaaaa]=[aaaaaa]-dddddddd
  32444 
  32445 Notes
  32446 A maximum of 30 increment/decrement codes can be used at a time.
  32447 A maximum of 60 conditionals can be used at a time (this includes Cx codes).
  32448 Increment/decrement codes should (must?) be used with conditionals.
  32449 Unknown if greater/less conditionals are signed or unsigned.
  32450 Unclear if greater/less compare dddd by [aaaaaa], or vice-versa.
  32451 Unknown if 16bit codes do require memory alignment.
  32452 
  32453 Cheat Devices - Xplorer Memory and I/O Map
  32454 ------------------------------------------
  32455 
  32456 Xplorer Memory Map
  32457   1F000000h-1F03FFFFh.RW  First 256K of FLASH (fixed mapping)
  32458   1F040000h-1F05FFFFh.RW  Map-able: 2x128K FLASH or 4x128K SRAM (if any)
  32459   1F060000h-1F060007h.xx  I/O Ports
  32460   1F060008h-1F06FFFFh     Mirrors of I/O at 1F060000h..1F060007h
  32461   1F070000h-1F07FFFFh     Unused (open bus)
  32462 FLASH can be 256Kbyte (normal), or 512Kbyte (in FX versions). When programming
  32463 FLASH chips: Observe that the carts can be fitted with chips from different
  32464 manufacturers, and, Xplorer carts can have either one or two 256K chips, or one
  32465 512K chip.
  32466 SRAM can be 0Kbyte (normal/none), or 128Kbyte (in FX versions). The PCB
  32467 supports max 512K SRAM (but there aren't any carts having that much memory
  32468 installed).
  32469 
  32470 Xplorer I/O Map
  32471   1F005555h.W  FLASH Cmd 1st/3rd byte ;\for first FLASH chip
  32472   1F002AAAh.W  FLASH Cmd 2nd byte     ;/
  32473   1F045555h.W  FLASH Cmd 1st/3rd byte ;\for 2nd FLASH chip (if any)
  32474   1F042AAAh.W  FLASH Cmd 2nd byte     ;/
  32475   1F060000h.R  I/O - Switch Setting (bit0: 0=Off, 1=On)
  32476   1F060001h.R  I/O - 8bit Data from PC (bit0-7)
  32477   1F060001h.W  I/O - 8bit Latch (Data to PC, and Memory Mapping)
  32478                  0  DB25.pin13.SLCT   ;\
  32479                  1  DB25.pin12.PE     ; used for data to PC
  32480                  2  DB25.pin11.BUSY   ;/
  32481                  3  DB25.pin10./ACK   ;-used for handshake to PC
  32482                  4  Memory Mapping (0=EEPROM, 1=SRAM)
  32483                  5  Memory Mapping (EEPROM A17 when A18=1)
  32484                  6  Memory Mapping (SRAM A17 or SRAM CE2)
  32485                  7  Memory Mapping (SRAM A18 or NC)
  32486   1F060002h.R  I/O - Handshake from PC (bit0)   (DB25.pin17./SEL)
  32487   1F060005h.W  I/O - Unknown (used by Xplorer v4.52, set to 03h)
  32488   1F060006h.R  I/O - Unknown (used by Xplorer v4.52, bit0 used)
  32489   1F060007h.R  I/O - Unknown (used by Xplorer v4.52, bit0 used)
  32490 
  32491 Cheat Devices - Xplorer DB25 Parallel Port Function Summary
  32492 -----------------------------------------------------------
  32493 
  32494 Xplorer Parallel Port Commands (from PC side)
  32495   GetByteByAddr32       Tx(5702h,Addr32), Rx(Data8)
  32496   OldMenuBuReadFile     Tx(5703h), TxFilename, RxDataFFEEh
  32497   OldMenuBuDeleteFile   Tx(5704h), TxFilename
  32498   OldMenuBuWriteFile    Tx(5705h), TxFilename, TxFiledata
  32499   OldMenuBuGetFileHdr   Tx(5706h), TxFilename, Rx(00h,00h), RxTurbo, Rx(02h)
  32500   OldMenuBuOpenEvents   Tx(5707h)
  32501   SetCop0Breakpoint     Tx(5708h,Addr32,Mask32,Ctrl32)   ;Menu: Dummy?
  32502   OldMenuBuCopyFile     Tx(5709h), TxFilename  ;to other memcard
  32503   OldMenuBuFormat       Tx(570Ah,Port8)
  32504   OldMenuBuGetStatus2x  Tx(570Bh), Rx(Stat8,Stat8)  ;\different in old/new
  32505   NewMenuBuGetStatus1x  Tx(570Bh,Port8), Rx(Stat8)  ;/
  32506   MenuGetSetFlag        Tx(570Ch), Rx(Flag8)   ;get old flg, then set flg=01h
  32507   NewMenuBuReadSector   Tx(570Dh,Port8,Sector16), Rx(Data[80h])
  32508   NewMenuBuWriteSector  Tx(570Eh,Port8,Sector16,Data[80h])
  32509   NewRawExecute         Tx(570Fh,Addr32)                 ;call Addr
  32510   MidMenuBuggedExecJump Tx(5710h,ORra32,ORgp32,ORsp32,pc32) ;aka r31,r28,r29,pc
  32511   MidMenuSendComment    Tx(5711h,Len8,AsciiMessage[Len])
  32512   NewMenuFillVram       Tx(5712h,Xloc32,Yloc32,Xsiz32,Ysiz32,FillValue32)
  32513   NewGetVram            Tx(5713h,Xloc32,Yloc32), Rx(Data[800h]) ;32x32pix
  32514   NewGetSetIrqMask      Tx(5714h), Rx(OldMask16), Tx(NewMask16) ;Menu: Dummy
  32515   NewSetVram            Tx(5715h,Xloc8,Yloc8,Data[800h]) ;X/Y=div32 ;32x32pix
  32516   NewMenuGetFlgAndOrVal Tx(5716h), Rx(00h, or 01h,Val32)             ;\
  32517   NewMenuGetTwoValues   Tx(5717h), Rx(Val32,Val32)                   ;
  32518   NewMenu...            Tx(5718h), ...                               ;
  32519   NewMenuGet2kGarbage   Tx(5719h,Dummy32), Rx(Garbage[800h])         ; whatever
  32520   NewMenuGetSomeValue   Tx(571Ah), Rx(Val32)                         ;
  32521   NewMenu...            Tx(571Bh,Data[4])  ;similar to 5763h         ;
  32522   NewMenuNoLongerSupp.  Tx(571Ch)    ;probably WAS supported someday ;/
  32523   GameAddCheatCode      Tx(5741h,Addr32,Data16), Rx(Index8)
  32524   MenuReBootKernel      Tx(5742h)              ;jumps to BFC00000h
  32525   GameDelCheatCode      Tx(5744h,Index8)
  32526   GetMem                Tx(5747h,Addr32,Len32), Rx(Data[Len]), TxRxChksum
  32527   Lock/Freeze           Tx(574Ch)
  32528   OldMenuBuGetDirectory Tx(574Dh), RxTurbo
  32529   MenuTestDB25Handshake Tx(574Eh), ...
  32530   MenuOptimalGetMem     Tx(574Fh,Addr32,Len32), RxFaster(Data[Len]), TxRxChksum
  32531   OldMenuGetWhatever    Tx(5750h), RxDataFFEEh                       ;-whatever
  32532   Release/Unfreeze      Tx(5752h)
  32533   SetMem                Tx(5753h,Addr32,Len32,Data[Len]), TxRxChksum
  32534   TurboGetMem           Tx(5754h,Addr32,Len32), RxFast(Data[Len]), TxRxChksum
  32535   MenuSetMemAndBurnFirm Tx(5755h,Addr32,Len32,Data[Len]), TxRxChksum ;burnFlash
  32536   GetStateGameOrMenu    Tx(5757h), Rx(47h=Game, or 58h=Menu)
  32537   SetMemAndExecute      Tx(5758h,Addr32,Len32,Data[Len]), TxRxChksum ;call Addr
  32538   NewMenu...            Tx(5763h,Val32)    ;similar to 571Bh         ;-whatever
  32539   GetByteByAddr24       Tx(5767h,Addr24), Rx(Data8)
  32540   NewMenuBuggedExecJump Tx(577Ah,ORra32,ORgp32,ORsp32,pc32)  ;formerly 5710h
  32541   NewMenuFlashAndReboot Tx(57C7h,Dest32,Len32,DataXorD3h[Len])
  32542 Function names starting with "Game/Menu" and/or "New/Mid/Old" are working only
  32543 in Game/Menu mode, or only in New/Old xplorer firmware versions (new commands
  32544 exist in v4.52, old commands exist in v1.091, mid commands exist in v2.005, but
  32545 neither in v1.091 nor v4.52, unknown when those new/mid/old commands have been
  32546 added/removed exactly, in which specific versions).
  32547 
  32548 The only useful command is SetMemAndExecute, which works in ALL versions, and
  32549 which can be used to do whatever one wants to do (unfortunately, most of the
  32550 official & inoffical tools are relying on other weird commands, which are
  32551 working only with specific xplorer firmware versions).
  32552 
  32553 Cheat Devices - Xplorer DB25 Parallel Port Command Handler
  32554 ----------------------------------------------------------
  32555 
  32556 The command handler is called once and then during booting, during xplorer GUI,
  32557 and during Game execution.
  32558 Each call to the command handler does allow to execute ONLY ONE command,
  32559 however, the "Freeze" command can be used to force the xplorer to stay in the
  32560 command handler, so one can send MORE commands, until leaving the command
  32561 handler by sending the "Unfreeze" command.
  32562 The command handling can vary depending on current boot phase (see below
  32563 cautions on Pre-Boot, Mid-Boot, and In-Game phases).
  32564 
  32565 Pre-Boot Handler
  32566 This is called shortly after the kernel has done some basic initialization, and
  32567 after the xplorer has relocated its EEPROM content to RAM (which means it may
  32568 called about a second after reset when using official PSX kernel and Xplorer
  32569 Firmware).
  32570   OLD Explorer Firmware: Call command handler ONCE (in MENU mode)
  32571   NEW Explorer Firmware: Call command handler TWICE (in MENU mode)
  32572   if SWITCH=ON or [80000030h]="WHB." then
  32573     NEW Explorer Firmware: Call command handler ONCE AGAIN (in MENU mode)
  32574     Install Mid-Boot hook
  32575   endif
  32576 Observe that the Kernel function vectors at A0h, B0h, and C0h aren't installed
  32577 at this point. If you want to upload an EXE with Kernel vectors installed: send
  32578 THREE dummy commands (eg. Unfreeze) to skip the above early command handling.
  32579 On the other hand, the ReBootKernel command can be used if you WANT to upload
  32580 something during Pre-Boot (the ReBootKernel command works only in MENU mode
  32581 though, ie. during Xplorer GUI, but not during Game).
  32582 
  32583 Mid-Boot Handler (Xplorer GUI)
  32584 The Xplorer GUI is called only if the Pre-Boot handler has installed it (eg. if
  32585 the SWITCH was ON). The handler is called alongsides with joypad reading (which
  32586 does NOT take place during the Xplorer intro, so there will be a long dead spot
  32587 between Pre-Boot and Mid-Boot command handling).
  32588   Call command handler ONCE (in MENU mode) alongsides with each joypad read
  32589 Observe that the GUI may have smashed various parts of the Kernel
  32590 initialization, so you can upload EXE files, and can use Kernel functions, but
  32591 the EXE won't get booted in same state as when booting from CDROM. The boot
  32592 state can also vary dramatically depending on the Xplorer Firmware version.
  32593 
  32594 Post-Boot Handler (at start of CDROM booting)
  32595 This is called when starting CDROM booting.
  32596   Install GAME mode hook for the B(17h) ReturnFromException() handler
  32597   OLD Explorer Firmware: Call command handler ONCE (still in MENU mode)
  32598   NEW Explorer Firmware: Call command handler ONCE (already in GAME mode)
  32599 
  32600 In-Game Handler (after CDROM booting) (...probably also DURING booting?)
  32601 This is called via the hooked B(17h) ReturnFromException() handler.
  32602   if SWITCH=ON
  32603     Call command handler ONCE (in GAME mode) upon each B(17h)
  32604     And, process game cheat codes (if any) upon each B(17h)
  32605   endif
  32606 Observe that GAME mode doesn't support all commands. And, above will work only
  32607 if the game does use B(17h), eg. when using non-kernel exception handling, or
  32608 if it has crashed, or disabled exceptions. Some internal kernel functions are
  32609 using ReturnFromException() directly (without going through the indirect B(17h)
  32610 function table entry; so the hook cannot trap such direct returns).
  32611 
  32612 Cheat Devices - Xplorer DB25 Parallel Port Low Level Transfer Protocol
  32613 ----------------------------------------------------------------------
  32614 
  32615 All 16bit/24bit/32bit parameters are transferred MSB first.
  32616 
  32617 Tx(Data) - transmit data byte(s)
  32618   Output 8bit data to DATA0-7     (DB25.pin2-9)        ;-Send Data (D0-D7)
  32619   Output /SEL=HIGH                (DB25.pin17)         ;\Handshake High
  32620   Wait until /ACK=HIGH            (DB25.pin10)         ;/
  32621   Output /SEL=LOW                 (DB25.pin17)         ;\Handshake Low
  32622   Wait until /ACK=LOW             (DB25.pin10)         ;/
  32623 
  32624 Rx(Data) - receive data byte(s)
  32625   Wait until /ACK=HIGH            (DB25.pin10)         ;\
  32626   Get 3bit from SLCT,PE,BUSY      (DB25.pin13,12,11)   ; 1st Part (D6,D7,HIGH)
  32627   Output /SEL=HIGH                (DB25.pin17)         ;/
  32628   Wait until /ACK=LOW             (DB25.pin10)         ;\
  32629   Get 3bit from SLCT,PE,BUSY      (DB25.pin13,12,11)   ; 2nd Part (D3,D4,D5)
  32630   Output /SEL=LOW                 (DB25.pin17)         ;/
  32631   Wait until /ACK=HIGH            (DB25.pin10)         ;\
  32632   Get 3bit from SLCT,PE,BUSY      (DB25.pin13,12,11)   ; 3rd Part (D0,D1,D2)
  32633   Output /SEL=HIGH                (DB25.pin17)         ;/
  32634   Wait until /ACK=LOW             (DB25.pin10)         ;\4th Part (ver,LOW,LOW)
  32635   Get 3bit from SLCT,PE,BUSY      (DB25.pin13,12,11)   ;  (ver=LOW  for v1.091)
  32636   Output /SEL=LOW                 (DB25.pin17)         ;/ (ver=HIGH for v4.52)
  32637   Wait until all 4bits LOW        (DB25.pin13,12,11,10);-xlink95 fails if not
  32638 
  32639 RxFast(Data) for TurboGetMem - slightly faster than normal Rx(Data)
  32640 First, for invoking the Turbo transfer:
  32641   Wait for BUSY=LOW               (DB25.pin11)
  32642   Output DATA = 00h               (DB25.pin2-9)
  32643   Wait for BUSY=HIGH              (DB25.pin11)
  32644   Output DATA = ECh               (DB25.pin2-9)
  32645 Thereafter, receive the actual Data byte(s) as so:
  32646   Wait for /ACK transition        (DB25.pin10)         ;\
  32647   Get 3bit from SLCT,PE,BUSY      (DB25.pin13,12,11)   ; 1st Part (D6,D7,LOW)
  32648   Output DATA = 02h               (DB25.pin2-9)        ;/
  32649   Wait for /ACK transition        (DB25.pin10)         ;\
  32650   Get 3bit from SLCT,PE,BUSY      (DB25.pin13,12,11)   ; 2nd Part (D3,D4,D5)
  32651   Output DATA = 04h               (DB25.pin2-9)        ;/
  32652   Wait for /ACK transition        (DB25.pin10)         ;\
  32653   Get 3bit from SLCT,PE,BUSY      (DB25.pin13,12,11)   ; 3rd Part (D0,D1,D2)
  32654   Output DATA = 01h               (DB25.pin2-9)        ;/
  32655 The /ACK transitions can be sensed by polling the parallel port IRQ flag on PC
  32656 side.
  32657 
  32658 RxFaster(Data) for OptimalGetMem - much faster than normal Rx(Data)
  32659 First, for invoking the Turbo transfer:
  32660   Output DATA = 00h  ;<-- crap    (DB25.pin2-9)        ;-BUGGY, but REQUIRED
  32661 Thereafter, receive the actual Data byte(s) as so:
  32662   Get 4bit from SLCT,PE,BUSY,/ACK (DB25.pin13,12,11,10);\1st Part (D4,D5,D6,D7)
  32663   Output DATA = 00h               (DB25.pin2-9)        ;/
  32664   Get 4bit from SLCT,PE,BUSY,/ACK (DB25.pin13,12,11,10);\2nd Part (D0,D1,D2,D3)
  32665   Output DATA = 01h               (DB25.pin2-9)        ;/
  32666 BUG: The first received byte will be garbage with upper and lower 4bit both
  32667 containing the lower 4bits (the bugged firmware does explicitely want DATA=00h
  32668 before transfer, although DATA=00h is also 'confirming' that the upper 4bit can
  32669 be 'safely' replaced by lower 4bit).
  32670 
  32671 TxRxChksum for SetMem/GetMem functions
  32672   Tx(chkMsb), Rx(chkMsb), Tx(chkLsb), Rx(chkLsb), Rx("OK" or "CF" or "BG")
  32673 The 16bit checksum is all bytes in Data[Len] added together. The two final
  32674 response bytes should be "OK"=Okay, or, if the transmitted chksum didn't match,
  32675 either "CF"=ChecksumFail (for SetMem functions) or "BG"=BadGetChecksum (for
  32676 GetMem functions). MenuSetMemAndBurnFirm is a special case with three response
  32677 codes: "OF"=FlashOkay, "CF"=ChecksumFail, "FF"=FlashWriteFail.
  32678 
  32679 TxFilename for Memcard (bu) functions
  32680   Rx(Addr32), Tx(Addr32,Len32,Data[Len]), TxRxChksum
  32681 This is internally using the standard "SetMem" function; preceeded by
  32682 Rx(Addr32). Whereas Addr is the target address for the filename (just pass the
  32683 Rx'ed address to the Tx part), Len should be max 38h, Data should be the
  32684 filename with ending zero (eg. "bu10:name",00h).
  32685 
  32686 TxFiledata for Memcard (bu) WriteFile
  32687   Rx(Filename[26h])                       ;-name from TxFilename, echo'ed back
  32688   Rx(Addr32)                              ;-buffer address for fragments
  32689   Tx(NumFragments8)                       ;-number of fragments
  32690   Tx(Addr32,Len32,Data[Len]), TxRxChksum  ;<-- repeat this for each fragment
  32691   Rx(FileHandle8)                         ;-ending dummy byte (filehandle)
  32692 This is also using the standard "SetMem" function, plus some obscure extra's.
  32693 The filedata is split into fragments, Len should be max 2000h per fragment.
  32694 
  32695 RxDataFFEEh for Memcard (bu) ReadFile and GetWhatever
  32696   Rx(FFEEh,"W",Len32,Data[Len]  ;<-- can be repeated for several fragments
  32697   Rx(FFEEh,"CA")                ;<-- End Code (after last fragment)
  32698 Memcard ReadFile does transfer N fragments of Len=2000h (depending on
  32699 filesize). The GetWhatever function transfers one fragment with Len=80h,
  32700 followed by N*6 fragments with Len=40Ah.
  32701 
  32702 RxTurbo for Memcard (bu) GetDirectory/GetFileHeader functions
  32703   Rx(Addr32), Tx(Addr32,Len32), RxFast(Data[Len]), TxRxChksum
  32704 This is internally using the standard "TurboGetMem" function; preceeded by
  32705 Rx(Addr32). Whereas Addr is the source address of the actual data (just pass
  32706 the Rx'ed address to the Tx part).
  32707 For GetDirectoy, Len should be max 800h (actual/data data is only 4B0h bytes,
  32708 ie. 258h bytes per memcard, aka 28h bytes per directory entry). For
  32709 GetFileHeader, Len should be max 80h.
  32710 
  32711 Cheat Devices - Xplorer Versions
  32712 --------------------------------
  32713 
  32714 Xplorer names
  32715   Xploder (Germany/USA)
  32716   Xplorer (England/Spain/Netherlands)
  32717   X-Terminator (Japan)
  32718 
  32719 Xplorer suffices
  32720   V1/V2/V3  normal boards   (256K EEPROM, no SRAM, no DB25 resistor)
  32721   FX/DX     extended boards (512K EEPROM, 128K SRAM, with DB25 resistor)
  32722   PRO       meaningless suffix
  32723 The V1/V2/V3 suffix does just indicate the pre-installed firmware version (so
  32724 that suffices become meaningless after software upgrades).
  32725 The FX suffix (or DX in japan) indicates that the PCB contains more memory and
  32726 an extra resistor (the memory/resistor are intended for use with the "X-Assist"
  32727 add-on device).
  32728 
  32729 Xplorer PCB types
  32730   1) PXT6     ;original board
  32731   2) Nameless ;with alternate solder pads for smaller SRAM/GAL
  32732   3) PXT6-3   ;with alternate solder pads for smaller SRAM/GAL and 2nd EEPROM
  32733 
  32734 Xplorer Compatibility Issues
  32735 The three PCB versions are functionally identical, and do differ only by
  32736 cosmetic changes for alternate/smaller chip packages.
  32737 However, some things that can make difference in functionality are the
  32738 installed components and installed firmware version:
  32739  - FX carts have some extra components & more memory installed.
  32740    (needed for "bigger" firmwares, mainly needed for the X-Assist add-on)
  32741  - FLASH chips from different manufacturers can occassionally cause problems
  32742    (eg. older software not knowing how to program newer FLASH chips).
  32743  - DB25 transfer protocol has some changed commands in each firmware version
  32744    (and most transfer tools tend to rely on such commands, so most tools will
  32745    fail unless the cart is flashed with a certain firmware version).
  32746 
  32747 X-Assist add-on for Xplorer carts
  32748 The X-Assist is a quity huge clumsy controller with DPAD, plus 4 buttons, plus
  32749 small LCD screen. The thing connects to the Xplorer's DB25 connector, allowing
  32750 to enter/search cheat codes without using a PC.
  32751 The device works only with "FX" Xplorer boards (which contain an extra resistor
  32752 for outputting supply power on the DB25 connector, plus more memory which is
  32753 somewhat intended for use by the X-Assist thing).
  32754 
  32755 Cheat Devices - Xplorer Chipset Pinouts
  32756 ---------------------------------------
  32757 
  32758 Xplorer Pinout GAL20V8 (generic array logic)
  32759   1  IN0  (DB25.pin17./SEL)
  32760   2  IN1  (PSX.pin14.A0)
  32761   3  IN2  (PSX.pin48.A1)
  32762   4  IN3  (PSX.pin15.A2)
  32763   5  IN4  (74373.pin15.Q5)
  32764   6  IN5  (PSX.pin4./EXP)
  32765   7  IN6  (74373.pin12.Q4)
  32766   8  IN7  (PSX.pin26.A16) (EEPROM.pin2.A16) (SRAM.pin2.A16) (10000h)
  32767   9  IN8  (PSX.pin60.A17)                                   (20000h)
  32768   10 IN9  (PSX.pin27.A18) (EEPROM.pin1.A18 or NC)           (40000h)
  32769   11 IN10 (PSX.pin30./RD)
  32770   12 GND
  32771   ---
  32772   13 IN11 (GND)
  32773   14 IN12 (/SWITCH_ON)
  32774   15 IO   (74373.pin11.LE)
  32775   16 IO   (PSX.pin6.D0)
  32776   17 IO   (SRAM./CE.pin22)
  32777   18 IO   (EEPROM2./CE.pin22) (for 2nd EEPROM chip, if any)
  32778   19 IO   (EEPROM1./CE.pin22) (for 1st EEPROM chip)
  32779   20 IO   (NC)                       (reportedly has wire?)
  32780   21 IO   (EEPROM.pin30.A17)         (reportedly A14 ?)
  32781   22 IO   (74245.pin19./E)
  32782   23 IN13 (PSX.pin64./WR) (SRAM.29, EEPROM.31)
  32783   24 VCC
  32784 The GALs are programmed nearly identical for all Xplorer versions, some small
  32785 differences are: One or two EEPROM chip selects (depending on EEPROM chipset),
  32786 and extra ports at 1F060005h, 1F060006h, 1F060007h (used in v4.52).
  32787 Note: The 28pin PLCC GAL has same pinout as the 24pin chip, but with four NC
  32788 pins inserted (at pin 1,8,15,22, whereof, there is a wire routed "through" pin
  32789 8, so that pin isn't literally NC).
  32790 
  32791 Xplorer Pinout 74373 (8bit tristate latch)
  32792   1  /OE (GND)
  32793   2  Q0  (DB25.pin13.SLCT)
  32794   3  D0  (PSX)
  32795   4  D1  (PSX)
  32796   5  Q1  (DB25.pin12.PE)
  32797   6  Q2  (DB25.pin11.BUSY)
  32798   7  D2  (PSX)
  32799   8  D3  (PSX)
  32800   9  Q3  (DB25.pin10./ACK)
  32801   10 GND
  32802   11 LE  (GAL.pin15.LatchEnable)
  32803   12 Q4  (GAL.pin7)             (0=EEPROM, 1=SRAM)
  32804   13 D4  (PSX)
  32805   14 D5  (PSX)
  32806   15 Q5  (GAL.pin5)             (EEPROM bank 2/3)
  32807   16 Q6  (SRAM.pin30.A17 or CE2)
  32808   17 D6  (PSX)
  32809   18 D7  (PSX)
  32810   19 Q7  (SRAM.pin1.A18 or NC)
  32811   20 VCC
  32812 
  32813 Xplorer Pinout 74245 (8bit bus transceiver)
  32814   1  DIR (GNDed)
  32815   2  D7  (PSX)
  32816   3  D6  (PSX)
  32817   4  D5  (PSX)
  32818   5  D4  (PSX)
  32819   6  D3  (PSX)
  32820   7  D2  (PSX)
  32821   8  D1  (PSX)
  32822   9  D0  (PSX)
  32823   10 GND
  32824   11 D0  (DB25.pin2)
  32825   12 D1  (DB25.pin3)
  32826   13 D2  (DB25.pin4)
  32827   14 D3  (DB25.pin5)
  32828   15 D4  (DB25.pin6)
  32829   16 D5  (DB25.pin7)
  32830   17 D6  (DB25.pin8)
  32831   18 D7  (DB25.pin9)
  32832   19 /E  (GAL.pin22)
  32833   20 VCC
  32834 
  32835 Xplorer Pinout 7805 (voltage regulator)
  32836   1 5V   (VCC)
  32837   2 GND  (GND)
  32838   3 7.5V (PSX.pin18,52)
  32839 
  32840 Xplorer Pinout SWITCH (on/off)
  32841   OFF  NC
  32842   COM  PAL.pin14 (with 10K pull-up to VCC)
  32843   ON   GND
  32844 
  32845 Xplorer Pinout DB25 (parallel/printer port)
  32846   1  In  /STB  (NC)
  32847   2  In  DATA0 (74245.pin11)
  32848   3  In  DATA1 (74245.pin12)
  32849   4  In  DATA2 (74245.pin13)
  32850   5  In  DATA3 (74245.pin14)
  32851   6  In  DATA4 (74245.pin15)
  32852   7  In  DATA5 (74245.pin16)
  32853   8  In  DATA6 (74245.pin17)
  32854   9  In  DATA7 (74245.pin18)
  32855   10 Out /ACK  (74373.Q3)
  32856   11 Out BUSY  (74373.Q2)
  32857   12 Out PE    (74373.Q1)
  32858   13 Out SLCT  (74373.Q0)
  32859   ---
  32860   14 In  /LF   (NC)
  32861   15 Out /ERR  (VCC via 0.47ohm) (installed only on carts with SRAM)
  32862   16 In  /INIT (NC)
  32863   17 In  /SEL  (GAL.IN0.pin1)
  32864   18..25 GND   (Ground)
  32865 
  32866 EEPROM.pin1 is NC on 256Kx8 chip (however it is wired to A18 for use with
  32867 512Kx8 chips).
  32868 EEPROM.pin30 is A17 from GAL.pin21 (not from PSX.A17), accordingly GAL.pin21 is
  32869 EEPROM.A17 (not A14).
  32870 Boards with solder pads for TWO EEPROMs are leaving A18 not connected on the
  32871 2nd EEPROM (but do connect A18 to the first EEPROM, so one could either use one
  32872 512K chip or two 256K chips).
  32873 DB25.pin15./ERR is VCC via 0.47ohm (installed only on carts with SRAM, intended
  32874 as supply for the X-ASSIST thing).
  32875 SRAM (if any) is wired to GAL.pin17 (/CE), 74373.Q6 (A17 or CE2), 74373.Q7 (A18
  32876 or NC), other SRAM pins are wired straight to D0-D7, A0-A16, /RD, /WR.
  32877 VCC is 5V, derived from a 7805 voltage converter (with 7.5V used as input).
  32878 Existing boards seem to have 128K SRAM (if any), so SRAM A17/A18 aren't
  32879 actually used (unless a board would have 512K SRAM), however, for 128K SRAMs
  32880 one should switch SRAM CE2 (aka A17) high.
  32881 
  32882 Cheat Devices - Xplorer Cheat Code Format
  32883 -----------------------------------------
  32884 
  32885 PSX Xplorer/Xploder Code Format
  32886   3taaaaaa 00dd  ;-8bit write  [aaaaaa]=dd
  32887   8taaaaaa dddd  ;-16bit write [aaaaaa]=dddd
  32888   00aaaaaa dddd  ;-32bit write [aaaaaa]=0000dddd  <-- not "0taaaaaa dddd" ?
  32889   4t000000 000x  ;-Slow Motion (delay "x" whatever/ns,us,ms,frames?)
  32890   7taaaaaa dddd  ;-IF [aaaaaa]=dddd then <execute following code>
  32891   9taaaaaa dddd  ;-IF [aaaaaa]<>dddd then <execute following code>
  32892   Ftaaaaaa dddd  ;-IF [aaaaaa]=dddd then activate "other selected" codes (uh?)
  32893   5taaaaaa ?nnn  ;\
  32894   d0d1d2d3 d4d5  ; write "?nnn" bytes to [aaaaaa]  ;ordered d0,d1,d2... ?
  32895   d6d7d8.. ....  ;/
  32896   6t000000 nnnn  ;\COP0 hardware breakpoint
  32897   aaaaaaaa cccc  ; aaaaaaaa=break_address, mmmmmmmm=break_mask
  32898   mmmmmmmm d0d1  ; nnnn=num_bytes (d0,d1,d2,etc.), cccc=break_type (see below)
  32899   d2d3d4.. ....  ;/
  32900   B?nnbbbb eeee  ;\Slide/Patch Code, with unclear end: "end=?nn+/-1" ?
  32901   10aaaaaa dddd  ;/for i=0 to end, [aaaaaa+(i*bbbb)]=dddd+(i*eeee), next i
  32902   C0aaaaaa dddd  ;-garbage/mirror of 70aaaaaa dddd ?  ;\or maybe meant to be
  32903   D0aaaaaa dddd  ;-garbage/mirror of 70aaaaaa dddd ?  ;/same as on GameShark?
  32904 The second code digit (t) contains encryption type (bit0-2), and a "default
  32905 on/off" flag (bit3: 0=on, 1=off; whatever that means, it does probably require
  32906 WHATEVER actions to enable codes that are "off"; maybe via the Ftaaaaaa dddd
  32907 code).
  32908 
  32909 break_type (cccc) (aka MSBs of cop0r7 DCIC register)
  32910   E180 (instruction gotton by CPU but not yet implemented) (uh, gotton what?)
  32911   EE80 (data to be read or written)  ;<--looks okay
  32912   E680 (data to be read)             ;<--looks okay
  32913   EA80 (data to be wrtten)           ;<--looks okay
  32914   EF80 (instruction)   ;<-- looks crap, should be probably E180
  32915 The CPU supports one data breakpoint and one instruction breakpoint (though
  32916 unknown if the Xplorer does support to use both simultaneously, or if it does
  32917 allow only one of them to be used).
  32918 If the break_type/address/mask to match up with CPU's memory access actions...
  32919 then "something" does probably happen (maybe executing a sub-function that
  32920 consists of the d0,d1,d2,etc-bytes, if so, maybe at a fixed/unknown memory
  32921 address, or maybe at some random address; which would require relocatable
  32922 code).
  32923 
  32924 Notes
  32925 The "Slide" code shall be used only with even addresses, unknown if other
  32926 16bit/32bit codes do also require aligned addresses.
  32927 
  32928 Cheat Devices - Xplorer Cheat Code and ROM-Image Decryption
  32929 -----------------------------------------------------------
  32930 
  32931 decrypt_xplorer_cheat_code:
  32932   key  = x[0] and 07h              ;'''''''' AABBCCDD EEFF '''''''';
  32933   x[0] = x[0] xor key              ;         / / /  \  \ \         ;
  32934   if key=0                         ; x[0] --' / /    \  \ '-- x[5] ;
  32935     ;unencrypted (keep as is)      ; x[1] ---' /      \  '--- x[4] ;
  32936   elseif key=4                     ; x[2] ----'        '----- x[3] ;
  32937     x[1] = x[1] xor (025h)         ;,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,;
  32938     x[2] = x[2] xor (0FAh + (x[1] and 11h))
  32939     x[3] = x[3] xor (0C0h + (x[2] and 11h) + (x[1] xor 12h))
  32940     x[4] = x[4] xor (07Eh + (x[3] and 11h) + (x[2] xor 12h) + x[1])
  32941     x[5] = x[5] xor (026h + (x[4] and 11h) + (x[3] xor 12h) + x[2] + x[1])
  32942   elseif key=5
  32943     x[1] = (x[1] + 057h)  ;"W"ayne
  32944     x[2] = (x[2] + 042h)  ;"B"eckett
  32945     x[3] = (x[3] + 031h)  ;"1"
  32946     x[4] = (x[4] + 032h)  ;"2"
  32947     x[5] = (x[5] + 033h)  ;"3"
  32948   elseif key=6
  32949     x[1] = (x[1] + 0ABh) xor 01h
  32950     x[2] = (x[2] + 0ABh) xor 02h
  32951     x[3] = (x[3] + 0ABh) xor 03h
  32952     x[4] = (x[4] + 0ABh) xor 04h
  32953     x[5] = (x[5] + 0ABh) xor 05h
  32954   elseif key=7
  32955     x[5] = x[5] + 0CBh
  32956     x[4] = x[4] + 0CBh + (x[5] and 73h)
  32957     x[3] = x[3] + 05Ah + (x[4] and 73h) - (x[5] xor 90h)
  32958     x[2] = x[2] + 016h + (x[3] and 73h) - (x[4] xor 90h) + x[5]
  32959     x[1] = x[1] + 0F5h + (x[2] and 73h) - (x[3] xor 90h) + x[4] + x[5]
  32960   else
  32961     error ;(key=1,2,3)
  32962   endif
  32963 
  32964 decrypt_xplorer_fcd_rom_image:
  32965   for i=0 to romsize-1
  32966     x=45h
  32967     y=(i and 37h) xor 2Ch
  32968     if (i and 001h)=001h then x=x xor 01h
  32969     if (i and 002h)=002h then x=x xor 01h
  32970     if (i and 004h)=004h then x=x xor 06h
  32971     if (i and 008h)=008h then x=x xor 04h
  32972     if (i and 010h)=010h then x=x xor 18h
  32973     if (i and 020h)=020h then x=x xor 30h
  32974     if (i and 040h)=040h then x=x xor 60h
  32975     if (i and 080h)=080h then x=x xor 40h
  32976     if (i and 100h)=100h then x=x xor 80h
  32977     if (i and 006h)=006h then x=x xor 0ch
  32978     if (i and 00Eh)=00Eh then x=x xor 08h
  32979     if (i and 01Fh)>=016h then x=x-10h
  32980     rom[i]=(rom[i] XOR x)+y
  32981   next i
  32982 
  32983 Cheat Devices - FLASH/EEPROMs
  32984 -----------------------------
  32985 
  32986 FLASH/EEPROM Commands
  32987 Below commands should work on all chips (for write: page size may vary, eg. 1
  32988 byte, 128 bytes, or 256 bytes). Some chips do have some extra commands (eg. an
  32989 alternate older get id command, or sector erase commands, or config commands),
  32990 but those extras aren't needed for basic erase/write operations.
  32991   [5555h]=AAh, [2AAAh]=55h, [5555h]=A0h, [addr..]=byte(s)  ;write page
  32992   [5555h]=AAh, [2AAAh]=55h, [5555h]=90h, id=[0000h..0001h] ;enter id mode
  32993   [5555h]=AAh, [2AAAh]=55h, [5555h]=F0h                    ;exit id mode
  32994   [5555h]=AAh, [2AAAh]=55h, [5555h]=80h                    ;erase chip, step 1
  32995   [5555h]=AAh, [2AAAh]=55h, [5555h]=10h                    ;erase chip, step 2
  32996 Above addresses are meant to be relative to the chip's base address (ie.
  32997 "5555h" would be 1F005555h in PSX expansion ROM area, or, if there are two
  32998 flash chips, then it would be 1F045555h for the 2nd chip in xplorer and datel
  32999 carts; whereas, that region is using bank switching in xplorer carts, so one
  33000 must output some FLASH address bits I/O ports, and the others via normal CPU
  33001 address bus; whilst datel carts have noncontinous FLASH areas at 1F000000h and
  33002 1F040000h, with a gap at 1F020000h).
  33003 Observe that the chips will output status info (instead of FLASH data) during
  33004 write/erase/id mode (so program code using those commands must execute in RAM,
  33005 not in FLASH memory).
  33006 
  33007 FLASH/EEPROM Wait Busy
  33008 Waiting is required after chip erase and page write (after writing the last
  33009 byte at page end), and on some chips it's also required after enter/exit id
  33010 mode. Some chips indicate busy state via a toggle bit (bit6 getting inverted on
  33011 each 2nd read), and/or by outputting a value different than the written data,
  33012 and/or do require hardcoded delays (eg. AM29F040). Using the following 3-step
  33013 wait mechanism should work with all chips:
  33014   Wait 10us (around 340 cpu cycles on PSX)   ;-step 1, hardcoded delay
  33015   Wait until [addr]=[addr]                   ;-step 2, check toggle bit
  33016   Wait until [addr]=data                     ;-step 3, check data
  33017 Whereas, "addr" should be the last written address (or 0000h for erase and
  33018 enter/exit id mode). And "data" should be the last written data (or FFh for
  33019 erase, or "don't care" for enter/exit id mode).
  33020 
  33021 Board and Chip Detection
  33022 First of, one should detect the expansion board type, this can be done as so:
  33023   Enter Chip ID mode (at 1F000000h)
  33024   Compare 400h bytes at 1F000000h vs 1F020000h
  33025   If different --> assume Datel PAR1/PAR2 hardware
  33026   If same --> assume Xplorer hardware (or Datel PAR3, whatever that is)
  33027   Exit Chip ID mode (at 1F000000h)
  33028 Next, detect the Chip ID for the (first) FLASH chip:
  33029   Enter Chip ID mode (at 1F000000h)
  33030   Read the two ID bytes (at 1F00000xh)
  33031   Exit Chip ID mode (at 1F000000h)
  33032 Finally, one needs to check if there's a second FLASH chip, there are two such
  33033 cases:
  33034   If cart=xplorer AND 1st_chip=256K --> might have a 2nd 256K chip
  33035   If cart=datel   AND 1st_chip=128K --> might have a 2nd 128K chip
  33036 In both cases, the 2nd chip would be mapped at 1F400000h, and one can test the
  33037 following four combinations:
  33038   Enter Chip ID (at 1F000000h) and Enter Chip ID (at 1F400000h) ;id1+id2
  33039   Exit  Chip ID (at 1F000000h) and Enter Chip ID (at 1F400000h) ;id2
  33040   Exit  Chip ID (at 1F400000h) and Enter Chip ID (at 1F000000h) ;id1
  33041   Exit  Chip ID (at 1F400000h) and Exit  Chip ID (at 1F000000h) ;none
  33042 For each combination compare 400h bytes at 1F000000h vs 1F400000h.
  33043   If they are all same --> there is only one chip (mirrored to both areas)
  33044   If different --> 1F400000h is either garbage, or a 2nd chip
  33045 In the latter case, do Chip ID detection at 1F400000h to see if there's really
  33046 another chip there, and which type it is (if present, then it should be usually
  33047 the same type as the 1st chip; and if it's not present, then there might be
  33048 just open bus garbage instead of valid ID values).
  33049 
  33050 FLASH/EEPROM Chip IDs
  33051   ChipID  Kbyte Page Maker/Name         ;notes
  33052   1Fh,D5h 128K  128  ATMEL AT29C010A    ;xplorer/prototypes?
  33053   1Fh,35h 128K  128  ATMEL AT29LV010A   ;-
  33054   1Fh,DAh 256K  256  ATMEL AT29C020     ;xplorer
  33055   1Fh,BAh 256K  256  ATMEL AT29BV020    ;xplorer
  33056   1Fh,A4h 512K  256  ATMEL AT29C040A    ;xplorer
  33057   1Fh,C4h 512K  256  ATMEL AT29xV040A   ;-
  33058   BFh,07h 128K  128  SST SST29EE010     ;-
  33059   BFh,08h 128K  128  SST SST29xE010     ;-
  33060   BFh,22h 128K  128  SST SST29EE010A    ;-
  33061   BFh,23h 128K  128  SST SST29xE010A    ;-
  33062   BFh,10h 256K  128  SST SST29EE020     ;xplorer & datel
  33063   BFh,12h 256K  128  SST SST29xE020     ;xplorer
  33064   BFh,24h 256K  128  SST SST29EE020A    ;-
  33065   BFh,25h 256K  128  SST SST2xEE020A    ;-
  33066   BFh,04h 512K  256  SST SST28SF040     ;said to be used in "AR/GS Pro"
  33067   DAh,C1h 128K  128  WINBOND W29EE01x   ;-
  33068   DAh,45h 256K  128  WINBOND W29C020    ;-
  33069   DAh,46h 512K  256  WINBOND W29C040    ;xplorer
  33070   01h,20h 128K    1  AMD AM29F010       ;pcb "JSZ-02" (power replay iii)
  33071   01h,A4h 512K    1  AMD AM29F040       ;nocash psone bios (intact console)
  33072   20h,20h 128K    1  ST M29F010B        ;nocash psone bios (broken console)
  33073   31h,B4h 128K   ??  CATALYST CAT28F010 ;NEEDS VPP=12V !!! ("PS-121 ZISAN")
  33074 The above Atmel/SST/Winbond chips are commonly used in Datel or Xplorer carts
  33075 (or both). The CATALYST chip is used in some Datel clones (but seems to require
  33076 12 volts, meaning that it can't be properly programmed on PSX, nethertheless,
  33077 it's reportedly working "well enough" to encounter flash corruption upon
  33078 programming attempts). The two ST/AMD chips aren't really common in PSX world
  33079 (except that I've personally used them in my PSones).
  33080 
  33081 PSX Dev-Board Chipsets
  33082 ----------------------
  33083 
  33084 Sony DTL-H2000 CPU Board
  33085   CL825  20pin pin test points (2x10 pins)
  33086   CL827  20pin pin test points (2x10 pins)
  33087   U83    64pin SEC KM4216V256G-60 (DRAM 256Kx16) ;dual-ported VRAM
  33088   U84    64pin SEC KM4216V256G-60 (DRAM 256Kx16) ;dual-ported VRAM
  33089   CL828  20pin pin test points (2x10 pins)
  33090   CL826  20pin pin test points (2x10 pins)
  33091   X10     4pin JC53.20     (PAL, 53.203425MHz)
  33092   X2      4pin 53.69317MHz (NTSC, 53.693175MHz)
  33093   U62    20pin LVT244 (dual 4-bit 3-state noninverting buffer/line driver)
  33094   U27    64pin Sony CXD2923AR    ;GPU'b
  33095   CL813  20pin pin test points (2x10 pins)
  33096   CL814  20pin pin test points (2x10 pins) (with one resistor or so installed)
  33097   U16   160pin Sony CXD8514Q     ;GPU'a
  33098   X7      4pin 67.73760 MHz
  33099   CL807  20pin pin test points (2x10 pins)
  33100   CL809  20pin pin test points (2x10 pins)
  33101   CL811  20pin pin test points (2x10 pins)
  33102   U801  208pin Sony CXD8530BQ    ;CPU
  33103   U11    28pin SEC KM48V2104AJ-6 (DRAM 2Mx8) ;Main RAM
  33104   U10    28pin SEC KM48V2104AJ-6 (DRAM 2Mx8) ;Main RAM
  33105   U9     28pin SEC KM48V2104AJ-6 (DRAM 2Mx8) ;Main RAM
  33106   U8     28pin SEC KM48V2104AJ-6 (DRAM 2Mx8) ;Main RAM
  33107   CN801 100pin Blue connector (to other ISA board)
  33108   U66    48pin LVT16244? (quad 4-bit 3-state noninverting buffer/line driver)
  33109   U65    48pin LVT16244? (quad 4-bit 3-state noninverting buffer/line driver)
  33110   U64    48pin LVT16245? (dual 8-bit 3-state noninverting bus transceiver)
  33111   U34   100pin Sony CXD2922Q     ;SPU
  33112   U63    14pin 74F74N (dual flipflop)
  33113   U32    44pin SEC KM416V256B1-8 (DRAM 256Kx16)  ;SoundRAM
  33114   CL801  20pin pin test points (2x10 pins)
  33115   CL802  20pin pin test points (2x10 pins)
  33116   Q881    3pin voltage stuff?
  33117   U31    20pin 74ACT244P (dual 4-bit 3-state noninverting buffer/line driver)
  33118   U35    18pin Sony CXD2554P or OKI M6538-01 (aka MSM6538-01?) (audio related?)
  33119   U36    20pin Sanyo LC78815  ;16bit D/A Converter
  33120   U37     8pin NEC ...?    C4558C?   D426N0B or 9426HOB or so?
  33121   J806    8pin solder pads...
  33122   J805    9pin solder pads...
  33123   J804   10pin solder pads... (11pins, with only 10 contacts?)
  33124   -      48pin solder pads (12x4pin config jumpers or so)
  33125   U26    20pin SN74ALSxxx logic?
  33126   U71    24pin Sony CXA1xxxx?  ;RGB?
  33127   JPxx    9pin PAL/NTSC Jumpers (three 3pin jumpers)
  33128   J801   24pin solder pads...
  33129   J803    9pin rear connector: Serial Port (3.3V) (aka "J308") (DB9) (5+4pin)
  33130   J802   15pin rear connector: AV Multi-out   (5+5+5pin)
  33131   CN881  98pin ISA Bus Cart-edge (2x31 basic pins, plus 2x18 extended pins)
  33132 
  33133 Sony DTL-H2000 PIO Board
  33134   JP72x 68pin Black connector (maybe equivalent to 68pin PSX expansion port?)
  33135   SWI    5pin solder pads...
  33136   U371  40pin HN27C4000G-12 (512Kx8 / 256Kx16 EPROM) (sticker: "94/7/27")
  33137   U370  84pin Altera EPM7160ELC84-12 (sticker: "U730, cntl 1")
  33138   U3    14pin SN74ALS1004N (hex inverters)
  33139   U43   44pin Altera EPM7032LC44-10 (sticker: "U43, add 1")
  33140   U716  28pin Sharp LH5498D-35 (FIFO 2Kx9)
  33141   U717  28pin Sharp LH5498D-35 (FIFO 2Kx9)
  33142   U719  28pin Sharp LH5498D-35 (FIFO 2Kx9)
  33143   U720  28pin Sharp LH5498D-35 (FIFO 2Kx9)
  33144   U724  20pin SN74ALS688N  (8bit inverting identity comparator with enable)
  33145   U722  20pin SN74ALS245AN (8bit tristate noninverting bus transceiver)
  33146   U47   20pin 74FCT244ATP  (dual 4-bit 3-state noninverting buffer/line driver)
  33147   U732  48pin LVT16245? (dual 8-bit 3-state noninverting bus transceiver)
  33148   U711  20pin SN74ALS244BN (dual 4-bit 3-state noninverting buffer/line driver)
  33149   U712  20pin SN74ALS244BN (dual 4-bit 3-state noninverting buffer/line driver)
  33150   U713  20pin 74HC244AP    (dual 4-bit 3-state noninverting buffer/line driver)
  33151   U714  20pin 74HC244AP    (dual 4-bit 3-state noninverting buffer/line driver)
  33152   U721  20pin SN74ALS244BN (dual 4-bit 3-state noninverting buffer/line driver)
  33153   U55   14pin SN74ALS08N   (quad 2-input AND gates)
  33154   U726  20pin SN74ALS245AN (8bit tristate noninverting bus transceiver)
  33155   U715  20pin 74HC244AP    (dual 4-bit 3-state noninverting buffer/line driver)
  33156   JPxx 100pin Blue connector (to other ISA board)
  33157   U738  20pin LVT244 (SMD) (dual 4-bit 3-state noninverting buffer/line driver)
  33158   U734  32pin KM684000G-7 (SRAM 512Kx8)         ;\maybe 1Mbyte EXP3 RAM ?
  33159   U733  32pin KM684000G-7 (SRAM 512Kx8)         ;/
  33160   U725  20pin SN74ALS688N  (8bit inverting identity comparator with enable)
  33161   S700  24pin 12bit DIP switch  (select I/O Address bits A15..A4)
  33162   JP700  8pin Jumper (4x2 pins) (select IRQ15/IRQ12/IRQ11/IRQ10)
  33163   JP7xx 12pin Jumper (3x4 pins) (select DMA7/DMA6/DMA5)
  33164   U64   48pin LVT16245? (dual 8-bit 3-state noninverting bus transceiver)
  33165   U65   48pin LVT16244? (quad 4-bit 3-state noninverting buffer/line driver)
  33166   U66   48pin LVT16244? (quad 4-bit 3-state noninverting buffer/line driver)
  33167   U737  48pin LVT16244? (quad 4-bit 3-state noninverting buffer/line driver)
  33168   U710  20pin SN74ALS244BN (dual 4-bit 3-state noninverting buffer/line driver)
  33169   U709  20pin HD74HC245P   (8bit tristate noninverting bus transceiver)
  33170   U723  14pin SN74ALS38AN (quad open-collector NAND gates with buffered output)
  33171   U2    14pin SN74LS19AN  (hex inverters with schmitt-trigger)
  33172   U1     8pin Dallas DS1232 (MicroMonitor Chip) ;power-good-detect ?
  33173   U708  20pin HD74HC245P   (8bit tristate noninverting bus transceiver)
  33174   X3     2pin 4.1900 (4.19MHz for SPC700 CPU)
  33175   U42   80pin P823, U01Q (Sony CXP82300 SPC700 CPU with piggyback EPROM socket)
  33176   U42'  32pin 27C256A-15 (EPROM 32Kx8) (sticker: "94/11/28")
  33177   U706  10pin some slim chip with 1x10 pins
  33178   BT700  2pin battery (or super-cap?) for DS1302S (?) (not installed)
  33179   U729?  5pin voltage stuff?
  33180   U40    8pin Dallas DS1302S (real time clock)
  33181   X4     2pin small crystal (32.768kHz for DS1302S)
  33182   JP702 34pin Black connector (maybe for internal CDROM Emulator ISA cart?)
  33183   U736  28pin Sony CXK58257ASP-70L (SRAM 32Kx8)         ;CDROM Sector Buffer?
  33184   U735 100pin Sony CXD1199BQ    ;CDROM Decoder/FIFO
  33185   JP715 40pin Blue connector... to external DTL-H2010 CDROM drive?
  33186   JP721  9pin rear connector: Joypad/Memcard 2 (DB9)
  33187   JP719  9pin rear connector: Joypad/Memcard 1 (DB9)
  33188   ?      -    rear hole for cdrom-cable to Blue 40pin connector?
  33189   J70x  98pin ISA Bus Cart-edge (2x31 basic pins, plus 2x18 extended pins)
  33190 JP715 must be either connected to an external CDROM drive, or to some of
  33191 "terminator" plug (which shortcuts Pin23 and Pin26 with each other; software
  33192 may hang upon certain I/O operations without that terminator).
  33193 
  33194 Sony DTL-H2500 Dev board (PCI bus)
  33195 Newer revision of the DTL-H2000 board. Consists of a single PCI card (plus tiny
  33196 daughterboard with Controller ports).
  33197   Mainboard     "PI-27 1-589-867-11, DTL-H2500, MAIN BOARD 1575E01A0, SONY"
  33198   Daughterboard "SONY,CN-102 1-589-865-11,CONNECTOR BOARD,DTL-H2500,1575E02A0"
  33199   CJ1      9pin rear connector: DB9
  33200   CJ2?    15pin rear connector: AV Multi-out   (5+5+5pin)
  33201   CJ3     10pin gray connector (to controller daughterboard with two DB9's)
  33202   CJ4     34pin black connector (maybe for internal CDROM Emulator ISA cart?)
  33203   CJ5     50pin black connector (to DTL-H2510, Gray Internal CDROM Drive?)
  33204   CJ6     68pin black connector (maybe equivalent to 68pin PSX expansion port?)
  33205   -      124pin PCI bus cart edge connector
  33206   CJ1'     9pin rear connector: DB9 (CTR1, joypad 1)     ;\
  33207   CJ2'     9pin rear connector: DB9 (CTR2, joypad 2)     ; on daughterboard
  33208   CJ3'    10pin gray ribbon cable (to CJ3 on main board) ;/
  33209   IC103  208pin Sony CXD8530CQ (CPU)
  33210   IC106   28pin SEC KM48V2104AT-6 (DRAM 2Mx8)
  33211   IC107   28pin SEC KM48V2104AT-6 (DRAM 2Mx8)
  33212   IC108   28pin SEC KM48V2104AT-6 (DRAM 2Mx8)
  33213   IC109   28pin SEC KM48V2104AT-6 (DRAM 2Mx8)
  33214   IC201   64pin SEC KM4216V256G-60 (DRAM 256Kx16) ;dual-ported VRAM
  33215   IC202   64pin SEC KM4216V256G-60 (DRAM 256Kx16) ;dual-ported VRAM
  33216   IC203  160pin Sony CXD8514Q     ;GPU'a
  33217   IC207   64pin Sony CXD2923AR    ;GPU'b
  33218   IC303   28pin HM62W256LFP-7T (CDROM SRAM 32Kx8)               ;on back side
  33219   IC304   52pin "D 2021, SC430920PB, G64C 185, JSAA9618A" (Sub-CPU)  ;on back
  33220   IC305  100pin Sony CXD1199BQ (CDROM Decoder/FIFO)             ;on back side
  33221   IC308  100pin Sony CXD2922BQ (SPU)                            ;on back side
  33222   IC310   44pin SEC KM416V256BLT-7 (DRAM 256Kx16)  ;SoundRAM    ;on back side
  33223   IC402   24pin something bigger
  33224   IC404    8pin something small
  33225   IC405    8pin something small
  33226   IC501   24pin Sony CXA1645M (Analog RGB to Composite)         ;on back side
  33227   IC701    4pin "RD, 5B" or so                                  ;on back side
  33228   IC801  +++pin "ALTERA, FLEX, EPF8820ARC208-3, A9607"
  33229   IC802   20pin LVT245A <--                                     ;on back side
  33230   IC803   52pin "IDT71321, LA35J, S9704P" (2Kx8 dual port SRAM)
  33231   IC804   20pin LVT244A
  33232   IC805    8pin something with socket (sticker: "PD3")
  33233   IC807-2 32pin MX 27C1000MC-90 (PROM)   ;\on back side
  33234   IC808   32pin F 29F040A-90    (FLASH)  ;/BIOS on these chip(s) or so?
  33235   IC901    4pin 37, 69      ;\on back side
  33236   IC902    4pin 37, 69      ;/
  33237   ICxxx?  28pin "DALLAS, DS1230Y-100, NONVOLATILE SRAM"
  33238   U28     20pin LVT244A
  33239   Z1      20pin LVT244A     ;\on back side
  33240   Z2      20pin LVT245A <-- ;/
  33241   Z3      20pin LVT244A
  33242   Z4      20pin LVT244A     ;\
  33243   Z5      20pin LVT245A <-- ; on back side
  33244   Z6      20pin LVT244A     ;/
  33245   Z7      20pin LVT244A
  33246   Z8      20pin LVT244A
  33247   Z9      20pin LVT244A
  33248   X101     4pin RC67.73, JVC 5L (67.7376MHz oscillator for main cpu)
  33249   X201     4pin JC53.20, JVC 6A (for GPU, PAL)
  33250   X202     4pin JC53.69, JVC 6A (for GPU, NTSC)
  33251   X302     3pin 4.000MHz (for sub-cpu)
  33252 
  33253 Sony DTL-H2700 Dev board (ISA bus) (CPU, ANALYZER ...?)
  33254 Another revision of the DTL-H2000/DTL-H2500 boards. Consists of a single ISA
  33255 card stacked together with two huge daughterboards, and probably additionally
  33256 having a small connector daughterboard. Exact chipset is unknown (there might
  33257 be components on both sides of the PCBs, most of them not visible due to the
  33258 PCB stacking, so taking photos/scans of the PCBs would require advanced
  33259 techniques with screwdrivers).
  33260 Currently the only known chip name is an EPROM (MX 27C1000DC-90, with sticker
  33261 "Title=DTL-H2700, Ver=1.00, Date=96.12.4, Sum=046B No."). The ISA card is
  33262 having markings: "SONY HCD MWB-7? MADE IN JAPAN, PA47 1-589-003-01 1642E03A0".
  33263 One uncommon feature is an extra connector for a "trigger switch" (foot pedal),
  33264 which is reportedly used for activating performance analyzer logging.
  33265 
  33266 Sony DTL-H201A / DT-HV - Graphic Artist Board (IBM PC/ATs to NTSC video)
  33267   X2     xpin TXC-2 OSC 66.000MHz
  33268   X1     xpin TXC-2AOSC 53.693MHz
  33269   U16   14pin 74F74 (dual flipflop)
  33270   U29   14pin 74AS04 (hex inverters)
  33271   U14   20pin LVT244 (dual 4-bit 3-state noninverting buffer/line driver)
  33272   U18   20pin LVT244 (dual 4-bit 3-state noninverting buffer/line driver)
  33273   U15   20pin ACT244 (dual 4-bit 3-state noninverting buffer/line driver)
  33274   U11   84pin Altera EPM7096LC84-12 (sticker: "artpc13" or "ARTPC13")
  33275   U13  160pin Sony CXD8514Q     ;GPU'a
  33276   U5    14pin ALS38A   ? (quad open-collector NAND gates with buffered output)
  33277   U27   20pin ALS244AJ ? (dual 4bit tristate noninverting buffer/line driver)
  33278   Q1     3pin T B596
  33279   U23   64pin KM4216V256G-60 (DRAM 256Kx16) ;dual-ported VRAM
  33280   U22   64pin KM4216V256G-60 (DRAM 256Kx16) ;dual-ported VRAM
  33281   U28   64pin Sony CXD2923AR    ;GPU'b
  33282   S1    16pin 8bit DIP switch (select I/O address A15..A8)
  33283   S2     8pin 4bit DIP switch (select I/O address A7..A4)
  33284   U1    20pin SN74ALS688N (8bit inverting identity comparator with enable)
  33285   U2    20pin SN74ALS688N (8bit inverting identity comparator with enable)
  33286   U3    20pin ALS245A (8bit tristate noninverting bus transceiver)
  33287   JP9   12pin Jumper (6x2 pins) (select IRQ15/IRQ11/IRQ10/IRQ9/IRQ5/IRQ3)
  33288   U26   24pin Sony CXA1145M ?  ;RGB?
  33289   JP10   3pin Jumper   ;\
  33290   JP12   3pin Jumper   ; select "S" or "O" (?)
  33291   JP11   3pin Jumper   ;/
  33292   J3    2pin? Yellow connector (composite video out?)
  33293   J2?    pin? Mini DIN? connector (maybe S-video out?)
  33294   J1    15pin High Density SubD (maybe video multi out?)
  33295   CJx   98pin ISA Bus Cart-edge (2x31 basic pins, plus 2x18 extended pins)
  33296 
  33297 DTL-S2020 aka Psy-Q CD Emu
  33298   Yellow PCB "CD Emulator System, (C) Cirtech & SN Systems Ldt, 1994 v1.2"
  33299   IC    24pin GAL20V8B
  33300   IC    68pin Analog Devices ADSP-2101 (16bit DSP Microprocessor)
  33301   IC    20pin HD74HC244P
  33302   IC15  20pin HD74HC244P
  33303   IC14  20pin CD74HCT245E
  33304   IC7   28pin 27C512-10     (EPROM 64Kx8) (yellow sticker, without text)
  33305   IC    28pin HY62256ALP-70 (SRAM 32Kx8)
  33306   IC12  28pin HY62256ALP-70 (SRAM 32Kx8)
  33307   IC    28pin HY62256ALP-70 (SRAM 32Kx8)
  33308   IC13  84pin Emulex/QLogic FAS216 (Fast Architecture SCSI Processor)
  33309   IC5   84pin Emulex/QLogic FAS216 (Fast Architecture SCSI Processor)
  33310   IC4   24pin GAL20V8B (near IO Addr jumpers)
  33311   IC    20pin 74LS244B1   (near lower 8bit of ISA databus)
  33312   IC    20pin SN74LS245N? (near lower 8bit of ISA databus)
  33313   IC    20pin SN74LS245N  (near upper 8bit of ISA databus)
  33314   DMA   12pin Jumpers (select DMA7/6/5)
  33315   IRQ   12pin Jumpers (select IRQ15/12/11/10/7/5)
  33316   IO    16pin Jumpers (select IO Addr 300/308/310/318/380/388/390/398)
  33317   SCSI   6pin Jumpers (select SCSI ID 4/2/1) (aka 3bit 0..7 ?)
  33318   PL3   34pin Connector to DTL-H2000 ?
  33319   PL1   50pin Connector to INTERNAL SCSI hardware ?
  33320   PL2  50pin? Connector to EXTERNAL SCSI hardware ? (25pin plug/50pin cable?)
  33321   Jx    98pin ISA Bus Cart-edge (2x31 basic pins, plus 2x18 extended pins)
  33322 Note: There's also a similar ISA cart (DTL-S510B) with less chips and less
  33323 connectors.
  33324 Note: The SN Systems carts seem to have been distributed by Sony (with
  33325 "DTL-Sxxxx" numbers), and also distributed by Psygnosis. The external SCSI
  33326 connectors can be possibly also used with Psy-Q Development Systems for SNES
  33327 and Sega Saturn?
  33328 
  33329 PSY-Q Development System (Psygnosis 1994)
  33330   32pin GM76C8128ALLFW85 (SRAM 128Kx8)
  33331   44pin ALTERA EPM7032LC44-15T
  33332   34pin EMULEX FAS101 (SCSI Interface Processor)
  33333   28pin 27C64 (EPROM 8Kx8) (green sticker, without text)
  33334   20pin LCX245 (=74245?)
  33335    8pin 2112, CPA, H9527 (?)
  33336    3pin transistor? voltage regulator?
  33337   20pin DIP socket (containing two 10pin resistor networks)
  33338   20pin DIP socket (containing two 10pin resistor networks)
  33339    2pin CR2032 Battery 3V
  33340   68pin Connector to PSX "Parallel I/O" expansion port
  33341   25pin Connector to SCSI hardware (to DTL-S510B or DTL-S2020 ISA cart or so?)
  33342 
  33343 Sony DTL-H800 Sound Artist Board (with optical fibre audio out)
  33344   U15  24pin ?
  33345   U5   28pin 27C256 (EPROM 32Kx8) (not installed)
  33346   U7    4pin 67.7376MHz oscillator
  33347   U8   14pin ?
  33348   U11  44pin SEC KM416V256B1-8 (DRAM 256Kx16)  ;SoundRAM
  33349                 (44pin package with middle 4pin missing, 40pins used)
  33350   U10 100pin Sony CXD2925Q  ;SPU
  33351   U4  160pin Lattice IspLSI 3256 (sticker: "VER3")
  33352   U6  128pin Lattice IspLSI xxxx ?
  33353   U12  48pin ?
  33354   U13  48pin ?
  33355   U3   20pin 74ACT244
  33356   U14   5pin "LM25755, -3.3 P+" ?
  33357   U2   54pin ?
  33358   U1   54pin ?
  33359   U9    ?pin GP1F31T (light transmitting unit for optical fibre cable)
  33360   ?   124pin PCI bus cart edge connector
  33361   ?     8pin internal jumper/connector? (7pin installed, 1pin empty)
  33362 Note: There's also a similar board (DTL-H700) for MAC/NuBus instead of PCI bus.
  33363 
  33364 Sony COH-2000 (unknown purpose)
  33365   U1   14pin SN74ALS388N  ?
  33366   U2   20pin SN74ALS688N (8bit inverting identity comparator with enable)
  33367   U3   20pin SN74ALS688N (8bit inverting identity comparator with enable)
  33368   U4   24pin PALxxx ?
  33369   U5   20pin SN74ALS245AN
  33370   U6   20pin SN74ALS245AN
  33371   U7   20pin SN74ALS244N
  33372   U8   20pin SN74ALS244N
  33373   U9   20pin SN74ALS245AN
  33374   U10  20pin SN74ALS245AN
  33375   U11  20pin SN74ALS244N
  33376   S2   16pin 8bit DIP switch (ISA 15/14/13/12/11/10/9/8) ;I/O address bit15-8
  33377   S1    8pin 4bit DIP switch (ISA 7/6/5/4)               ;I/O address bit7-4
  33378   S3    8pin 4bit DIP switch (BISO? 3/2/1/0)         ;BISO? or BISD? or 8150?
  33379   JPxx  .... several jumpers (unknown purpose)
  33380   Jx    98pin ISA Bus Cart-edge (2x31 basic pins, plus 2x18 extended pins)
  33381   J5    68pin Connector on rear side (unknown purpose)
  33382 Unknown what COH-2000 was used for. One theory was that it's related to
  33383 PSX-based arcade cabinets. The 68pin connector might be also related to the
  33384 68pin PSX "Parallel I/O" expansion port.
  33385 
  33386 Sony DTL-H2010 (Black External CDROM Drive for DTL-H2000, CD-R compatible)
  33387 External front loading CDROM drive with Eject button. Connects to the blue
  33388 40pin connector on DTL-H2000 boards.
  33389   IC101 100pin SONY CXD2515Q (Signal Processor + Servo Amp)   ;\
  33390   IC102 28pin  BA6297AFP                                      ; on mainboard
  33391   ICxx  20pin  SONY CXA1571N (RF Amp) (on tiny daughtboard)   ; (HCMK-81X)
  33392   CN101 21pin connector to DEX2010.SCH board                  ;
  33393   CN10x 12pin connector to KSS-240A (laser pickup)            ;
  33394   S101   2pin pos0 switch or so?                              ;
  33395   M101   2pin spindle motor                                   ;/
  33396   U1    20pin 74ALS244BN                        ;\
  33397   U2    20pin 74ALS244BN                        ;
  33398   U3    20pin 74ALS244BN                        ; on DEX2010.SCH board
  33399   J1     2pin connector to EJECT BUTTON         ;
  33400   J2     5pin connector to LOADING MOTOR        ;
  33401   J3    21pin connector to mainboard            ;
  33402   JP1   40pin external connector to DTL-H2000   ;/
  33403   CN151  5pin connector to DEX2010.SCH board    ;\
  33404   M151   2pin loading motor (eject motor)       ; on CDM 14, CMK PSX board
  33405   S151   2pin OUT SW ;\switches, probably to    ;
  33406   S152   2pin IN SW  ;/sense load/eject status  ;/
  33407   CN1    2pin connector to DEX2010.SCH board    ;\on DTL-H2010(1) board
  33408   SW1    2pin eject button                      ;/
  33409 The required cable consists of a Yamaichi NFS-40a female connector (blue
  33410 connector on DTL-H2000 side), 0.635mm pitch ribbon cable, and 3M Sub-D MDR40
  33411 connector (silver connector on DTL-H2010 side). But caution: the odd/even pins
  33412 on the cable are somewhat swapped, on DTL-H2000 side the wires should be
  33413 ordered 1,2,3,4,..,39,40, but on DTL-H2010 side they should be ordered
  33414 2,1,4,3,..,40,39.
  33415 
  33416 Sony DTL-H2510 (Gray Internal CDROM Drive)
  33417 This is some sort of a mimmicked front loading PC CDROM drive (consisting of a
  33418 tray that contains a normal (top-loading) PSX cdrom drive unit).
  33419   IC309 80pin Sony CXD2510Q (CDROM Signal Processor)
  33420   ICxx   ?pin Unknown if there are further ICs (eg. CXA1782BR should exist?)
  33421   CN1   10pin Connector to daughterboard (with drive unit)
  33422   CN2    4pin Connector to PC power supply (12V/5V and 2xGND)
  33423   CN3   50pin Connector to DTL-H2500 or so? (need "PCS-E50FC" plug?)
  33424 There is no eject button, unknown if there's some eject motor, or if one does
  33425 need to push/pull drive tray manually.
  33426 
  33427 Sony SCPH-9903 (Gray SCEx-free Playstation)
  33428 A rare SCEx-free Playstation that can boot from CDR's without SCEx strings;
  33429 maybe intended for beta-testers. Marked "Property of Sony Computer
  33430 Entertainment", "U/C".
  33431 
  33432 Hardware Numbers
  33433 ----------------
  33434 
  33435 Sony's own hardware (for PSX) (can be also used with PSone)
  33436   SCPH-1000 PlayStation (1994) (NTSC-J)   (with S-Video)
  33437   SCPH-1001 PlayStation (1995) (NTSC-U/C) (without S-Video)
  33438   SCPH-1002 PlayStation (199x) (PAL)      (without S-Video)
  33439   SCPH-1010 Digital joypad (with short cable) (1994)
  33440   SCPH-1020 Memory Card 1Mbits (1994)
  33441   SCPH-1030 2-button Mouse (with short cable) (1994)
  33442   SCPH-1040 Serial Link Cable
  33443   SCPH-1050 RGB Cable (21-pin RGB Connector)
  33444   SCPH-1060 RFU Cable/Adaptor (antennae connector) (NTSC-JP?) (1995)
  33445   SCPH-1061 RFU Cable/Adaptor (antennae connector) (NTSC-US?)
  33446   SCPH-1062 RFU Cable/Adaptor (antennae connector) (PAL)
  33447   SCPH-1070 Multitap adaptor (four controllers/memory cards on one slot) (1995)
  33448   SCPH-1080 Digital joypad (with longer cable) (1996)
  33449   SCPH-1090 2-button Mouse (with longer cable) (1998)
  33450   SCPH-1100 S Video Cable (1995)
  33451   SCPH-1110 Analog Joystick (1996)
  33452   SCPH-1120 RFU Adaptor (antennae connector) (NTSC-JP?) (1996)
  33453   SCPH-1121 RFU Adaptor (antennae connector) (NTSC-US?)
  33454   SCPH-1122 RFU Adaptor (antennae connector) (PAL)
  33455   SCPH-1130 AC Power Cord (1996)
  33456   SCPH-1140 AV Cable (1997)
  33457   SCPH-1150 Analog Joypad (with one vibration motor, with red/green led) (1997)
  33458   SCPH-1160 AV Adaptor (1997)
  33459   SCPH-1170 Memory Card Triple Pack (three Memory Cards) (1996)
  33460   SCPH-1180 Analog Joypad (without vibration motors, with red/green led)
  33461   SCPH-119X Memory Card (X=different colors) (1997)
  33462   SCPH-1200 Analog Joypad (with two vibration motors) (dualshock) (1997)
  33463   SCPH-1210 Memory Card Case (1998)
  33464   SCPH-2000 Keyboard/Mouse adapter (PS/2 to PSX controller port; for Lightspan)
  33465   SCPH-3000 PlayStation (1995) (NTSC-J) (with the S-video output removed)
  33466   SCPH-3500 PlayStation Fighting Box (console bundled with 2 controllers)(1996)
  33467   SCPH-4000 PocketStation (Memory Card with LCD-screen) (1999)
  33468   SCPH-4010 VPick (guitar-pick controller) (for Quest for Fame, Stolen Song)
  33469   SCPH-4020 Long Strap for PocketStation (1999)
  33470   SCPH-4030 Wrist Strap for PocketStation (1999)
  33471   SCPH-5000 PlayStation (cost reduced) (Japan) (1996)  ;\exists in these three
  33472   SCPH-5001 PlayStation (cost reduced) (North America) ; regions only (not
  33473   SCPH-5003 PlayStation                (Asia)          ;/in Europe)
  33474   SCPH-5500 PlayStation without Cinch sockets (ie. AV Multi Out only) (1996)(J)
  33475   SCPH-5501 "" North American version of the 5500
  33476   SCPH-5502 "" European version of the 5500    (shipped with 1 digital joypad)
  33477   SCPH-5552 Same as SCPH-5502 (but shipped with memcard and 2 digital joypads)
  33478   SCPH-5903 PlayStation with built-in MPEG Video-CD decoder (Asia-only)
  33479   SCPH-7000 PlayStation with Dualshock (1997) (Japan)
  33480   SCPH-7001 PlayStation with Dualshock (199x) (North America)
  33481   SCPH-7002 PlayStation with Dualshock (199x) (Europe)
  33482   SCPH-7003 PlayStation with Dualshock (199x) (Asia)
  33483   SCPH-7000W PlayStation (10 million model, not for sale, blue, region free)
  33484   SCPH-7500 PlayStation with Dualshock, cost reduced (1999) (Japan)
  33485   SCPH-7501 PlayStation with Dualshock, cost reduced (199x) (North America)
  33486   SCPH-7502 PlayStation with Dualshock, cost reduced (199x) (Europe)
  33487   SCPH-7503 PlayStation with Dualshock, cost reduced (199x) (Asia)
  33488   SCPH-9000 PlayStation without Parallel I/O port (1999) (Japan)
  33489   SCPH-9001 PlayStation without Parallel I/O port (199x) (North America)
  33490   SCPH-9002 PlayStation without Parallel I/O port (199x) (Europe)
  33491   SCPH-9003 PlayStation without Parallel I/O port (199x) (Asia)
  33492   SCPH-9903 Rare SCEx-free PSX (Property of Sony Computer Entertainment, U/C)
  33493   SCPH-1000R PlayStation Classic (2018) (ARM CPU with emulated PSX games)
  33494   SFX-100   PlayStation Super Disc Prototype (with SNES chipset, no PSX chips)
  33495 
  33496 Sony's own hardware (for PSone)
  33497   SCPH-100 PSone (miniaturized PlayStation) (2000) (Japan)
  33498   SCPH-101 PSone (miniaturized PlayStation) (200x) (North America)
  33499   SCPH-102 PSone (miniaturized PlayStation) (200x) (Europe)
  33500   SCPH-103 PSone (miniaturized PlayStation) (200x) (Asia)
  33501   SCPH-102A PSone Europe (UK/AU, with A/V cable)     ;\revision of "SCPH-102"
  33502   SCPH-102B PSone Europe (UK, with RFU adaptor)      ; with PM-41(2) board ?
  33503   SCPH-102C PSone Europe (Continent, with A/V cable) ;/
  33504   SCPH-110 Dual Analog Pad (for PSone) (Dualshock) (2000)
  33505   SCPH-111 Multitap for PSone (seems to be quite rare, except in brazil)
  33506   SCPH-112 AC adapter for PSone (In: 110-220VAC,  Out: 7.5VDC, 2.0A, Japan)
  33507   SCPH-113 AC adapter for PSone (In: 120VAC/60Hz, Out: 7.5VDC, 2.0A, USA)
  33508   SCPH-114 AC adapter for PSone (In: 220-240VAC,  Out: 7.5VDC, 2.0A, Europe)
  33509   SCPH-115 AC adapter for PSone (In: 220-240VAC,  Out: 7.5VDC, 2.0A, UK)
  33510   SCPH-116 AC adapter for PSone (In: 220-240VAC,  Out: 7.5VDC, 2.0A, Australia)
  33511   SCPH-117 AC adapter for PSone (In: 110VAC,      Out: 7.5VDC, 2.0A, Asia?)
  33512   SCPH-120 AC adapter for PSone with LCD Screen (In: 100VAC, Out: 7.5VDC, 3.0A)
  33513   SCPH-130 LCD Screen for PSone (to be attached to the console) (2001)
  33514   SCPH-140 PSone and LCD screen combo (2001)
  33515   SCPH-152 LCD screen for PSone (PAL SCPH-152C)
  33516   SCPH-162 PSone and LCD screen (PAL SCPH-162C)
  33517   SCPH-170 Car Adapter for PSone from car cigarette lighter (2001)
  33518   SCPH-180 AV Connection Cable for LCD-screen's AV IN
  33519   SCPH-10180K DoCoMo I-Mode Adaptor Cable (for internet via mobile phones)
  33520 
  33521 Sony's own devkits
  33522   DTL-H201A Graphic Artist Board (ISA bus) (with NTSC video out)
  33523   DTL-H240  PS-X RGB Cable
  33524   DTL-H500C Digital joypad prototype (SNES-style design, with DB9 connector)
  33525   DTL-H505  PS-X (Code Name) Target Box ? (PSX prototype, SCSI instead CDROM?)
  33526   DTL-H700  Sound Artist Board (NuBus for Mac)
  33527   DTL-H800  Sound Artist Board (PCI Bus for IBM) (with optical fibre sound out)
  33528   DTL-H1000 Debugging Station (CD-R compatible PSX console) (Japan)
  33529   DTL-H1001 Debugging Station (CD-R compatible PSX console) (North America)
  33530   DTL-H1002 Debugging Station (CD-R compatible PSX console) (Europe)
  33531   DTL-H1030 Mouse ?
  33532   DTL-H1040 Link Cable ?
  33533   DTL-H1050 RGB Cable ?
  33534   DTL-H110x Debugging Station revision? (DC-powered)
  33535   DTL-H120x Debugging Station revision? (AC-powered)
  33536   DTL-H1500 Stand-Alone Box ? With ethernet, for SGI Workstation ?
  33537   DTL-H2000 Dev board v1 (PSX on two ISA carts) (old pre-retail)
  33538   DTL-H2010 Black External CDROM Drive for DTL-H2000 (CD-R compatible)
  33539   DTL-H2040 Memory Box ?
  33540   DTL-H2050 Adaptor for Controller port ?
  33541   DTL-H2060 Serial Link cable
  33542   DTL-H2070 RGB Cable ?
  33543   DTL-H2080 Controller Box (joypad/memcard adaptor for DTL-H2000/DTL-xxxx?)
  33544   DTL-H2500 Dev board (PCI bus)
  33545   DTL-H2510 Gray Internal CDROM Drive for DTL-H2500/DTL-H2700 (CD-R compatible)
  33546   DTL-H2700 Dev board (ISA bus) (CPU, ANALYZER ...?)
  33547   DTL-H3000 Net Yaroze (hobby programmer dev kit) (Japan)
  33548   DTL-H3001 Net Yaroze (hobby programmer dev kit) (North America)
  33549   DTL-H3002 Net Yaroze (hobby programmer dev kit) (Europe)
  33550   DTL-H3020 Access Card (for yaroze)
  33551   DTL-H3050 Communication Cable (link port to rs232, for yaroze)
  33552   DTL-D2020 Documentation: BUILD CD (Manual of Programmer's Tool)
  33553   DTL-D2120 Documentation: (Manual of Programmer's Tool)
  33554   DTL-D2130 Documentation: PsyQ (Manual of Programmer's Tool)
  33555   DTL-D2130 Documentation: SdevTC (Manual of Programmer's Tool)
  33556   DTL-D2140A Documentation: Ver.1.0 (Manual of Programmer's Tool)
  33557   DTL-D2150A Documentation: Ver.2.0 (Manual of Programmer's Tool)
  33558 
  33559 SN System / Psy-Q devkit add-ons / SCSI cards
  33560   DTL-S510B Unknown (another CDROM emulator version?)
  33561   DTL-S2020 CD-ROM EMULATOR for DTL-H2000/DTL-H2500/DTL-H2700
  33562 
  33563 Sony Licensed Hardware (Japan)
  33564   SLPH-00001 Namco neGcon (white) (NPC-101), Twist controller (SLEH-0003)
  33565   SLPH-00002 Hori Fighting stick, digital stick with autofire/slowmotion/rumble
  33566   SLPH-00003 ASCII Fighter stick V, psx-shaped digital stick (SLEH-0002)
  33567   SLPH-00004 Sunsoft Sunstation pad, digital pad with autofire/slowmotion
  33568   SLPH-00005 ASCII ASCIIPAD V, digital pad with autofire/slowmotion
  33569   SLPH-00006 Imagineer Sandapaddo ThunderPad
  33570   SLPH-00007 SANKYO N.ASUKA aka Nasca Pachinco Handle, bizarre paddle
  33571   SLPH-00008 Spital SANGYO Programmable joystick
  33572   SLPH-00009 Hori Fighting commander 2way controller
  33573   SLPH-00010 Optec Super Pro Commander
  33574   SLPH-00011 Super Pro Commander Accessory / Extended memo repack memory
  33575   SLPH-00012 Hori Fighting Commander 10B Pad (gray), digital pad with extras
  33576   SLPH-00013 Konami Hyper Blaster (green)  ;\IRQ10-based Lightgun
  33577   SLPH-00014 Konami Hyper Blaster (black)  ;/(SLEH-0005/SLUH-00017)
  33578   SLPH-00015 Namco Volume controller, paddle with 2 buttons
  33579   SLPH-00016 Waka Up Scan Converter "[chiyo] clean! peripheral equipment?"
  33580   SLPH-00017 Hori Fighting Commander 10B Pad (black), digital pad with extras
  33581   SLPH-00018 Hori Real Arcade Stick, digital stick, small L1/L2 (HPS-10)
  33582   SLPH-00019 Konami Hyperstick
  33583   SLPH-00020 Imagineer Thunder Pad Transparent
  33584   SLPH-00021 Imagineer Imagegun
  33585   SLPH-00022 Optec AI Commander Pro, digital pad with extras / lcd display
  33586   SLPH-00023 Namco Joystick (SLEH-00004)
  33587   SLPH-00024 Optec Cockpit Wheel, analog joystick/analog pedals or so
  33588   SLPH-00025 Optec AI Commander Accessory (extended memo repack ZERO2 version)
  33589   SLPH-00026 Hori Command Stick PS (SLPH-00026 aka HPS11)
  33590   SLPH-00027 ASCII Grip, single-handed digital pad (SLEH-00008)
  33591   SLPH-00028 Hori Grip (gray) (see also: SLPH-00040, and 00086..00088)
  33592   SLPH-00029 Hori Horipad (clear), digital pad
  33593   SLPH-00030 Hori Horipad (black), digital pad
  33594   SLPH-00031 Hori Horipad (gray),  digital pad
  33595   SLPH-00032 Hori Horipad (white), digital pad
  33596   SLPH-00033 Hori Horipad (blue),  digital pad
  33597   SLPH-00034 Namco G-CON 45, Cinch-based Lightgun (SLEH-0007/SLUH-00035)
  33598   SLPH-00035 ASCII Fighter stick V Jr. (SLEH-00009)
  33599   SLPH-00036 Optec Wireless Dual Shot, digital pad with turbo button
  33600   SLPH-00037 ?
  33601   SLPH-00038 ASCII Pad V Jr., digital pad without any extras
  33602   SLPH-00039 ASCII Pad V2 (gray), digital pad with turbo switches (SLEH-00010)
  33603   SLPH-00040 Hori Grip (black)
  33604   SLPH-00041 ASCII Grip V
  33605   SLPH-00042 ASCII Grip V plus (Derby Stallion'99 supplement set), single-hand
  33606   SLPH-00043 ASCII Pad V2 (clear pink)
  33607   SLPH-00044 ASCII Pad V2 (clear white)
  33608   SLPH-00045 ASCII Pad V2 (clear blue)
  33609   SLPH-00046 ASCII Pad V2 (clear green)
  33610   SLPH-00047 ASCII Pad V2 (clear black)
  33611   SLPH-00048 ASCII Pad V2 (clear red/lead?)
  33612   SLPH-00049 ASCII Pad V2 (clear yellow)
  33613   SLPH-00050 ASCII Pad V2 (clear orange)
  33614   SLPH-00051 Taito Streetcar GO! Controller 2 steering "wheel?" tie toe strange
  33615   SLPH-00052 Koei Video Capture, Ergosoft EGWord, and Lexmark Printer bundle
  33616   SLPH-00053 Koei Word Processor Ergosoft September EGWORD Ver.2.00
  33617   SLPH-00054 Hori Zerotech Steering Controller (black)
  33618   SLPH-00055 Hori Grip (clear blue)
  33619   SLPH-00056 Hori Grip (clear pink)
  33620   SLPH-00057 Hori Grip (clear yellow)
  33621   SLPH-00058 ASCII Pad V2 (gold)
  33622   SLPH-00059 ASCII Pad V2 (silver)
  33623   SLPH-00060 ASCII Biohazard, digital pad with re-arranged buttons (SLEH-0011)
  33624   SLPH-00061 ASCII Pad V2 (pearl white)
  33625   SLPH-00062 ASCII Pad V2 (pearl blue)
  33626   SLPH-00063 ASCII Pad V2 (pearl pink)
  33627   SLPH-00064 ASCII Pad V2 (pearl green)
  33628   SLPH-00065 ASCII Pad V Pro, with lcd for button-combinations (ASC-0508GX)
  33629   SLPH-00066 ASCII Arcade Stick 3 "Ultimate"
  33630   SLPH-00067 ASCII Pad V2 (purple metallic)
  33631   SLPH-00068 ASCII Pad V2 (lead metallic)
  33632   SLPH-00069 Namco neGcon (black) (NPC-104), Twist controller (SLEH-0003)
  33633   SLPH-00070 Sankyo Pachinko FF Controller (alternate to SLPH-00007)
  33634   SLPH-00071 Hori Command Stick PS Custom
  33635   SLPH-00072 ASCII Command Pack (memory card add-on or so)
  33636   SLPH-00073 Optec Wireless digital set (gray)         ;\
  33637   SLPH-00074 Optec Wireless digital set (black)        ; pad with receiver
  33638   SLPH-00075 Optec Wireless digital set (clear)        ;
  33639   SLPH-00076 Optec Wireless digital set (clear blue)   ;
  33640   SLPH-00077 Optec Wireless digital set (clear black)  ;/
  33641   SLPH-00078 Optec Wireless digital shot (gray)        ;\
  33642   SLPH-00079 Optec Wireless digital shot (black)       ; extra pad for
  33643   SLPH-00080 Optec Wireless digital shot (clear)       ; second player
  33644   SLPH-00081 Optec Wireless digital shot (clear blue)  ; (without receiver)
  33645   SLPH-00082 Optec Wireless digital shot (clear black) ;/
  33646   SLPH-00083 ASCII Stick Justice controller
  33647   SLPH-00084 Hori ZeroTech Steering Controller (clear)
  33648   SLPH-00085 Hori Compact joystick (black)
  33649   SLPH-00086 Hori Compact joystick (clear)
  33650   SLPH-00087 Hori Compact joystick (clear blue)
  33651   SLPH-00088 Hori Multi Analog Pad (clear) or Hori Grip (pink?)
  33652   SLPH-00089 Hori AV Cable with selector
  33653   SLPH-00090 Hori Multi Analogue Pad (clear black)
  33654   SLPH-00091 Hori AV Multi-Out Converter
  33655   SLPH-00092 ASCII Pad V2 (margin green)
  33656   SLPH-00093 ASCII Pad V2 (margin blue)
  33657   SLPH-00094 ASCII Pad V2 (margin pink)
  33658   SLPH-00095 ASCII Pad V2 (margin orange)
  33659   SLPH-00096 ASCII Hyper Steering V ("high pass tear ring V controller?")
  33660   SLPH-00097 Hori S Cable with selector (uh, maybe S-video or so?) (HPS-36)
  33661   SLPH-00098 NSYSCOM Pachinko slot controller (NSC-1)
  33662   SLPH-00099 ASCII Pad V2 (rainbow)
  33663   SLPH-00100 ASCII 'Hanging' Fishing Controller, controller for fishing games
  33664   SLPH-00101 Optec Cockpit big shock
  33665   SLPH-00102 ASCII Grip V (set for mars story)
  33666   SLPH-00103 Hori Pad V2 (clear)
  33667   SLPH-00104 Hori Pad V2 (clear blue)
  33668   SLPH-00105 Hori Pad V2 (clear pink)
  33669   SLPH-00106 Hori Pad V2 (black)
  33670   SLPH-00107 Hori Compact Joystick (camouflage)
  33671   SLPH-00108 Hori Rumble Digital Pad (clear blue)
  33672   SLPH-00109 Hori Monoaural AV Cable
  33673   SLPH-00110 ASCII Pad V2 (marble)
  33674   SLPH-00111 ASCII Pad V2 (camouflage)
  33675   SLPH-00112 ASCII Pad V3
  33676   SLPH-00113 ASCII Pad V3 with cable reel
  33677   SLPH-00114 ASCII Pad V3 with V2 (pearl white) bundle
  33678   SLPH-00115 ASCII Pad V3 with V2 (pearl pink) bundle
  33679   SLPH-00116 ASCII Pad V3 with V2 (pearl blue) bundle
  33680   SLPH-00117 ASCII Pad V3 (blue) with V2 (pearl green) bundle
  33681   SLPH-00118 Hori Pad V3
  33682   SLPH-00119 Hori Pad V3 (white)
  33683   SLPH-00120 Hori Analog Rumble Pad (clear pink)
  33684   SLPH-00121 Hori Analog Rumble Pad (clear)
  33685   SLPH-00122 Hori Analog Rumble Pad (clear blue)
  33686   SLPH-00123 Hori Analog Rumble Pad (clear red)
  33687   SLPH-00124 Hori Analog Rumble Pad (clear black)
  33688   SLPH-00125 Hori Analog Rumble Pad (clear yellow)
  33689   SLPH-00126 Namco Jogcon, digital pad, steering dial (SLEH-0020/SLUH-00059)
  33690   SLPH-00127 ?
  33691   SLPH-00128 ASCII stick ZERO3
  33692   SLPH-00129 ASCII Pad V2 (wood grain pitch)
  33693   SLPH-00130 Hori Real Arcade (camouflage)
  33694   SLPH-00131 Hori Ehrgeiz Stick
  33695   SLPH-00132 ASCII Pad V3 (blue)
  33696   SLPH-00133 ASCII Fighter Stick V Jr. (limited edition)
  33697   SLPH-00134 ASCII Pad V3 (blue) with cable reel
  33698   SLPH-00135 ASCII Pad V3 (blue) with V2 (silver)
  33699   SLPH-00136 ASCII Pad V3 with V2 (purple metallic)
  33700   SLPH-00137 ASCII Pad V3 with V2 (gold)
  33701   SLPH-00138 ASCII Pad V3 with "VPRO. aka Ascii Fighter Stick V"
  33702   SLPH-00139 Hori Analog Rumble Pad (gray)
  33703   SLPH-00140 Hori Analog Rumble Pad (black)
  33704   SLPH-00141 Hori Analog Rumble Pad (blue)
  33705 And, maybe unlicensed (they don't have official SLPH numbers, still they are
  33706 listed as official controllers on PSX CDROM back covers):
  33707   ASC-05158B ASCII Beatmania Junk (similar to SLEH-0021)
  33708   ASC-0528T  Sammy Shakkato Tambourine
  33709   BANC-0001  Bandai Fishing Controller
  33710   BANC-0002  Bandai Kids Station
  33711   RU017      Konami Dance Dance Revolution Controller (Dance Mat)
  33712   GAE001     G.A.E. Baton stick with 2 buttons (for The Maestromusic)
  33713 And whatever:
  33714   RU029      Konami Beatmania IIDX
  33715   RU014      Konami Pop'n Music (buttons A,B,C,D,E,F,G,H,I, and Select/Start)
  33716   ?          Produce! Paca Paca Passion
  33717   ?          Sega/Ascii Minimoni Shakatto Tambourine
  33718 
  33719 Sony Licensed Hardware (Europe)
  33720   SLEH-00001 Ascii Specialized Pad (similar to SLPH-00005: ASCII ASCIIPAD V)
  33721   SLEH-00002 Ascii Arcade Stick, psx-shaped digital stick (SLPH-00003)
  33722   SLEH-00003 Namco Negcon, Twist controller (SLPH-00001)
  33723   SLEH-00004 Namco Arcade Stick (SLPH-00023)
  33724   SLEH-00005 Konami Hyper Blaster, IRQ10-based Lightgun (SLPH-00014/SLUH-00017)
  33725   SLEH-00006 Mad Catz Steering Wheel (SLPH-?)
  33726   SLEH-00007 Namco G-Con 45, Cinch-based Lightgun (SLPH-00034/SLUH-00035)
  33727   SLEH-00008 Ascii Grip, single-handed digital pad (SLPH-00027/SLUH-00038)
  33728   SLEH-00009 Ascii Arcade Stick v2 (SLPH-00035)
  33729   SLEH-00010 Ascii Enhanced Control Pad (similar as SLEH-00001) (SLPH-00039)
  33730   SLEH-00011 Resident Evil Pad (aka SLPH-00060 ASCII Biohazard)
  33731   SLEH-00012 Reality-Quest The Glove (right-handed only) (SLUH-00045/SLPH-?)
  33732   SLEH-00013 CD Case (small nylon bag for fourteen CDs) (SLPH-?)
  33733   SLEH-00014 ?
  33734   SLEH-00015 PlayStation Case (bigger bag for the console) (SLPH-?)
  33735   SLEH-00016 PlayStation Case + Digital Joypad + Memory Card
  33736   SLEH-00017 ?
  33737   SLEH-00018 Ascii Sphere 360 (SLUH-00028/SLPH-?)
  33738   SLEH-00019 Interact V3 Racing Wheel (SLPH-?)
  33739   SLEH-00020 Namco JogCon, digital pad, steering dial (SLPH-00126/SLUH-00059)
  33740   SLEH-00021 Konami Beatmania Controller (SLPH-?)
  33741   SLEH-00022 ?
  33742   SLEH-00023 Official Dance Mat (RU017/SLUH-00071) (for PSone and PS2)
  33743   SLEH-00024 Fanatec Speedster 2 (wheel with pedals) (for PSone and PS2)
  33744   SLEH-00025 Mad Catz 8MB Memory Card (for PS2)
  33745   SLEH-00026 Olympus Eye-Trek FMD-20P Game/DVD glasses (for PS2)
  33746   SLEH-00027 Logitech Cordless Controller... or Eye-Trek FMD-20P, too? (PSx?)
  33747   SLEH-00028 ?
  33748   SLEH-00029 Fanatec Speedster 3 (for PS2)
  33749   SLEH-00030 Logitech Eye Toy (camera?) (for PS2)
  33750 And, maybe unlicensed:
  33751   Weird Madcatz-device (rumble upgrade/add-on for Mad Catz steering wheel)
  33752 
  33753 Sony Licensed Hardware (USA)
  33754   SLUH-00001 Specialized Joystick (single-axis, digital?)
  33755   SLUH-00002 Control Pad (redesigned joypad)
  33756   SLUH-00003 InterAct Piranha Pad, digital pad, autofire/slowmotion
  33757   SLUH-00017 Konami Justifier, IRQ10-based Lightgun (Hyperblaster/SLPH-00014)
  33758   SLUH-00018 Enhanced Pad (joypad with whatever extra functions)
  33759   SLUH-00022 Analog and Digital Steering Wheel with pedals (for testdrive 4?)
  33760   SLUH-00026 Optec Mach 1 (gray steering/flight controller with pedals)
  33761   SLUH-00028 Ascii Sphere 360 (SLEH-00018)
  33762   SLUH-00029 Namco NPC-102 Joystick (single-axis, digital?)
  33763   SLUH-00031 Interact Program Pad
  33764   SLUH-00033 Piranha Pad (redesigned joypad)
  33765   SLUH-00034 NUBY Manufacturing The Heater, white lightgun (irq10 or cinch?)
  33766   SLUH-00035 Namco G-CON 45, Cinch-based Lightgun (SLEH-0007/SLPH-00034)
  33767   SLUH-00037 Arcade Stick (single-axis, digital?)
  33768   SLUH-00038 ASCII Grip V, single-handed digital pad (SLPH-00027/SLEH-00008)
  33769   SLUH-00040 System Organizer (huh? looks like... a black storage box?)
  33770   SLUH-00041 V3 Racing Wheel with pedals
  33771   SLUH-00043 GunCon (bundled with Time Crisis 1)
  33772   SLUH-00044 Remote Wizard (looks like wireless joypad or so)
  33773   SLUH-00045 Reality-Quest The Glove (right-handed only) (SLEH-00012/SLPH-?)
  33774   SLUH-00046 GunCon (bundled with Point Blank)
  33775   SLUH-00055 Aftershock Wheel with pedals
  33776   SLUH-00056 UltraRacer Steering Controller (grip-style)
  33777   SLUH-00057 EA Sports Game Pad (redesigned joypad)
  33778   SLUH-00058 something for point blank 2 (?) (maybe a lightgun)
  33779   SLUH-00059 Namco Jogcon, digital pad, steering dial (SLEH-0020/SLPH-00126)
  33780   SLUH-00061 MadCatz MC2 Racing Wheel (black/gray)
  33781   SLUH-00063 Bass Landing Fishing Reel controller
  33782   SLUH-00066 Sportster racing wheel
  33783   SLUH-00068 Jungle Book Rhythm N Groove Dance Pack
  33784   SLUH-00071 Konami Dance Pad (DDR Dance Pad) (RU017)
  33785   SLUH-00072 GunCon (bundled with Point Blank 3)
  33786   SLUH-00073 GunCon (bundled with Time Crisis 2 - Project Titan)
  33787   SLUH-00077 Logitech Cordless Controller, analog pad (ps1/ps2)
  33788   SLUH-00081 Logitech NetPlay Controller, pad with keyboard (usb/ps2)
  33789   SLUH-00083 Konami Dance Dance Revolution Controller (for PS1 and PS2)
  33790   SLUH-00084 NYKO iType2, pad with keyboard (usb/ps2)
  33791   SLUH-00085 Logitech Cordless Action Controller (for PS2)
  33792   SLUH-00086 Namco/Taiko Drum Master (Taiko Controller Pack) (for PS2)
  33793   SLUH-00088 RedOctane In the Groove Dance Pad Controller ?
  33794   SLUH-00090 Dance Pad (bundled with Pump It Up) (for PS2)
  33795 
  33796 Sony Licensed Hardware (Asia)
  33797   Unknown (if any)
  33798 
  33799 Newer hardware add-ons?
  33800   SCEH-0001 SingStar (USB to Microfon) (for PS2)
  33801 
  33802 Note
  33803 Early SLEH/SLUH devices used 4-digit numbers (eg. the "official" name for
  33804 SLEH-00003 is SLEH-0003; unlike as shown in the above list).
  33805 
  33806 Software (CDROM Game Codes)
  33807   SCES-NNNNN Sony Computer Europe Software
  33808   SCED-NNNNN Sony Computer Europe Demo
  33809   SLES-NNNNN Sony Licensed Europe Software
  33810   SLED-NNNNN Sony Licensed Europe Demo
  33811   SCPS-NNNNN Sony Computer Japan Software
  33812   SLPS-NNNNN Sony Licensed Japan Software
  33813   SLPM-NNNNN Sony Licensed Japan ... maybe promo/demo?
  33814   SCUS-NNNNN Sony Computer USA Software
  33815   SLUS-NNNNN Sony Licensed USA Software
  33816   PAPX-NNNNN Demo ...?
  33817   PCPX-NNNNN Club ...?
  33818   LSP-NNNNNN Lightspan series (non-retail educational games)
  33819 Note: Multi-disc games have more than one game code. The game code for Disc 1
  33820 is also printed on the CD cover, and used in memory card filenames. The
  33821 per-disk game codes are printed on the discs, and are used as boot-executable
  33822 name in SYSTEM.CNF file. There is no fixed rule for the multi-disc numbering;
  33823 some games are using increasing numbers of XNNNN or NNNNX (with X increasing
  33824 from 0 upwards), and some are randomly using values like NNNXX and NNNYY for
  33825 different discs.
  33826 
  33827 Pinouts
  33828 -------
  33829 
  33830 External Connectors
  33831 --> Pinouts - Controller Ports and Memory-Card Ports
  33832 --> Pinouts - Audio, Video, Power, Expansion Ports
  33833 --> Pinouts - SIO Pinouts
  33834 
  33835 Internal Pinouts
  33836 --> Pinouts - Chipset Summary
  33837 --> Pinouts - CPU Pinouts
  33838 --> Pinouts - GPU Pinouts (for old 160-pin GPU)
  33839 --> Pinouts - GPU Pinouts (for new 208-pin GPU)
  33840 --> Pinouts - SPU Pinouts
  33841 --> Pinouts - DRV Pinouts
  33842 --> Pinouts - VCD Pinouts
  33843 --> Pinouts - HC05 Pinouts
  33844 --> Pinouts - MEM Pinouts
  33845 --> Pinouts - CLK Pinouts
  33846 --> Pinouts - PWR Pinouts
  33847 --> Pinouts - Component List and Chipset Pin-Outs for Digital Joypad, SCPH-1080
  33848 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-1150
  33849 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-1200
  33850 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-110
  33851 --> Pinouts - Component List and Chipset Pin-Outs for Dualshock2, SCPH-10010
  33852 --> Pinouts - Component List and Chipset Pin-Outs for Namco Lightgun, NPC-103
  33853 --> Pinouts - Component List and Chipset Pin-Outs for Multitap, SCPH-1070
  33854 --> Pinouts - Memory Cards
  33855 
  33856 Mods/Upgrades
  33857 --> Mods - Nocash PSX-XBOO Upload
  33858 --> Mods - PAL/NTSC Color Mods
  33859 
  33860 Pinouts - Controller Ports and Memory-Card Ports
  33861 ------------------------------------------------
  33862 
  33863 Controller Ports and Memory-Card Ports
  33864   1 In  JOYDAT Data from joypad/card (data in)    _______________________
  33865   2 Out JOYCMD Data to joypad/card (command out) |       |       |       |
  33866   3 -   +7.5V  +7.5VDC supply (eg. for Rumble)   | 9 7 6 | 5 4 3 |  2 1  | CARD
  33867   4 -   GND    Ground                            |_______|_______|_______|
  33868   5 -   +3.5V  +3.5VDC supply (normal supply)     _______________________
  33869   6 Out /JOYn  Select joypad/card in Slot 1/2    |       |       |       |
  33870   7 Out JOYCLK Data Shift Clock                  | 9 8 7 | 6 5 4 | 3 2 1 | PAD
  33871   8 In  /IRQ10 IRQ10 (Joy only, not mem card)     \______|_______|______/
  33872   9 In  /ACK   IRQ7 Acknowledge (each eight CLKs)
  33873   Shield       Ground (Joypad only, not memory card)
  33874 /JOYn are two separate signals (/JOY1 for left card/pad, /JOY2 for right
  33875 card/pad) (whether it is an card or pad access depends on the first CMD bit).
  33876 All other signals are exactly the same on all four connectors (except that pin8
  33877 and shield are missing on the card slots).
  33878 
  33879 Pin8 (/IRQ10)
  33880 Most or all controllers leave pin8 unused, the pin can be used as lightpen
  33881 input (not sure if the CPU is automatically latching a timer somewhere?), if
  33882 there's no auto-latched timer, then the interrupt would be required to be
  33883 handled as soon as possible; ie. don't disable interrupts, and don't "halt" the
  33884 CPU for longer periods (as far as I understood, the GTE can halt the CPU when
  33885 trying to read results of incomplete operations; to avoid that, one could wait
  33886 by software, eg. inserting NOPs, before reading GTE results...?)
  33887 (Some (or maybe all?) existing psx lightguns are reportedly connected to the
  33888 Video output on the Multiout port for determining the current cathode ray
  33889 position though).
  33890 
  33891 Pinouts - Audio, Video, Power, Expansion Ports
  33892 ----------------------------------------------
  33893 
  33894 AV Multi Out (Audio/Video Port)
  33895   1      RGB-Video Green
  33896   2      RGB-Video Red
  33897   3      Supply +5.0V (eg. supply for external RF adaptor)
  33898   4      RGB-Video Blue
  33899   5      Supply Ground
  33900   6      S-Video C (chrominance)
  33901   7      Composite Video (yellow cinch)
  33902   8      S-Video Y (luminance)                    ____________________________
  33903   9      Audio Left      (white cinch)           |                            |
  33904   10     Audio Left Ground                       | 12 11 10 9 8 7 6 5 4 3 2 1 |
  33905   11     Audio Right     (red cinch)             |____________________________|
  33906   12     Audio Right Ground
  33907   Shield Video Ground
  33908 The standard AV-cable connects only to Pins 7,9,10,11,12,Shield (with pin 1 and
  33909 3 and Shield shortcut with each other, used for both audio and video ground).
  33910 The plug on that cable does have additional sparings for pin 1,3,5 (though
  33911 without any metal-contacts installed in there) (pin 3,5 would be used as supply
  33912 for external RF modulators) (no idea what pin 1 could be used for though?).
  33913 RGB displays may (or may not) be able to extract /SYNC from the Composite
  33914 signal, if that doesn't work, note that /SYNC (and separate /VSYNC, /HSYNC
  33915 signals) are found on the GPU pinouts, moreover, the GPU outputs 24bit digital
  33916 RGB.
  33917 Not sure if a VGA monitor can be connected? The SYNC signals are there (see GPU
  33918 pinputs), but the vertical resolution is only 200/240 lines... standard VGA
  33919 displays probably support only 400/480 lines (or higher resolutions for newer
  33920 multisync SVGA displays) (as far as I know, the classic 200 lines VGA mode is
  33921 actually outputting 400 lines, with each line repeated twice).
  33922 
  33923 Parallel Port (PIO) (Expansion Port) (CN103)
  33924 This port exists only on older PSX boards (not on newer PSX boards, and not on
  33925 PSone boards).
  33926 The parallel port is used by Gameshark, Game Enhancer II, and Gold Finger cheat
  33927 devices (not used by the Code Breaker CDROM cheat software).
  33928              ________
  33929             |        |                            Console Rear View
  33930       GND ==| 1   35 |== GND                 .-------------------------.
  33931    /RESET  =| 2   36 |=  DACK5               |1  2  3  ... ... 32 33 34|
  33932     DREQ5  =| 3   37 |=  /IRQ10              |35 36 37 ... ... 66 67 68|
  33933     /EXP?  =| 4   38 |=  /WR1? (CPU99)       |__.-------------------.__|
  33934   NC?GND?  =| 5   39 |=  GND?NC?
  33935        D0  =| 6   40 |=  D1
  33936        D2  =| 7   41 |=  D3
  33937        D4  =| 8   42 |=  D5
  33938        D6  =| 9   43 |=  D7
  33939        D8  =|10   44 |=  D9
  33940       D10  =|11   45 |=  D11
  33941       D12  =|12   46 |=  D13
  33942       D14  =|13   47 |=  D15
  33943        A0  =|14   48 |=  A1
  33944        A2  =|15   49 |=  A3
  33945   NC?GND?  =|16   50 |=  GND?NC?
  33946     +3.5V ==|17   51 |== +3.5V
  33947     +7.5V ==|18   52 |== +7.5V
  33948      GND?  =|19   53 |=  GND?NC?
  33949        A4  =|20   54 |=  A5
  33950        A6  =|21   55 |=  A7
  33951        A8  =|22   56 |=  A9
  33952       A10  =|23   57 |=  A11
  33953       A12  =|24   58 |=  A13
  33954       A14  =|25   59 |=  A15
  33955       A16  =|26   60 |=  A17
  33956       A18  =|27   61 |=  A19
  33957       A20  =|28   62 |=  A21
  33958       A22  =|29   63 |=  A23
  33959       /RD  =|30   64 |=  /WR0
  33960     NC!X?  =|31   65 |=  X?NC!
  33961    SYSCK?  =|32   66 |=  LRCK (44.1kHz)
  33962     SCLK?  =|33   67 |=  SDATA?
  33963       GND ==|34   68 |== GND
  33964             |________|
  33965 Lots of pins are still unknown?
  33966   EDIT: see http://cgfm2.emuviews.com/new/psx-pio.png
  33967   apparently, many of the "unknown" pins are just GROUND, is that possible?
  33968 
  33969 Internal Power Supply (PSX)
  33970 The PSX contains an internal power supply, however, like the PSone, it's only
  33971 having a "Standby" button, which merely disconnects 3.5V and 7.9V from the
  33972 mainboard. The actual power supply remains powered, and wastes energy day and
  33973 night, thanks Sony!
  33974 
  33975 External Power Supply (PSone)
  33976   Inner +7.5V DC 2.0A   (inside diameter 0.8mm)
  33977   Outer GND             (outside diameter 5.0mm)
  33978 
  33979 Pinouts - SIO Pinouts
  33980 ---------------------
  33981 
  33982 Serial Port
  33983 That port exists only on original Playstation (not on the PSone). The shape of
  33984 the Serial Port is identical to the 12pin Multiout (audio/video) port, but with
  33985 only 8pins.
  33986   1 SIO1 In  RXD receive data    (from remote TXD)
  33987   2 SIO2 -   VCC +3.5VDC         (supply, eg. for voltage conversion)
  33988   3 SIO3 In  DSR                 (from remote CTS)           _________________
  33989   4 SIO4 Out TXD transmit data   (to remote RXD)            |                 |
  33990   5 SIO5 In  CTS clear to send   (from remote RTS)          | 8 7 6 5 4 3 2 1 |
  33991   6 SIO6 Out DTR                 (to remote DSR)            |_________________|
  33992   7 SIO7 -   GND Ground          (supply, eg. for voltage conversion)
  33993   8 SIO8 Out RTS request to send (to remote CTS)
  33994   Shield     GND Ground          (to/from remote GND)
  33995 Can be used to communicate with another PSX via simple cable connection. With
  33996 an external RS232 adaptor (for voltage conversion) it could be also used to
  33997 communicate with a PC, a mouse, a modem, etc.
  33998 
  33999 PSone Serial Port
  34000 The PSone doesn't have an external serial connector, however, easy to use
  34001 soldering points for serial port signals are found as cluster of 5 soldering
  34002 points (below CPU pin52), and a single soldering point (below CPU pin100),
  34003 arranged like so (on PM-41 boards) (might be different on PM-41(2) boards):
  34004                      CPU70.RTS
  34005                CPU71.CTS   CPU74.TxD
  34006                      CPU72.DTR   CPU75.RxD                       CPU73.DSR
  34007 The three outputs (RTS,DTR,TXD) are left floating, the RXD input is wired via a
  34008 1K ohm pull-up resistor to 3.5V, the other two inputs (CTS,DSR) are wired via
  34009 1K ohm pull-down resistors to GND.
  34010 If you want to upgrade the PSone, remove that resistors, and then install the
  34011 PSX-style serial circuit (as shown below), or, think of a more simplified
  34012 circuit without (dis-)inverted signals.
  34013 
  34014 PSX Serial Port Connection (PU-23 board) (missing on PM-41 board)
  34015 The PSX serial circuit basically consists of a few transistors, diodes, and
  34016 resistors. The relevant part is that most of the signals are inverted -
  34017 compared with RS232 signals, the CPU uses normal high/low levels (of course
  34018 with 0V and 3.5V levels, not -12V and +12V), and the signals at the serial port
  34019 socket are inverted. Ie. if you want to built a RS232 adaptor, you must either
  34020 externally undo the inversion, or, disconnect the transistors, and wire your
  34021 circuit directly to the CPU signals.
  34022   SIO8    SIO6    SIO4    SIO1    SIO3    SIO5    SIO2    SIO7---GND
  34023     |       |       |       |       |       |      |
  34024   FB112   FB114   FB116   FB115   FBnnn   FBnnn    o--L102-------3.5V
  34025     |       |       |       |       |       |
  34026     |       |       o-------|-------|-------|--------diode-------GND
  34027     |       |       |       o-------|-------|--------diode-------GND
  34028     |       |       |       |       o-------|--------diode-------GND
  34029     |       |       |       |       |       o--------diode-------GND
  34030     |       |       |       |       |       |
  34031     |       |       |       o-------|-------|--------[1K]--------3.5V
  34032     |       |       |       |       o-------|--------[1K]--------3.5V
  34033    [22]    [22]    [22]    [22]     |       o--------[1K]--------3.5V
  34034     |       |       |       |       |       |
  34035    Q105-----|-------|-------|-------|-------|--------------------GND
  34036     |      Q105-----|-------|-------|-------|--------------------GND
  34037     |       |       |       |      Q106-----|--------------------GND
  34038     |       |       |       |       |      Q106------------------GND
  34039     |       |       |       |       |       |
  34040     |       |       |       |       o-------|--------[470]-------3.5V
  34041     |       |       |       |       |       o--------[470]-------3.5V
  34042     |       |       |       |       |       |
  34043    RTS     DTR     TxD     RxD     DSR     CTS
  34044   CPU70   CPU72   CPU74   CPU75   CPU73   CPU71   <-- CPU Pin Numbers
  34045    out     out     out     in      in      in
  34046 All six signals are passed through fuses (or loops or so). The three inputs
  34047 have 1K ohm pull-ups, and diodes as protection against negative voltages, two
  34048 of the inputs are inverted via transistors, with 470 ohm pull-ups at the CPU
  34049 side, the other input is passed through 22 ohm to the CPU. The three outputs
  34050 are also passed through 22 ohm, one of them having a diode as negative voltage
  34051 protection, the other two are inverted via transistors (which may also serve as
  34052 negative voltage protection).
  34053 Note that there is no positive voltage protection (ie. +12V inputs would do no
  34054 good, also strong -12V inputs might overheat the diodes/fuses, so if you want
  34055 to use RS232 voltages, better use a circuit for voltage conversion).
  34056 
  34057 Serial RS232 Adaptor
  34058 The PSX serial port uses 0V/3.5V logic, whilst RS232 uses -5V/+5V...-15V/+15V
  34059 logic. An example circuit for converting the logic levels would be:
  34060     PSX.VCC--+||--PSX.GND  PSX.GND----DSUB.5.GND----DSUB.SHIELD  DSUB.1,9----NC
  34061                    ______                                 ______
  34062   ,-----------||+-|1   16|-------PSX.VCC ,-----------||+-|1   16|-------PSX.VCC
  34063   | PSX.GND---||+-|2   15|-------PSX.GND | PSX.GND---||+-|2   15|-------PSX.GND
  34064   '---------------|3   14|----DSUB.3.TXD '---------------|3   14|--- N/A
  34065          ,---+||--|4   13|----DSUB.2.RXD        ,---+||--|4   13|--- N/A
  34066          '--------|5   12|-------PSX.RXD        '--------|5   12|--- N/A
  34067     PSX.GND--+||--|6   11|-------PSX.TXD   PSX.GND--+||--|6   11|--- N/A
  34068     DSUB.7.RTS----|7   10|--o<|--PSX.RTS   DSUB.4.DTR----|7   10|--o<|--PSX.DTR
  34069     DSUB.8.CTS----|8    9|--|>o--PSX.CTS   DSUB.6.DSR----|8    9|--|>o--PSX.DSR
  34070                   |______|                               |______|
  34071 Parts List: 1 or 2 MAX232 chips (voltage conversion), 0 or 1 7400 (NAND, used
  34072 as inverter), 4 or 8 1uF/16V capacitors, 1x 10uF/16V capacitor, 1x 9pin male
  34073 SubD plug.
  34074 The four inverters are needed only for external adapters (which need to undo
  34075 the transistor inversion on the PSX mainboard) (ie. the inverters are not
  34076 needed when when connecting the circuit directly to the PSX CPU).
  34077 The second MAX232 chip is needed only if DTR/DSR "not ready" conditions are
  34078 required (for an "always ready" condition: DSUB.4.DTR can be wired to -8.5V,
  34079 which is available at Pin6 of the first MAX232 chip, and PSX.DSR can be wired
  34080 to +3.5V).
  34081 With the above DSUB pin numbers, peripherals like mice or modems can be
  34082 connected directly to the circuit. For connection to another computer, use a
  34083 "null modem" cable (with crossed RXD/TXD, RTS/CTS, DTR/DSR wires).
  34084 The circuit works with both VCC=5V (default for MAX232) and with VCC=3.5V
  34085 (resulting in slightly weaker signals, but still strong enough even for serial
  34086 mice; which are mis-using the RS232 signals as power supply).
  34087 
  34088 Pinouts - Chipset Summary
  34089 -------------------------
  34090 
  34091 PSX/PSone Mainboards
  34092   Board    Expl.
  34093   PU-7     PSX, with AV multiout+cinch+svideo, GPU in two chips (160+64pins)
  34094   PU-8     PSX, with AV multiout+cinch, four 8bit Main RAM chips
  34095             EARLY-PU-8: "PU-8 1-658-467-11, N4" --> old chipset, resembles PU-7
  34096             LATE-PU-8:  "PU-8 1-658-467-22, N6" --> new chipset, other as PU-7
  34097   PU-9     PSX, without SCPH-number (just sticker saying "NOT FOR SALE, SONY)
  34098   PU-16    PSX, with extra Video CD daughterboard (for SCPH-5903)
  34099   PU-18    PSX, with AV multiout only, single 32bit Main RAM (instead 4x8bit)
  34100   PU-20    PSX, unknown if/how it differs from PU-18
  34101   PU-22    PSX, unknown if/how it differs from PU-18
  34102   PU-23    PSX, with serial port, but without expansion port
  34103   PM-41    PSone, older PSone, for GPU/SPU with RAM on-board (see revisions)
  34104   PM-41(2) PSone, newer PSone, for GPU/SPU with RAM on-chip
  34105 There are at least two revisions of the "PM-41" board:
  34106   PM-41, 1-679-335-21  PSone with incomplete RGB signals on multiout port
  34107   PM-41, 1-679-335-51  PSone with complete RGB signals on multiout port
  34108 The "incomplete" board reportedly requires to solder one wire to the multiout
  34109 port to make it fully functional... though no idea which wire... looks like the
  34110 +5V supply? Also, the capacitors near multiout are arranged slightly
  34111 differently.
  34112 
  34113 CPU chips
  34114   IC103 - 208pin - "SONY CXD8530BQ"  ;seen on PU-7 board
  34115   IC103 - 208pin - "SONY CXD8530CQ"  ;seen on PU-7 and PU-8 boards
  34116   IC103 - 208pin - "SONY CXD8606Q"   ;seen in PU-18 schematic
  34117   IC103 - 208pin - "SONY CXD8606AQ"  ;seen on PU-xx? board
  34118   IC103 - 208pin - "SONY CXD8606BQ"  ;seen on PM-41, PU-23, PU-20 boards
  34119   IC103 - 208pin - "SONY CXD8606CQ"  ;seen on PM-41 board, too
  34120 These chips contain the MIPS CPU, COP0, and COP2 (aka GTE), MDEC and DMA.
  34121 
  34122 GPU chips - Graphics Processing Unit
  34123   IC203 - 160pin - "SONY CXD8514Q"   ;seen on PU-7 and EARLY-PU-8 boards
  34124   IC203 - 208pin - "SONY CXD8561Q"   ;seen on LATE-PU-8 board
  34125   IC203 - 208pin - "SONY CXD8561BQ"  ;seen on PU-18, PU-20 boards
  34126   IC203 - 208pin - "SONY CXD8561CQ"  ;seen on PM-41 board
  34127   IC203 - 208pin - "SONY CXD9500Q"   ;with on-chip RAM ;for PM-41(2) board
  34128   IC21  - 208pin - "SONY CXD8538Q"   ;seen on GP-11 (namco System 11) boards
  34129   IC103 - 208pin - "SONY CXD8654Q"   ;seen on GP-15 (namco System 12) boards
  34130 
  34131 SPU chips - Sound Processing Unit
  34132   IC308 - 100pin - "SONY CXD2922Q" (SPU)               ;PU-7 and EARLY-PU-8
  34133   IC308 - 100pin - "SONY CXD2922BQ"(SPU)               ;EARLY-PU-8
  34134   IC308 - 100pin - "SONY CXD2925Q" (SPU)               ;LATE-PU-8, PU-18, PU-20
  34135   IC732 - 208pin - "SONY CXD2938Q" (SPU+CDROM)         ;PSone/PM-41 Board
  34136   IC732 - 176pin - "SONY CXD2941R" (SPU+CDROM+SPU_RAM) ;PSone/PM-41(2) Board
  34137   IC402 - 24pin  - "AKM AK4309VM"  (Serial 2x16bit DAC);older boards only
  34138   IC405 - 8pin   - "NJM2100E (TE2)" Audio Amplifier    ;PU-8 and PU-22 boards
  34139   IC405 - 14pin  - "NJM2174" Audio Amplifier with Mute ;later boards
  34140 
  34141 IC106 CPU-RAM / Main RAM chips
  34142   IC106/IC107/IC108/IC109 - NEC 424805AL-A60 (28pin, 512Kx8) (PU-8 board)
  34143   IC106 - "Samsung K4Q153212M-JC60" (70pin, 512Kx32) (newer boards)
  34144   IC106 - "Toshiba T7X16 (70pin, 512Kx32) (newer boards, too)
  34145 
  34146 GPU-RAM / Video RAM chips
  34147   IC201 - 64pin NEC uPD482445LGW-A70-S ;VRAM  ;\on PU-7 and EARLY-PU-8 board
  34148   IC202 - 64pin NEC uPD482445LGW-A70-S ;VRAM  ;/split into 2 chips !
  34149   IC201 - 64pin SEC KM4216Y256G-60     ;VRAM  ;\on other PU-7 board
  34150   IC202 - 64pin SEC KM4216Y256G-60     ;VRAM  ;/split into 2 chips !
  34151   IC201 - 100pin - Samsung KM4132G271BQ-10 (128Kx32x2)  ;-on later boards
  34152   IC201 - 100pin - Samsung K4G163222A-PC70 (256Kx32x2)  ;-on PM-41
  34153 Note: The older 64pin VRAM chips are special dual-ported DRAM, the newer 100pin
  34154 VRAM chips are just regular DRAM.
  34155 Note: The PM-41 board uses a 2MB VRAM chip (but allows to access only 1MB)
  34156 Note: The PM-41(2) board has on-chip RAM in the GPU (no external memory chip)
  34157 
  34158 IC310 - SPU-RAM - Sound RAM chips
  34159   IC310 - 40pin - "TOSHIBA TC51V4260DJ-70"  ;seen on PU-8 board
  34160   IC310 - 40pin - EliteMT M11B416256A-35J (256K x 16bit)
  34161 Note: The PM-41(2) board has on-chip RAM in the SPU (no external memory chip)
  34162 
  34163 BIOS ROM
  34164   IC102 - 40pin - "SONY ..."          ;seen on PU-7 & early-PU-8 board (40pin!)
  34165   IC102 - 44pin - "SONY M538032E-02"  ;seen on PU-16 (video CD, 1Mbyte BIOS)
  34166   IC102 - 32pin - "SONY M534031C-25"  ;seen on later-PU-8 board
  34167   IC102 - 32pin - "SONY 2030"         ;seen on PU-18 board
  34168   IC102 - 32pin - "SONY M534031E-47"  ;seen on PM-41 board and PM-41(2)
  34169   IC102 - 32pin - "SONY M27V401D-41"  ;seen on PM-41 board, too
  34170 
  34171 Oscillators and Clock Multiplier/Divider
  34172   X101 - 4pin - "67.737" (NTSC, presumably)         ;PU-7 .. PU-20
  34173   X201 - 2pin - "17.734" (PAL) or "14.318" (NTSC)   ;PU-22 .. PM-41(2)
  34174   IC204 - 8pin - "2294A" (PAL) or <unknown?> (NTSC) ;PU-22 .. PM-41(2)
  34175 
  34176 Voltage Converter (for +7.5V to +5.0V conversion)
  34177   IC601 - 3pin - "78M05" or "78005"  ;used in PSone
  34178 
  34179 Pulse-Width-Modulation Power-Control Chip
  34180   IC606 16pin/10mm "TL594CD" (alternately to IC607) ;seen on PM-41 board
  34181   IC607 16pin/5mm  "T594"    (alternately to IC606) ;seen on PM-41 board, too
  34182 The PM-41 board has locations for both IC606 and IC607, some boards have the
  34183 bigger IC606 (10mm) installed, others the smaller IC607 (5mm), both chips have
  34184 exactly the same pinouts, the only difference is the size.
  34185 
  34186 Reset Generator
  34187   IC002 - 8pin - <not installed> (would be alternately to IC003) ;\on PSone
  34188   IC003 - 5pin - <usually installed>                             ;/
  34189   IC101 - 5pin - M51957B (Reset Generator) (on PSX-power supply boards)
  34190 
  34191 CDROM Chips
  34192   U42   80pin    SUB-CPU (CXP82300) with piggyback EPROM ;DTL-H2000
  34193   IC304 80pin    SUB-CPU (MC68HC05L16) 80pin package     ;PU-7 and EARLY-PU-8
  34194   IC304 52pin    SUB-CPU (MC68HC05G6) 52pin package      ;LATE-PU-8 and up
  34195   IC305 - 100pin SONY CXD1199BQ (Decoder/FIFO)           ;PU-7
  34196   IC305 - 100pin SONY CXD1815Q  (Decoder/FIFO)           ;PU-8, PU-18
  34197   IC309 - 100pin SONY CXD2516Q  (Signal Processor)       ;PU-7 (100pin!)
  34198   IC309 - 80pin  SONY CXD2510Q  (Signal Processor)       ;PU-8 and DTL-H2510
  34199   IC702 - 48pin  SONY CXA1782BR (Servo Amplifier)        ;PU-7, PU-8
  34200   IC101 - 100pin SONY CXD2515Q  (=CXD2510Q+CXA1782BR)    ;DTL-H2010
  34201   IC701 - 100pin SONY CXD2545Q  (=CXD2510Q+CXA1782BR)    ;PU-18
  34202   IC720 - 144pin SONY CXD1817R  (=CXD2545Q+CXD1815Q)     ;PU-20
  34203   IC102 - 28pin - "BA6297AFP"           ;seen on DTL-H2010 drives
  34204   IC704 - 28pin - "BA6398FP"            ;seen on PU-7
  34205   IC722 - 28pin - "BA6397FP"            ;seen on late PU-8
  34206   IC722 - 28pin - "BA5947FP"            ;seen on PM-41 and various boards
  34207   IC722 - 28pin - "Panasonic AN8732SB"  ;seen on PM-41 board
  34208   ICxxx - 20pin  SONY CXA1571N    (RF Amplifier) (on DTL-H2010 drives)
  34209   IC703 - 20pin  SONY CXA1791N    (RF Amplifier) (on PU-18 boards)
  34210   IC723 - 20pin  SONY CXA2575N-T4 (RF Matrix Amplifier) (on PU-22 .. PM-41(2))
  34211 Note: The SUB-CPU contains an on-chip BIOS (which does exist in at least seven
  34212 versions, plus US/JP/PAL-region variants, plus region-free debug variants).
  34213 
  34214 RGB Chips
  34215   IC207 64pin "SONY CXD2923AR" VRAM Data to Analog RGB         ;\oldest
  34216   IC501 24pin "SONY CXA1645M" Analog RGB to Composite          ;/
  34217   IC202 44pin "Philips TDA8771H" Digital RGB to Analog RGB     ;\old boards
  34218   IC202 44pin "Motorola MC141685FT" Digital RGB to Analog RGB  ;/
  34219   IC?   48pin "H7240AKV" 24bit RGB to Analog+Composite         ;-SCPH-7001?
  34220   IC502 48pin "SONY CXA2106R-T4" 24bit RGB to Analog+Composite ;-newer boards
  34221 
  34222 MISC
  34223   CDROM Drive: "KSM-440BAM" ;seen used with PM-41 board
  34224   IC602 5pin           "L/\1B" or "<symbol> 3DR"
  34225 
  34226 Controller/Memory Card Chips
  34227   U?  24pin "9625H, CFS8121"     ;SCPH-1080, digital pad (alternate?)
  34228   U?   ?pin "SC438001"           ;SCPH-1080, digital pad (alternate?)
  34229   U?  32pin "(M), SC401800"      ;SCPH-1080, digital pad
  34230   U?  32pin "(M), SC442116"      ;SCPH-xxxx, mouse
  34231   IC? 64pin "SONY CXD103, -166Q" ;SCPH-1070, multitap
  34232   U1  42pin "SD657, 9702K3006"   ;SCPH-1150, analog pad, single motor
  34233   U1  42pin "SD657, 9726K3002"   ;SCPH-1180, analog pad, without motor
  34234   U1  44pin "SONY CXD8771Q"      ;SCPH-1200, analog pad, two motors (PSX)
  34235   U1  44pin "SD707, 039 107"     ;SCPH-110,  analog pad, two motors (PSone)
  34236   U1  44pin "SD787A"             ;SCPH-xxx,  analog pad, two motors (PS2?)
  34237   U?  64pin "SONY CXD8732AQ"     ;SCPH-1020, memory card, on-chip FLASH
  34238   U?  XXpin other chips          ;SCPH-xxxx, memory card, external FLASH
  34239   U1  44pin "NAMCO103P"          ;NPC-103, namco lightgun
  34240 
  34241 Pinouts - CPU Pinouts
  34242 ---------------------
  34243 
  34244 CPU Pinouts (IC103)
  34245   1-3.5V  27-GND   53-3.5V  79-3.5V   105-3.5V 131-3.5V   157-3.5V   183-3.5V
  34246   2-3.5V  28-DQ12  54-3.5V  80-/JOY1  106-3.5V 132-A5     158-3.5V   184-GD19
  34247   3-67/NC 29-DQ11 55-A11:A8 81-JOYCLK 107-D0   133-A6     159-HBLANK 185-GD20
  34248   4-67MHz 30-DQ10 56-A10:NC 82-/IRQ7  108-D1   134-A7     160-DOTCLK 186-GD21
  34249   5-DQ31  31-DQ9   57-A9    83-JOYCMD 109-D2   135-A8     161-GD0    187-GD22
  34250   6-DQ30  32-DQ8   58-A8:NC 84-JOYDAT 110-D3   136-A9     162-GD1    188-GD23
  34251   7-DQ29  33-DQ7   59-A7    85-DACK5  111-D4   137-A10    163-GD2    189-GD24
  34252   8-DQ28  34-DQ6   60-A6    86-DREQ5  112-D5   138-A11    164-GD3    190-GD25
  34253   9-DQ27  35-DQ5   61-A5    87-DMA4   113-D6   139-A12    165-GD4    191-GD26
  34254   10-DQ26 36-DQ4   62-A4    88-/SPUW  114-D7   140-A13    166-GD5    192-GD27
  34255   11-DQ25 37-DQ3   63-A3    89-/IRQ10 115-D8   141-A14    167-GD6    193-GD28
  34256   12-DQ24 38-3.5V  64-A2    90-/IRQ9  116-D9   142-A15    168-GD7    194-GD29
  34257   13-DQ23 39-GND   65-GND   91-GND    117-GND  143-GND    169-GD8    195-GND
  34258   14-3.5V 40-DQ2   66-3.5V  92-3.5V   118-3.5V 144-3.5V   170-GND    196-3.5V
  34259   15-GND  41-DQ1   67-A1    93-GND    119-D10  145-A16    171-3.5V   197-GD30
  34260   16-DQ22 42-DQ0   68-A0    94-/IRQ2  120-D11  146-A17    172-GD9    198-GD31
  34261   17-DQ21 43-/W    69-3.5V  95-/CD    121-D12  147-A18    173-GD10   199-VBLANK
  34262   18-DQ20 44-/RAS1 70-RTS   96-/SPU   122-D13  148-A19    174-GD11   200-GPU12
  34263   19-DQ19 45-/RAS  71-CTS   97-/BIOS  123-D14  149-A20    175-GD12   201-33MHzG
  34264   20-DQ18 46-/CAS3 72-DTR   98-/EXP   124-D15  150-A21    176-GD13   202-GPU5
  34265   21-DQ17 47-/CAS2 73-DSR   99- CPU99 125-A0   151-A22    177-GD14   203-/GWR
  34266   22-DQ16 48-/CAS1 74-TxD   100-/WR   126-A1   152-A23    178-GD15   204-/GRD
  34267   23-DQ15 49-/CAS0 75-RxD   101-/RD   127-A2   153-GPU.A2 179-GD16   205-/GPU
  34268   24-DQ14 50-3.5V  76-/RES  102-/IRQ1 128-A3   154-33MHzS 180-GD17   206-67MHzG
  34269   25-DQ13 51-GND   77-/JOY2 103-GND   129-A4   155-GND    181-GD18   207-GND
  34270   26-3.5V 52-GND   78-GND   104-GND   130-GND  156-GND    182-GND    208-GND
  34271 Pin5-68 = Main RAM bus. Pin 95-152 = System bus. Pin 102,153,159-206 = Video
  34272 bus.
  34273   85=DACK5  93=GND=/CSHTST  199=/INT0   44=/RAS1:NC
  34274   86=DREQ5  99=/SWR1=NC     200=DREQ2   45=/RAS0
  34275   87=DACK4  100=/SWR0       201=SYSCLK0
  34276   88=DREQ4  154=SYSCLK1     202=DACK2
  34277 
  34278 CPU Pinout Notes
  34279 Pin 3,4: 67MHz is Pin3/old or Pin4/new (with Pin3=NC/new or Pin4=GND/old)
  34280 Pin 43,45..49,100,101,125(A0!),201,203..206 are connected via 22 ohm.
  34281 Pin 77,80,81,83 are connected via 470 ohm.
  34282 Pin 82,84,89 are connected via 47 ohm.
  34283 Pin 95,96,97 are connected via 100 ohm.
  34284 Pin 44: goes LOW for a short time once every N us (guessed: maybe /REFRESH ?)
  34285 Pin 4: 67MHz (from IC204.pin5)
  34286 Pin 87/88: SPU-DMA related (/SPUW also permanent LOW for Manual SPU-RAM Write)
  34287 Pin 154: 33MHzS (via 22ohm and FB102 to SPU) (and TESTPOINT near MainRAM pin70)
  34288 Pin 160: DOTCLK (via 22ohm), and IC502.Pin41 (without 22ohm)
  34289 Pin 56,58 are maybe additional address lines for the addressable 8MB RAM.
  34290 The System Bus address lines are latched outputs (containing the most recently
  34291 used /BIOS /EXP /SPU /CD address) (not affected by Main RAM and GPU
  34292 addressing).
  34293 
  34294 Pinouts - GPU Pinouts (for old 160-pin GPU)
  34295 -------------------------------------------
  34296 
  34297 Old 160-pin GPU is used on PU-7 boards and EARLY-PU-8 boards.
  34298 
  34299 IC203 - Sony CXD8514Q - Old 160pin GPU for use with Dual-ported VRAM
  34300 Unlike the later 208pin GPU's, the old 160pin GPU has less supply pins, and, it
  34301 doesn't have a 24bit RGB output (nor any other video output at all), instead,
  34302 it's used with a RGB D/A converter that reads the video data directly from the
  34303 Dual-ported VRAM chips (ie. from special RAM chips with two data busses, one
  34304 bus for GPU read/write access, and one for the RGB video output).
  34305   1-VCC     21-GND  41-D16  61-D2     81-D12'a  101-GND     121-D7'b 141-GND
  34306   2-GND     22-D31  42-D15  62-D1     82-D11'a  102-DT/OE'b 122-D6'b 142-53MHz
  34307   3-/GPU    23-D30  43-VCC  63-D0     83-D10'a  103-DT/OE'a 123-D5'b 143-VCC
  34308   4-GPU.A2  24-D29  44-GND  64-GND    84-D9'a   104-/RAS    124-D4'b 144-GND
  34309   5-/GRD    25-D28  45-D14  65-VCC    85-D8'a   105-/WE'a   125-D3'b 145-FSC
  34310   6-/GWR    26-D27  46-D13  66-A8'a   86-VCC    106-/WE'b   126-D2'b 146-VCC
  34311   7-DACK2   27-D26  47-D12  67-A7'a   87-GND    107-/SE     127-D1'b 147-GND
  34312   8-/RES    28-VCC  48-D11  68-A6'a   88-D7'a   108-SC      128-D0'b 148-DOTCLK
  34313   9-VCC     29-GND  49-D10  69-A5'a   89-D6'a   109-VCC     129-VCC  149-VCC
  34314   10-GND    30-D25  50-GND  70-GND    90-D5'a   110-GND     130-GND  150-GND
  34315   11-33MHzG 31-D24  51-VCC  71-A4'a   91-D4'a   111-D15'b   131-A8'b 151-MEMCK1
  34316   12-VCC    32-D23  52-D9   72-A3'a   92-D3'a   112-D14'b   132-A7'b 152-MEMCK2
  34317   13-GND    33-D22  53-D8   73-A2'a   93-D2'a   113-D13'b   133-A6'b 153-BLANK
  34318   14-DREQ2  34-D21  54-D7   74-A1'a   94-D1'a   114-D12'b   134-A5'b 154-/24BPP
  34319   15-/IRQ1  35-D20  55-D6   75-A0'a   95-D0'a   115-D11'b   135-A4'b 155-/SYNC
  34320   16-HBLANK 36-VCC  56-D5   76-GND    96-VCC    116-D10'b   136-A3'b 156-/HSYNC
  34321   17-VBLANK 37-GND  57-D4   77-VCC    97-DSF    117-D9'b    137-A2'b 157-/VSYNC
  34322   18-high?  38-D19  58-D3   78-D15'a  98-/CAS'b 118-D8'b    138-A1'b 158-VCC
  34323   19-high?  39-D18  59-GND  79-D14'a  99-/CAS'a 119-VCC     139-A0'b 159-GND
  34324   20-VCC    40-D17  60-VCC  80-D13'a  100-VCC   120-GND     140-VCC  160-67MHzG
  34325 Pin 1-63,148,160 = CPU Bus, Pin 66-139 = VRAM Bus (two chips, A and B), Pin
  34326 142-155 = Misc (CXA and RGB chips), Pin 18-19,156-157 = Test points.
  34327 Pin 3,5,6,11,98,99,102,103,108,148,160 via 22 ohm. Pin 104,105,106 via 100 ohm.
  34328 Pin 107 via 220 ohm. Pin 155 via 2200 ohm. Pin 145 via 220+2200 ohm.
  34329   151-?       ---   (mem clock?)
  34330   152-?             (mem clock?)
  34331   153-BLANK         (high in HBLANK & VBLANK)
  34332   154-/24BPP        (high=15bpp, low=24bpp)
  34333   156-/HSYNC        rate:65us=15KHz, low:3.5us
  34334   157-/VSYNC        rate:20ms=50Hz, low:130us=TwoLines
  34335 
  34336 IC207 - SONY CXD2923AR - Digital VRAM to Analog RGB Converter (for old GPU)
  34337 This chip is used with the old 160pin GPU and two Dual-ported VRAM chips. The
  34338 2x16bit databus is capable of reading up to 32bits of VRAM data, and the chip
  34339 does then extract the 15bit or 24bit RGB values from that data (depending on
  34340 the GPU's current color depth).
  34341 The RGB outputs (pin 5,7,9) seem to be passed through transistors and
  34342 capacitors... not sure how the capacitors could output constant voltage
  34343 levels... unless the RGB signals are actually some kind of edge-triggering PWM
  34344 pulses rather than real analog levels(?)
  34345   1-test?  9-BLUE    17-GND     25-D0'a  33-D8'a   41-D15'a  49-D7'b   57-D13'b
  34346   2-test?  10-Vxx    18-MEMCK1  26-D1'a  34-D9'a   42-D0'b   50-D8'b   58-D14'b
  34347   3-Vxx    11-test?  19-/24BPP  27-D2'a  35-D10'a  43-D1'b   51-D9'b   59-D15'b
  34348   4-Vxx    12-test?  20-MEMCK2  28-D3'a  36-D11'a  44-D2'b   52-D10'b  60-GND
  34349   5-RED    13-test?  21-BLANK   29-D4'a  37-D12'a  45-D3'b   53-D11'b  61-GND
  34350   6-Vxx    14-aGND?  22-DOTCLK  30-D5'a  38-D13'a  46-D4'b   54-D12'b  62-GND
  34351   7-GREEN  15-aGND?  23-GND     31-D6'a  39-D14'a  47-D5'b   55-GND    63-test?
  34352   8-GND    16-aGND?  24-Vxx     32-D7'a  40-GND    48-D6'b   56-Vxx    64-GND
  34353 Pin 5,7,9 = RGB outputs (via transistors and capacitors?), Pin 18-22 = GPU, Pin
  34354 25-59 = VRAM (chip A and B), Pin 1-2,11-13,63 = Test points.
  34355 
  34356 IC201 - 64pin NEC uPD482445LGW-A70-S or SEC KM4216Y256G-60 (VRAM 256Kx16)
  34357 IC202 - 64pin NEC uPD482445LGW-A70-S or SEC KM4216Y256G-60 (VRAM 256Kx16)
  34358 These are special Dual-ported VRAM chips (with two data busses), the D0-D15
  34359 pins are wired to the GPU (for read/write access), the Q0-Q15 pins are wired to
  34360 the RGB D/A converter (for sequential video output).
  34361   1-VCC     9-Q2    17-D5    25-/UWE  33-GND   41-DSF  49-Q10   57-VCC
  34362   2-/DT/OE  10-D2   18-VCC   26-/RAS  34-A3    42-GND  50-D11   58-D14
  34363   3-GND     11-Q3   19-Q6    27-A8    35-A2    43-D8   51-Q11   59-Q14
  34364   4-Q0      12-D3   20-D6    28-A7    36-A1    44-Q8   52-GND   60-D15
  34365   5-D0      13-GND  21-Q7    29-A6    37-A0    45-D9   53-D12   61-Q15
  34366   6-Q1      14-Q4   22-D7    30-A5    38-QSF   46-Q9   54-Q12   62-GND
  34367   7-D1      15-D4   23-GND   31-A4    39-/CAS  47-VCC  55-D13   63-/SE
  34368   8-VCC     16-Q5   24-/LWE  32-VCC   40-NC    48-D10  56-Q13   64-SC
  34369 The 8bit /LWE and /UWE write signals are shortcut with each other and wired to
  34370 the GPU's 16bit /WE write signal.
  34371 
  34372 IC501 24pin "SONY CXA1645M" Analog RGB to Composite (older boards only)
  34373   1-GND1  4-BIN   7-NPIN   10-SYNCIN  13-IREF  16-YOUT   19-VCC2   22-GOUT
  34374   2-RIN   5-NC    8-BFOUT  11-BC      14-VREF  17-YTRAP  20-CVOUT  23-ROUT
  34375   3-GIN   6-SCIN  9-YCLPC  12-VCC1    15-COUT  18-FO     21-BOUT   24-GND2
  34376 Used only on older boards (eg. PU-7, PU-8, PU-16), newer boards generate
  34377 composite signal via 48pin IC502.
  34378 Pin7 (NPIN aka /PAL): NTSC=VCC, PAL=GND. Pin6 (SCIN aka FSC): Sub Carrier aka
  34379 PAL/NTSC color clock, which can be derived from three different sources:
  34380   GPU pin 145 (old 160-pin GPU)
  34381   GPU pin 154 (new 208-pin GPU)
  34382   IC204 (on later boards, eg. PSone)
  34383 for the color clocks from GPU pins, the GPU does try to automatically generate
  34384 PAL or NTSC clock depending on current frame rate, which is resulting in
  34385 "wrong" color clock when chaning between 50Hz/60Hz mode).
  34386 
  34387 Pinouts - GPU Pinouts (for new 208-pin GPU)
  34388 -------------------------------------------
  34389 
  34390 New 206-pin GPU is used LATE-PU-8 boards and up.
  34391 
  34392 GPU Pinouts (IC203)
  34393   1-/GPU    27-GD28  53-GD10   79-D29  105-GND  131-CLK   157-/PAL   183-R3
  34394   2-GPU.A2  28-GD27  54-GD9    80-3.5V 106-3.5V 132-GND   158-/VSYNC 184-GND
  34395   3-/GRD    29-3.5V  55-GD8    81-GND  107-D17  133-3.5V  159-/HSYNC 185-3.5V
  34396   4-/GWR    30-GND   56-GD7    82-D28  108-D16  134-CLK   160-B0     186-R4
  34397   5-CPU202  31-GD26  57-GD6    83-D27  109-D7   135-GND   161-B1     187-R5
  34398   6-/RES    32-GD25  58-GD5    84-D26  110-D6   136-3.5V  162-B2     188-R6
  34399   7-3.5V    33-GD24  59-GD4    85-D25  111-D5   137-(A10) 163-B3     189-R7
  34400   8-GND     34-GD23  60-GND    86-D24  112-D4   138-A9/AP 164-GND    190-GND
  34401   9-33MHzG  35-GD22  61-3.5V   87-3.5V 113-GND  139-A7    165-3.5V   191-3.5V
  34402   10-3.5V   36-GD21  62-GD3    88-GND  114-3.5V 140-A6    166-B4     192-53MHzP
  34403   11-GND    37-3.5V  63-GD2    89-D15  115-D3   141-3.5V  167-B5     193-3.5V
  34404   12-CPU200 38-GND   64-GD1    90-D14  116-D0   142-GND   168-B6     194-GND
  34405   13-/IRQ1  39-GD20  65-GD0    91-D13  117-D1   143-A5    169-B7     195-3.5V
  34406   14-HBLANK 40-GD19  66-GND    92-D12  118-D2   144-A4    170-G0     196-53MHzN
  34407   15-GND    41-GD18  67-3.5V   93-D11  119-GND  145-A3    171-G1     197-3.5V
  34408   16-3.5V   42-GD17  68-(high) 94-D10  120-3.5V 146-GND   172-G2     198-GND
  34409   17-VBLANK 43-3.5V  69-(high) 95-D9   121-NC   147-3.5V  173-G3     199-DOTCLK
  34410   18-(pull) 44-GND   70-(high) 96-GND  122-/CS  148-A2    174-GND    200-GND
  34411   19-(low)  45-GD16  71-3.5V   97-3.5V 123-DSF  149-A1    175-3.5V   201-3.5V
  34412   20-GND    46-GD15  72-3.5V   98-D8   124-/RAS 150-A0    176-G4     202-BLANK
  34413   21-(low)  47-GD14  73-3.5V   99-D18  125-/CAS 151-3.5V  177-G5     203-(low)
  34414   22-3.5V   48-GD13  74-3.5V   100-D19 126-/WE  152-GND   178-G6     204-GND
  34415   23-3.5V   49-GD12  75-3.5V   101-D20 127-DQM1 153-FSC   179-G7     205-3.5V
  34416   24-GD31   50-GD11  76-GND    102-D21 128-DQM0 154-3.5V  180-R0     206-67MHzG
  34417   25-GD30   51-3.5V  77-D31    103-D22 129-GND  155-GND   181-R1     207-GND
  34418   26-GD29   52-GND   78-D30    104-D23 130-3.5V 156-/SYNC 182-R2     208-3.5V
  34419 Pin 77..150 = Video RAM Bus. Pin 156..189 = Video Out Bus. Other = CPU Bus. Pin
  34420 153: Sub Carrier (NC on newer boards whick pick color clock from IC204).
  34421 
  34422 GPU Pinout Notes
  34423 Pin 1,3,4,9,122..128,199,206 are connected via 22 ohm.
  34424 Pin 18 has a 4K7 ohm pullup to 3.5V
  34425 Pin 77..118 data lines (DQ0..DQ31) are connected via 82 ohm.
  34426 Pin 192/196: via 220 ohm to IC204.pin1 (53MHz)
  34427 At RAM Side: CKE via 4K7 to 3.5V, and, A8 is GROUNDED!
  34428 DQM0 is wired to both DQM0 and DQM2, DQM1 is wired to both DQM1 and DQM3.
  34429 CLK is wired to both GPU pin 131 and 134.
  34430 RGBnn = IC502 pin nn
  34431 /VSYNC, /HSYNC, (and BLANK?) are test points (not connected to any components).
  34432 /SYNC = (/VSYNC AND /HSYNC). BLANK = (VBLANK OR HBLANK).
  34433 
  34434 IC202 44pin "Philips TDA8771H" Digital to Analog RGB (older boards only)
  34435 Region Japan+Europe: TDA8771AN
  34436 Region America+Asia: MC151854FLTEG or so?
  34437   1-IREF  6-GNDd1  11-R1   16-G4   21-B7  26-B2     31-CLK    36-OUTB  41-NC
  34438   2-GNDa1 7-VDDd1  12-R0   17-G3   22-B6  27-VDDd2  32-VDDa1  37-NC    42-GNDa2
  34439   3-R7    8-R4     13-G7   18-G2   23-B5  28-GNDd2  33-VREF   38-NC    43-VDDa4
  34440   4-R6    9-R3     14-G6   19-G1   24-B4  29-B1     34-NC     39-VDDa3 44-OUTR
  34441   5-R5    10-R2    15-G5   20-G0   25-B3  30-B0     35-VDDa2  40-OUTG
  34442 Used only LATE-PU-8 boards (and PU-16, which does even have two TDA8771AH
  34443 chips: one on the mainboard, and one on the VCD daughterboard).
  34444 Earlier boards are generating analog RGB via 64pin IC207, and later boards RGB
  34445 via 48pin IC502.
  34446 
  34447 IC502 48pin "SONY CXA2106R-T4" - 24bit RGB video D/A converter
  34448   1-(cap) 7-Comp.  13-/PAL   19-R4     25-G7     31-G1     37-B3     43-NC
  34449   2-GND   8-Chro.  14-/SYNC  20-5.0V   26-G6     32-G0     38-B2     44-(cap)
  34450   3-Red   9-5.0V   15-4.4MHz 21-R3     27-G5     33-B7     39-B1     45-GND
  34451   4-Green 10-YTRAP 16-R7     22-R2     28-G4     34-B6     40-B0     46-(cap)
  34452   5-Blue  11-NC    17-R6     23-R1     29-G3     35-B5     41-DOTCLK 47-5.0V
  34453   6-Lum.  12-NC    18-R5     24-R0     30-G2     36-B4     42-GND    48-(cap)
  34454 Pin 3..8 (analogue outputs) are passed via external 75 ohm resistors.
  34455 Pin 6,7 additionally via 220uF. Pin 8 additionally via smaller capacitor.
  34456 Pin 10 (YTRAP) wired via 2K7 to 5.0V.
  34457 Pin 1,44,46,48 (can) connect via capacitors to ground (only installed for 44).
  34458 The 4.4MHz clock is obtained via 2K2 from IC204.Pin6.
  34459 The /PAL pin can be reportedly GROUNDED to force PAL colors in NTSC mode, when
  34460 doing that, you may first want to disconnect the pin from the GPU.
  34461 Note: Rohm BH7240AKV has same pinout (XXX but with pin7/pin8 swapped?)
  34462 
  34463 Beware
  34464 Measuring in the region near GPU Pin10 is the nocash number one source for
  34465 blowing up components on the mainboard. If you want to measure that signals
  34466 while power is on, better measure them at the CPU side.
  34467 
  34468 Pinouts - SPU Pinouts
  34469 ---------------------
  34470 
  34471 IC308 - SONY CXD2922Q (SPU) (on PU-7, EARLY-PU-8 boards)
  34472 IC308 - SONY CXD2925Q (SPU) (on LATE-PU-8, PU-16, PU-18, PU-20 boards)
  34473   1-D0    14-D11  27-A8    40-GND    53-3.5V  66-A15  79-5V    92-LRIA
  34474   2-D1    15-GND  28-3.5V  41-SYSCK  54-GND   67-A14  80-A3    93-DTIA
  34475   3-3.5V  16-D12  29-GND   42-GND    55-D7    68-A13  81-A2    94-BCIB
  34476   4-GND   17-D13  30-A9    43-TEST   56-D6    69-A12  82-A1    95-LRIB
  34477   5-D2    18-D14  31-/SPU  44-TES2   57-D5    70-A11  83-A0    96-DTIB
  34478   6-D3    19-D15  32-/RD   45-D15    58-D4    71-A10  84-/WE0  97-BCKO
  34479   7-D4    20-A1   33-/WR   46-D14    59-D3    72-A9   85-/OE0  98-LRCO
  34480   8-D5    21-A2   34-DACK  47-D13    60-D2    73-A8   86-/WE1  99-DATO
  34481   9-D6    22-A3   35-/IRQ  48-D12    61-D1    74-A7   87-/OE1  100-WCKO
  34482   10-D7   23-A4   36-DREQ  49-D11    62-D0    75-A6   88-GND
  34483   11-D8   24-A5   37-MUTE  50-D10    63-/RAS  76-A5   89-XCK
  34484   12-D9   25-A6   38-/RST  51-D9     64-/CAS  77-A4   90-GND
  34485   13-D10  26-A7   39-NC    52-D8     65-GND   78-GND  91-BCIA
  34486 Pin 1..36 = MIPS-CPU bus. Pin 45..87 = SPU-RAM bus (A0,A10-A15,/WE1,OE1=NC).
  34487 Pin 91..99 = Digital serial audio in/out (A=CDROM, B=EXP, O=OUT).
  34488 
  34489 IC732 - SONY CXD2941R (SPU+CDROM+SPU_RAM) (on PM-41(2) boards)
  34490   1-DA16   23-FILO  45-LOCK  67-FSTO  89-SCSY   111-XCS   133-HD9   155-VSS5
  34491   2-DA15   24-FILI  46-SSTP  68-COUT  90-SCLK   112-XRD   134-HD8   156-HA1
  34492   3-DA14   25-PCO   47-SFDR  69-XDRST 91-SQSO   113-XWR   135-HD7   157-HA0
  34493   4-VDDM0  26-CLTV  48-SRDR  70-DA11  92-SENS   114-HINT  136-HD6   158-VDDM3
  34494   5-DA13   27-AVSSO 49-TFDR  71-DA10  93-DATA   115-XIRQ  137-VDD4  159-XCK
  34495   6-DA12   28-RFAC  50-TRDR  72-DA09  94-XLAT   116-VDDM2 138-HD5   160-DTIB
  34496   7-LRCK   29-BIAS  51-VSSM1 73-DA08  95-CLOK   117-XSCS  139-HD4   161-BCKO
  34497   8-WDCK   30-ASYI  52-FFDA  74-AVSMO 96-XINT   118-XHCS  140-HD3   162-LRCO
  34498   9-VDD0   31-AVDDO 53-FRDA  75-AVDMO 97-A4     119-XHRD  141-HD2   163-DAVDD0
  34499   10-VSS0  32-ASYO  54-MDP   76-DA07  98-A3     120-XHWR  142-VSS4  164-DAREFL
  34500   11-PSSL  33-VC    55-MDS   77-DA06  99-A2     121-DACK  143-HD1   165-AOUTL
  34501   12-ASYE  34-CE    56-VDD2  78-VDDM1 100-A1    122-DREQ  144-HD0   166-DAVSS0
  34502   13-GND   35-CEO   57-VSS2  79-DA05  101-A0    123-XRST  145-VSSM3 167-DAVSS1
  34503   14-C4M   36-CEI   58-MIRR  80-DA04  102-D7    124-VDD3  146-HA9   168-AOUTR
  34504   15-C16M  37-RFDC  59-DFCT  81-DA03  103-D6    125-SYSCK 147-HA8   169-DAREFR
  34505   16-FSOF  38-ADIO  60-AVSM1 82-DA02  104-D5    126-VSS3  148-HA7   170-DAVDD1
  34506   17-XTSL  39-AVDD1 61-AVDM1 83-DA01  105-D4    127-HD15  149-HA6   171-MUTO
  34507   18-VDD1  40-IGEN  62-FOK   84-WFCK  106-VSSM2 128-HD14  150-HA5   172-DATO
  34508   19-GND   41-AVSS1 63-PWMI  85-SCOR  107-D3    129-HD13  151-HA4   173-MTS3
  34509   20-VPCO1 42-TE    64-FSW   86-SBSO  108-D2    130-HD12  152-VDD5  174-MTS2
  34510   21-VPCO2 43-SE    65-MON   87-EXCK  109-D1    131-HD11  153-HA3   175-MTS1
  34511   22-VCTL  44-FE    66-ATSK  88-SQCK  110-D0    132-HD10  154-HA2   176-MTS0
  34512 
  34513 IC732 - SONY CXD2938Q (SPU+CDROM) (on newer boards) (PM-41 boards)
  34514   1-SCLK    27-RFAC  53-TrckR 79-/XINT 105-A0    131-3.5V   157-(tst) 183-A8
  34515   2-GNDed   28-GNDed 54-TrckF 80-SQCK  106-3.5V  132-D9     158-(tst) 184-A7
  34516   3-GNDed   29-CLTV  55-FocuR 81-SQSO  107-A1    133-D8     159-GND   185-A6
  34517   4-SBSO    30-PCO   56-3.5V  82-SENSE 108-A2    134-D7     160-D15   186-A5
  34518   5-WFCK    31-FILI  57-FocuF 83-GND   109-A3    135-D6     161-D0    187-GND
  34519   6-GNDed   32-FILO  58-SledR 84-GND   110-A4    136-D5     162-D14   188-A4
  34520   7-C16M    33-VCTL  59-SledF 85-CD.D7 111-A5    137-3.5V   163-D1    189-A3
  34521   8-3.5V    34-VPC02 60-NC    86-CD.D6 112-3.5V  138-D4     164-D13   190-A2
  34522   9-C4M     35-VPC01 61-GND   87-CD.D5 113-A6    139-D3     165-3.5V  191-A1
  34523   10-GNDed  36-VC    62-NC    88-CD.D4 114-A7    140-D2     166-D2    192-A0
  34524   11-4.3MHz 37-FE    63-GND   89-CD.D3 115-A8    141-D1     167-D12   193-3.5V
  34525   12-12MHz  38-SE    64-(tst) 90-CD.D2 116-A9    142-D0     168-D3    194-NC
  34526   13-V16M   39-TE    65-(tst) 91-CD.D1 117-/IRQ2 143-GND    169-D11   195-(tst)
  34527   14-DOUT   40-CE    66-note  92-CD.D0 118-/IRQ9 144-33MHzS 170-D10   196-GND
  34528   15-LACK   41-CEO   67-note  93-3.5V  119-/RD   145-       171-D4    197-(tst)
  34529   16-WDCK   42-CEI   68-(tst) 94-CD/CS 120-/WR   146-3.48V  172-D9    198-NC
  34530   17-3.5Ved 43-RFDC  69-3.5V  95-CD/WR 121-DMA4  147-ZZ11   173-GND   199-NC
  34531   18-LOCK   44-ADIO  70-(tst) 96-CD/RD 122-GND   148-GND    174-D5    200-NC
  34532   19-GND    45-GND   71-(tst) 97-CD.A0 123-GND   149-GND    175-D8    201-3.5V
  34533   20-MDS    46-IGEN  72-(tst) 98-CD.A1 124-/SPUW 150-ZZ7    176-D6    202-NC
  34534   21-MDP    47-AVD1  73-(tst) 99-CD.A2 125-D15   151-3.48V  177-D7    203-NC
  34535   22-3.5Ved 48-GNDed 74-DATA  100-GND  126-D14   152-/RES   178-/CAS  204-NC
  34536   23-AVDO   49-GNDed 75-XLAT  101-CDA3 127-D13   153-3.5V   179-/WE   205-GND
  34537   24-ASYO   50-GND   76-CLOK  102-CDA4 128-D12   154-ZZ5    180-3.5V  206-(tst)
  34538   25-ASYI   51-GNDed 77-SCOR  103-/CD  129-D11   155-(tst)  181-/OE   207-(tst)
  34539   26-BIAS   52-GNDed 78-GND   104-/SPU 130-D10   156-(tst)  182-/RAS  208-GND
  34540 Pin 74..102 = SubCPU. Pin 103..144 = MainCPU. Pin 160..192 = Sound RAM Bus.
  34541 Pin 21 and 53..59 = Drive Motor Control (IC722).
  34542 Pin 1..47 are probably mainly CDROM related.
  34543 Pin 39 "TE9" = IC723.Pin16 - CL709, and via 15K to SPU.39
  34544 Pin 66 connects via 4K7 to IC723.Pin19.
  34545 Pin 67 not connected (but there's room for an optional capacitor or resistor)
  34546 The (tst) pins are wired to test points (but not connected to any components)
  34547 
  34548 CXD2938Q SPU Pinout Notes
  34549 Pin 74,75,76,119,120 are connected via 22 ohm.
  34550 Pin 103,104 are connected via 100 ohm.
  34551 ZZnn = IC405 Pin nn (analog audio related, L/R/MUTE).
  34552 Pin 103..142 = System Bus (BIOS,CPU). Pin 160..192 = Sound RAM Bus.
  34553 Pin 178 used for both /CASL and /CASH (which are shortcut with each other).
  34554 Pin 146 and 151 are 3.48V (another supply, not 3.5V).
  34555 Pin 147 and 150 are connected via capacitors.
  34556 Pin 195 and 197 testpoints are found below of the pin 206/207 testpoints.
  34557  SPU155 (tst) always low         ;=maybe external audio (serial) this?
  34558  SPU156 (tst) 45kHz  (22us)      ;=probably 44.1kHz (ext audio sample-rate)
  34559  SPU157 (tst) 2777kHz  (0.36us)  ;=probably 64*44.1kHz (ext audio bit-rate)
  34560  SPU158 (tst) always high        ;=maybe external audio (serial) or this?
  34561 SPU.Pin5 connects to MANY modchips
  34562 SPU.Pin42 connects to ALL modchips
  34563 SPU.Pin42 via capacitor to SPU.Pin41, and via resistor?/diode? to IC723.10
  34564 
  34565 CXD2938Q CDROM clocks
  34566   SPU197  (*) 7.35kHz (44.1kHz/6) (stable clock, maybe DESIRED drive speed)
  34567   SPU5    (*) 7.35kHz (44.1kHz/6) (unstable clock, maybe ACTUAL drive speed)
  34568   SPU15   (*) 44.1kHz (44.1kHz*1)
  34569   SPU16   (*) 88.2kHz (44.1kHz*2)
  34570   SPU206  (*) circa 2.27MHz
  34571   SPU70   (*) whatever clock (with SHORT low pulses)
  34572 (*) these frequencies are twice as fast in double speed mode.
  34573 
  34574 CXD2938Q CDROM signals
  34575   SPU207  fastsignal?
  34576   SPU195  slowsignal?
  34577   SPU18   usually high, low during seek or spinup or so
  34578   SPU44   superslow hi/lo with superfast noise on it
  34579   SPU73   mainly LOW with occasional HIGH levels...
  34580   SPU71   LOW=SPIN_OK, PULSE=SPIN_UP/DOWN_OR_STOPPED
  34581   SPU72   similar as SPU71
  34582   SPU64   LOW=STOP, HI=SPIN
  34583   SPU68   always low...?
  34584   SPU65   whatever?
  34585   SPU75   mainly HIGH, short LOW pulses when changing speed up/down/break
  34586 
  34587 CXD2938Q CDROM/SPU Testpoints (on PM-41 board)
  34588                 |                                       | SPU73
  34589                 |          CXD2938Q (SPU)               |       SPU72
  34590                 |          (on PM-41 board)             | SPU70 SPU71
  34591                 |                                       | SPU64 SPU65 SPU68
  34592   SPU206 SPU207 |_______________________________________|
  34593    SPU197
  34594     SPU195                   SPU16                   SPU44
  34595                   SPU18 SPU5 SPU15
  34596                           SPU12
  34597 
  34598 IC402 - 24pin AKM AK4309VM (or AK4309AVM/AK4310VM) - Serial 2x16bit DAC
  34599   1-TST?  4-/PD   7-CKS    10-LRCK  13-NC?    16-AOUTL  19-GNDa  22-VREFH
  34600   2-VCCd  5-/RST  8-BICK   11-NC?   14-NC?    17-VCOM   20-NC?   23-VREFL
  34601   3-GNDd  6-MCLK  9-SDATA  12-NC?   15-AOUTR  18-VCCa   21-NC?   24-DZF?
  34602 Used only on older boards (eg. PU-8), newer boards seem to have the DAC in the
  34603 208pin SPU.
  34604 No 24pin AK4309VM datasheet exists (however it seems to be same as 20pin
  34605 AK4309B's, with four extra NC pins at pin10-14).
  34606 
  34607 IC405 - "2174, 1047C, JRC" or "3527, 0A68" (on newer boards)
  34608 Called "NJM2174" in service manual. Audio Amplifier with Mute.
  34609   1  GND
  34610   2  NC     ? via 100ohm to multiout pin 9    ;Audio Left (white cinch)
  34611   3  OUT-R  ?
  34612   4  MUTE1      ;specified as LOW = Mute
  34613   5  MUTE2      ;specified as HIGH = Mute
  34614   6  MUTEC      ;unspecified, maybe capacitor, or output based on MUTE1+MUTE2?
  34615   7  IN-R     via capacitor to SPU.150
  34616   8  BIAS
  34617   9  NC
  34618   10 NC
  34619   11 IN-L     via capacitor to SPU.147
  34620   12 OUT-L  ?
  34621   13 NC     ? via 100ohm to multiout pin 11   ;Audio Right (red cinch)
  34622   14 VCC      +5.0V (via L401)
  34623 Audio amplifier, for raising the signals to 5V levels.
  34624 
  34625 IC405 - "NJM2100E (TE2)" Audio Amplifier (on older PU-8 and PU-22 boards)
  34626   1-ROUT
  34627   2-RIN- IC732.SPU.150
  34628   3-RIN+
  34629   4-GND
  34630   5-LIN+
  34631   6-LIN- IC732.SPU.147
  34632   7-LOUT
  34633   8-VCC 4.9V (+5.0V via L401)
  34634 
  34635 Pinouts - DRV Pinouts
  34636 ---------------------
  34637 
  34638 IC304 - 52pin/80pin - Motorola HC05 8bit CPU
  34639 --> Pinouts - HC05 Pinouts
  34640 
  34641 IC305 - SONY CXD1815Q - CDROM Decoder/FIFO (used on PU-8, PU-16, PU-18)
  34642   1-D0    14-/XINT 27-/HRD  40-GND   53-VDD   66-/MWR  79-GND   92-LRCO
  34643   2-D1    15-GND   28-VDD   41-HDRQ  54-GND   67-MDB0  80-CLK   93-WCKO
  34644   3-VDD   16-A0    29-GND   42-/HAC  55-MA8   68-MDB1  81-HCLK  94-BCKO
  34645   4-GND   17-A1    30-/HWR  43-MA0   56-MA9   69-MDB2  82-CKSL  95-MUTE
  34646   5-D2    18-A2    31-HD0   44-MA1   57-MA10  70-MDB3  83-RMCK  96-TD7
  34647   6-D3    19-A3    32-HD1   45-MA2   58-MA11  71-MDB4  84-LRCK  97-TD6
  34648   7-D4    20-A4    33-HD2   46-T01   59-MA12  72-MDB5  85-DATA  98-TD5
  34649   8-D5    21-TD0   34-HD3   47-T02   60-MA13  73-MDB6  86-BCLK  99-TD4
  34650   9-D6    22-/HRS  35-HD4   48-MA3   61-MA14  74-MDB7  87-C2PO  100-TD3
  34651   10-D7   23-/HCS  36-HD5   49-MA4   62-MA15  75-MDBP  88-EMP
  34652   11-/CS  24-HA0   37-HD6   50-MA5   63-MA16  76-XTL2  89-/RST
  34653   12-/RD  25-HA1   38-HD7   51-MA6   64-/MOE  77-XTL1  90-GND
  34654   13-/WR  26-HINT  39-HDP   52-MA7   65-GND   78-VDD   91-DATO
  34655 Pin 1..20 to HC05 CPU, pin 22..42 to MIPS cpu, pin 43..75 to SRAM cd-buffer.
  34656 The pinouts/registers in CXD1199AQ datasheet are about 99% same as CXD1815Q.
  34657 Note: Parity on the 8bit data busses is NC. SRAM is 32Kx8 (A15+A16 are NC).
  34658 Later boards have this integrated in the SPU.
  34659 
  34660 ICsss - SONY CXA1782BR - CDROM Servo Amplifier (used on PU-8 boards)
  34661   1-FEO    7-FE_M   13-RA_O  19-CLK    25-FOK   31-RF_O  37-FE_BIAS 43-LPFI
  34662   2-FEI    8-SRCH   14-SL_P  20-XLT    26-CC2   32-RF_M  38-F       44-TEI
  34663   3-FDFCT  9-TGU    15-SL_M  21-DATA   27-CC1   33-LD    39-E       45-ATSC
  34664   4-FGD    10-TG2   16-SL_O  22-XRST   28-CB    34-PD    40-EI      46-TZC
  34665   5-FLB    11-FSET  17-ISET  23-C.OUT  29-CP    35-PD1   41-GND     47-TDFCT
  34666   6-FE_O   12-TA_M  18-VCC   24-SENS   30-RF_I  36-PD2   42-TEO     48-VC
  34667 Datasheet exists. Later boards have CXA1782BR+CXD2510Q integrated in CXD2545Q,
  34668 and even later boards have it integrated in the SPU.
  34669 
  34670 IC309 - SONY CXD2510Q - CDROM Signal Processor (used on PU-8, PU-16 boards)
  34671   1-FOK   11-PDO   21-GNDa 31-WDCK        41-DA09-XPLCK 51-APTL 61-EMPH 71-DATA
  34672   2-FSW   12-GND   22-VLTV 32-LRCK        42-DA08-GFS   52-GND  62-WFCK 72-XLAT
  34673   3-MON   13-TEST0 23-VDDa 33-VDD 5V      43-DA07-RFCK  53-XTAI 63-SCOR 73-VDD
  34674   4-MDP   14-NC    24-RF   34-DA16-SDTA48 44-DA06-C2PO  54-XTAO 64-SBSO 74-CLOK
  34675   5-MDS   15-NC    25-BIAS 35-DA15-SCLK48 45-DA05-XRAOF 55-XTSL 65-EXCK 75-SEIN
  34676   6-LOCK  16-VPCO  26-ASYI 36-DA14-SDTA64 46-DA04-MNT3  56-FSTT 66-SQSO 76-CNIN
  34677   7-NC    17-VCKI  27-ASYO 37-DA13-SCLK64 47-DA03-MNT2  57-FSOF 67-SQCK 77-DATO
  34678   8-VCOO  18-FILO  28-ASYE 38-DA12-LRCK64 48-DA02-MNT1  58-C16M 68-MUTE 78-XLTO
  34679   9-VCOI  19-FILI  29-NC   39-DA11-GTOP   49-DA01-MNT0  59-MD2  69-SENS 79-CLKO
  34680   10-TEST 20-PCO   30-PSSL 40-DA10-XUGF   50-APTR       60-DOUT 70-XRST 80-MIRR
  34681 Datasheet exists. Later boards have CXA1782BR+CXD2510Q integrated in CXD2545Q,
  34682 and even later boards have it integrated in the SPU.
  34683 
  34684 IC701 - SONY CXD2545Q - Signal Processor + Servo Amp (used on PU-18 boards)
  34685   1-SRON  14-TEST 27-TE   40-VDDa        53-DA09-XPLCK 66-FSTI 79-MUTE 92-DFCT
  34686   2-SRDR  15-GND  28-SE   41-VDD         54-DA08-GFS   67-FSTO 80-SENS 93-FOK
  34687   3-SFON  16-TES2 29-FE   42-ASYE        55-DA07-RFCK  68-FSOF 81-XRST 94-FSW
  34688   4-TFDR  17-TES3 30-VC   43-PSSL        56-DA06-C2PO  69-C16M 82-DIRC 95-MON
  34689   5-TRON  18-PDO  31-FILO 44-WDCK        57-DA05-XRAOF 70-MD2  83-SCLK 96-MDP
  34690   6-TRDR  19-VPCO 32-FILI 45-LRCK        58-DA04-MNT3  71-DOUT 84-DFSW 97-MDS
  34691   7-TFON  20-VCKI 33-PCO  46-DA16-SDTA48 59-DA03-MNT2  72-EMPH 85-ATSK 98-LOCK
  34692   8-FFDR  21-VDDa 34-CLTV 47-DA15-SCLK48 60-DA02-MNT1  73-WFCK 86-DATA 99-SSTP
  34693   9-FRON  22-IGEN 35-GNDa 48-DA14-SDTA64 61-DA01-MNT0  74-SCOR 87-XLAT 100-SFDR
  34694   10-FRDR 23-GNDa 36-RFAC 49-DA13-SCLK64 62-XTAI       75-SBSO 88-CLOK
  34695   11-FFON 24-ADIO 37-BIAS 50-DA12-LRCK64 63-XTAO       76-EXCK 89-COUT
  34696   12-VCOO 25-RFC  38-ASYI 51-DA11-GTOP   64-XTSL/GNDed 77-SQSO 90-VDD
  34697   13-VCOI 26-RFDC 39-ASYO 52-DA10-XUGF   65-GND        78-SQCK 91-MIRR
  34698 Datasheet exists. The CXD2545Q combines the functionality of CXA1782BR+CXD2510Q
  34699 from older boards (later boards have it integrated in the SPU). XTAI/XTAO input
  34700 is 16.9344MHz (44.1kHz*180h), with XTSL=GND. Clock outputs are
  34701 FSTO=16.9344MHz/3, FSOF=16.9344MHz/4, C16M=16.9344MHz/1.
  34702 
  34703 IC101 - SONY CXD2515Q - Signal Processor + Servo Amp (used on DTL-H2010)
  34704 Pinouts are same as CXD2545Q, except, three pins are different: Pin24=ADII
  34705 (instead of ADIO), Pin25=ADIO (instead of RFC), Pin68=C4M (instead of FSOF).
  34706 
  34707 IC720 - 144pin SONY CXD1817R  (=CXD2545Q+CXD1815Q)  ;PU-20
  34708   1..48 - unknown
  34709   49 - SCOR
  34710   50..144 - unknown
  34711 
  34712 IC701 - 8pin chip (on bottom side, but NOT installed) (PU-7 and EARLY-PU-8)
  34713   1-8 Unknown (maybe CDROM related, at least it's near other CDROM chips)
  34714 
  34715 IC722 "BA5947FP" or "Panasonic AN8732SB" - IC for Compact Disc Players
  34716 Drive Motor related.
  34717   1 to pin24,27
  34718   2 SPINDLE            - via 15K to SPU21
  34719   3 SW (ON/OFF)        - IC304.27
  34720   4 TRACKING FORWARD
  34721   5 TRACKING REVERSE
  34722   6 FOCUS FORWARD
  34723   7 FOCUS REVERSE
  34724   8 GND                - CN702 pin 11
  34725   9 NC (INTERNAL)      - via C731 (10uF) to GND
  34726   10 +7.5V (Pow VCC ch1,2)
  34727   11 FOCUS COIL (1)    - CN702 pin 15
  34728   12 FOCUS COIL (2)    - CN702 pin 14
  34729   13 TRACKING COIL (1) - CN702 pin 16
  34730   14 TRACKING COIL (2) - CN702 pin 13
  34731   15 SPINDLE MOTOR (1) - CN701 pin 4
  34732   16 SPINDLE MOTOR (2) - CN701 pin 3
  34733   17 SLED MOTOR (1)    - CN701 pin 1
  34734   18 SLED MOTOR (2)    - CN701 pin 2
  34735   19 +7.5V (Pow VCC ch3,4)
  34736   20 MUTE              - /RES (via 5K6)
  34737   21 GND
  34738   22 SLED REVERSE
  34739   23 SLED FORWARD
  34740   24 to pin1
  34741   25 via capacitors to pin1
  34742   26 BIAS 1.75V
  34743   27 to pin1
  34744   28 +7.5V (Pre VCC)
  34745 Additionally to the above 28pins, the chip has two large grounded pins (between
  34746 pin 7/8 and 21/22) for shielding or cooling purposes.
  34747 
  34748 IC703 - 20pin - "SONY CXA1791N" (RF Amplifier) (on PU-18 boards)
  34749   1 LD       O APC amplifier output
  34750   2 PD       I APC amplifier input
  34751   3 PD1      I Input 1 for RF I-V amplifiers
  34752   4 PD2      I Input 2 for RF I-V amplifiers
  34753   5 GND/VEE  - Supply Ground
  34754   6 F        I Input F for I-V amplifier
  34755   7 E        I Input E for I-V amplifier
  34756   8 VR       O DC Voltage Output (VCC+VEE)/2
  34757   9 VC       I Center Voltage Input
  34758   10 NC      - NC
  34759   11 NC      - NC
  34760   12 EO      O Monitoring Output for I-V amplifier E
  34761   13 EI      - Gain Adjust for I-V amplifier E
  34762   14 TE      O Tracking Error Amplifier Output
  34763   15 FE_BIAS I BIAS Adjustment for Focus Error
  34764   16 FE      O Focus Error Amplifier Output
  34765   17 RFO     O RF Amplifier Output
  34766   18 RFI     I RF Amplifier Input
  34767   19 /LD_ON  I APC amplifier ON=GND, OFF=VCC
  34768   20 VCC     - Supply
  34769 Datasheet for CXA1791N does exist. Later boards have IC703 replaced by IC723.
  34770 Older PU-7/PU-8 boards appear to have used a bunch of smaller components (8pin
  34771 chips and/or transistors) instead of 20pin RF amplifiers.
  34772 
  34773 IC723 - 20pin - "SONY CXA2575N-T4" (RF (Matrix?) Amplifier) (PU-22..PM-41(2))
  34774   1-TEIM
  34775   2-TEIG
  34776   3-VEE     GND
  34777   4-E       via 33K to CN702 pin 4
  34778   5-F       via 33K to CN702 pin 8
  34779   6-PD2     via 36K to CN702 pin 6
  34780   7-PD1     via 36K to CN702 pin 7
  34781   8-PD      to CN702 pin 9
  34782   9-LD
  34783   10-VC     CL710, and CN702.Pin3, and via resistor?/diode? to SPU42
  34784   11-LD_ON    IC304.Pin49 "LDON"  ..... XXX or is that Pin 20 "LD_ON" ?
  34785   12-G_CONT                                                        ;or AL/TE?
  34786   13-RF0    CL704, and...
  34787   14-RFM
  34788   15-FE     CL708, and...                 (maybe focus error?)
  34789   16-TE     CL709, and via 15K to SPU.39  (maybe tracking error?)
  34790   17-TE0
  34791   18-COMP+
  34792   19-MIRR   via 4K7 to SPU66
  34793   20-VCC    3.48V (not 3.5V)
  34794 Used only on PU-22 .. PM-41(2) boards (PU-18 boards used IC703 "CXA1791N", and
  34795 even older boards... maybe had this in CXA1782BR... or maybe had it in a bunch
  34796 of 8pin NJMxxxx chips?).
  34797 There is no CXA2575N datasheet (but maybe some signals do resemble
  34798 CXA2570N/CXA2571N/CXA1791N datasheets).
  34799 
  34800 CN702 CDROM Data Signal socket (PU-23 and PM-41 board)
  34801   1-LD     to Q701
  34802   2-VCC    to Q701
  34803   3-VC     to IC723.Pin10 (and CL710)
  34804   4-F-     to IC723.Pin4 (via 33K ohm)
  34805   5-NC     to CL776
  34806   6-PD2    to IC723.Pin6 (via 33K ohm)
  34807   7-PD1    to IC723.Pin7 (via 33K ohm)
  34808   8-E-     to IC723.Pin5 (via 33K ohm)
  34809   9-M1     to IC723.Pin8
  34810   10-VR    via 91 ohm to GND
  34811   11-GND   GND
  34812   12-LS    /POS0 (switch, GNDed when at head is at inner-most position)
  34813   13-FCS+  TRACKING COIL (2)   ;\
  34814   14-TRK+  FOCUS COIL (2)      ; or swapped?
  34815   15-TRK   FOCUS COIL (1)      ;
  34816   16-FCS   TRACKING COIL (1)   ;/
  34817 PU-23 and PM-41 board seem to be using exactly the same Drive, the only
  34818 difference is the length (and folding) of the attached cable.
  34819 
  34820 CN701 CDROM Motor socket (PU-8, PU-18, PU-23, PM-41 boards)
  34821   1-SL-   SLED MOTOR (1)
  34822   2-SL+   SLED MOTOR (2)
  34823   3-SP+   SPINDLE MOTOR (2)
  34824   4-SP-   SPINDLE MOTOR (1)
  34825 
  34826 CLnnn - Calibration Points (PU-23 and PM-41 boards)
  34827   CL616 +7.5V (PM-41 only, not PM-23) (before power switch)
  34828   CL617 GND   (PM-41 only, not PM-23)
  34829   CL316 to IC304 pin 21
  34830   CL704 to IC723.Pin13
  34831   CL706 GND
  34832   CL708 to IC723.Pin15
  34833   CL709 to IC723.Pin16
  34834   CL710 to IC723.Pin10, and CN702.Pin3
  34835   CL711 via 1K to IC723.Pin15
  34836   CL776 to CN702.Pin5
  34837 Probably test points for drive calibration or so.
  34838 
  34839 Pinouts - VCD Pinouts
  34840 ---------------------
  34841 
  34842 SCPH-5903 Video CD PlayStation
  34843 
  34844 VCD Mainboard "PU-16, 1-655-191-11" Component List
  34845 The overall design is very close to LATE-PU-8 boards (1-658-467-2x). Changed
  34846 components are IC102/IC304 (different kernel and cdrom firmware),
  34847 C318/C325/C327 (height reduced capacitors for mounting the daughterboard above
  34848 of them). Plus some extra components: Three triple multiplexors (for switching
  34849 between PSX and VCD audio/video), and the daughterboard connector.
  34850   IC102 44pin SONY, M538032E-02, JAPAN 6465401 (uncommonly big BIOS, 1Mx8)
  34851   IC304 52pin C 4021 SC430924PB (HC05 sub-cpu, with extra Video CD command 1Fh)
  34852   C318   2pin S5        ;\tantalum capacitors with lower height (instead
  34853   C325   2pin CA7       ; of the electrolytic capacitors on PU-8 boards)
  34854   C327   2pin CA7       ;/
  34855   ICnnn 16pin 4053C (Triple multiplexor, for Audio LRCK,BCLK,DATA) (PCB top)
  34856   ICnnn 16pin 4053C (Triple multiplexor, for Video FSC,CSYNC)      (PCB bottom)
  34857   ICnnn 16pin 2283  (Triple multiplexor, for Video R,G,B)          (PCB bottom)
  34858   CNnnn 30pin Connector to daughterboard                           (PCB top)
  34859 
  34860 VCD Daughterboard "MP-45, 1-665-192-11" Component List
  34861   IC102   3pin  TA78M05F voltage regulator (7.5V to 5V) (Toshiba)
  34862   IC104 120pin  CXD1852AQ Video CD decoder (Sony)
  34863   IC106  40pin  MB814260-70 (256Kx16 DRAM) (Fujitsu) ;see also: IC114
  34864   IC107  20pin  6230FV 649 115 (OSD, similar to BU6257AFV-E2) (PCB back)
  34865   IC109  14pin  Y2932 (TLC2932 PLL) (TI) (for RGB.DAC.CLK)
  34866   IC110  44pin  TDA8771AH Triple Video DAC for RGB (Philips) (PCB back)
  34867   IC111  64pin  CXP10224-603R 732A02E (MCU) (Sony)
  34868   IC112  14pin  HCT32A (74HCT32 Quad OR gate) (TI) (PCB back) (for RGB.DAC.CLK)
  34869   IC113   8pin  H74 7H (single D-type flip-flop; OSD clock divider) (PCB back)
  34870   IC114  40pin  MB814260-70 (256Kx16 DRAM) (Fujitsu) ;see also: IC106
  34871   CN101  30pin  Male Connector (to female 30pin socket on PU-16 mainboard)
  34872   X103    2pin  45.00MHz (for VCD decoder chip)
  34873   X104    4pin  12.000MHz (for MCU chip)
  34874   X105    2pin  28.636MHz (for VCD decoder chip) (8*3.579545 NTSC clock)
  34875 
  34876 VCD Daughterboard Connector
  34877                                .--.---.
  34878                          GND  / 1   2 | GND
  34879     (CXD1815Q.86)    CD.BCLK |  3   4 | CD.LRCK    (CXD1815Q.84)
  34880     (CXD1815Q.87)    CD.C2PO |  5   6 | CD.DATA    (CXD1815Q.85)
  34881                          GND |  7   8 | CD.SQCK    (CXD2510Q.67) CXP.31
  34882          (TDA.44) VIDEO.OUTR |  9  10 | CD.SQSO    (CXD2510Q.66) CXP.29
  34883                          GND | 11  12 | SIO.OUT    (HC05.51.PORTF1 to CXP.47)
  34884          (TDA.40) VIDEO.OUTG | 13  14 | SIO.IN     (HC05.50.PORTF0 from CXP.48)
  34885                          GND | 15  16 | SIO.CLK    (HC05.52.PORTF2 to CXP.49)
  34886          (TDA.36) VIDEO.OUTB | 17  18 | VIDEO.FSC  (CXD1852AQ.95)
  34887                          GND | 19  20 | VIDEO.CSYNC(CXD1852AQ.96)
  34888           (PSU.3)       3.5V | 21  22 | 3.5V       (PSU.3)
  34889           (PSU.1)       7.5V | 23  24 | AUDIO.FSXI (CXD1852AQ.103 to VCD)
  34890           (PSU.7)       /RES | 25  26 | AUDIO.DATA (CXD1852AQ.100)
  34891   (CXD1852AQ.102) AUDIO.BCLK | 27  28 | AUDIO.LRCK (CXD1852AQ.101)
  34892                          GND | 29  30 | GND
  34893                              '--------'
  34894 
  34895 IC104 "Sony CXD1852AQ" (MPEG-1 Decoder for Video CD) (120 pin)
  34896    1-GND   16-HD7   31-GND   46-MD4   61-GND   76-G/Y3  91-GND       106-XTL2O
  34897    2-XTL0O 17-MA3   32-MA7   47-MD11  62-/VOE  77-G/Y4  92-HSYNC     107-XTL2I
  34898    3-XTL0I 18-MA4   33-MA8   48-MD3   63-R/Cr0 78-G/Y5  93-VSYNC     108-VDD
  34899    4-VDD   19-MA2   34-/RAS  49-MD12  64-R/Cr1 79-G/Y6  94-FID/FHREF 109-C2PO
  34900    5-HA2   20-MA5   35-/MWE  50-MD2   65-R/Cr2 80-G/Y7  95-CBLNK/FSC 110-LRCI
  34901    6-HA3   21-MA1   36-/CAS2 51-MD13  66-R/Cr3 81-B/Cb0 96-CSYNC     111-DATI
  34902    7-HD0   22-GND   37-/CAS0 52-MD1   67-R/Cr4 82-B/Cb1 97-/SGRST    112-BCKI
  34903    8-HD1   23-MA6   38-MD7   53-MD14  68-R/Cr5 83-B/Cb2 98-CLK0O     113-DOIN
  34904    9-HD2   24-MA0   39-MD8   54-MD0   69-R/Cr6 84-B/Cb3 99-DOUT      114-/HCS
  34905   10-HD3   25-BC    40-MD6   55-MD15  70-R/Cr7 85-B/Cb4 100-DATO     115-/HDT
  34906   11-HD4   26-TCKI  41-MD9   56-OSDEN 71-G/Y0  86-B/Cb5 101-LRCO     116-HRW
  34907   12-HD5   27-TDI   42-MD5   57-OSDB  72-G/Y1  87-B/Cb6 102-BCKO     117-/HIRQ
  34908   13-HD6   28-TENA1 43-MD10  58-OSDG  73-G/Y2  88-B/Cb7 103-FSXI     118-/RST
  34909   14-VDD   29-TDO   44-VDD   59-OSDR  74-VDD   89-DCLK  104-VDD      119-HA0
  34910   15-GND   30-VST   45-GND   60-VDD   75-GND   90-VDD   105-GND      120-HA1
  34911 The Hxxx pins are for the Host (the 8bit CXP CPU), the Mxxx for the RAM chips,
  34912 the R/G/B pins are 24bit RGB video. Pin36 can be /CAS2 or MA9 (and, the VCD
  34913 daughterboard has alternate solderpads for one large RAM instead of two small
  34914 RAMs).
  34915 
  34916 IC107 "6230FV" (OSD chip, similar to BU6257AFV-E2) (20 pin)
  34917    1-SIO.CLK   5-VDD      9-TEST  13-BLK2   17-OSDG
  34918    2-SIO./CS   6-/CKOUT  10-GND   14-VC2    18-OSDB
  34919    3-SIO.DTA   7-OSCOUT  11-BLK1  15-OSDEN  19-/VSYNC
  34920    4-/RESET    8-OSCIN   12-VC1   16-OSDR   20-/HSYNC
  34921 SIO pin1/2/3 are wired to CXP pin38/37/36. OSCIN is the RGB DAC CLK divided by
  34922 two (from H74 chip pin5). OSD/SYNC on pin15-20 connect to the MPEG1 decoder
  34923 chip.
  34924 No datasheet (but pinouts are same/similar as for BU6257AFV, documented in
  34925 several service manuals for tape decks with vcd player: HCD-V5500,
  34926 HCD-V8900/V8900AV, HCD-V909AV).
  34927 
  34928 IC111 "Sony CXP10224-603R" (8bit SPC700 CPU) (64pin LQFP)
  34929    1-PB5=TP    17-PD5=/HCS       33-AVREF=VDD             49-PG5/SCK1=HC05.PF2
  34930    2-PB4=TP    18-PD4=TP         34-AVDD=VDD              50-PG4=/RST.OUT
  34931    3-PB3=HA3   19-PD3=TP         35-PF7/AN7=TP            51-PG3/TO=TP
  34932    4-PB2=HA2   20-PD2=TP         36-PF6/AN6=OSD.DTA       52-PA7=TP
  34933    5-PB1=HA1   21-PD1=TP         37-PF5/AN5=OSD./CS       53-PA6=TP
  34934    6-PB0=HA0   22-PD0=TP         38-PF4/AN4=OSD.CLK       54-PA5=TP
  34935    7-PC7=HD7   23-MP/TEST=GND    39-PF3/AN3=GND           55-PA4=TP
  34936    8-PC6=HD6   24-XTAL=12MHZ     40-PF2/AN2=GND           56-VPP=VDD
  34937    9-PC5=HD5   25-EXTAL=12MHZ    41-PF1/AN1=GND           57-VDD=VDD
  34938   10-PC4=HD4   26-VSS=GND        42-PF0/AN0=10KtoGND      58-VSS=GND
  34939   11-PC3=HD3   27-/RST=/RES      43-PE3/PWM1=TP           59-PA3=TP
  34940   12-PC2=HD2   28-/CS0=VDD       44-PE2/PWM0=TP           60-PA2=TP
  34941   13-PC1=HD1   29-SI0=CD.SQSO    45-PE1/INT2/EC=/VSYNC    61-PA1=TP
  34942   14-PC0=HD0   30-SO0=TP         46-PE0/INT0=/HIRQ        62-PA0=TP
  34943   15-PD7=HRW   31-/SCK0=CD.SQCK  47-PG7/SI1/INT1=HC05.PF1 63-PB7=TP
  34944   16-PD6=/HDT  32-AVSS=GND       48-PG6/SO1=HC05.PF0      64-PB6=TP
  34945 Pin 3-15,45,46,50 connect to MPEG1 decoder. Pin 36-38 to OSD. Pin 47-49 to
  34946 HC05.PortF. Pin 27 is /RESET from PSU. Pin 29,31 are SUBQ from CXD2510Q. The
  34947 "TP" pins connect to test points (but seem to be NC otherwise).
  34948 Pinouts are same as in CXP811P24 datasheet (which uses SPC700 instruction set;
  34949 that instruction set is also used by SNES sound CPU).
  34950 
  34951 IC109 "TLC2932" (PLL) (14pin)
  34952   1-LOGIC_VDD=5V            5-FIN-B=HSYNC.PLL 9-PFD_INHIBIT=GND  13-BIAS
  34953   2-SELECT=5V               6-PFD_OUT         10-VCO_INHIBIT=GND 14-VCO_VDD=5V
  34954   3-VCO_OUT=RGB.DAC.CLK.PLL 7-LOGIC_GND=GND   11-VCO_GND=GND
  34955   4-FIN-A=FID/FHREF.PLL     8-NC              12-VCO_IN
  34956 Used to generate the CLK for the TDA chip (that is, the dotclk, paused during
  34957 VSYNC, or so?). The same CLK, divided by two, is also used as OSD.OSCIN.
  34958 
  34959 IC112 "74HCT32" (Quad OR gate) (14pin)
  34960    1-FID/FHREF.MPEG  4-HSYNC.MPEG   8-(low)  11-RGB.DAC.CLK.TDA  7-GND
  34961    2-FID/FHREF.MPEG  5-HSYNC.MPEG   9-GNDed  12-RGB.DAC.CLK.PLL  14-VCC/5V
  34962    3-FID/FHREF.PLL   6-HSYNC.PLL   10-GNDed  13-RGB.DAC.CLK.PLL
  34963 Used to sharpen the output from the PLL chip, and to level-shift signals for
  34964 the two PLL inputs from 3.5V to 5V. The input-pairs for the OR gates are
  34965 shortcut with each other, so the chip isn't actually ORing anything.
  34966 
  34967 IC113 "H74 7H" (single D-type flip-flop; OSD clock divider) (8 pin)
  34968   1-CLK   2-D   3-/Q   4-GND   5-Q   6-/RES   7-/SET   8-VCC
  34969 Used to divide the RGB DAC CLK by two. CLK comes from TDA.pin31, D and /Q are
  34970 shortcut with each other, /RES and /SET are wired to VDD, and Q goes to
  34971 OSD.OSCIN.
  34972 
  34973 ICnnn "4053C" (Triple multiplexor, for Audio LRCK,BCLK,DATA) (16pin)
  34974   1-IN2B=DATA.VCD   5-IN3A=LRCK.SPU    9-SEL3=LRCK.SEL   13-IN1B=BCLK.VCD
  34975   2-IN2A=DATA.SPU   6-/OE=GNDed       10-SEL2=DATA.SEL   14-OUT1=BCLK.OUT
  34976   3-IN3B=LRCK.VCD   7-VEE=GNDed       11-SEL1=BCLK.SEL   15-OUT2=DATA.OUT
  34977   4-OUT3=LRCK.OUT   8-GND=GND         12-IN1A=BCLK.SPU   16-VDD=VDD/3.5V
  34978 The three SEL pins are wired to HC05.PortF3, the three SPU pins are wired via
  34979 10Kohm.
  34980 
  34981 ICnnn "4053C" (Triple multiplexor, for Video FSC,CSYNC) (16pin)
  34982   1-IN2B=FSC.VCD    5-IN3A=CSYNC.PSX   9-SEL3=CSYNC.SEL  13-IN1B=GNDed
  34983   2-IN2A=FSC.PSX    6-/OE=GNDed       10-SEL2=FSC.SEL    14-OUT1=NCed
  34984   3-IN3B=CSYNC.VCD  7-VEE=GNDed       11-SEL1=DUMMY.SEL  15-OUT2=FSC.OUT
  34985   4-OUT3=CSYNC.OUT  8-GND=GND         12-IN1A=GNDed      16-VDD=VCC/5V
  34986 The three SEL pins are wired to HC05.PortF3, the two OUTx pins are wired via
  34987 2.2Kohm.
  34988 
  34989 ICnnn "NJM2283" (Triple multiplexor, for Video R,G,B) (16pin)
  34990   1-IN1B=R.VCD      5-OUT2=G.OUT       9-IN3B=B.VCD      13-V=VCC/5V
  34991   2-SEL1=R.SEL      6-OUT3=B.OUT      10-GND3=81ohm/GND  14-IN2B=G.VCD
  34992   3-OUT1=R.OUT      7-SEL3=B.SEL      11-IN2A=G.PSX      15-GND1=GND
  34993   4-GND2=GND        8-IN3A=B.PSX      12-SEL2=G.SEL      16-IN1A=R.PSX
  34994 The three SEL pins are wired to HC05.PortF3, the six INxx pins wired through
  34995 resistors and capacitors, the three OUTx pins are wired through capacitors.
  34996 
  34997 Pinouts - HC05 Pinouts
  34998 ----------------------
  34999 
  35000 Motorola HC05 chip versions for PSX cdrom control
  35001   80pin "4246xx" - MC68HC05L16, on-chip ROM (DTL-H120x & old retail consoles)
  35002   80pin "MC68HC705L16CFU" - MC68HC705L16, on-chip ROM (DTL-H100x, and PU-9)
  35003   52pin "SC4309xx" - MC68HC05G6, on-chip ROM (newer retail consoles)
  35004 The early DTL-H2000 devboard is also using a 80pin CPU (with piggyback EPROM
  35005 socket), but that CPU is a Sony CXP82300 SPC700 CPU, not a Motorola HC05 CPU.
  35006 
  35007 IC304 - "C 3060, SC430943PB, G63C 185" (PAL/PSone) - CDROM Controller
  35008 Called "MC68HC05G6PB" in service manual (=8bit CPU).
  35009   1  NC     NC (TEST:DTR/out) (VCD:AVSEL/out)   ;-Port F           ;PortF.Bit3
  35010   2  VDD    3.5V
  35011   3  NC     NC          ;\                                   ;maybe PortE.Bit7?
  35012   4  NC     NC          ; maybe MSBs of Port E               ;maybe PortE.Bit6?
  35013   5  NC     NC          ;/                                   ;maybe PortE.Bit5?
  35014   6  DECA4  SPU102      ;\                                         ;PortE.Bit4
  35015   7  DECA3  SPU101      ; Port E [04h], aka Address/Index          ;PortE.Bit3
  35016   8  DECA2  SPU99       ;                                          ;PortE.Bit2
  35017   9  DECA1  SPU98       ;                                          ;PortE.Bit1
  35018   10 DECA0  SPU97       ;/                                         ;PortE.Bit0
  35019   11 VSS    GND
  35020   12 NDLY   GND     reserved for factory test, should be wired to VDD, not GND?
  35021   13 /RES   /RES (via 5K6)
  35022   14 OSC1   4.3MHz (SPU11)(used as external clock for some modchips)(low volts)
  35023   15 OSC2   NC
  35024   16 F-BIAS         aka FOK=NC (in SCPH-5500)                      ;PortB.Bit0
  35025   17 CG     NC      aka CG=CG (in SCPH-5500)     ;this IS portb.1! ;PortB.Bit1
  35026   18 LMTSW  /POS0 (switch, GNDed when head at inner-most position) ;PortB.Bit2
  35027   19 DOOR   SHELL_OPEN                                             ;PortB.Bit3
  35028   20 TEST2  NC                                                     ;PortB.Bit4
  35029   21 TEST1  to CL316                                               ;PortB.Bit5
  35030   22 COUT               NC                                         ;PortB.Bit6
  35031   23 SENSE  SPU82  ;CXD2510Q.69                                    ;PortB.Bit7
  35032   24 SUBQ   SPU81  ;CXD2510Q.66                                    ;PortC.Bit0
  35033   25 NC     NC     ;NC                                             ;PortC.Bit1
  35034   26 SQCK   SPU80  ;CXD2510Q.67                                    ;PortC.Bit2
  35035   27 SPEED  IC722.Pin3 (SW)                                        ;PortC.Bit3
  35036   28 AL/TE         ;transistor aka MIRROR=.. (in SCPH-5500) ;ISN'T PortB.Bit1 !
  35037   29 ROMSEL        ;NC        aka ROMSEL=SCLK (in SCPH-5500)       ;PortC.Bit5
  35038   30 /XINT  SPU79  ;CXD1815Q.14                                    ;PortC.Bit6
  35039   31 SCOR   SPU77  ;CXD2510Q.63                                    ;PortC.Bit7
  35040   32 VDD    3.5V
  35041   33 DECD0  CD.D0       ;\                                         ;PortA.Bit0
  35042   34 DECD1  CD.D1       ;                                          ;PortA.Bit1
  35043   35 DECD2  CD.D2       ;                                          ;PortA.Bit2
  35044   36 DECD3  CD.D3       ; Port A [00h], aka Data                   ;PortA.Bit3
  35045   37 DECD4  CD.D4       ;                                          ;PortA.Bit4
  35046   38 DECD5  CD.D5       ;                                          ;PortA.Bit5
  35047   39 VSS    GND         ;
  35048   40 DECD6  CD.D6       ;                                          ;PortA.Bit6
  35049   41 DECD7  CD.D7       ;/                                         ;PortA.Bit7
  35050   42 NC     NC                                               ;maybe PortD.Bit0?
  35051   43 DATA   SPU74 (via 22 ohm)                                     ;PortD.Bit1
  35052   44 XLAT   SPU75 (via 22 ohm)                                     ;PortD.Bit2
  35053   45 CLOK   SPU76 (via 22 ohm)                                     ;PortD.Bit3
  35054   46 DECCS  SPU94                                                  ;PortD.Bit4
  35055   47 DECWR  SPU95                                                  ;PortD.Bit5
  35056   48 DECRD  SPU96                                                  ;PortD.Bit6
  35057   49 LDON   IC723.Pin11                                            ;PortD.Bit7
  35058   50 NC     NC (TEST:TX/out)  (VCD:SIO.IN/in)   ;\PortF (used by   ;PortF.Bit0
  35059   51 NC     NC (TEST:RX/in)   (VCD:SIO.OUT/out) ; Motorola Testmode;PortF.Bit1
  35060   52 NC     NC (TEST:RTS/out) (VCD:SIO.CLK/out) ;/and VCD version) ;PortF.Bit2
  35061 This chip isn't connected directly to the CPU, but rather to a Fifo Interface,
  35062 which is then forwarding data to/from the CPU. On older PSX boards, that Fifo
  35063 Interface has been located in a separate chip, on newer PSX boards and PSone
  35064 boards, the Fifo stuff is contained in the SPU chip. The CDROM has a 32K
  35065 buffer, which is also implemeted at the Fifo Interface side.
  35066 OSC input (internally HC05 is running at OSC/2, ie. around 2MHz):
  35067   PU-8      4.0000MHz from separate 4.000MHz oscillator (X302)
  35068   PU-16     4.0000MHz from separate 4.000MHz oscillator (X302)
  35069   DTL-H2000 4.1900MHz from separate 4.1900MHz oscillator (SPC700, not HC05)
  35070   PU-18     4.2336MHz from CXD2545Q.pin68 (Servo+Signal) (FSOF=16.9344MHz/4)
  35071   PU-20     4.2xxxMHz from CXD1817R.pin?  (Servo+Signal+Decoder)
  35072   PM-41     4.2xxxMHz from CXD2938Q.pin11 (Servo+Signal+Decoder+SPU)
  35073 
  35074 HC05 - 80pin version (pinout from MC68HC05L16 datasheet)
  35075   1 VDD
  35076   2 FP28/PE6    ;\
  35077   3 FP29/PE5    ;
  35078   4 FP30/PE4    ;
  35079   5 FP31/PE3    ; Port E LSBs
  35080   6 FP32/PE2    ;
  35081   7 FP33/PE1    ;
  35082   8 FP34/PE0    ;/
  35083   9 FP35/PD7    ;\
  35084   10 FP36/PD6   ; Port D MSBs
  35085   11 FP37/PD5   ;
  35086   12 FP38/PD4   ;/
  35087   13 VLCD3
  35088   14 VLCD2
  35089   15 VLCD1
  35090   16 VSS
  35091   17 NDLY
  35092   18 XOSC1
  35093   19 XOSC2
  35094   20 /RESET
  35095   ---
  35096   21 OSC1
  35097   22 OSC2
  35098   23 PA0        ;\
  35099   24 PA1        ;
  35100   25 PA2        ;
  35101   26 PA3        ; Port A
  35102   27 PA4        ;
  35103   28 PA5        ;
  35104   29 PA6        ;
  35105   30 PA7        ;/
  35106   31 PB0/KWI0   ;\
  35107   32 PB1/KWI1   ;
  35108   33 PB2/KWI2   ;
  35109   34 PB3/KWI3   ; Port B
  35110   35 PB4/KWI4   ;
  35111   36 PB5/KWI5   ;
  35112   37 PB6/KWI6   ;
  35113   38 PB7/KWI7   ;/
  35114   39 PC0/SDI    ;\
  35115   40 PC1/SDO    ;
  35116   ---           ;
  35117   41 PC2/SCK    ; Port C
  35118   42 PC3/TCAP   ;
  35119   43 PC4/EVI    ;
  35120   44 PC5/EVO    ;
  35121   45 PC6/IRQ2   ;
  35122   46 PC7/IRQ1   ;/
  35123   47 VDD
  35124   48 BP3/PD3            ;\
  35125   49 BP2/PD2            ; Port D LSBs
  35126   50 BP1/PD1            ;
  35127   51 BP0 (no "PD0")     ;/
  35128   52 FP0
  35129   53 FP1
  35130   54 FP2
  35131   55 FP3
  35132   56 FP4
  35133   57 FP5
  35134   58 FP6
  35135   59 FP7
  35136   60 VSS
  35137   ---
  35138   61 FP8
  35139   62 FP9
  35140   63 FP10
  35141   64 FP11
  35142   65 FP12
  35143   66 FP13
  35144   67 FP14
  35145   68 FP15
  35146   69 FP16
  35147   70 FP17
  35148   71 FP18
  35149   72 FP19
  35150   73 FP20
  35151   74 FP21
  35152   75 FP22
  35153   76 FP23
  35154   77 FP24
  35155   78 FP25
  35156   79 FP26
  35157   80 FP27/PE7   ;- Port E MSB
  35158 
  35159 HC05 - 32pin/64pin Versions
  35160 Sony's Digital Joypad and Mouse contain 32pin CPUs, which are probably also
  35161 HC05's:
  35162 --> Pinouts - Component List and Chipset Pin-Outs for Digital Joypad, SCPH-1080
  35163 Moreover, some old memory cards contain a 64pin Motorola SC419510FU (probably
  35164 also a HC05) with separate Atmel AT29LV010A (128Kx8 FLASH).
  35165 
  35166 Pinouts - MEM Pinouts
  35167 ---------------------
  35168 
  35169 IC102 - BIOS ROM (32pin, 512Kx8, used on LATE-PU-8 boards, and newer boards)
  35170   1-A19  5-A7  9-A3   13-D0   17-D3  21-D7   25-A11  29-A14
  35171   2-A16  6-A6  10-A2  14-D1   18-D4  22-/CE  26-A9   30-A17     ;/CE=/BIOS
  35172   3-A15  7-A5  11-A1  15-D2   19-D5  23-A10  27-A8   31-A18
  35173   4-A12  8-A4  12-A0  16-GND  20-D6  24-/OE  28-A13  32-3.5V    ;/OE=/RD
  35174 Uses standard EPROM pinouts, VCC is 3.5V though, when replacing the ROM by an
  35175 EPROM, it may be required to replace the supply by 5V. Note that, on PM-41
  35176 boards at least, Pin 1 is connected to A19 (allowing to install a 1MB BIOS chip
  35177 on that board, however, normally, a 512KB BIOS chip is installed, and, the CPU
  35178 is generating an exception when trying to access more than 512KB, but that 512K
  35179 limit can be disabled via memory control registers).
  35180 Datasheet for (MS-)M534031E does exist.
  35181 
  35182 IC102 - BIOS ROM (40pin, 512Kx8, used on PU-7 boards, and EARLY-PU-8 boards)
  35183   1-A18  6-A4   11-GND   16-D9   21-VCC  26-D6      31-GND(/BYTE) 36-A13
  35184   2-A8   7-A3   12-/OE   17-D2   22-D4   27-D14     32-A17        37-A12
  35185   3-A7   8-A2   13-D0    18-D10  23-D12  28-D7      33-A16        38-A11
  35186   4-A6   9-A1   14-D8    19-D3   24-D5   29-A0(D15) 34-A15        39-A10
  35187   5-A5   10-/CS 15-D1    20-D11  25-D13  30-GND     35-A14        40-A9
  35188 The chip supports 8bit/16bit mode, on the PSX D0-D14 are actually wired, but
  35189 A0/D15 is wired to A0, and /BYTE is wired to GND, so 16bit mode doesn't work.
  35190 Datasheet for MX23L4100 does exist.
  35191 
  35192 IC102 - BIOS ROM (44pin, 1Mx8, used on P16-boards, ie. VCD console)
  35193   1-NC  5-A7 9-A3   13-GND 17-D1  21-D3  25-D12 29-D14    33-/BYT 37-A14 41-A10
  35194   2-A19 6-A6 10-A2  14-/OE 18-D9  22-D11 26-D5  30-D7     34-A17  38-A13 42-A9
  35195   3-A18 7-A5 11-A1  15-D0  19-D2  23-VCC 27-D13 31-D15/A0 35-A16  39-A12 43-NC
  35196   4-A8  8-A4 12-/CE 16-D8  20-D10 24-D4  28-D6  32-GND    36-A15  40-A11 44-NC
  35197 Pinouts are from OKI MSM538032E datasheet.
  35198 
  35199 IC106 - CPU-RAM (single 70pin chip, on newer boards)
  35200 "Samsung K4Q153212M-JC60" (70pin, 512Kx32) (newer boards)
  35201 "Toshiba T7X16" (70pin, 512Kx32) (newer boards, too)
  35202   1-VCC   11-N.C   21-DQ15  31-A3   41-N.C   51-DQ17  61-DQ24
  35203   2-DQ0   12-VCC   22-N.C   32-A4   42-N.C   52-DQ18  62-DQ25
  35204   3-DQ1   13-DQ8   23-N.C!  33-A5   43-/OE   53-DQ19  63-DQ26
  35205   4-DQ2   14-DQ9   24-N.C   34-A6   44-/W    54-VSS   64-DQ27
  35206   5-DQ3   15-DQ10  25-N.C   35-VCC  45-/CAS3 55-DQ20  65-VSS
  35207   6-VCC   16-DQ11  26-N.C   36-VSS  46-/CAS2 56-DQ21  66-DQ28
  35208   7-DQ4   17-VCC   27-/RAS  37-A7   47-/CAS1 57-DQ22  67-DQ29
  35209   8-DQ5   18-DQ12  28-A0    38-A8   48-/CAS0 58-DQ23  68-DQ30
  35210   9-DQ6   19-DQ13  29-A1    39-A9   49-N.C   59-VSS   69-DQ31
  35211   10-DQ7  20-DQ14  30-A2    40-N.C  50-DQ16  60-N.C   70-VSS
  35212 Notes: Pin23 must NC or VSS. In the PSone, /OE is wired to GND.
  35213 Datasheet for K4Q153212M-JC60 does exist (the chip supports 27ns Hyper Page
  35214 mode access, which seems to be used for DMA).
  35215 The RAM chip comes up without external /REFRESH signal, but maybe the CPU does
  35216 tweak RAS/CAS to generate refresh (the CPU has some odd delays once and when).
  35217 
  35218 IC106/IC107/IC108/IC109 - CPU-RAM (four 28pin chips, on PU-8, PU-18 boards)
  35219 SEC KM48V514BJ-6 (DRAM 512Kx8) (four pieces = 512Kx32 = 2Mbyte)
  35220   1-VCC  5-DQ3   9-A9     13-A3     17-A5  21-NC    25-DQ5
  35221   2-DQ0  6-NC    10-A0    14-VCC    18-A6  22-/OE   26-DQ6
  35222   3-DQ1  7-/W    11-A1    15-GND    19-A7  23-/CAS  27-DQ7
  35223   4-DQ2  8-/RAS  12-A2    16-A4     20-A8  24-DQ4   28-GND
  35224 Datasheet for KM48V514B-6 and BL-6 exist (though none for BJ-6). The chips
  35225 support 25ns Hyper Page mode access.
  35226 
  35227 IC310 - SPU-RAM (512Kbyte)
  35228 EliteMT M11B416256A-35J (256K x 16bit) (40pin SOJ, PM-41 boards)
  35229 Nippon Steel NN514256ALTT-50 (256K x 16bit) (40pin TSOP-II, PU-23 boards)
  35230 Toshiba TC51V4260DJ-70 (40pin, PU-8 board) (PseudoSRAM)
  35231   1-5.0V  6-5.0V   11-NC   16-A0    21-VSS  26-A8    31-I/O8   36-I/O12
  35232   2-I/O0  7-I/O4   12-NC   17-A1    22-A4   27-/OE   32-I/O9   37-I/O13
  35233   3-I/O1  8-I/O5   13-/WE  18-A2    23-A5   28-/CASH 33-I/O10  38-I/O14
  35234   4-I/O2  9-I/O6   14-/RAS 19-A3    24-A6   29-/CASL 34-I/O11  39-I/O15
  35235   5-I/O3  10-I/O7  15-NC   20-5.0V  25-A7   30-NC    35-VSS    40-VSS
  35236 Note: SPU-RAM supply can be 3.5V (PU-8), or 5.0V (PU-22 and PM-41).
  35237 Note: The /CASL and /CASH pins are shortcut with each other on the mainboard,
  35238 both wired to the /CAS pin of the SPU (ie. always accessing 16bit data at
  35239 once).
  35240 Note: The TSOP-II package (18mm length, super-flat and with spacing between pin
  35241 10/11 and 30/31) is used on PU-23 boards. The pinouts and connections are
  35242 identical for SOJ and TSOP-II.
  35243 Note: Nippon Steels NN514256-series is normally 256Kx4bit, nethertheless, for
  35244 some bizarre reason, their 256Kx16bit chip is marked "NN514256ALTT"... maybe
  35245 that happened accidently in the manufacturing process.
  35246 Note: The PM-41(2) board has on-chip RAM in the SPU (no external memory chip).
  35247 
  35248 IC303 - CDROM Buffer (32Kbyte)
  35249 "HM62W256LFP-7T" (SRAM 32Kx8) (PCB bottom side) (PU-8)
  35250 "SONY CXK5V8257BTM" 32Kx8 SRAM (PU-18)
  35251   1-A14  4-A6  7-A3  10-A0  13-D2   16-D4  19-D7   22-/OE  25-A8   28-VCC
  35252   2-A12  5-A5  8-A2  11-D0  14-GND  17-D5  20-/CS  23-A11  26-A13
  35253   3-A7   6-A4  9-A1  12-D1  15-D3   18-D6  21-A10  24-A9   27-/WE
  35254 Used only on older boards (eg. PU-8, PU-18), newer boards seem to have that RAM
  35255 included in the 208pin SPU chip.
  35256 
  35257 IC201 - GPU-RAM (1MByte) (or 2MByte, of which, only 1MByte is used though)
  35258 Samsung KM4132G271BQ-10 (128K x 32bit x 2 Banks, Synchronous Graphic RAM) 1MB
  35259 Samsung K4G163222A-PC70 (256K x 32bit x 2 Banks, Synchronous Graphic RAM) 2MB
  35260   1-DQ3   13-DQ19  25-/WE     37-N.C 49-A6    61-DQ9   73-VDDQ  85-VSS  97-DQ0
  35261   2-VDDQ  14-VDDQ  26-/CAS    38-N.C 50-A7    62-VSSQ  74-DQ24  86-N.C  98-DQ1
  35262   3-DQ4   15-VDD   27-/RAS    39-N.C 51-A8    63-DQ10  75-DQ25  87-N.C  99-VSSQ
  35263   4-DQ5   16-VSS   28-/CS     40-N.C 52-N.C   64-DQ11  76-VSSQ  88-N.C  100-DQ2
  35264   5-VSSQ  17-DQ20  29-A9(BA)  41-N.C 53-DSF   65-VDD   77-DQ26  89-N.C
  35265   6-DQ6   18-DQ21  30-NC(GND) 42-N.C 54-CKE   66-VSS   78-DQ27  90-N.C
  35266   7-DQ7   19-VSSQ  31-A0      43-N.C 55-CLK   67-VDDQ  79-VDDQ  91-N.C
  35267   8-VDDQ  20-DQ22  32-A1      44-N.C 56-DQM1  68-DQ12  80-DQ28  92-N.C
  35268   9-DQ16  21-DQ23  33-A2      45-N.C 57-DQM3  69-DQ13  81-DQ29  93-N.C
  35269   10-DQ17 22-VDDQ  34-A3      46-VSS 58-NC    70-VSSQ  82-VSSQ  94-N.C
  35270   11-VSSQ 23-DQM0  35-VDD     47-A4  59-VDDQ  71-DQ14  83-DQ30  95-N.C
  35271   12-DQ18 24-DQM2  36-N.C     48-A5  60-DQ8   72-DQ15  84-DQ31  96-VDD
  35272 Newer boards often have 2MB VRAM installed (of which only 1MB is used,
  35273 apparently the 2MB chips became cheaper than the 1MB chips). At the chip side,
  35274 the only difference is that Pin30 became an additional address line (that,
  35275 called A8, and, accordingly, the old A8,A9 pins were renamed to A9,A10). At the
  35276 mainboard side, the connection is exactly the same for both 1MB and 2MB chips;
  35277 Pin30 is grounded on both PU-23 boards (which typically have 1MB) and PM-41
  35278 boards (which typically have 2MB).
  35279 Note: The PM-41(2) board has on-chip RAM in the GPU (no external memory chip).
  35280 
  35281 Pinouts - CLK Pinouts
  35282 ---------------------
  35283 
  35284 The "should-be" CPU clock is 33.868800 Hz (ie. the 44100Hz CDROM/Audio clock,
  35285 multiplied by 300h). However, the different PSX/PSone boards are using
  35286 different oscillators, multipliers and dividers, which aren't exactly reaching
  35287 that "should-be" value. The PSone are using a single oscillator for producing
  35288 CPU/GPU clocks, and for producing the TV/color signal:
  35289   For PAL,  Fsc=4.43361875MHz (5^6*283.75Hz+25Hz) --> 4*Fsc=17.734MHz
  35290   For NTSC, Fsc=3.579545MHz   (4.5*455/572 MHz)   --> 4*Fsc=14.318MHz
  35291 
  35292 PSone/PAL - IC204 8pin - "CY2081, SL-509" or "2294A, 1913"
  35293 Clock Multiplier/Divider
  35294   1 53MHz          ;17.734MHz*3 = 53.202 MHz (?)
  35295   2 GND
  35296   3 X1 17.734MHz
  35297   4 X2 17.734MHz
  35298   5 67MHz          ;17.734MHz*3*2*7/11 = 67.711636 MHz (?)
  35299   6 4.4Mhz         ;17.734MHz/4 = 4.4335MHz  (?)  ;via 2K2 to IC502.pin15
  35300   7 3.5V
  35301   8 3.5V
  35302 
  35303 PSone/NTSC - IC204 8pin "CY2081 SL-500" (PSone, and PSX/PU-20 and up)
  35304 Unknown. Uses a 14.318MHz oscillator, so multiply/divide factors must be
  35305 somehow different.
  35306    3*3*7*5/2/11 = 14.3181818
  35307    3*3*7*7*100  = 44100
  35308 The "optimal" conversion would be (hardware is barely able to do that):
  35309    14.3181818 * 3*7*11*64 / (5*5*5*5*5) = 67.737600
  35310 So, maybe it's doing
  35311    14.3181818 * 2*2*13/11   ... or so?
  35312 
  35313 PSX/PAL
  35314 PU-7 and PU-8 boards are using three separate oscillators:
  35315   X101: 67.737MHz (div2 = CPU Clock = 33.8685MHz) (div600h = 44.1kHz audio)
  35316   X201: 53.20MHz (GPU Clock) (div12 = PAL color clock)
  35317   X302: 4.000MHz (for CDROM SUB CPU)
  35318 PU-18 does have same X101/X201 as above, but doesn't seem to have X302.
  35319 
  35320 PSX/NTSC
  35321 PU-7 and PU-8 boards are using three separate oscillators:
  35322   X101: 67.737MHz (div2 = CPU Clock = 33.8685MHz) (div600h = 44.1kHz audio)
  35323   X201: 53.69MHz (GPU Clock) (div15 = NTSC color clock)
  35324   X302: 4.000MHz (for CDROM SUB CPU)
  35325 PU-20 works more like PSone (a single oscillator, and CY2081 SL-500 divider)
  35326 
  35327 Pinouts - PWR Pinouts
  35328 ---------------------
  35329 
  35330 Voltage Summary
  35331   +7.5V  Used to generate other voltages and CDROM/Joypad/MemoryCard/Expansion
  35332   +5.0V  Used for Multiout, IC405, and IC502, and IC602
  35333   +3.5V  Used for most ICs, and for Joypad/MemoryCard/Expansion
  35334   +3.48V Used for SPU and CDROM
  35335   GND    Ground, shared for all voltages
  35336 
  35337 Fuses
  35338 There are a lot of SMD elements marked FBnnn, these are NOT fuses (at least
  35339 they don't seem to blow-up whatever you do). The actual fuses are marked PSnnn,
  35340 found near the power switch and near the power socket.
  35341 
  35342 IC601 3pin   +5.0V   "78M05, RZ125, (ON)"
  35343   1 +7.5V
  35344   2 GND
  35345   3 +5.0V   (used for Multiout, IC405, and IC502)
  35346 
  35347 IC602 - Audio/CDROM Supply
  35348 Called "LP29851MX-3.5" in service manual.
  35349   1 VIN    5.0V (in)
  35350   2 GND    GND
  35351   3 ON/OFF 5.0V (in)
  35352   4 NOISE  ?
  35353   5 VOUT   3.48V (out)
  35354 
  35355 IC002/IC003 - Reset Generator (PM-41 board)
  35356   IC002  IC003  Expl.
  35357   2      2      connected to Q002 (reset input?)
  35358   5      5      connected via capacitor to GND
  35359   6      1      reset-output (IC002=wired to /RES, IC003: via Q004 to /RES)
  35360   7      -      7.5V
  35361   4      3      GND
  35362   1,3,8  4      NC
  35363 /RES is connected via 330 ohm to GPU/CPU, and via 5K6 SPU/IC722/IC304.
  35364 Note: Either IC002 or IC003/Q004 can be installed on PM-41 boards. Most or all
  35365 boards seem to contain IC003/Q004.
  35366 Note: PSX consoles have something similar on the Power Supply boards (IC101:
  35367 M51957B).
  35368 
  35369 IC606/IC607 - TL594CD - Pulse-Width-Modulation Power-Control Chip
  35370   1 1IN+
  35371   2 1IN-
  35372   3 FEEDBACK
  35373   4 DTC
  35374   5 CT
  35375   6 RT
  35376   7 GND
  35377   8 C1
  35378   9  E1
  35379   10 E2
  35380   11 C2
  35381   12 VCC
  35382   13 OUTPUT CTRL
  35383   14 REF
  35384   15 2IN-
  35385   16 2IN+
  35386 
  35387 Q602
  35388   x +7.5V
  35389   y +3.5V
  35390   z REG
  35391 
  35392 CN602 - PU-8, PU-9 board Power Socket (to internal power supply board)
  35393   1 Brown   7.5V (actually 7.69V)
  35394   2 Red     GND  Ground
  35395   3 Orange  3.5V (actually 3.48V)
  35396   4 Yellow  GND  Ground
  35397   5 White   STAND-BY (3.54V, always ON, even if power switch is off)
  35398   6 Blue    GND  Ground
  35399   7 Magenta /RES Reset input (from power-on logic and reset button)
  35400 Purpose of the standy-by voltage is unknown... maybe to expansion port?
  35401 
  35402 CN602 - PU-18, PU-23 board Power Socket (to internal power supply board)
  35403   1 Brown   7.5V (actually 7.92V or so) (ie. higher than in PSone)
  35404   2 Red     GND  Ground
  35405   3 Orange  3.5V (actually 3.53V or so) (ie. quite same as PSone)
  35406   4 Yellow  GND  Ground
  35407   5 White   /RES Reset input (from power-on logic and reset button)
  35408 
  35409 CN102 - Controller/memory card daughter-board connector (PU-23 board)
  35410   1 /IRQ10 (/IRQ10)
  35411   2 /ACK (/IRQ7)
  35412   3 /JOY2
  35413   4 7.5V (or actually 7.92V)
  35414   5 /JOY1
  35415   6 DAT
  35416   7 GND
  35417   8 CMD
  35418   9 3.5V
  35419   10 CLK
  35420 
  35421 Pinouts - Component List and Chipset Pin-Outs for Digital Joypad, SCPH-1080
  35422 ---------------------------------------------------------------------------
  35423 
  35424 Digital Joypad Component List (SCPH-1080)
  35425   Case: "SONY, CONTROLLER, Sony Computer Entertainment Inc. H"
  35426   Case: "SCPH-1080 Made in China"
  35427   PCB: "CMK-PIHB /\, CFS8121-200010-01"
  35428   U?: 32pin "(M), SC401800, FB C37B, JSJD520C" (Motorola) (TQFP-32 package)
  35429   U?: 14pin "BA10339F, 528 293" (Quad Comparator) (/ACK,JOYDAT,and reset or so)
  35430   X?:  3pin "4.00G1f" (on PCB bottom side)
  35431   Z1:  2pin z-diode or so (on PCB bottom side) (+1.7V VREF for BA10339F)
  35432   CN?: 7pin cable to controller port (plus shield; but not connected to PCB)
  35433   C1   2pin   to GND and R5
  35434   C2   2pin capacitor for power supply input (between +3.5V and GND)
  35435   C3   2pin   between BA.pin8 and (via R6) BA.pin15
  35436   R1   2pin 1M ohm (for X1)
  35437   R2   2pin 2.7K
  35438   R3   2pin 8xK ohm?
  35439   R4   2pin 100K
  35440   R5   2pin 22K ohm
  35441   R6   2pin 56K ohm
  35442   RN1  8pin 4x200 ohm (/JOYn,JOYCMD,JOYCLK)
  35443   RN2  8pin 4x22K ohm (pull-ups for button bit0..3)
  35444   RN3  8pin 4x22K ohm (pull-ups for button bit12..15)
  35445   RN4  8pin 4x22K ohm (pull-ups for button bit8..11)
  35446   RN5  8pin 4x22K ohm (pull-ups for button bit4..7)
  35447 
  35448 Digital Joypad Connection Cable:
  35449   PSX.1 -------brown---- PAD.2 JOYDAT
  35450   PSX.2 -------orange--- PAD.6 JOYCMD
  35451   PSX.3 ---              NC    +7.5V
  35452   PSX.4 -------black---- PAD.3 GND
  35453   PSX.5 -------red------ PAD.4 +3.5V
  35454   PSX.6 -------yellow--- PAD.5 /JOYn
  35455   PSX.7 -------blue----- PAD.7 JOYCLK
  35456   PSX.8 ---              NC    /IRQ10
  35457   PSX.9 -------green---- PAD.1 /ACK
  35458   PSX.Shield --shield--- NC    (cable is shielded but isn't connected in
  35459 joypad)
  35460 
  35461 Digital Joypad 32pin SC401800 Chip Pin-Outs
  35462   1 Bit14 SW-X
  35463   2 Bit13 SW-O
  35464   3 Bit12 SW-/\
  35465   4 Bit11 SW-R1 (via cable pin1, white wire)
  35466   5 Bit10 SW-L1 (via cable pin1, white wire)
  35467   6 Bit9  SW-R2 (via cable pin3, black wire)
  35468   7 Bit8  SW-L2 (via cable pin3, black wire)
  35469   8 via BA10339F.pin7 to cn.2 JOYDAT (PSX.1)
  35470   ---
  35471   9  via RN1 (200 ohm) to cn.5 /JOYn  (PSX.6)
  35472   10 via RN1 (200 ohm) to cn.6 JOYCMD (PSX.2)
  35473   11 via RN1 (200 ohm) to cn.7 JOYCLK (PSX.7)
  35474   12 GND to cn.3 (PSX.4)
  35475   13 Bit7 SW-LEFT
  35476   14 Bit6 SW-DOWN
  35477   15 Bit5 SW-RIGHT
  35478   16 via BA10339F.pin5 to cn.1 /ACK (PSX.9)
  35479   ---
  35480   17 Bit4 SW-UP
  35481   18 Bit3 SW-START
  35482   19 Bit2 (HI) (would be R3 on Analog Pads) ;\unused, but working button inputs
  35483   20 Bit1 (HI) (would be L3 on Analog Pads) ;/(each fitted with a RN2 pullup)
  35484   21 Bit0 SW-SELECT
  35485   22
  35486   23
  35487   24 wired to SC401800.pin25
  35488   ---
  35489   25 wired to SC401800.pin24
  35490   26 4.00MHz'a
  35491   27 4.00MHz'b
  35492   28 +3.5V to cn.4 (PSX.5)
  35493   29 wired to SC401800.pin32, and via 22K ohm to +3.5V, and to BA.14
  35494   30
  35495   31 Bit15 SW-[]
  35496   32 wired to SC401800.pin29
  35497 
  35498 Digital Joypad 14pin BA10339F Chip Pin-Outs
  35499   1 OUT2  CN.2 JOYDAT (PSX.1)
  35500   2 OUT1  CN.1 /ACK (PSX.9)
  35501   3 VCC   +3.5V
  35502   4 -IN1  +1.7V VREF via Z1 to GND
  35503   5 +IN1  CXD.16 /ACK
  35504   6 -IN2  +1.7V VREF via Z1 to GND
  35505   7 +IN2  CXD.8  JOYDAT
  35506   ---
  35507   8 -IN3  +1.7V VREF via Z1 to GND
  35508   9 +IN3      C3,R3,R4
  35509   10 -IN4     C1 to +3.5V
  35510   11 +IN4 GND
  35511   12 GND  GND
  35512   13 OUT4     NC ??
  35513   14 OUT3 CXD.29/32
  35514 
  35515 Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-1150
  35516 --------------------------------------------------------------------------
  35517 
  35518 This applies for two controller versions:
  35519   SCPH-1150 Analog Pad with Single Rumble Motor (japan only)
  35520   SCPH-1180 Analog Pad without Rumble Motor
  35521 Both are using the same PCB, and the same SD657 chip. The difference is that
  35522 the motor, transistors, and some resistors aren't installed in SCPH-1180.
  35523 
  35524 Analog Joypad Component List (SCPH-1150, single motor)
  35525   Case "SONY, ANALOG, CONTROLLER, SonyCompEntInc. A, SCPH-1150 MADE IN CHINA"
  35526   PCB1 "DD1P09A" (mainboard with digital buttons)
  35527   PCB2 "DD1Q14A" (daughterboard with analog joysticks)
  35528   PCB3 "DD1Q15A-R" (daughterboard with R-1, R-2 buttons) (J3)
  35529   PCB4 "DD1Q15A-L" (daughterboard with L-1, L-2 buttons) (J2)
  35530   U1  42pin "SD657, 9702K3006"   (2x21pins, L=17.8mm, W=7mm, W+Pins=11mm)
  35531   U2   3pin "DR, 4.Z"
  35532   Q1   3pin "BQ03" or so (motor post-amp)
  35533   Q2   3pin "S6","SG","9S" or so (motor pre-amp)
  35534   Y1   3pin "400CMA"
  35535   CN1  8pin cable to PSX controller port
  35536   CN2  8pin ribbon cable to analog-joystick daughterboard (not so robust cable)
  35537   J1   2pin wires to rumble motor (in left handle) (digital, on/off)
  35538   J2   3pin ribbon cable to L-1, L-2 button daughterboard
  35539   J3   3pin ribbon cable to R-1, R-2 button daughterboard
  35540   LED1 4pin red/green LED (optics without mirror)
  35541   D1,D2 diodes
  35542   plus resistors/capacitors
  35543 
  35544 Analog Joypad Connection Cables (SCPH-1150)
  35545 CN1 (cable to PSX controller port) (same for SCPH-1150 and SCPH-1200)
  35546   PSX.1 -------brown---- PAD.2 JOYDAT
  35547   PSX.2 -------orange--- PAD.6 JOYCMD
  35548   PSX.3 -------magenta-- PAD.8 +7.5V
  35549   PSX.4 -------black---- PAD.3 GND
  35550   PSX.5 -------red------ PAD.4 +3.5V
  35551   PSX.6 -------yellow--- PAD.5 /JOYn
  35552   PSX.7 -------blue----- PAD.7 JOYCLK
  35553   PSX.8 ---              NC    /IRQ10
  35554   PSX.9 -------green---- PAD.1 /ACK
  35555   PSX.Shield --shield--- NC    (cable is shielded but isn't connected in
  35556 joypad)
  35557 CN2 (ribbon cable to analog-joystick daughterboard) (SCPH-1150)
  35558   8 +3.5V to POT pins
  35559   7 Button L3 pins A,C
  35560   6 GND to POT pins and Button L3/R3 pins B,D
  35561   5 Button R3 pins A,C
  35562   4 Axis R_Y middle POT pin (SD657.18)
  35563   3 Axis R_X middle POT pin (SD657.17)
  35564   2 Axis L_Y middle POT pin (SD657.16)
  35565   1 Axis L_X middle POT pin (SD657.15)
  35566 J3 (ribbon cable to R-1, R-2 button daughterboard) (SCPH-1150)
  35567   1 (red)  R1
  35568   2 (gray) GND
  35569   3 (gray) R2
  35570 J2 (ribbon cable to L-1, L-2 button daughterboard) (SCPH-1150)
  35571   1 (red)  L1
  35572   2 (gray) GND
  35573   3 (gray) L2
  35574 J1 wires to small rumble motor (SCPH-1150)
  35575   1 (red)   +7.5V
  35576   2 (black) Q1
  35577 
  35578 Analog Joypad Chipset Pin-Outs (SCPH-1150)
  35579 U1 42pin "SD657, 9702K3006"
  35580   1  NC?
  35581   2  NC?
  35582   3  /RESET? (U2.3)
  35583   4  OSC
  35584   5  OSC
  35585   6  BUTTON Bit3 START SW1
  35586   7  BUTTON Bit2 R3 (via CN2.5)
  35587   8  BUTTON Bit1 L3 (via CN2.7)
  35588   9  BUTTON Bit0 SELECT SW3
  35589   10 GND
  35590   11 BUTTON Bit7 LEFT  SW4
  35591   12 BUTTON Bit6 DOWN  SW5
  35592   13 BUTTON Bit5 RIGHT SW6
  35593   14 BUTTON Bit4 UP    SW7
  35594   15 Analog Axis L_X (via CN2.1)
  35595   16 Analog Axis L_Y (via CN2.2)
  35596   17 Analog Axis R_X (via CN2.3)
  35597   18 Analog Axis R_Y (via CN2.4)
  35598   19 NC?
  35599   20 3.5V
  35600   21 3.5V
  35601   ---
  35602   22 BUTTON Bit15 [] SW11
  35603   23 BUTTON Bit14 >< SW10
  35604   24 BUTTON Bit13 () SW9
  35605   25 BUTTON Bit11 R1 (via J3.1)
  35606   26 BUTTON Bit12 /\ SW8
  35607   27 BUTTON Bit10 L1 (via J3.1)
  35608   28 BUTTON Bit9  R2 (via J3.3)
  35609   29 BUTTON Bit8  L2 (via J3.3)
  35610   30 PSX.2/CN1.6 JOYCMD  orange (via 220 ohm R14)
  35611   31 PSX.1/CN1.2.JOYDAT  brown  (via 22 ohm R13 and diode D2)
  35612   32 PSX.7/CN1.7 JOYCLK  blue   (via 220 ohm R12)
  35613   33 PSX.6/CN1.5./JOYn   yellow (via 220 ohm R11)
  35614   34 LED.GREEN (LED.4)
  35615   35 LED.RED   (LED.3)
  35616   36 MOTOR (via 4.7Kohm R8 to Q2, then via Q1 to motor)
  35617   37 NC?
  35618   38 NC?
  35619   39 PSX.9/CN1.1./ACK    green  (via 22 ohm R10)
  35620   40 NC?
  35621   41 MODE SW2 (analog button)
  35622   42 GND
  35623 U2 (probably reset signal related)
  35624   1  from 3.5V (via R1,D1,R2)
  35625   2  to U1.3 (/RESET?) (U2.rear contact = same as U2.pin2)
  35626   3  GND
  35627 Q1 "BQ03" or so (motor post-amp)
  35628   1  Q2.2 (via 1Kohm R7)
  35629   2  to Motor (-)
  35630   3  GND
  35631 Q2 "S6","SG","9S" or so (motor pre-amp)
  35632   1  SD657.36 (via 4.7Kohm R8)
  35633   2  Q1.1 (via 1Kohm R7) (and via 100Kohm R13 to GND)
  35634   3  3.5V
  35635 
  35636 Motor
  35637 Left/Single Motor (SCPH-1150)
  35638   27.5mm Total Length (18.5mm Motor, 2mm Axis, 7mm Weight/block)
  35639   12.0mm Width/Diameter (of Weight, and of Motor at flat side)
  35640 
  35641 Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-1200
  35642 --------------------------------------------------------------------------
  35643 
  35644 Analog Joypad Component List (SCPH-1200, two motors)
  35645   Case "SONY, ANALOG, CONTROLLER, SonyCompEntInc. H, SCPH-1200 MADE IN CHINA"
  35646   PCB1 "01, /\YG-H2, (r)RU" (mainboard with digital buttons)
  35647   PCB2 "M-29-01, YG-H3, (r)RU" (daughterboard with analog joysticks)
  35648   PCB3 "E, /\YG-H2, (r)RU, 01" (daughterboard with R-1, R-2 buttons) (J1)
  35649   PCB4 "01, W, /\YG-H2, (r)RU" (daughterboard with L-1, L-2 buttons) (J2)
  35650   U1 44pin "SONY, CXD8771Q 4A03, JAPAN 9840 HAL, 148896"
  35651   U2  4pin ",\\ 29" (PST9329) (System Reset with 2.9V detection voltage)
  35652   U3  8pin "2904, 8346G, JRC" (NJM2904) (Dual Operational Amplifier)
  35653   Q1  3pin ".Y S'" (big transistor for big M1 rumble motor)
  35654   Q2  3pin "Z" (small transistor for small M2 rumble motor)
  35655   Y1  3pin "800CMLX" or so (hides underneath of the CN2 ribbon cable)
  35656   CN1 8pin cable to PSX controller port
  35657   CN2 8pin ribbon cable to analog-joystick daughterboard
  35658   J1  3pin ribbon cable to R-1, R-2 button daughterboard
  35659   J2  3pin ribbon cable to L-1, L-2 button daughterboard
  35660   M1  2pin wires to left/big rumble motor (analog, slow/fast)
  35661   M2  2pin wires to right/small rumble motor (digital, on/off)
  35662   ZD1,ZD2 some Z-diodes
  35663   D1,D2 diodes near M1,M2 motors (these diodes aren't installed)
  35664   LED1  red analog mode LED (with transparent optics/light direction mirror)
  35665   plus resistors/capacitors
  35666 
  35667 Note: There's also a different SCPH-1200 revision, which having a smaller
  35668 mainboard with analog joysticksonboard, plus a single sided PCB for the digital
  35669 buttons (that is, similar to SCPH-110, but with the single sided PCB instead of
  35670 membrane foil).
  35671 
  35672 Analog Joypad Connection Cables (SCPH-1200)
  35673 CN1 (cable to PSX controller port) (same for SCPH-1150 and SCPH-1200)
  35674   PSX.1 -------brown---- PAD.2 JOYDAT
  35675   PSX.2 -------orange--- PAD.6 JOYCMD
  35676   PSX.3 -------magenta-- PAD.8 +7.5V
  35677   PSX.4 -------black---- PAD.3 GND
  35678   PSX.5 -------red------ PAD.4 +3.5V
  35679   PSX.6 -------yellow--- PAD.5 /JOYn
  35680   PSX.7 -------blue----- PAD.7 JOYCLK
  35681   PSX.8 ---              NC    /IRQ10
  35682   PSX.9 -------green---- PAD.1 /ACK
  35683   PSX.Shield --shield--- NC    (cable is shielded but isn't connected in
  35684 joypad)
  35685 CN2 (ribbon cable to analog-joystick daughterboard) (SCPH-1200)
  35686   1 +3.5V to POT pins
  35687   2 Button L3 pins C,D
  35688   3 GND to POT pins and Button L3/R3 pins A,B
  35689   4 Button R3 pins C,D
  35690   5 Axis R_Y middle POT pin (CXD.20)
  35691   6 Axis R_X middle POT pin (CXD.19)
  35692   7 Axis L_X middle POT pin (CXD.21)
  35693   8 Axis L_Y middle POT pin (CXD.22)
  35694 J1 (ribbon cable to R-1, R-2 button daughterboard) (SCPH-1200)
  35695   1 (red)  R1
  35696   2 (gray) GND
  35697   3 (gray) R2
  35698 J2 (ribbon cable to L-1, L-2 button daughterboard) (SCPH-1200)
  35699   1 (red)  L1
  35700   2 (gray) GND
  35701   3 (gray) L2
  35702 M1 wires to big rumble motor (SCPH-1200)
  35703   + (red)   Q1.E
  35704   - (black) GND
  35705 M2 wires to small rumble motor (SCPH-1200)
  35706   + (red)   +7.5V
  35707   - (black) Q2.C
  35708 
  35709 Analog Joypad Chipset Pin-Outs (SCPH-1200)
  35710 U1 SONY CXD8771Q
  35711   1 PSX.7/CN1.7 JOYCLK (via 220 ohm R2)
  35712   2 via R10 to U3.3 (for big M1 motor)
  35713   3 via R15 to Q2.B (for small M2 motor)
  35714   4 GND
  35715   5 BUTTON Bit15 []
  35716   6 BUTTON Bit14 ><
  35717   7 BUTTON Bit13 ()
  35718   8 BUTTON Bit12 /\
  35719   9 BUTTON Bit11 R1 (via J1.1)
  35720   10 BUTTON Bit10 L1 (via J2.1)
  35721   11 BUTTON Bit9 R2 (via J1.3)
  35722   ---
  35723   12 BUTTON Bit8 L2 (via J2.3)
  35724   13 GND
  35725   14 U2.Pin3 (reset)
  35726   15 Y1'a
  35727   16 Y1'b
  35728   17 GND
  35729   18 +3.5V
  35730   19 Analog Axis R_X via CN2.6
  35731   20 Analog Axis R_Y via CN2.5
  35732   21 Analog Axis L_X via CN2.7
  35733   22 Analog Axis L_Y via CN2.8
  35734   ---
  35735   23 GND
  35736   24 GND
  35737   25 GND
  35738   26 GND
  35739   27 GND
  35740   28 +3.5V
  35741   29 BUTTON Bit0 SELECT
  35742   30 BUTTON Bit1 L3 (via CN2.2)
  35743   31 BUTTON Bit2 R3 (via CN2.4)
  35744   32 BUTTON Bit3 START
  35745   33 BUTTON Bit4 UP
  35746   ---
  35747   34 BUTTON Bit5 RIGHT (aka spelled RIHGT on the PCB)
  35748   35 BUTTON Bit6 DOWN
  35749   36 BUTTON Bit7 LEFT
  35750   37 PSX.6/CN1.5./JOYn  (via 220 ohm R1)
  35751   38 ANALOG BUTTON
  35752   39 GND
  35753   40 +3.5V
  35754   41 /LED (to LED1, and from there via 300 ohm R6 to +3.5V)
  35755   42 PSX.9/CN1.1./ACK   (via 22 ohm R5)
  35756   43 PSX.1/CN1.2.JOYDAT (via 22 ohm R3)
  35757   44 PSX.2/CN1.6 JOYCMD (via 220 ohm R4)
  35758 U2 PST9329 (System Reset with 2.9V detection voltage)
  35759   1 NC   GND
  35760   2 GND  GND
  35761   3 Vout U1.14
  35762   4 VCC  +3.5V
  35763 U3 NJM2904 (Dual Operational Amplifier)
  35764   1 A.OUTPUT  Q1.B (big motor M1 transistor)
  35765   2 A.INPUT-  to R11/R12
  35766   3 A.INPUT+  to R10/R17
  35767   4 GND       PSX.4/CN1.3 GND
  35768   5 B.INPUT+  GND
  35769   6 B.INPUT-  NC?
  35770   7 B.OUTPUT  NC?
  35771   8 VCC       PSX.3/CN1.8 +7.5V
  35772 Q1 (transistor for big M1 motor)
  35773   E M1+
  35774   B U3.1 (NJM2904)
  35775   C +7.5V
  35776 Q2 (transistor for small M2 motor)
  35777   E GND
  35778   B via 1K ohm R15 to U1.3 (CXD), and via 100K ohm R16 to GND
  35779   C M2-
  35780 
  35781 Motors
  35782  Left/Large Motor (SCPH-1200)
  35783   24.0mm Total Length (12.0mm Motor, 2.5mm Axis, 9.5mm Weight/plates)
  35784   24.0mm Diameter (Motor), 20.0mm Diameter (Weight/plates)
  35785  Right/Small Motor (SCPH-1200)
  35786   25.4mm Total Length (18.7mm Motor, 2mm Axis, 4.7mm Weight/plates)
  35787   12.0mm Width/Diameter (of Weight, and of Motor at flat side)
  35788 
  35789 Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-110
  35790 -------------------------------------------------------------------------
  35791 
  35792 Analog Joypad Component List (SCPH-110, two motors, PSone-design)
  35793   Case "SONY, ANALOG CONTROLLER, SonyCompEntInc. A, SCPH-110 MADE IN CHINA"
  35794   PCB1 "SA1Q22A, <PF-LP>, KPC, 7694V-0" (mainboard with joysticks onboard)
  35795   PCB2 "..." (membrane/foil with digital buttons)
  35796   U1  44pin "SD707, 039 107"" (4x11pin)
  35797   Q1   3pin "KA" (big transistor for left/big M1 rumble motor)
  35798   Q2   3pin "LG" (small transistor for right/small M2 rumble motor)
  35799   D1   2pin diode (for large motor, reference Z-diode with pull-up?)
  35800   D2   3pin dual-diode (R5/IRQ7 to GND and R3/DAT to GND)
  35801   CN1  9pin cable to PSX controller port
  35802   J1  16pin ribbon cable from membrane/foil
  35803   M1   2pin wires to left/big rumble motor (analog, slow/fast)
  35804   M2   2pin wires to right/small rumble motor (digital, on/off)
  35805   LED1 2pin red analog mode LED (with long legs, without mirror/optics)
  35806   plus resistors/capacitors
  35807 
  35808 Analog Joypad Connection Cables (SCPH-110)
  35809 CN1 (cable to PSX controller port)
  35810   1 +3.5V (logic supply)
  35811   2 GND3  (logic supply)
  35812   3 /IRQ7
  35813   4 /SEL
  35814   5 CMD
  35815   6 DAT
  35816   7 CLK
  35817   8 GND7  (motor supply)
  35818   9 +7.5V (motor supply)
  35819 J1 (ribbon cable with membrane/foil with digital buttons)
  35820   1 BUTTON Bit8 L2
  35821   2 BUTTON Bit10 L1
  35822   3 BUTTON Bit4 UP
  35823   4 BUTTON Bit5 RIGHT
  35824   5 BUTTON Bit6 DOWN
  35825   6 BUTTON Bit7 LEFT
  35826   7 GND3
  35827   8 ANALOG BUTTON
  35828   9 BUTTON Bit0 SELECT
  35829   10 BUTTON Bit3 START
  35830   11 BUTTON Bit15 SQUARE   []
  35831   12 BUTTON Bit14 CROSS    ><
  35832   13 BUTTON Bit13 CIRCLE   ()
  35833   14 BUTTON Bit12 TRIANGLE /\
  35834   15 BUTTON Bit11 R1
  35835   16 BUTTON Bit9 R2
  35836 M1 wires to left/big rumble motor (SCPH-110)
  35837   1 (red)   Q1
  35838   2 (black) GND (via some ohm)
  35839 M2 wires to right/small rumble motor (SCPH-110)
  35840   1 (red)   +7.5V
  35841   2 (black) Q2
  35842 
  35843 U1 ("SD707, 039 107")
  35844   1 via R9/Q2 to M2 (right/small)     (digital 0V=off, 3V=on)
  35845   2 via "JP1" to LED (330 ohm)
  35846   3 +3.5V
  35847   4 BUTTON Bit2 R3
  35848   5 vr2 RX (lt/rt)
  35849   6 vr1 RY (up/dn)
  35850   7 vr4 LX (lt/rt)
  35851   8 vr3 LY (up/dn)
  35852   9 BUTTON Bit1 L3
  35853   10 GND3
  35854   11 GND7
  35855   ---
  35856   12 via Q1 to M1 (left/large)       (1V=off, 6V=fast)
  35857   13 via D1/R7 to M1 (left/large)    (6.7V)
  35858   14 +7.5V
  35859   15 +7.5V
  35860   16 BUTTON Bit8 L2
  35861   17 BUTTON Bit10 L1
  35862   18 BUTTON Bit4 UP
  35863   19 BUTTON Bit5 RIGHT
  35864   20 BUTTON Bit6 DOWN
  35865   21 BUTTON Bit7 LEFT
  35866   22 GND3
  35867   ---
  35868   23 BUTTON Bit9 R2
  35869   24 BUTTON Bit11 R1
  35870   25 BUTTON Bit12 TRIANGLE /\
  35871   26 BUTTON Bit13 CIRCLE   ()
  35872   27 BUTTON Bit14 CROSS    ><
  35873   28 BUTTON Bit15 SQUARE   []
  35874   29 BUTTON Bit3 START
  35875   30 BUTTON Bit0 SELECT
  35876   31 ANALOG BUTTON
  35877   32 NC
  35878   33 +3.5V
  35879   ---
  35880   34 GND3
  35881   35 NC
  35882   36 via R5 to /IRQ7
  35883   37 via R1 to /SEL
  35884   38 via R4 to CMD
  35885   39 via R3 to DAT
  35886   40 via R2 to CLK
  35887   41 +7.5V
  35888   42 +7.5V
  35889   43 GND7
  35890   44 GND7
  35891 
  35892 Misc
  35893 VR1..VR4 -- analog inputs
  35894 R1..R5 -- signals to/from psx
  35895 R6              ?
  35896 R7              M1
  35897 R8
  35898 R9
  35899 R10
  35900 JP1
  35901 C1 3.5V to GND3 (22uF)
  35902 C2 3.5V to GND3 (U1)
  35903 C3 VR1 to GND3
  35904 C4 VR2 to GND3
  35905 C5 VR3 to GND3
  35906 C6 VR4 to GND3
  35907 C7 M2+ to M2-
  35908 C8 M1+ to M1-
  35909 C9 M1 related
  35910 S5
  35911 S6
  35912 
  35913 Motors
  35914  Left/Large Motor (SCPH-110)
  35915   23.0mm Total Length (12.0mm Motor, 3mm Axis, 8.0mm Weight/plates)
  35916   24.0mm Diameter (Motor), 20.0mm Diameter (Weight/plates)
  35917  Right/Small Motor (SCPH-110)
  35918   25.4mm Total Length (18.7mm Motor, 2mm Axis, 4.7mm Weight/plates)
  35919   12.0mm Width/Diameter (of Weight, and of Motor at flat side)
  35920 
  35921   M1+ --o---Q1---o--------- U1.12
  35922         |   |    |          analog
  35923   Left  |   |    C9
  35924   Large |   |    |
  35925         |   o----o--------- 7.5V
  35926         |        |
  35927        C8       R7
  35928         |   D1   |          6.7V
  35929         o---|>|--o--------- U1.13
  35930         |
  35931   M1- --o------------------ GND7
  35932 
  35933 D1 is probably a Z-diode with R7 as pull-up, creating a reference/source
  35934 voltage at U1.13 for the analog output at U1.12.
  35935 
  35936   M2+ --o------------------ 7.5V
  35937         |
  35938   Right |   o-------o--R9-- U1.1
  35939   Small |   |       |       on/off
  35940        C7   |       R10
  35941         |   |       |
  35942   M2- --o---Q2------o------ GND7
  35943                                    ___                          ___ ____
  35944        axis                       |   |                        /   \    \
  35945      __/___                 ______| m |        __.____________|__.  |    |
  35946    /__/__/ |               | w |  |   |       |  '  | | axis  |  '  |    |
  35947   |      |/  weight        |___|  |___|        \___/_/         \___/____/
  35948    \____/                                      weight             motor
  35949 
  35950 Pinouts - Component List and Chipset Pin-Outs for Dualshock2, SCPH-10010
  35951 ------------------------------------------------------------------------
  35952 
  35953 Dualshock2 Component List
  35954 PCB  "SA1P07A, >PF-LP<, HCMK-P3X, 9 RU"
  35955 Foil "9, SA1Q28B, 237T1, 3 S"
  35956   U1   8pin   "358, 937" (LM358, dual op-amp)
  35957   Ux  44pin   "9950KP003, SD718A" (whatever microprocessor)
  35958   U3  16pin   "HC, 4051A, 941" (74HC4051A, 8-to-1 analog mux)
  35959   U4  16pin   "HC, 4051A, 941" (74HC4051A, 8-to-1 analog mux)
  35960   U5   4pin   "CUJ" (reset detection?)
  35961   Y1   3pin   "400G945" (ceramic resonator)
  35962   Q1   3pin   driver for motor M1 (with large weight; input from U1 op-amp)
  35963   Q5   3pin   driver for motor M2 (with small weight; input directly from CPU)
  35964   Q6   3pin   driver for button [], X
  35965   Q7   6pin   driver for button DPAD.LT, DPAD.RT
  35966   Q8   6pin   driver for button R1, R2, /\, O
  35967   Q9   3pin   driver for button L1, L2
  35968   Q10  6pin   driver for button DPAD.UP, DPAD.DN
  35969   D3   3pin   dual-diode (GND to .. and JOYDAT) (CN3.2 to CN3.3 and CN3.4)
  35970   D5   2pin   (not installed) (GND to VCC 3.5V)   (CN3.2 to CN3.1)
  35971   D6   2pin   (not installed) (AGND to AVCC 7.5V) (CN3.8 to CN3.9)
  35972   D7   2pin   (not installed) (GND to JOYCLK)     (CN3.2 to CN3.7)
  35973   LED1 2pin   Analog LED (red)
  35974   VR4  3pin   analog joystick RY potentiometer
  35975   VR5  3pin   analog joystick RX potentiometer
  35976   VR6  3pin   analog joystick LY potentiometer
  35977   VR7  3pin   analog joystick LX potentiometer
  35978   S1   4pin   digital button R3
  35979   S2   4pin   digital button L3
  35980   CN1  16pin  Ribbon/foil (left half)
  35981   CN2  16pin  Ribbon/foil (right half)
  35982   CN3  9pin   Cable to controller connector
  35983   M1   2pin   Left Motor with large weight  (wire1=red, wire2=black)
  35984   M2   2pin   Right Motor with small weight (wire1=white, wire2=black)
  35985   R1..R28     resistors (plus additional resistors printed on the foil)
  35986   C1..C14     capacitors
  35987 
  35988 Analog Buttons
  35989 The foil contains printed resistors (large 19K ohm pull-down resistors, and
  35990 small 7.6K ohm pull-up resistors). The pull-downs can get shorted by pressing a
  35991 conductive piece of rubber against it:
  35992    ____________
  35993   |            |        ____________
  35994   '.          .'       |            |        ____________
  35995     '--____--'         '.          .'       |            |     <-- rubber
  35996                          '--____--'         '.__________.'
  35997   .############.###.   .############.###.   .############.###. <-- resistors
  35998     no contact          some contact         full contact
  35999 There are some oddities: The microprocessor has only two ADC inputs (the PCB
  36000 contains analog multiplexors to map the currently selected signals to the ADC
  36001 inputs). And, the pull-downs are GNDed via transistors instead of being
  36002 directly wired to GND (that is used to share DPAD inputs, and may also reduce
  36003 power consumption during inactivity).
  36004   .############.       .############.###.   .############.###. <-- resistor
  36005   |   DPAD.LT  |       |   DPAD.RT  |   |   |  NON-DPAD  |   |
  36006   |            '------ | -----------+   |   |            |   |
  36007   |                    |            |   |   |            |   |
  36008   Q--.                 Q--.     .--MUX  |   Q--.     .--MUX  |
  36009   |  |                 |  |     |   |   |   |  |     |   |   |
  36010  GND EN               GND EN   SEL ADC VCC GND EN   SEL ADC VCC
  36011 There is only one MUX and one pull-up shared for DPAD LT/RT (and same for
  36012 DPAD.UP/DN). Shared access is done by activating only one of the pull-down
  36013 transistors (that should work reliably even if it were mechanically possible to
  36014 push LT/RT simultaneously).
  36015 
  36016 CN1 (foil, left half)
  36017   1  button L2
  36018   2  button L1
  36019   3  button L1 and resistor                   U3.5
  36020   4  button DPAD.LT
  36021   5  button DPAD.LT, DPAD.RT and resistor?    U3.4
  36022   6  button DPAD.RT
  36023   7  button DPAD.UP
  36024   8  button DPAD.UP, DPAD.DN and resistor?    U3.13
  36025   9  button DPAD.DN
  36026   10 VCC (to resistors)
  36027   11 NC on foil
  36028   12 button L2 and resistor                   U3.12
  36029   13 button SELECT
  36030   14 GND (for SELECT, ANALOG, START)
  36031   15 button ANALOG
  36032   16 NC on foil
  36033 
  36034 CN2 (foil, right half)
  36035   1  button START
  36036   2  button R2 and resistor       U3.14
  36037   3  NC on foil
  36038   4  VCC (to resistors)
  36039   5  NC on foil
  36040   6  button [] and resistor       U4.15
  36041   7  button []
  36042   8  button X  and resistor       U4.14
  36043   9  button X
  36044   10 button O  and resistor       U4.13
  36045   11 button O
  36046   12 button /\ and resistor       U4.12
  36047   13 button /\
  36048   14 button R1 and resistor       U3.15
  36049   15 button R1
  36050   16 button R2
  36051 
  36052 CN3 (cable to controller plug)
  36053   1  red     VCC 3.5V        (PSX.5 4ohm)
  36054   2  black   GND             (PSX.4 3ohm)
  36055   3  green   /JOYACK         (PSX.9 4ohm)
  36056   4  brown   JOYDAT          (PSX.1 4ohm)
  36057   5  orange  JOYCMD          (PSX.2 4ohm)
  36058   6  yellow  /JOYn           (PSX.6 4ohm)
  36059   7  blue    JOYCLK          (PSX.7 4ohm)
  36060   8  gray    Motor AGND      (PSX.4 3ohm)
  36061   9  purple  Motor AVCC 7.5V (PSX.3 4ohm)
  36062   -  N/A     /IRQ10          (PSX.8 none)
  36063 GND and AGND have separate wires with 3 ohm each (so there's about 6 ohm
  36064 between GND and AGND).
  36065 
  36066 VR4,VR5,VR6,VR7 (potentiometers for analog joysticks)
  36067   1  GND
  36068   2  POT (to U4 pin 5,4,1,2 for VR4,VR5,VR6,VR7)
  36069   3  STICKSEL (Ux.10)
  36070 
  36071 U1 (LM358, dual op-amp)
  36072   1  1OUT NC?
  36073   2  1IN- NC?
  36074   3  1IN+ Digital GND (CN3.2 black)
  36075   4  GND  Motor AGND  (CN3.8 gray)
  36076   5  2IN+ via R1 to Ux.26 and via C3 to GND
  36077   6  2IN- via R3 and via R4
  36078   7  2OUT to Q1 lower left
  36079   8  VCC  Motor AVCC 7.5V (CN3.9 purple)
  36080 
  36081 Ux (whatever microprocessor)
  36082   1  CN2.1  button START
  36083   2  CN1.13 button ANALOG
  36084   3  U3.11 (mux sel0)
  36085   4  U3.10 (mux sel1)
  36086   5  U3.9  (mux sel2)
  36087   6  Q6 lower left   to CN2.7+9
  36088   7  S2 digital button L3
  36089   8  CN1.13 button SELECT
  36090   9  VCC
  36091   10 STICKSEL (to VR4,VR5,VR6,VR7)
  36092   11 U3.3  (mux signal)
  36093   ---
  36094   12 U4.3  (mux signal)
  36095   13 GND
  36096   14 GND
  36097   15 GND
  36098   16 S1 digital button R3
  36099   17 MOTOR2 (via 1Kohm/R20 to Q5 motor M2)
  36100   18 GND
  36101   19 VCC
  36102   20 LED (via 330ohm/R5 to LED1-)
  36103   21 ?
  36104   22 /JOYACK (via 22ohm/R15 to CN3.3 green)
  36105   ---
  36106   23 JOYDAT  (via 22ohm/R18 to CN3.4 brown)
  36107   24 JOYCLK  (via 220ohm/R19 to CN3.7 blue)
  36108   25 JOYCMD  (via 220ohm/R17 to CN3.5 orange)
  36109   26 MOTOR1  (via R1 to U1.5 and via R2 to GND)
  36110   27 /JOYn   (via 220ohm/R16 to CN3.6 yellow)
  36111   28 GND
  36112   29 VCC
  36113   30 OSC  (from Y1)
  36114   31 OSC' (from Y1)
  36115   32 GND
  36116   33 VCC
  36117   ---
  36118   34 via 220ohm/R27 to U5.1
  36119   35 via R26 to ... U5.1
  36120   36 via R25 to ... U5.1
  36121   37 to Q8.3
  36122   38 to Q8.5
  36123   39 to Q9
  36124   40 to Q7.3 and Q10.3
  36125   41 to Q7.5 and Q10.5
  36126   42 U4.9  (mux sel2)
  36127   43 U4.10 (mux sel1)
  36128   44 U4.11 (mux sel0)
  36129 
  36130 U3 (74HC4051, 8-to-1 mux)
  36131   1  X4   NC?         NC?
  36132   2  X6   NC?         NC?
  36133   3  Y    to Ux.11    CPU analog input
  36134   4  X7   from CN1.5  button DPAD.LT and DPAD.RT
  36135   5  X5   from CN1.3  button L1
  36136   6  /EN  GND         enable
  36137   7  VEE  GND         ground'
  36138   8  GND  GND         ground
  36139   9  S2   from Ux.5   sel2
  36140   10 S1   from Ux.4   sel1
  36141   11 S0   from Ux.3   sel0
  36142   12 X3   from CN1.12 button L2
  36143   13 X0   from CN1.8  button DPAD.UP and DPAD.DN
  36144   14 X1   from CN2.2  button R2
  36145   15 X2   from CN2.14 button R1
  36146   16 VCC  VCC         supply
  36147 
  36148 U4 (74HC4051, 8-to-1 mux)
  36149   1  X4   from VR6.2  analog joystick LY
  36150   2  X6   from VR7.2  analog joystick LX
  36151   3  Y    to Ux.12    CPU analog input
  36152   4  X7   from VR5.2  analog joystick RX
  36153   5  X5   from VR4.2  analog joystick RY
  36154   6  /EN  GND         enable
  36155   7  VEE  GND         ground'
  36156   8  GND  GND         ground
  36157   9  S2   from Ux.    sel2
  36158   10 S1   from Ux.    sel1
  36159   11 S0   from Ux.    sel0
  36160   12 X3   from CN2.12 button /\
  36161   13 X0   from CN2.10 button O
  36162   14 X1   from CN2.8  button X
  36163   15 X2   from CN2.6  button []
  36164   16 VCC  VCC         supply
  36165 
  36166 U5 (reset detection?)
  36167   1  via 220ohm/R27 to Ux.34, and via R25 to Ux.36
  36168   2  VCC
  36169   3  via 1.3Kohm/R24 to U5.1
  36170   4  NC?
  36171 
  36172 Q1
  36173   x  from U1.7 (op-amp)
  36174   x  supply AVCC 7.5V (CN3.9 purple)
  36175   x  to motor M1.1 (with large weight)
  36176 
  36177 Q5
  36178   x  via 1Kohm/R20 from Ux.17
  36179   x  to motor M2.2 (with small weight)
  36180   x  supply AGND 7.5V (CN3.8 gray)
  36181 
  36182 Q6
  36183   x  from Ux.6
  36184   x  to to CN2.7 (button []) and CN2.9 (button X)
  36185   x  GND
  36186 
  36187 Q7
  36188   1  GND
  36189   2  GND
  36190   3  from Ux.40
  36191   4  to CN1.6 (button DPAD.RT)
  36192   5  from Ux.41
  36193   6  to CN1.4 (button DPAD.LT)
  36194 
  36195 Q8
  36196   1  GND
  36197   2  GND
  36198   3  from Ux.37
  36199   4  to CN2.15 (button R1) and CN2.16 (button R2)
  36200   5  from Ux.38
  36201   6  to CN2.11 (button O) and CN2.13 (button /\)
  36202 
  36203 Q9
  36204   x  from Ux.39
  36205   x  to CN1.1 (button L2) and CN1.2 (button L1)
  36206   x  GND
  36207 
  36208 Q10
  36209   1  GND
  36210   2  GND
  36211   3  from Ux.40
  36212   4  to CN1.7 (button DPAD.UP)
  36213   5  from Ux.41
  36214   6  to CN1.9 (button DPAD.DN)
  36215 
  36216 Pinouts - Component List and Chipset Pin-Outs for Namco Lightgun, NPC-103
  36217 -------------------------------------------------------------------------
  36218 
  36219 Schematic
  36220 http://www.nicolaselectronics.be/reverse-engineering-the-playstation-g-con45/
  36221 
  36222 Namco Lightgun "NPC-103, (C) 1996 NAMCO LTD." Component List
  36223 PCB "DNP-0500A, NPC10300, namco, CMK-P3X"
  36224   U1  44pin "NAMCO103P, 1611U1263, JAPAN 9847EAI, D0489AAF"
  36225   U2   8pin "7071, 8C19" (=BA7071F, Sync Separator IC with AFC)
  36226   XTAL 2pin "CSA 8.00WT"
  36227   PS1  3pin Light sensor with metal shielding
  36228   J1   9pin Connector for 9pin cable to PSX controller and GunCon plugs
  36229   plus resistors and capacitors, and A1,A2,B1,B2,T1,T2 wires to buttons
  36230 PCB "DN-P-0501"
  36231   DIP Button (with black T1,T2 wires) (trigger)
  36232 PCB "DN-P-0502"
  36233   Button A (with red A1,A2 wires) (left side)
  36234   Button B (with white B1,B2 wires) (right side)
  36235 Other Components
  36236   Lens (20mm)
  36237 Cable Pinouts
  36238   J1.Pin1 green  PSX.Controller.Pin5 +3.5V
  36239   J1.Pin2 brown  PSX.Controller.Pin4 GND
  36240   J1.Pin3 black  PSX.Controller.Pin9 /ACK/IRQ7
  36241   J1.Pin4 red    PSX.Controller.Pin6 /JOYn
  36242   J1.Pin5 yellow PSX.Controller.Pin1 JOYDAT
  36243   J1.Pin6 orange PSX.Controller.Pin2 JOYCMD
  36244   J1.Pin7 blue   PSX.Controller.Pin7 JOYCLK
  36245   J1.Pin8 gray   GunCon shield (GND)
  36246   J1.Pin9 white  GunCon composite video
  36247   N/A            PSX.Controller.Pin3 +7.5V
  36248   N/A            PSX.Controller.Pin8 /IRQ10
  36249   N/A            PSX.Controller Shield
  36250 U1 "NAMCO103P" Pinouts (44pin, arranged as 4x11pin)
  36251   1 GND    12 SYNC (from U2)                     23 3.5V   34 SW1 (A)
  36252   2 GND    13 3.5V                               24 3.5V   35 3.5V
  36253   3 GND    14 3.5V                               25 3.5V   36 3.5V
  36254   4 GND    15 SW3 (TRIGGER)                      26 GND    37 SW2 (B)
  36255   5 GND    16 JOYCLK (J1.Pin7 via 220 ohm R7)    27 GND    38 3.5V
  36256   6 GND    17 3.5V                               28 GND    39 3.5V
  36257   7 GND    18 JOYCMD (J1.Pin6 via 220 ohm R8)    29 GND    40 LIGHT (from PS1)
  36258   8 GND    19 JOYDAT (J1.Pin5 via 0 ohm R10)     30 -      41 GND
  36259   9 -      20 /JOYn (J1.Pin4 via 220 ohm R9)     31 GND    42 GND
  36260   10 GND   21 /ACK/IRQ7 (J1.Pin3 via 0 ohm R11)  32 GND    43 OSC 8MHz
  36261   11 GND   22 GND                                33 GND    44 OSC 8MHz
  36262 U2 "7071" Pinouts (=BA7071F, Sync Separator IC with AFC) (2x4pin)
  36263   1 VIN      = SYNC.IN from J1.Pin9 Composite Video (via C5/C6/C7/R6)
  36264   2 HD_OUT   = NC
  36265   3 GND      = GND
  36266   4 PD_OUT   = NC
  36267   5 HOSC_R   = via 100K to GND
  36268   6 VCC      = 3.5V
  36269   7 VD_OUT   = NC
  36270   8 SYNC_OUT = SYNC.OUT to U1.pin12 (with R4 pull-up)
  36271 
  36272 Pinouts - Component List and Chipset Pin-Outs for Multitap, SCPH-1070
  36273 ---------------------------------------------------------------------
  36274 
  36275 Multitap Component List
  36276   Case "SONY, MULTITAP, SonyComputerEntertainmentInc, SCPH-1070 MADE IN CHINA"
  36277   PCB1 "SONY 1-659-343-11" (mainboard with Slot A,B, ICs, X1, PSX-cable)
  36278   PCB2 "SONY 1-711-414-11" (daughterboard with Slot C,D)
  36279   IC? 64pin "SONY JAPAN, CXD103, -166Q, 550D66E"            (smd/back side)
  36280   IC02 8pin "7W14, 5K" some tiny SMD chip (for JOYCLK)      (smd/back side)
  36281   X1   2pin "4.00G CMj" oscillator                          (front side)
  36282   J34  2pin fuse or 1 ohm resistor or so (for +3.5V input)  (front side)
  36283   Jxx  2pin normal wire bridges (except: J34 is NOT a wire) (front side)
  36284 Cables from Multitap PCB1 to PCB2:
  36285   1pin black wire Shield/GND (lower edge)
  36286   1pin black wire Shield/GND (upper edge)
  36287   2x8pin red/gray ribbon cable (side edge)
  36288   2x2pin red/gray ribbon cable (lower edge)
  36289   2pin red/gray ribbon cable (upper middle) (gray=+3.3V, red=+7.5V)
  36290 plus a bunch of SMD capacitors and around 70 SMD resistors.
  36291 
  36292 Multitap PSX Controller Port Cable
  36293   PSX.1 -------brown------ TAP.1 JOYDAT ;via  47 ohm (R57) to CXD.35
  36294   PSX.2 -------orange----- TAP.2 JOYCMD ;via 220 ohm (R58) to CXD.37
  36295   PSX.3 -------magenta---- TAP.3 +7.5V  ;directly to +7.5V on JOY/CARD's
  36296   PSX.4 -------black------ TAP.4 GND    ;directly to GND
  36297   PSX.5 -------red-------- TAP.5 +3.5V  ;via 1 ohm or so (J34) to +3.3V
  36298   PSX.6 -------yellow----- TAP.6 /JOYn  ;via 220 ohm (R59) to CXD.46
  36299   PSX.7 -------blue------- TAP.7 JOYCLK ;via 220 ohm (R60) to IC02.pin6
  36300   PSX.8 -------gray------- TAP.8 /IRQ10 ;via 47 ohm (R02/R16/R30/R44) to JOY's
  36301   PSX.9 -------green------ TAP.9 /ACK   ;via 47 ohm (R61) to CXD.51
  36302   PSX.Shield --shield----- TAP.shielding.plate (GND)
  36303 
  36304 Multitap CARD A/B/C/D Slots
  36305   1 JOYDAT Via  47 ohm (R11/R25/R38/R5x) to CXD.18/29/60/5 (and to JOY slot)
  36306   2 JOYCMD Via 220 ohm (R10/R24/R39/R52) to CXD.19/30/62/6
  36307   3 +7.5V  Directly to PSX.3
  36308   4 GND    Directly to PSX.4
  36309   5 +3.3V  Via J34 to PSX.5 (+3.5V)
  36310   6 /JOYn  Via 220 ohm (R09/R2x/Rxx/R51) to CXD.11/22/52/61
  36311   7 JOYCLK Via 220 ohm (R08/R2x/Rxx/R50) to CXD.33/33/47/47
  36312   9 /ACK   Via  47 ohm (R07/R2x/Rxx/R49) to CXD.12/21/45/64
  36313 
  36314 Multitap JOY A/B/C/D Slots
  36315   1 JOYDAT Via  47 ohm (R06/Rxx/R34/R5x) to CXD.18/29/60/5 (and to CARD slot)
  36316   2 JOYCMD Via 220 ohm (R05/R19/R35/R5x) to CXD.17/28/59/4
  36317   3 +7.5V  Directly to PSX.3
  36318   4 GND    Directly to PSX.4
  36319   5 +3.3V  Via 1 ohm or so (J34) to PSX.5 (+3.5V)
  36320   6 /JOYn  Via 220 ohm (R04/R18/R32/R4x) to CXD.16/20/55/63
  36321   7 JOYCLK Via 220 ohm (R03/R17/R31/R45) to CXD.15/23/56/2
  36322   8 /IRQ10 Via  47 ohm (R02/R16/R30/R44) to PSX.8
  36323   9 /ACK   Via  47 ohm (R01/R15/R29/R43) to CXD.13/27/54/7
  36324   Shield   Directly to Shield/GND
  36325 
  36326 Multitap IC02 8pin "7W14, 5K" some tiny SMD chip
  36327   1
  36328   2
  36329   3
  36330   4 GND
  36331   5
  36332   6 via 220 ohm (R60) to PSX.7 (JOYCLK)
  36333   7 to CXD.Pin48
  36334   8 +3.3V, aka via 1 ohm (J34) to PSX.5 (+3.5V)
  36335 
  36336 Multitap "SONY CXD103-166Q" Chip Pin-Outs (Multitap CPU)
  36337   1 via to 10K (R63) to +3.3V, and via C13 to GND (probably power-on reset)
  36338   2 JOY.D.7.JOYCLK
  36339   3
  36340   4 JOY.D.2.JOYCMD
  36341   5 JOY/CARD.D.1.JOYDAT
  36342   6 CARD.D.2.JOYCMD
  36343   7 JOY.D.9./ACK
  36344   8 4MHz X1/C12
  36345   9 4MHz X1/C11
  36346   10 GND
  36347   11 CARD.A.6./JOYn
  36348   12 CARD.A.9./ACK
  36349   13 JOY.A.9./ACK
  36350   14
  36351   15 JOY.A.7.JOYCLK
  36352   16 JOY.A.6./JOYn
  36353   17 JOY.A.2.JOYCMD
  36354   18 JOY/CARD.A.1.JOYDAT
  36355   19 CARD.A.2.JOYCMD
  36356   ---
  36357   20 JOY.B.6./JOYn
  36358   21 CARD.B.9./ACK
  36359   22 CARD.B.6./JOYn
  36360   23 JOY.B.7.JOYCLK
  36361   24
  36362   25 GND
  36363   26 +3.3V
  36364   27 JOY.B.9./ACK
  36365   28 JOY.B.2.JOYCMD
  36366   29 JOY/CARD.B.1.JOYDAT
  36367   30 CARD.B.2.JOYCMD
  36368   31 GND
  36369   32
  36370   ---
  36371   33 CARD.A/B.7.JOYCLK
  36372   34
  36373   35 PSX.1.JOYDAT
  36374   36
  36375   37 PSX.2.JOYCMD
  36376   38
  36377   39
  36378   40
  36379   41
  36380   42 GND
  36381   43
  36382   44 GND
  36383   45 CARD.C.9./ACK
  36384   46 PSX.6./JOYn
  36385   47 CARD.C/D.7.JOYCLK
  36386   48 IC02.Pin7.PSX.JOYCLK
  36387   49
  36388   50
  36389   51 PSX.9./ACK
  36390   ---
  36391   52 CARD.C.6./JOYn
  36392   53
  36393   54 JOY.C.9./ACK
  36394   55 JOY.C.6./JOYn
  36395   56 JOY.C.7.JOYCLK
  36396   57 GND
  36397   58 +3.3V
  36398   59 JOY.C.2.JOYCMD
  36399   60 JOY/CARD.C.1.JOYDAT
  36400   61 CARD.D.6./JOYn
  36401   62 CARD.C.2.JOYCMD
  36402   63 JOY.D.6./JOYn
  36403   64 CARD.D.9./ACK
  36404 
  36405 Pinouts - Memory Cards
  36406 ----------------------
  36407 
  36408 Sony Playstation Memory Card (SCPH-1020)
  36409 The "SONY CXD8732AQ" chip is installed on memory cards with "SPC02K1020B"
  36410 boards, however, the text layer on the board says that it's an "LC86F8604A"
  36411 chip. So, the CXD8732AQ is most probably a standard LC86F8604A chip (more on
  36412 that below) with a Sony Memory Card BIOS ROM on it.
  36413 The "SONY CXD8732AQ" comes in a huge 64pin package, but it connects only to:
  36414   5 = /IRQ7   (via 22 ohm)         2 = /RESET (from U2)
  36415   6 = JOYCLK  (via 220 ohm)        30,31 = CF1,CF2 (12 clock pulses per 2us)
  36416   7 = /JOYn   (via 220 ohm)        14,16,25,32,38,39,61 = 3.5V (via 3.3 ohm)
  36417   12 = JOYCMD (via 220 ohm)        8,15,28,29 = GND
  36418   13 = JOYDAT (via 22 ohm)         All other pins = Not connected
  36419 Aside from that chip, the board additionally contains some resistors,
  36420 capacitors, z-diodes (for protection against too high voltages), a 6MHz
  36421 oscillator (for the CPU), and a 5pin reset generator (on the cart edge
  36422 connector, the supply pins are slightly longer than the data signal pins, so
  36423 when inserting the cartridge, power/reset gets triggered first; the 7.5V supply
  36424 pin is left unconnected, only 3.5V are used).
  36425 Caution: The "diagonal edge" at the upper-left of the CXD8732AQ chip is Pin 49
  36426 (not pin 1), following the pin numbers on the board (and the Sanyo datasheet
  36427 pinouts), pin 1 is at the lower-left.
  36428 
  36429 Sanyo LC86F8604A
  36430 8bit CPU with 132Kbyte EEPROM, 4Kbyte ROM, 256 bytes RAM, 2 timers, serial
  36431 port, and general purpose parallel ports. The 132K EEPROM is broken into 128K
  36432 plus 4K, the 4K might be internally used by the CPU, presumably containing the
  36433 BIOS (not too sure if it's really containing 4K EEPROM plus 4K ROM, or if it's
  36434 meant to be only either one).
  36435   1=P40/A0  9=P13   17=TP0  25=VDD  33=A11  41=NC   49=A7    57=NC
  36436   2=/RES    10=P14  18=TP1  26=NC   34=A9   42=NC   50=A6    58=NC
  36437   3=TEST2   11=P15  19=TP2  27=NC   35=A8   43=NC   51=A5    59=NC
  36438   4=TEST1   12=P16  20=TP3  28=NC   36=A13  44=NC   52=A4    60=NC
  36439   5=P10     13=P17  21=TP4  29=VSS  37=A14  45=A17  53=NC    61=NC61
  36440   6=P11     14=/CE  22=TP5  30=CF1  38=/WE  46=A16  54=NC    62=P43/A3
  36441   7=P12     15=A10  23=TP6  31=CF2  39=VDD  47=A15  55=NC    63=P42/A2
  36442   8=VSS     16=/OE  24=TP7  32=VDD  40=EP   48=A12  56=NC    64=P41/A1
  36443 Ports P10..P17 have multiple functions (I/O port, data bus, serial, etc):
  36444   P10/DQ0/SEPMOD       P12/DQ2/FSI0  P14/DQ4    P16/DQ6/SI0/FSTART
  36445   P11/DQ1/SCLK0/FSCLK  P13/DQ3       P15/DQ5    P17/DQ7/SO0/FRW
  36446 In March 1998, Sanyo has originally announced the LC86F8604A as an 8bit CPU
  36447 with "2.8V FLASH, achieved for the first time in the industry", however,
  36448 according to their datasheet, what they have finally produced is an 8bit CPU
  36449 with "3.5V EEPROM". Although, maybe the 3.5V EEPROM version came first, and the
  36450 2.8V FLASH was announced to be a later low-power version of the old chip;
  36451 namely, otherwise, it'd be everyones guess what kind of memory Sony used in
  36452 memory cards before 1998?
  36453 
  36454 Note
  36455 For the actual pin-outs of the cart-edge connector, see
  36456 --> Pinouts - Controller Ports and Memory-Card Ports
  36457 
  36458 Mods - Nocash PSX-XBOO Upload
  36459 -----------------------------
  36460 
  36461 Nocash PSX-XBOO Connection (required)
  36462   GND (BOARD)       --------- GND    (SUBD.18-25, CNTR.19-30)
  36463   A16 (ROM.2)       --------- SLCT   (SUBD.13, CNTR.13)     ;\
  36464   A17 (ROM.30)      --------- PE     (SUBD.12, CNTR.12)     ; 4bit.dta.out
  36465   A18 (ROM.31)      --------- /ACK   (SUBD.10, CNTR.10)     ;
  36466   A19 (ROM.1)       --------- BUSY   (SUBD.11, CNTR.11)     ;/
  36467   /RESET            ---|>|--- /INIT  (SUBD.16, CNTR.31)     ;-reset.in
  36468   D0..D7 (74HC541)  --------- DATA   (SUBD.2-9, CNTR.2-9)   ;\
  36469   Y0..Y7 (74HC541)  --------- D0..D7 (ROM.13-15,17-21)      ; 7bit.dta.in, and
  36470   /OE1 (74HC541.1)  --------- /EXP   (CPU.98)               ; 1bit.dta.clk.in
  36471   /OE2 (74HC541.19) --------- /OE    (ROM.24)               ;
  36472   GND  (74HC541.10) --------- GND    (BOARD)                ;
  36473   VCC  (74HC541.20) --------- +5V    (BOARD)                ;/
  36474 
  36475 Nocash PSX-BIOS Connection (required)
  36476   A0..A19 (ROM) --------- A0..A19 (EPROM)
  36477   D0..D7  (ROM) --------- D0..D7  (EPROM)
  36478   /BIOS (CPU.97)--------- /CS  (EPROM.22)
  36479   /OE (ROM.24)  --------- /OE  (EPROM.24)
  36480   +5V (BOARD)   --------- VCC  (EPROM.32)
  36481   GND (BOARD)   --------- GND  (EPROM.16)
  36482   /CS (ROM.22)  --/cut/-- /BIOS (CPU.97)
  36483   /CS (ROM.22)  --------- +5V  (BOARD) (direct, or via 100k ohm)
  36484 
  36485 Nocash BIOS "Modchip" Feature (optional)
  36486   SPU.Pin42 "data" -------|>|------ CPU.Pin149 (A20)
  36487   SPU.Pin5  "sync" ---------------- IC723.Pin17
  36488 The nocash PSX bios outputs the "data" signal on the A20 address line, so
  36489 (aside from the BIOS chip) one only needs to install a 1N4148 diode and two
  36490 wires to unlock the CDROM. For more variants, see:
  36491 --> CDROM Protection - Chipless Modchips
  36492 
  36493 Composite NTSC/PAL Mod (optional)
  36494 --> Mods - PAL/NTSC Color Mods
  36495 
  36496 Component List
  36497   32pin socket for EPROM
  36498   EPROM (or FLASH)
  36499   74HC541 (8-bit 3-state noninverting buffer/line driver)
  36500   1N4148 diode (for reset signal)
  36501   1N4148 diode (for optional "modchip" feature)
  36502   36pin Centronics socket for printer cable (or 25pin dsub)
  36503 
  36504 PSX-XBOO Upload BIOS
  36505 The required BIOS is contained in no$psx (built-in in the no$psx.exe file), the
  36506 Utility menu contains a function for creating a standalone ROM-image (file
  36507 PSX-XBOO.ROM in no$psx folder; which can be then burned to FLASH or EPROM).
  36508 
  36509 Pinouts
  36510               ______  ______                      ____  ____
  36511              |      \/      |                    |    \/    |
  36512   A19,VPP12  | 1         32 |  VCC6         /OE1 |1       20| VCC
  36513         A16  | 2         31 |  A18,/PGM       D0 |2       19| /OE2
  36514         A15  | 3         30 |  A17            D1 |3       18| Y0
  36515         A12  | 4         29 |  A14            D2 |4       17| Y1
  36516          A7  | 5         28 |  A13            D3 |5 74541 16| Y2
  36517          A6  | 6         27 |  A8             D4 |6       15| Y3
  36518          A5  | 7         26 |  A9,IDENT12     D5 |7       14| Y4
  36519          A4  | 8         25 |  A11            D6 |8       13| Y5
  36520          A3  | 9         24 |  /OE,VPP12      D7 |9       12| Y6
  36521          A2  | 10        23 |  A10           GND |10      11| Y7
  36522          A1  | 11        22 |  /CE,(/PGM)        |__________|
  36523          A0  | 12        21 |  D7
  36524          D0  | 13        20 |  D6
  36525          D1  | 14        19 |  D5
  36526          D2  | 15        18 |  D4
  36527         GND  | 16        17 |  D3
  36528              |______________|
  36529 
  36530 Note
  36531 Instead of the above internal mod, the nocash kernel clone can be also
  36532 installed on cheat devices, which do also include DB25 connectors for parallel
  36533 port uploads, too.
  36534 For DB25 parallel port uploads, do the following mods to the cheat device:
  36535  - Datel: use the FiveWire mod to get it parallel port compatible
  36536  - Xplorer: simply wire DB25./INIT to EXP./RESET (with diode, if needed)
  36537 
  36538 Mods - PAL/NTSC Color Mods
  36539 --------------------------
  36540 
  36541 The PSX hardware is more or less capable of generating both PAL and NTSC
  36542 signals. However, it's having the bad habbit to do this automatically depending
  36543 on the game's frame rate. And worse, it's doing it regardless of whether the
  36544 board is having matching oscillators installed (eg. a PAL board in 60Hz mode
  36545 will produce NTSC encoding with faulty NTSC color clock).
  36546   color encoding    PAL             NTSC
  36547   color clock       4.43361875MHz   3.579545MHz
  36548   frame rate        50Hz            60Hz
  36549 
  36550 RGB Cables
  36551 RGB cables don't rely on composite PAL/NTSC color encoding, and thus don't need
  36552 any color mods (except, see the caution on GNDed pins for missing
  36553 53.20MHz/53.69MHz oscillators below).
  36554 
  36555 Newer Consoles (PU-22, PU-23, PM-41, PM-41(2))
  36556 These consoles have 17.734MHz (PAL) or 14.318MHz (NTSC) oscillators with
  36557 constant dividers, so the color clock will be always constant, and one does
  36558 only need to change the color encoding:
  36559   /PAL (IC502.CXA2106R.pin13) ---/cut/--- /PAL (GPU.pin157)
  36560   /PAL (IC502.CXA2106R.pin13) ----------- GND (PAL) or VCC (NTSC)
  36561 This forces the console to be always producing the desired composite color
  36562 format (regardless of whether the GPU is in 50Hz or 60Hz mode).
  36563 That works for NTSC games on PAL consoles (and vice-versa). However, it won't
  36564 work for NTSC consoles with PAL TV Sets (for that case it'd be easiest to
  36565 install an extra oscillator, as done on older consoles).
  36566 
  36567 Older Consoles (PU-7, PU-8, PU-16, PU-18, PU-20)
  36568 These consoles have 53.20MHz (PAL) or 53.69MHz (NTSC) oscillators and the GPU
  36569 does try to change the clock divider depending on the frame rate (thereby
  36570 producing a nonsense clock signal that's neither PAL nor NTSC). Best workaround
  36571 is to install an extra 4.43361875MHz (PAL) or 3.579545MHz (NTSC) oscillator
  36572 (with internal amplifier, ie. in 4pin package, which resembles DIP14, hence the
  36573 pin 1,7,8,14 numbering):
  36574   GPU ------------------/cut/--- CXA1645M.pin6  SCIN
  36575   GPU ------------------/cut/--- CXA1645M.pin7  /PAL
  36576   Osc.pin14 VCC ---------------- CXA1645M.pin12 VCC (5V)
  36577   Osc.pin7  GND ---------------- CXA1645M.pin1  GND
  36578   Osc.pin8  OUT ---------------- CXA1645M.pin6  SCIN
  36579   Osc.pin1  NC  --
  36580   GND (PAL) or VCC (NTSC) ------ CXA1645M.pin7  /PAL
  36581 Caution: Many mainboards have solder pads for both 53.20MHz and 53.69MHz
  36582 oscillators, the missing oscillator is either GNDed or shortcut with the
  36583 installed oscillator (varies from board to board, usually via 0 ohm resistors
  36584 on PCB bottom side). If it's GNDed, remove that connection, and instead have it
  36585 shortcut with the installed oscillator.
  36586 Alternately, instead of the above mods, one could also install the missing
  36587 oscillator (and remove its 0 ohm resistor), so the board will have both
  36588 53.20MHz and 53.69MHz installed; that will produce perfect PAL and NTSC signals
  36589 in 50Hz and 60Hz mode accordingly, but works only if the TV Set recognizes both
  36590 PAL and NTSC signals.
  36591 
  36592 Notes
  36593 External 4.433MHz/3.579MHz osciallors won't be synchronized with the GPU frame
  36594 rate (normally you don't want them to be synchronized, but there's some small
  36595 risk that they might get close to running in sync, which could result in static
  36596 or crawling color artifacts).
  36597 For the CXA1645 chip modded to a different console region, one should also
  36598 change one of the resistors (see datasheet), there's no noticable difference on
  36599 the TV picture though.
  36600 
  36601 Region Checks
  36602 Some kernel versions contain regions checks (additionally to the SCEx check),
  36603 particulary for preventing NTSC games to run on PAL consoles, or non-japanese
  36604 games on japanese consoles. Some PAL modchips can bypass that check (by
  36605 patching the region byte in BIOS). Expansions ROMs or nocash kernel clone could
  36606 be also used to avoid such checks.
  36607 
  36608 
  36609 No$psx Emulation Controls
  36610 -------------------------
  36611 
  36612 Below are hotkeys & controls for the no$psx emulator.
  36613 
  36614 Emulation Hotkeys
  36615   ESC           Stop Emulation (switch to debugger)
  36616   Keypad-Mul    Reset
  36617   Keypad-Sub    Same as ESC
  36618   Keypad-Add    Whoosh (run as fast as possible)
  36619   Backspace     Whoosh (run as fast as possible)
  36620 
  36621 Mouse Controller Emulation (via Mouse)
  36622   Left-Mouse-Button   --> Pass mouse to PSX Emulation
  36623   Middle-Mouse-Button --> Pass mouse to Operation System
  36624   ESC                 --> Pass mouse to Operation System
  36625 
  36626 Lightguns (Namco GunCon, and Konami IRQ10) (via Mouse)
  36627   Mouse Position  --> Lightgun Position
  36628   Left Button     --> Lightgun Trigger
  36629   Middle Button   --> Namco Button A (left), or Konami Start Button (left)
  36630   Right Button    --> Namco Button B (right), or Konami Back Button (rear)
  36631 XXX Konami (IRQ10) Lightguns aren't working yet (the actual lightgun is
  36632 implemented, but the required timer0 dotclk mode isn't yet properly emulated).
  36633 
  36634 Dance Mat (via Keyboard)
  36635   Q W E  or  Keypad: 7 8 9  -->  ><  Up  ()
  36636   A   D  or  Keypad: 4   6  -->  Lt      Rt
  36637   Z X C  or  Keypad: 1 2 3  -->  []  Dn  /\
  36638 Plus, Select/Start as assigned for joypads.
  36639 
  36640 No$psx Emulation Files
  36641 ----------------------
  36642 
  36643 CDROM Images
  36644 CDROMs are supported via complete disk images (in .CCD+IMG, .CDI, .CUE+BIN,
  36645 .MDS+MDF, or .NRG format), via single-track images (.ISO files), or as raw
  36646 executables (.EXE files).
  36647 Decompressing .ECM and .CDZ files is supported. Subchannel data (for
  36648 libcrypt'ed games) can be read from .SBI, .M3S, .SUB, .MDF files. Reading from
  36649 real CDROM drives is also supported, but does require wnaspi32.dll (which
  36650 appears to be a problem on WinNT/Win2K and higher).
  36651 
  36652 Memory Card Images
  36653 Memory Cards are stored as 128Kbyte .MCD files in MEMCARD directory. If a CDROM
  36654 image is loaded, then the first memory card (for machine 1, slot 1A) will be
  36655 assigned to "<cdrom_filename>.mcd". The other memory cards (for other slots or
  36656 other machines) are just using general filenames: "_MM_N_X_.mcd"; with
  36657 MM=Machine (01 and up), N=Slot (1 or 2), X=Multitap Sub-Slot (A..D).
  36658 To manage files in memory cards via BIOS boot menu: Eject CDROM and reset
  36659 emulation (to get to the boot menu), then load a CDROM image with the Autostart
  36660 checkbox disabled in lower-left (this will load the corresponding memory card
  36661 alongsides with the CDROM, and stays in boot menu as autostart is off).
  36662 
  36663 BIOS ROM Image
  36664 No$psx contains its own PSX BIOS clone. Optionally, a copy of the original PSX
  36665 BIOS can be stored as file PSX-BIOS.ROM in no$psx folder. Doing that may be
  36666 useful for two purposes:
  36667 Compatibility Issues: There are no known problems, but please let me know if
  36668 you discover a game that works only with the original BIOS, but not with the
  36669 nocash BIOS.
  36670 Font Issues: The nocash BIOS doesn't contain its own SHIFT-JIS font (this font
  36671 is used by a few games; mainly in memory card screens). By default, the nocash
  36672 BIOS copies the font from PSX-BIOS.ROM (if it is present), otherwise it uses
  36673 fonts from the operating system: The so-called "MS Gothic" font (if you have
  36674 japanese fonts installed on your computer), or otherwise "Courier New" (which
  36675 covers only latin letters of course).
  36676 Notes: There's is also a setup option to select between nocash BIOS and
  36677 original BIOS (the default is to use original BIOS, if present). Aside from
  36678 using the fixed PSX-BIOS.ROM filename, you can also select .ROM files in the
  36679 CDROM loading screen (useful if you want to test different BIOS versions).
  36680 
  36681 Expansion ROM Image
  36682 Expansion ROMs can be loaded via CDROM loading screen. Supported file
  36683 extensions are .ROM (raw rom-image) and .FCD (encrypted Xplorer rom-image). The
  36684 files must contain valid Expansion ROM IDs at offset 004h and/or 084h,
  36685 otherwise they are treated as normal BIOS ROMs. Typical expansion ROMs are
  36686 Cheat Device firmwares; there is no real use loading these into no$psx, except
  36687 for viewing them in the debugger.
  36688 Note: Some expansions do work only with original Sony BIOS (for example, Caetla
  36689 is using various hardcoded BIOS addresses which are incompatible with no$psx
  36690 BIOS clone). On the contrary, Xplorer is working only with no$psx BIOS clone
  36691 (with Sony BIOS it would place a COP0 break inside of a branch delay, which
  36692 isn't supported by no$psx). Action Replay may refuse to start GPU transfers
  36693 unless the GPU is NOT ready for transfer (due to misunderstanding GPU status
  36694 bits) (this does actually 'work' on real hardware because the GPU isn't
  36695 <instantly> ready, but that effect isn't yet emulated in no$psx, so it works
  36696 only when manually skipping the faulty waitloop in the debugger).
  36697 
  36698 CDROM BIOS Image
  36699 If present, file MC68HC05.ROM (16.5kbytes) is loaded automatically as CDROM
  36700 BIOS image (alternately it can be loaded manually via file menu, which treats
  36701 any 16.5Kbyte .ROM file as CDROM BIOS image). The file used ONLY if low level
  36702 CDROM BIOS emulation is enabled in setup.
  36703 In low level mode, timings and responses to cdrom commands are closer to real
  36704 hardware, which might be useful for bug testing, but otherwise it isn't too
  36705 useful or recommended (the more accurate seek times are making the cdrom
  36706 emulation much slower; the SCEx protection is also emulated, meaning that
  36707 region problems may occur when using a CDROM BIOS version that doesn't match
  36708 the CDROM DISC region).
  36709 In the debugger, use Ctrl+T toggle between MIPS and HC05 disassembler view. The
  36710 TTY window can log various HC05 I/O events (eg. Spindle and Sled control).
  36711 
  36712 No$psx Emulation Notes
  36713 ----------------------
  36714 
  36715 Important Notes
  36716 Do not expose the emulator to extreme heat, cold, noise, darkness, or direct
  36717 sunlight.
  36718 Do not drink, eat, or smoke when using this software.
  36719 Sit upright and put your hands on the table.
  36720 Defragment your harddisk weekly.
  36721 Use specialized defragmentation tools.
  36722 This product may contain rude and disturbing language.
  36723 
  36724 
  36725 No$psx Debugger - Hotkeys in Debug Mode
  36726 ---------------------------------------
  36727 
  36728 Most debug functions are available via hotkeys and via mouse accessible popup
  36729 boxes. The popup boxes generally also show the corresponding hotkey.
  36730 
  36731  Cursor             (*) Move around
  36732  Cursor Right           Follow (in codewin: map window to jump/call dest adr)
  36733  Cursor Right           Follow (in stckwin: map codewin to return adr)
  36734  Cursor Left            Undo follow (if nothing to undo: goto program counter)
  36735  Page Up/Down       (*) Move around
  36736  Home               (*) Goto Start or to 0000
  36737  End                (*) Goto End
  36738  Ret                (*) Center/Uncenter current line in code window
  36739  Shift+Cursor           Change Active Window (Code,Data,Stck,Regs)
  36740  Shift+Cursor       (*) Toggle between Hex- and Ascii-input in data window
  36741  Tab                (*) Toggle Standard and Symbolic Display in code window
  36742  Tab                (*) Toggle Lower Window (Data or Break/Watch)
  36743  Ctrl+B                 Enter Breakpoint Address, Condition
  36744  Ctrl+N                 Find Next Breakpoint
  36745  Ctrl+G                 Goto Address (prompts for address) (does not affect pc)
  36746  Ctrl+E             (*) Toggle Warnings on/off
  36747  Ctrl+O                 OS Shell (calls DOS, type 'exit' to come back)
  36748  Ctrl+I                 Inspect (Define Watchpoint address)
  36749  Ctrl+R                 Reload Cartridge
  36750  Ctrl+S                 Search (see below! this works a bit strange)
  36751  Ctrl+C                 Continue Search
  36752  Ctrl+V            (**) Toggle Screen Size 25/50 lines (DOS version only)
  36753  Ctrl+D                 Toggle Datazone (see below)
  36754  Ctrl+A/T/X         (*) Add/Toggle/Remove Machine (up to 12 consoles at 1 time)
  36755                         Ctrl+T also toggles MIPS/HC05 (if low-level CD enabled)
  36756  Ctrl+L/W               Load/Save Snapshot (RAM, CPU-state and ROM-cartname)
  36757  Ctrl+Left/Right    (*) Decrease/Increase start address of window by one byte
  36758  <..>                   Assemble into Memory (input box appears on 1st char)
  36759  F1                     Help
  36760  F2                     Toggle Breakpoint at cursor
  36761  F3                     Trace with calls executed
  36762  F4                     Run to Cursor
  36763  F5                     VRAM Viewer (last accessed screen, TAB toggles)
  36764  F6                     Jump to Cursor (sets programcounter (pc) and rombank)
  36765  F7                     Trace (Execute one instruction)
  36766  F8                     Run until current sub-routine returns
  36767  F9                     Run (until breakpoint or user break)
  36768  F10                    Hardware Info Screen (splits in 50 lines DOS mode)
  36769  F11                    Setup Screen (last accessed setup window)
  36770  F12                    Cartridge Menu (last accessed, filename or files.lst)
  36771  Scroll Lock            Toggle Datacur follows Codecur (or 16bit reg) on/off
  36772  Keypad "/"             Run one Frame
  36773  Keypad "*"             Reset and Run
  36774  Keypad "-"         (*) Continue Run (same as F9)
  36775  ESC                (*) Popup File Menu or close current window/menu
  36776  Alt+<..>           (*) Popup Menus (eg. Alt+F for File Menu)
  36777  Alt+A                  Animate (Repeated trace until key pressed)
  36778  Alt+B                  Place Bookmark
  36779  Alt+E                  Edit File
  36780  Alt+P                  Profiler Window
  36781  Alt+X                  Exit No$psx
  36782  Right Mouse Button (*) DOS: Continue Run (same as F9), Windows: Context Menu
  36783  Left Mouse Button  (*) Select Window, Place Cursor, Toggle Breakpoint or
  36784                          CPU-flag, Open Popup Menu, Click Option, etc.
  36785 
  36786 The functions that are marked by (*) are not shown in the popup menues of the
  36787 menu bar. Vice versa, not all functions can be accessed through hotkeys, so to
  36788 be able to access all functions you must use both hotkeys and menu bars.
  36789 
  36790 No$psx Debugger - Breakpoints
  36791 -----------------------------
  36792 
  36793 Normal Breaks (F2-key)
  36794 Normal breakpoints are set (or removed) by moving the code-window cursor onto
  36795 the desired opcode, and then pushing the F2-key.
  36796 
  36797 Run-to-Cursor (F4-key)
  36798 Hitting F4-key directly starts emulation, and stops when reaching the code
  36799 window cursor. The break address is not memorized, ie. it is used only once.
  36800 
  36801 Global Memory Read/Write Breaks
  36802 This break-family allows to capture reads/writes to specific memory addresses,
  36803 or memory areas. Membreaks are defined by pressing Ctrl+B, and then entering a
  36804 memory address or area in square brackets,
  36805   [3007FFc]            single address (eg. IRQ vector)
  36806   [6000000..6003fff]   memory area    (eg. first 16K of VRAM)
  36807 followed by question and/or exclamation marks, indicating the type,
  36808   ?     break on any read (from specified address/area)
  36809   !?    break on any read or changed write
  36810   !!?   break on any read or any write
  36811   !     break on changed write
  36812   !!    break on any write
  36813 Question marks ("?") capture reads. Double exclamation marks ("!!") will
  36814 capture ALL writes, single exclamation marks ("!") capture only writes that are
  36815 changing the memory content (ie. the new data must be different than old data).
  36816 The ordering (eg. "!!?" or "!?!" or "?!!") is don't care.
  36817 
  36818 Local Conditional Breakpoints
  36819 [XXX this isn't yet fully implemented in no$psx]
  36820 Press Ctrl-B and define the break by entering "address, condition". The
  36821 emulator will stop when the program counter reaches the address, and when the
  36822 condition is true. The "$" symbol represents the current cursor address of code
  36823 window. Examples:
  36824   $, r1<>0           --> break at cursor position if r1 is non-zero
  36825   $, r1 & 2          --> break at cursor position if bit 1 of r1 is set
  36826   $, r1 !& 2         --> break at cursor position if bit 1 of r1 is zero
  36827   8001234, [r1]=r2   --> break at 8001234 if r1 points at a value equal to r2
  36828   wrchr              --> break at wrchr (always, no condition, same as F2-key)
  36829   wrchr, r1=0d       --> break at wrchr if r1 contains 0dh
  36830   $, [4000006] > 0A0 --> break at cursor if VCOUNT is greater than 0A0h
  36831   $, r4 <= r5        --> break at cursor if r4 is less or equal than r5
  36832   $, [r4] <> [r5]    --> break at cursor if r4 points at other value than r5
  36833   mainloop, ..5      --> break every 5th time that pc gets to mainloop (timer)
  36834 The conditions are verified BEFORE the instruction is executed.
  36835   Operators:              Operands:          Timer Identifier:
  36836   ==  =   <   >   &       n   [nn]  r        ..
  36837   !=  <>  <=  >=  !&      nn  [rr]  rr
  36838 Operators == and != are pseudonyms for = and <>
  36839 
  36840 Global Conditional Breakpoints
  36841 [XXX this isn't yet fully implemented in no$psx]
  36842 Global breaks are working exactly as above local breaks, except that the
  36843 condition is verfied after <each> executed opcode. In the Ctrl+B window, enter
  36844 a condition (without specifying a address). Examples:
  36845   r1 = 0            --> break whenever register r1 becomes zero
  36846   [4000006]>20      --> break whenever VCOUNT becomes greater than 20h
  36847 The emulator stops only when a condition changes from false to true, ie. it
  36848 does not permanently break after each opcode if the condition stays true for a
  36849 while.
  36850 
  36851 The Break Window
  36852 The lower left window of the debug screen is shared for Data and Breakpoints,
  36853 use TAB-key in this window to switch between Data and Break windows. The Break
  36854 window lists all defined breakpoints, DEL-key can be used to delete a selected
  36855 breakpoint. When pressing ENTER on a local breakpoint, the code window will be
  36856 moved to the break address, this works also for bookmarks (that are
  36857 non-functional 'dummy' breaks, defined by Alt+B key in code window).
  36858 
  36859 No$psx Debugger - General Debug Features
  36860 ----------------------------------------
  36861 
  36862 Cursor Left/Right - Follow and Undo Follow
  36863 Cursor Right in the code window moves the code window to the jump-target of the
  36864 current opcode (if it is a jump/call opcode), or the data window to the memory
  36865 access address (for load/store opcodes). Cursor Right in the stack window moves
  36866 the code window to return addresses pushed on stack.
  36867 Cursor Left in code/stack windows does undo the above (moves the windows back
  36868 to their old addresses). Undo works also after goto (ctrl+g), and after running
  36869 the emulation (eg. via F9-key). If there aren't any undo addresses memorized,
  36870 then Cursor Left moves the code window to the program counter (PC).
  36871 
  36872 Changing MIPS register values
  36873 In the debugger code window, typing text does prompt for MIPS assembler
  36874 instructions to be entered. However, the assembler input box does also accept
  36875 register assignments: For example, "r1=12345678" or "sp=8001FFFF".
  36876 
  36877 Dummy-Mappings
  36878 In the debugger code/data windows, some unused addresses in the PSX memory map
  36879 are misused to view "hidden" memory that is normally not part of the PSX memory
  36880 map:
  36881   60000000h = vram
  36882   70000000h = spu-ram
  36883 
  36884 Filesystem Viewer (Window --> Filesystem)
  36885 Allows to view the contents of the CDROM image (and memory cards). The whole
  36886 filesystem is shown as tree view, which can be neatly browsed via cursur keys:
  36887   Up/Down     Select current item
  36888   Left/Right  Open/close folders and archives
  36889 The viewer supports hundreds of archive formats, and dozens of compression and
  36890 bitmap formats. The supported formats are documented here:
  36891 --> CDROM File Formats
  36892 
  36893 XED Editor
  36894 ----------
  36895 
  36896 --> XED About
  36897 --> XED Hotkeys
  36898 --> XED Assembler/Debugger Interface
  36899 --> XED Commandline based standalone version
  36900 
  36901 XED About
  36902 ---------
  36903 
  36904 About XED
  36905 XED is a text editor, the executable is fast and small, and it includes
  36906 comfortable editing functions. It is both intended for standard .TXT files (or
  36907 any other ASCII files, such like .ASM for assembler source code). Also, the
  36908 line-wrapping support (.XED files) can be used for authoring stories,
  36909 specifications, etc. Most of the features are much the same as for other text
  36910 editors, some special functions are pointed out below:
  36911 
  36912 Block Selection
  36913 XED supports good old quality block mechanisms, allowing to copy/move the
  36914 selection directly to cursor position by Ctrl+K,C/V hotkeys (without needing to
  36915 use paste). For data exchange with other programs or text files, the block can
  36916 be directly written to (or loaded from) file by Ctrl+K,R/W. And, mainstream
  36917 copy/cut/paste functions are supported as well, by Ctrl+Ins, Shift+Del,
  36918 Shift+Ins.
  36919 Note: The block remains selected even when typing text, and it won't get
  36920 deleted when touching Del-key.
  36921 
  36922 Condensed Display Mode
  36923 Condensed mode is activated by "F6,C" key combination. In this mode, only lines
  36924 beginning with colon ":", or (for assembler source code files) with
  36925 semicolon-colon ";:", for example:
  36926   :Chapter IV
  36927   ;:---Sound Engine---
  36928 Normal block functions can be used in this mode to Move, Copy, or Delete whole
  36929 'chapter(s)'. Cursor keys can be used to move the cursor to a specific chapter.
  36930 Pushing Enter or Escape terminates condensed mode.
  36931 
  36932 Column Block Mode
  36933 Column mode is activated by "Ctrl+K,N" key combination. In this mode, the block
  36934 selection appears as a rectangular area, allowing to deal with tables & columns
  36935 in text files by using copy/delete, indent/unindent block functions.
  36936 Typing "Ctrl+K,N" again will return to normal block mode (in which any lines
  36937 between begin/end of the block will be selected at full length).
  36938 
  36939 Blank Space
  36940 Unlike most other editors, XED allows to move the cursor to any screen
  36941 location, including at horizontal positions after the end of the current line.
  36942 Entering space characters at such locations advances the cursor position, but
  36943 does not actually store space characters in the file.
  36944 When typing text, spaces are automatically inserted between line-end and cursor
  36945 position. Respectively, ending spaces are automatically deleted (eg. assume
  36946 that the line contains "Hello !", deleting "!" will also remove the space
  36947 character, internally).
  36948 That is of course all happening behind your back, you won't have to care about
  36949 it - but you can be sure that there'll be no hidden spaces filling up disk
  36950 space.
  36951 
  36952 Tabulation Marks / TAB-Key
  36953 The TAB Key advances the cursor to the next higher tabulation location (usually
  36954 in steps of eight columns, counted from leftmost screen border), and the
  36955 appropriate number of spaces is inserted into the file if necessary.
  36956 In overwrite mode (de-/activated by INS Key), the TAB Key simply advances the
  36957 cursor without actually inserting spaces (and without overwriting existing text
  36958 by spaces).
  36959 
  36960 Tabulation Marks / CHR(9)
  36961 When enabled in setup (default), TAB marks are automatically expanded into
  36962 appropriate number of spaces (ie. towards next "8-column" position) when
  36963 loading a file.
  36964 The file is normally saved by using raw SPC characters, without any TABs.
  36965 Optionally, it can be saved by using "best-fill" SPCs and TABs (disabled by
  36966 default), that feature may conflict with third party tools (assemblers,
  36967 compilers, etc). In order to reduce the risk of such problems, best-fill is
  36968 suppressed in quoted lines (by using ' or " or <> quotation marks, eg. db
  36969 'Hello !').
  36970 
  36971 Line Wrapping
  36972 Line wrapping is enabled/disabled by "F5+W" key combination. Wrapping is
  36973 automatically enabled when loading a file with extension ".XED".
  36974 In the file, wrapped lines are using CR characters as soft linebreaks,
  36975 paragraphs are terminated by normal CR,LF characters.
  36976 Note: It'd be recommended to convert .XED files into 'standard' formats such
  36977 like .TXT or .HTM before releasing them, but preferably NOT into disliked
  36978 bloated file formats such like .PDF or .DOC.
  36979 
  36980 Word Processing
  36981 Aside from the above line-wrapping support, no other 'word processing' features
  36982 are included, the program provides normal 'type writer' functions, not more,
  36983 not less. In particular, any overload such like bold or colored text, big and
  36984 small fonts, bitmaps and different fonts are disliked.
  36985 
  36986 XED Hotkeys
  36987 -----------
  36988 
  36989 XED recognizes both CP/M Wordstar hotkeys (also used by Borland PC compilers),
  36990 and Norton editor hotkeys (NU.EXE). The "Ctrl+X,Y" style hotkeys are wordstar
  36991 based, particulary including good block functions. The F4,X and Alt/Ctrl+X type
  36992 hotkeys are norton based, particulary very useful for forwards/backwards
  36993 searching.
  36994 
  36995 Standard Cursor Keys
  36996   Up         Move line up
  36997   Down       Move line down
  36998   Left       Move character left
  36999   Right      Move character right
  37000   Pgup       Scroll page up / to top of screen
  37001   Pgdn       Scroll page down / to bottom of screen
  37002   Ctrl+Home  Go to start of file
  37003   Ctrl+End   Go to end of file
  37004   Ctrl+Pgup  Go to start of previous chapter
  37005   Ctrl+Pgdn  Go to start if next chapter
  37006   Home       Go to start of line
  37007   End        Go to end of line
  37008   Ctrl+Left  Move word left
  37009   Ctrl+Right Move word right
  37010   Ins        Toggle Insert/Overwrite mode
  37011   Del        Delete char below cursor
  37012   Backspace  Delete char left of cursor
  37013   Tab        Move to next tabulation mark
  37014   Enter      New line/paragraph end
  37015   Esc        Quit (or Alt+X, F3+Q, Ctrl+K+D, Ctrl+K+Q, Ctrl+K+X)
  37016 Note: Pgup/Pgdn are moving the cursor to top/bottom of screen, page scrolling
  37017 takes place only if the cursor was already at that location.
  37018 
  37019 Editor Keys
  37020   Ctrl+Y     Delete line (or Alt+K)
  37021   Alt+L      Delete to line end (or Ctrl+Q,Y)
  37022   Alt+V      Caseflip to line end
  37023   Ctrl+V     Caseflip from line beginning
  37024 
  37025 Norton Search/Replace Functions
  37026   Alt+F      Norton - search/replace, forwards
  37027   Ctrl+F     Norton - search/replace, backwards
  37028   Alt+C      Norton - continue search/replace, forwards  (or Ctrl+Down)
  37029   Ctrl+C     Norton - continue search/replace, backwards (or Ctrl+Up)
  37030 Search: Type "Alt/Ctrl+F, String, Enter".
  37031 Search+replace: "Type Alt/Ctrl+F, String1, Alt+F, String2, Enter".
  37032 Non-case sensitive: Terminate by Escape instead of Enter.
  37033 
  37034 Wordstar Search/Replace Functions
  37035   Ctrl+Q,F   Wordstar - search
  37036   Ctrl+Q,A   Wordstar - replace
  37037   Ctrl+L     Wordstar - continue search/replace
  37038 Search options: B=Backwards, G=Global, N=No query,
  37039 U=non-casesensitive, W=whole words only, n=n times.
  37040 
  37041 Disk Commands
  37042   F3,E       Save+exit
  37043   F3,S       Save (or Ctrl+K,S)
  37044   F3,N       Edit new file
  37045   F3,A       Append a file
  37046 See also: Block commands (read/write block).
  37047 
  37048 Block Selection
  37049   Shift+Cursor  Select block begin..end
  37050   Ctrl+K,B   Set block begin (or F4,S)
  37051   Ctrl+K,K   Set block end   (or F4,S)
  37052   Ctrl+K,H   Remove/hide block markers (or F4,R)
  37053   F4,L       Mark line including ending CRLF (or Ctrl+K,L)
  37054   F4,E       Mark line excluding ending CRLF
  37055   Ctrl+K,T   Mark word
  37056   Ctrl+K,N   Toggle normal/column blocktype
  37057 
  37058 Clipboard Commands
  37059   Shift+Ins  Paste from Clipboard
  37060   Shift+Del  Cut to Clipboard
  37061   Ctrl+Ins   Copy to Clipboard
  37062   Ctrl+Del   Delete Block
  37063 
  37064 Block Commands
  37065   Ctrl+K,C   Copy block (or F4,C)
  37066   Ctrl+K,V   Move block (or F4,M)
  37067   Ctrl+K,Y   Delete block (or F4,D)
  37068   Ctrl+K,P   Print block  (or F7,B)
  37069   Ctrl+Q,B   Find block begin (or F4,F)
  37070   Ctrl+Q,K   Find block end   (or F4,F)
  37071   Ctrl+K,R   Read block from disk towards cursor location
  37072   Ctrl+K,W   Write block to disk
  37073   Ctrl+K,U   Unindent block (delete one space at begin of each line)
  37074   Ctrl+K,I   Indent block (insert one space at begin of each line)
  37075   F5,F       Format block (with actual x-wrap size) (or ;Ctrl+B)
  37076   F8,A       Add values within column-block
  37077 
  37078 Setup Commands
  37079   F11        Setup menu (or F8,S)
  37080   F5,S       Save editor configuration
  37081   F5,L       Set line len for word wrap (or Ctrl+O,R)
  37082   F5,W       Wordwrap on/off (or Ctrl+O,W) (*)
  37083   F5,I       Auto indent on/off (or Ctrl+O,I)
  37084   F5,T       Set tab display spacing
  37085 (*) Wrapped lines will be terminated by CR, paragraphs by CRLF.
  37086 
  37087 Other
  37088   F1         Help
  37089   F2         Status (displays info about file & currently selected block)
  37090   F8,M       Make best fill tabs
  37091   F8,T       Translate all tabs to spaces
  37092   SrcLock    Freeze cursor when typing text ("useful" for backwards writing)
  37093   Ctrl+O,C   Center current line
  37094   Ctrl+K,#   Set marker (#=0..9)
  37095   Ctrl+Q,#   Move to marker (#=0..9)
  37096   Ctrl+Q,P   Move to previous pos
  37097   F6,C       Condensed display mode on/off (*)
  37098   Ctrl+G     Go to line nnnn (or F6,G) (or commandline switch /l:nnnn)
  37099 (*) only lines starting with ':' or ';:' will be displayed. cursor and block
  37100 commands can be used (e.g. to copy a text-sequence by just marking it's
  37101 headline)
  37102 
  37103 Hex-Edit Keys (Binary Files)
  37104 This mode is activated by /b commandline switch, allowing to view and modify
  37105 binary files. Aside from normal cursor keys, the following hotkeys are used:
  37106   Tab        Toggle between HEX and ASC mode (or Shift+Left/Right)
  37107   Ctrl+Arrow Step left/right one full byte (instead one single HEX digit)
  37108   Ctrl+G     Goto hex-address
  37109   Ctrl+K,S   Save file (as usually)
  37110 
  37111 Printer Commands
  37112   F7,P       Print file
  37113   F7,B       Print block (or Ctrl+K,P)
  37114   F7,E       Eject page
  37115   F7,S       Set page size
  37116 More printer options can be found in setup. Printing was working well (at least
  37117 with my own printer) in older XED versions, but it is probably badly bugged (at
  37118 least untested) for years now.
  37119 
  37120 XED Assembler/Debugger Interface
  37121 --------------------------------
  37122 
  37123 Nocash Debuggers
  37124 The XED editor provides simple but very useful interaction with the various
  37125 nocash debuggers/emulators (no$gba, no$gmb, no$cpc, no$msx, no$c64, no$2k6,
  37126 no$zx, no$nes, no$sns, no$x51).
  37127 The editor can be launched from inside of the debugger (by Alt+E hotkey, by
  37128 retaining the recently edited line number when re-launching the editor).
  37129 And, when editing assembler source code files, F9-key can used to launch the
  37130 assembler from inside of XED. That is, the file is saved to disk, the A22i
  37131 assembler is started (built-in in all debuggers), and, in case of successful
  37132 assembly, the program is loaded & started in the emulator. Otherwise, the
  37133 assembler displays a list of errors, and the editor is moved directly to the
  37134 source code line number in which the first error has occured.
  37135 
  37136 16bit DOS debuggers
  37137 The XED editor is included built-in in all nocash windows debuggers, and in the
  37138 no$gba 32bit DOS version only.
  37139 For use with other nocash 16bit DOS debuggers the XED editor must be downloaded
  37140 separately at http://problemkaputt.de/xed.htm, and must be installed in a
  37141 directory which is included in your PATH statement.
  37142 
  37143 XED Commandline based standalone version
  37144 ----------------------------------------
  37145 
  37146 Standalone 16bit DOS version
  37147 This version is written in turbo pascal, nevertheless fast enough to work on
  37148 computer with less than 10MHz. It uses 16bit 8086 code, and works with all
  37149 80x86 compatible CPUs, including very old XTs.
  37150 The downside is that it is restricted to Conventional DOS Memory, so that the
  37151 maximum filesize is 640K (actually less, because the program and operating
  37152 system need to use some of that memory).
  37153 
  37154 Using the 32bit debugger-built-in version as 32bit standalone editor
  37155 I haven't yet compiled a 32bit standalone version, however, any of the no$xxx
  37156 32bit debuggers can be used for that purpose. By commandline input:
  37157   no$xxx /x <filename>   Edit text file in standalone mode
  37158   no$xxx /b <filename>   Edit binary file in standalone hexedit mode
  37159 
  37160 Standalone Commandline Syntax
  37161 Syntax: XED <filename> [/l:<line number>] | /?
  37162   <name>    Filename, optionally d:\path\name.ext
  37163   /?        Displays commandline help
  37164   /l:<nnn>  Moves to line number nnn after loading
  37165 The filename does not require to include an extension, the program
  37166 automatically loads the first existing file with any of following extensions
  37167 appended: XED, ASM, ASC, INC, BAT, TXT, HTM, DOC, A22, PAS.
  37168 
  37169 Standalone DOS Return Value
  37170 XED returns a three-byte return value after closing the program. This data is
  37171 used when calling XED as external editor from inside of nocash DOS debuggers,
  37172 but it might be also useful for other purposes.
  37173 Because normal DOS return values are limited to 8bits only, the three bytes are
  37174 written into video RAM at rightmost three character locations in first line:
  37175   VSEG:77*2  Exit code   (00h=Exit normal, F9h=Exit by F9-key)
  37176   VSEG:78*2  Line number (Lower 8bits, 1..65536 in total)
  37177   VSEG:79*2  Line number (Upper 8bits)
  37178 The color attribute for these characters is set to zero (invisible, black on
  37179 black). Use INT 10h/AH=0Fh to determine the current video mode (AL AND 7Fh), if
  37180 it is monochrome (07h) then use VSEG=B000h, otherwise VSEG=B800h.
  37181 
  37182 
  37183 
  37184 About & Credits
  37185 ---------------
  37186 
  37187 Credits
  37188 GPU.TXT by doomed/padua; based on info from K-communications & Nagra/Blackbag
  37189 GTE.TXT by doomed@c64.org / psx.rules.org
  37190 SPU.TXT by doomed@c64.org / psx.rules.org
  37191 CDINFO.TXT by doomed with big thanks to Barubary, who rewrote a large part
  37192 SYSTEM.TXT by doomed with thanx to Herozero for breakpoint info
  37193 PS_ENG.TXT PlayStation PAD/Memory Interface Protocol by HFB03536
  37194 IDT79R3041 Hardware User's Manual by Integrated Device Technology, Inc.
  37195 IDTR3051, R3052 RISController User's Manual by Integrated Device Technology
  37196 PSX.* by Joshua Walker (additional details in various distorted file formats)
  37197 LIBMIRAGE by Rok; info/source code for various cdrom-image formats
  37198 psxdev.ru; cdrom sub-cpu decapping
  37199 
  37200 PSXSPX homepage
  37201 http://problemkaputt.de/psx.htm       no$psx emulator/debugger
  37202 http://problemkaputt.de/psx-spx.htm   psx specs in html formal
  37203 http://problemkaputt.de/psx-spx.txt   psx specs in text formal
  37204 
  37205 Contact
  37206 http://problemkaputt.de/email.htm (spam-shielded)
  37207 
  37208 
  37209 Index
  37210 -----
  37211 
  37212 --> Contents
  37213 --> Memory Map
  37214 --> I/O Map
  37215 --> Graphics Processing Unit (GPU)
  37216 --> GPU I/O Ports, DMA Channels, Commands, VRAM
  37217 --> GPU Render Polygon Commands
  37218 --> GPU Render Line Commands
  37219 --> GPU Render Rectangle Commands
  37220 --> GPU Rendering Attributes
  37221 --> GPU Memory Transfer Commands
  37222 --> GPU Other Commands
  37223 --> GPU Display Control Commands (GP1)
  37224 --> GPU Status Register
  37225 --> GPU Versions
  37226 --> GPU Depth Ordering
  37227 --> GPU Video Memory (VRAM)
  37228 --> GPU Texture Caching
  37229 --> GPU Timings
  37230 --> GPU (MISC)
  37231 --> Geometry Transformation Engine (GTE)
  37232 --> GTE Overview
  37233 --> GTE Registers
  37234 --> GTE Saturation
  37235 --> GTE Opcode Summary
  37236 --> GTE Coordinate Calculation Commands
  37237 --> GTE General Purpose Calculation Commands
  37238 --> GTE Color Calculation Commands
  37239 --> GTE Division Inaccuracy
  37240 --> Macroblock Decoder (MDEC)
  37241 --> MDEC I/O Ports
  37242 --> MDEC Commands
  37243 --> MDEC Decompression
  37244 --> MDEC Data Format
  37245 --> Sound Processing Unit (SPU)
  37246 --> SPU Overview
  37247 --> SPU ADPCM Samples
  37248 --> SPU ADPCM Pitch
  37249 --> SPU Volume and ADSR Generator
  37250 --> SPU Voice Flags
  37251 --> SPU Noise Generator
  37252 --> SPU Control and Status Register
  37253 --> SPU Memory Access
  37254 --> SPU Interrupt
  37255 --> SPU Reverb Registers
  37256 --> SPU Reverb Formula
  37257 --> SPU Reverb Examples
  37258 --> SPU Unknown Registers
  37259 --> Interrupts
  37260 --> DMA Channels
  37261 --> Timers
  37262 --> CDROM Drive
  37263 --> CDROM Controller I/O Ports
  37264 --> CDROM Controller Command Summary
  37265 --> CDROM - Control Commands
  37266 --> CDROM - Seek Commands
  37267 --> CDROM - Read Commands
  37268 --> CDROM - Status Commands
  37269 --> CDROM - CD Audio Commands
  37270 --> CDROM - Test Commands
  37271 --> CDROM - Test Commands - Version, Switches, Region, Chipset, SCEx
  37272 --> CDROM - Test Commands - Test Drive Mechanics
  37273 --> CDROM - Test Commands - Prototype Debug Transmission
  37274 --> CDROM - Test Commands - Read/Write Decoder RAM and I/O Ports
  37275 --> CDROM - Test Commands - Read HC05 SUB-CPU RAM and I/O Ports
  37276 --> CDROM - Secret Unlock Commands
  37277 --> CDROM - Video CD Commands
  37278 --> CDROM - Mainloop/Responses
  37279 --> CDROM - Response Timings
  37280 --> CDROM - Response/Data Queueing
  37281 --> CDROM Disk Format
  37282 --> CDROM Subchannels
  37283 --> CDROM Sector Encoding
  37284 --> CDROM Scrambling
  37285 --> CDROM XA Subheader, File, Channel, Interleave
  37286 --> CDROM XA Audio ADPCM Compression
  37287 --> CDROM ISO Volume Descriptors
  37288 --> CDROM ISO File and Directory Descriptors
  37289 --> CDROM ISO Misc
  37290 --> CDROM Extension Joliet
  37291 --> CDROM File Formats
  37292 --> CDROM File Official Sony File Formats
  37293 --> CDROM File Playstation EXE and SYSTEM.CNF
  37294 --> CDROM File PsyQ .CPE Files (Debug Executables)
  37295 --> CDROM File PsyQ .SYM Files (Debug Information)
  37296 --> CDROM File Video Texture Image TIM/PXL/CLT (Sony)
  37297 --> CDROM File Video Texture/Bitmap (Other)
  37298 --> CDROM File Video Texture/Bitmap (TGA)
  37299 --> CDROM File Video Texture/Bitmap (PCX)
  37300 --> CDROM File Video 2D Graphics CEL/BGD/TSQ/ANM/SDF (Sony)
  37301 --> CDROM File Video 3D Graphics TMD/PMD/TOD/HMD/RSD (Sony)
  37302 --> CDROM File Video STR Streaming and BS Picture Compression (Sony)
  37303 --> CDROM File Video Streaming STR (Sony)
  37304 --> CDROM File Video Streaming STR Variants
  37305 --> CDROM File Video Streaming Framerate
  37306 --> CDROM File Video Streaming Audio
  37307 --> CDROM File Video Streaming Chunk-based formats
  37308 --> CDROM File Video Streaming Mis-mastered files
  37309 --> CDROM File Video BS Compression Versions
  37310 --> CDROM File Video BS Compression Headers
  37311 --> CDROM File Video BS Compression DC Values
  37312 --> CDROM File Video BS Compression AC Values
  37313 --> CDROM File Video BS Picture Files
  37314 --> CDROM File Video Wacwac MDEC Streams
  37315 --> CDROM File Video Polygon Streaming
  37316 --> CDROM File Audio Single Samples VAG (Sony)
  37317 --> CDROM File Audio Sample Sets VAB and VH/VB (Sony)
  37318 --> CDROM File Audio Sequences SEQ/SEP (Sony)
  37319 --> CDROM File Audio Streaming XA-ADPCM
  37320 --> CDROM File Audio CD-DA Tracks
  37321 --> CDROM File Archives with Filename
  37322 --> CDROM File Archives with Offset and Size
  37323 --> CDROM File Archives with Offset
  37324 --> CDROM File Archives with Size
  37325 --> CDROM File Archives with Chunks
  37326 --> CDROM File Archives with Folders
  37327 --> CDROM File Archive HUG/IDX/BIZ (Power Spike)
  37328 --> CDROM File Archive TOC/DAT/LAY
  37329 --> CDROM File Archive WAD (Doom)
  37330 --> CDROM File Archive WAD (Cardinal Syn/Fear Effect)
  37331 --> CDROM File Archive DIR/DAT (One/Viewpoint)
  37332 --> CDROM File Archive Darkworks Chunks (Alone in the Dark)
  37333 --> CDROM File Archive Blue Chunks (Blue's Clues)
  37334 --> CDROM File Archive HED/CDF (Parasite Eve 2)
  37335 --> CDROM File Archive IND/WAD (MTV Music Generator)
  37336 --> CDROM File Archive GAME.RSC (Colonly Wars Red Sun)
  37337 --> CDROM File Archive BIGFILE.DAT (Soul Reaver)
  37338 --> CDROM File Archive FF8 IMG (Final Fantasy VIII)
  37339 --> CDROM File Archive FF9 IMG (Final Fantasy IX)
  37340 --> CDROM File Archive GTFS (Gran Turismo 2)
  37341 --> CDROM File Archive Nightmare Project: Yakata
  37342 --> CDROM File Archive FAdj0500 (Klonoa)
  37343 --> CDROM File Archives in Hidden Sectors
  37344 --> CDROM File Archive HED/DAT/BNS/STR (Ape Escape)
  37345 --> CDROM File Archive WAD.WAD, BIG.BIN, JESTERS.PKG (Crash/Herc/Pandemonium)
  37346 --> CDROM File Archive BIGFILE.BIG (Gex)
  37347 --> CDROM File Archive BIGFILE.DAT (Gex - Enter the Gecko)
  37348 --> CDROM File Archive FF9 DB (Final Fantasy IX)
  37349 --> CDROM File Archive Ace Combat 2 and 3
  37350 --> CDROM File Archive NSD/NSF (Crash Bandicoot 1-3)
  37351 --> CDROM File Archive STAGE.DIR and *.DAT (Metal Gear Solid)
  37352 --> CDROM File Archive DRACULA.DAT (Dracula)
  37353 --> CDROM File Archive Croc 1 (DIR, WAD, etc.)
  37354 --> CDROM File Archive Croc 2 (DIR, WAD, etc.)
  37355 --> CDROM File Archive Headerless Archives
  37356 --> CDROM File Compression
  37357 --> CDROM File Compression LZSS (Moto Racer 1 and 2)
  37358 --> CDROM File Compression LZSS (Dino Crisis 1 and 2)
  37359 --> CDROM File Compression LZSS (Serial Experiments Lain)
  37360 --> CDROM File Compression ZOO/LZSS
  37361 --> CDROM File Compression Ulz/ULZ (Namco)
  37362 --> CDROM File Compression SLZ/01Z (chunk-based compressed archive)
  37363 --> CDROM File Compression LZ5 and LZ5-variants
  37364 --> CDROM File Compression PCK (Destruction Derby Raw)
  37365 --> CDROM File Compression GT-ZIP (Gran Turismo 1 and 2)
  37366 --> CDROM File Compression GT20 and PreGT20
  37367 --> CDROM File Compression HornedLZ
  37368 --> CDROM File Compression LZS (Gundam Battle Assault 2)
  37369 --> CDROM File Compression BZZ
  37370 --> CDROM File Compression RESOURCE (Star Wars Rebel Assault 2)
  37371 --> CDROM File Compression TIM-RLE4/RLE8
  37372 --> CDROM File Compression RLE_16
  37373 --> CDROM File Compression PIM/PRS (Legend of Mana)
  37374 --> CDROM File Compression BPE (Byte Pair Encoding)
  37375 --> CDROM File Compression RNC (Rob Northen Compression)
  37376 --> CDROM File Compression Darkworks
  37377 --> CDROM File Compression Blues
  37378 --> CDROM File Compression Z (Running Wild)
  37379 --> CDROM File Compression ZAL (Z-Axis)
  37380 --> CDROM File Compression EA Methods
  37381 --> CDROM File Compression EA Methods (LZSS RefPack)
  37382 --> CDROM File Compression EA Methods (Huffman)
  37383 --> CDROM File Compression EA Methods (BPE)
  37384 --> CDROM File Compression EA Methods (RLE)
  37385 --> CDROM File Compression ZIP/GZIP/ZLIB (Inflate/Deflate)
  37386 --> Inflate - Core Functions
  37387 --> Inflate - Initialization & Tree Creation
  37388 --> Inflate - Headers and Checksums
  37389 --> CDROM File Compression LArc/LHarc/LHA (LZS/LZH)
  37390 --> CDROM File Compression ARJ
  37391 --> CDROM File Compression ARC
  37392 --> CDROM File Compression RAR
  37393 --> CDROM File Compression ZOO
  37394 --> CDROM File Compression nCompress.Z
  37395 --> CDROM File Compression Octal Oddities (TAR, CPIO, RPM)
  37396 --> CDROM File Compression MacBinary, BinHex, PackIt, StuffIt, Compact Pro
  37397 --> CDROM File XYZ and Dummy/Null Files
  37398 --> CDROM Protection - SCEx Strings
  37399 --> CDROM Protection - Bypassing it
  37400 --> CDROM Protection - Modchips
  37401 --> CDROM Protection - Chipless Modchips
  37402 --> CDROM Protection - LibCrypt
  37403 --> CDROM Disk Images CCD/IMG/SUB (CloneCD)
  37404 --> CDROM Disk Images CDI (DiscJuggler)
  37405 --> CDROM Disk Images CUE/BIN/CDT (Cdrwin)
  37406 --> CDROM Disk Images MDS/MDF (Alcohol 120%)
  37407 --> CDROM Disk Images NRG (Nero)
  37408 --> CDROM Disk Image/Containers CDZ
  37409 --> CDROM Disk Image/Containers ECM
  37410 --> CDROM Subchannel Images
  37411 --> CDROM Disk Images Other Formats
  37412 --> CDROM Internal Info on PSX CDROM Controller
  37413 --> CDROM Internal HC05 Instruction Set
  37414 --> CDROM Internal HC05 On-Chip I/O Ports
  37415 --> CDROM Internal HC05 On-Chip I/O Ports - Extras
  37416 --> CDROM Internal HC05 I/O Port Usage in PSX
  37417 --> CDROM Internal HC05 Motorola Selftest Mode
  37418 --> CDROM Internal HC05 Motorola Selftest Mode (52pin chips)
  37419 --> CDROM Internal HC05 Motorola Selftest Mode (80pin chips)
  37420 --> CDROM Internal CXD1815Q Sub-CPU Configuration Registers
  37421 --> CDROM Internal CXD1815Q Sub-CPU Sector Status Registers
  37422 --> CDROM Internal CXD1815Q Sub-CPU Address Registers
  37423 --> CDROM Internal CXD1815Q Sub-CPU Misc Registers
  37424 --> CDROM Internal Commands CX(0x..3x) - CXA1782BR Servo Amplifier
  37425 --> CDROM Internal Commands CX(4x..Ex) - CXD2510Q Signal Processor
  37426 --> CDROM Internal Commands CX(0x..Ex) - CXD2545Q Servo/Signal Combo
  37427 --> CDROM Internal Commands CX(0x..Ex) - CXD2938Q Servo/Signal/SPU Combo
  37428 --> CDROM Internal Commands CX(xx) - Notes
  37429 --> CDROM Internal Commands CX(xx) - Summary of Used CX(xx) Commands
  37430 --> CDROM Internal Coefficients (for CXD2545Q)
  37431 --> CDROM Video CDs (VCD)
  37432 --> VCD ISO Basic Files (INFO, ENTRIES, AVSEQnn, ISO Filesystem)
  37433 --> VCD ISO Playback Control PBC Files (PSD, LOT, ITEMnnnn)
  37434 --> VCD ISO Search Files (SCANDATA, SEARCH, TRACKS, SPICONTX)
  37435 --> VCD ISO Misc files (CAPTnn, AUDIOnn, KARINFO, PICTURES, CDI)
  37436 --> VCD MPEG-1 Multiplex Stream
  37437 --> VCD MPEG-1 Video Stream
  37438 --> VCD MP2 Audio Stream
  37439 --> Controllers and Memory Cards
  37440 --> Controller and Memory Card I/O Ports
  37441 --> Controller and Memory Card Misc
  37442 --> Controller and Memory Card Signals
  37443 --> Controller and Memory Card Multitap Adaptor
  37444 --> Controllers - Communication Sequence
  37445 --> Controllers - Standard Digital/Analog Controllers
  37446 --> Controllers - Mouse
  37447 --> Controllers - Racing Controllers
  37448 --> Controllers - Lightguns
  37449 --> Controllers - Lightguns - Namco (GunCon)
  37450 --> Controllers - Lightguns - Konami Justifier/Hyperblaster (IRQ10)
  37451 --> Controllers - Lightguns - PSX Lightgun Games
  37452 --> Controllers - Configuration Commands
  37453 --> Controllers - Vibration/Rumble Control
  37454 --> Controllers - Analog Buttons (Dualshock2)
  37455 --> Controllers - Dance Mats
  37456 --> Controllers - Fishing Controllers
  37457 --> Controllers - I-Mode Adaptor (Mobile Internet)
  37458 --> Controllers - Keyboards
  37459 --> Controllers - Additional Inputs
  37460 --> Controllers - Misc
  37461 --> Memory Card Read/Write Commands
  37462 --> Memory Card Data Format
  37463 --> Memory Card Images
  37464 --> Memory Card Notes
  37465 --> Pocketstation
  37466 --> Pocketstation Overview
  37467 --> Pocketstation I/O Map
  37468 --> Pocketstation Memory Map
  37469 --> Pocketstation IO Video and Audio
  37470 --> Pocketstation IO Interrupts and Buttons
  37471 --> Pocketstation IO Timers and Real-Time Clock
  37472 --> Pocketstation IO Infrared
  37473 --> Pocketstation IO Memory-Control
  37474 --> Pocketstation IO Communication Ports
  37475 --> Pocketstation IO Power Control
  37476 --> Pocketstation SWI Function Summary
  37477 --> Pocketstation SWI Misc Functions
  37478 --> Pocketstation SWI Communication Functions
  37479 --> Pocketstation SWI Execute Functions
  37480 --> Pocketstation SWI Date/Time/Alarm Functions
  37481 --> Pocketstation SWI Flash Functions
  37482 --> Pocketstation SWI Useless Functions
  37483 --> Pocketstation BU Command Summary
  37484 --> Pocketstation BU Standard Memory Card Commands
  37485 --> Pocketstation BU Basic Pocketstation Commands
  37486 --> Pocketstation BU Custom Pocketstation Commands
  37487 --> Pocketstation File Header/Icons
  37488 --> Pocketstation File Images
  37489 --> Pocketstation XBOO Cable
  37490 --> Serial Port (SIO)
  37491 --> Expansion Port (PIO)
  37492 --> EXP1 Expansion ROM Header
  37493 --> EXP2 Dual Serial Port (for TTY Debug Terminal)
  37494 --> EXP2 DTL-H2000 I/O Ports
  37495 --> EXP2 Post Registers
  37496 --> EXP2 Nocash Emulation Expansion
  37497 --> Memory Control
  37498 --> Unpredictable Things
  37499 --> CPU Specifications
  37500 --> CPU Registers
  37501 --> CPU Opcode Encoding
  37502 --> CPU Load/Store Opcodes
  37503 --> CPU ALU Opcodes
  37504 --> CPU Jump Opcodes
  37505 --> CPU Coprocessor Opcodes
  37506 --> CPU Pseudo Opcodes
  37507 --> COP0 - Register Summary
  37508 --> COP0 - Exception Handling
  37509 --> COP0 - Misc
  37510 --> COP0 - Debug Registers
  37511 --> Kernel (BIOS)
  37512 --> BIOS Overview
  37513 --> BIOS Memory Map
  37514 --> BIOS Function Summary
  37515 --> BIOS File Functions
  37516 --> BIOS File Execute and Flush Cache
  37517 --> BIOS CDROM Functions
  37518 --> BIOS Memory Card Functions
  37519 --> BIOS Interrupt/Exception Handling
  37520 --> BIOS Event Functions
  37521 --> BIOS Event Summary
  37522 --> BIOS Thread Functions
  37523 --> BIOS Timer Functions
  37524 --> BIOS Joypad Functions
  37525 --> BIOS GPU Functions
  37526 --> BIOS Memory Allocation
  37527 --> BIOS Memory Fill/Copy/Compare (SLOW)
  37528 --> BIOS String Functions
  37529 --> BIOS Number/String/Character Conversion
  37530 --> BIOS Misc Functions
  37531 --> BIOS Internal Boot Functions
  37532 --> BIOS More Internal Functions
  37533 --> BIOS PC File Server
  37534 --> BIOS TTY Console (std_io)
  37535 --> BIOS Character Sets
  37536 --> BIOS Control Blocks
  37537 --> BIOS Boot State
  37538 --> BIOS Versions
  37539 --> BIOS Patches
  37540 --> Arcade Cabinets
  37541 --> Cheat Devices
  37542 --> Cheat Devices - Datel I/O
  37543 --> Cheat Devices - Datel DB25 Comms Link Protocol
  37544 --> Cheat Devices - Datel Chipset Pinouts
  37545 --> Cheat Devices - Datel Cheat Code Format
  37546 --> Cheat Devices - Xplorer Memory and I/O Map
  37547 --> Cheat Devices - Xplorer DB25 Parallel Port Function Summary
  37548 --> Cheat Devices - Xplorer DB25 Parallel Port Command Handler
  37549 --> Cheat Devices - Xplorer DB25 Parallel Port Low Level Transfer Protocol
  37550 --> Cheat Devices - Xplorer Versions
  37551 --> Cheat Devices - Xplorer Chipset Pinouts
  37552 --> Cheat Devices - Xplorer Cheat Code Format
  37553 --> Cheat Devices - Xplorer Cheat Code and ROM-Image Decryption
  37554 --> Cheat Devices - FLASH/EEPROMs
  37555 --> PSX Dev-Board Chipsets
  37556 --> Hardware Numbers
  37557 --> Pinouts
  37558 --> Pinouts - Controller Ports and Memory-Card Ports
  37559 --> Pinouts - Audio, Video, Power, Expansion Ports
  37560 --> Pinouts - SIO Pinouts
  37561 --> Pinouts - Chipset Summary
  37562 --> Pinouts - CPU Pinouts
  37563 --> Pinouts - GPU Pinouts (for old 160-pin GPU)
  37564 --> Pinouts - GPU Pinouts (for new 208-pin GPU)
  37565 --> Pinouts - SPU Pinouts
  37566 --> Pinouts - DRV Pinouts
  37567 --> Pinouts - VCD Pinouts
  37568 --> Pinouts - HC05 Pinouts
  37569 --> Pinouts - MEM Pinouts
  37570 --> Pinouts - CLK Pinouts
  37571 --> Pinouts - PWR Pinouts
  37572 --> Pinouts - Component List and Chipset Pin-Outs for Digital Joypad, SCPH-1080
  37573 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-1150
  37574 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-1200
  37575 --> Pinouts - Component List and Chipset Pin-Outs for Analog Joypad, SCPH-110
  37576 --> Pinouts - Component List and Chipset Pin-Outs for Dualshock2, SCPH-10010
  37577 --> Pinouts - Component List and Chipset Pin-Outs for Namco Lightgun, NPC-103
  37578 --> Pinouts - Component List and Chipset Pin-Outs for Multitap, SCPH-1070
  37579 --> Pinouts - Memory Cards
  37580 --> Mods - Nocash PSX-XBOO Upload
  37581 --> Mods - PAL/NTSC Color Mods
  37582 --> No$psx Emulation Controls
  37583 --> No$psx Emulation Files
  37584 --> No$psx Emulation Notes
  37585 --> No$psx Debugger - Hotkeys in Debug Mode
  37586 --> No$psx Debugger - Breakpoints
  37587 --> No$psx Debugger - General Debug Features
  37588 --> XED Editor
  37589 --> XED About
  37590 --> XED Hotkeys
  37591 --> XED Assembler/Debugger Interface
  37592 --> XED Commandline based standalone version
  37593 --> About & Credits