Technical Information about the Ultima 6 Music Drivers
======================================================

Last updated on 9-March-2005.
Please send additions, corrections and feedback to this e-mail address:
Remove space + vowels from "marc winterrowd" and append "at yahoo dot com"


The File Format
===============

The Ultima 6 music drivers are compressed, probably to save space and reduce
loading time.
The first four bytes contain the uncompressed size of the driver:

uncompressed_size = byte_0 + byte_1*2^8 + byte_2*2^16 +byte_3*2^24

The rest of the file contains the driver, compressed with the LZW algorithm.
It starts with a code word size of 9 bits and can go up to 12 bits, in steps
of 1 bit.
The code words 0x100 and 0x101 have special meanings:
0x100 = Wipe the dictionary and restart with a code word size of 9 bits.
0x101 = End of compressed data.
Therefore, the first available code word is 0x102.

After you've read the first 4 bytes of the file and determined the
uncompressed size, you must read the next 9 bits, which should be 0x100.
After re-initializing the dictionary, you keep reading blocks of 9 bits
until the dictionary overflows. When this happens, you must set the code
word size to 10 bits.


The Patch
=========

In the original MT-32 driver, there are three small loops where the driver
waits until the MPU-401 is ready to accept a command or send an acknowledge
signal. These loops are located at offsets 0x275, 0x282 and 0x292 in the
uncompressed u6roland.drv, and look like this:

               mov    dx, 331h 
               mov    cx, 0ffffh
local_loop:
               in     al, dx
               test   al, 40h
               jz     continue
               loop   local_loop
continue:

On fast systems, the computer completes the loop long before the condition
becomes true. One way to solve this problem:

local_loop:
               in     al, dx
               test   al, 40h
               jnz    local_loop
               nop
               nop
continue:

This looks like a potentially infinite loop, but in practice, it always
terminates, even if you turn off the MT-32 while the game is running.


Recompressing the Patched Driver
================================

Instead of compressing the driver, it's easier to encode it like this:

1) Create a new file.
2) Write the 4 length bytes to the file.
3) Divide the uncompressed driver into blocks of approximately 64 bytes.
4) For each block:
   a) Write the 9-bit value 0x100 to the file.
   b) Write each byte of the 64-byte-block to the file (as a 9-bit value
      with the MSB set to 0)
5) Write the 9-bit value 0x101 to the file.

A file encoded with this method is actually larger than the original file,
but it can be decoded by Ultima 6.
