RST0 (File Format)

The RST0 format is an archive format found in Donkey Kong Country Returns 3D. It appears under a few different file extensions: .lvl, .res, and .trk; all are the same format though, with the extension just describing the contents of the file rather than the format. Like all DKCR3D formats, RST0 is a little-endian format; all fourCCs and magic values that appear in the file appear reversed.

Format
RST0 files contain a header, which is a static size of 0x44 bytes, then are padded until 0x80, where a table of contents is present, listing every resource in the file. Some RST0 files are compressed; on compressed files, the header will be uncompressed, and most of the rest of the file (including the ToC and most of the resources in the file) will be compressed. There are some RST0 files that contain uncompressed resource data following the end of the compressed data, though.

Table of Contents
The ToC contains three arrays:

Compression
RST0 files use a custom run-length encoding compression algorithm. The compressed data begins with a 0x19-byte header before the actual compressed data begins. The header is actually two separate headers - one for the entire compressed section, comprising the first 0x10 bytes, and then one for the compressed data, comprising the last 0x9 bytes, which is why there's some redundant values included.

The compressed data is made up of multiple chunks. Each chunk has a 32-bit value as a header, where each bit tells you how to read the next part of the data. After reading in the header value, check each bit separately, starting at the least significant bit (0x1) and going up to the 31st bit (0x40000000). Note that although the header value is 32-bit, the top bit (0x80000000) is always set and doesn't actually correspond to anything in the file, so it should be ignored. After checking all 31 bits, read the next header byte and repeat.

For each bit, do the following depending on the value of the bit:
 * 0: Read a single byte directly out of the compressed data stream
 * 1: Seek backwards in the decompressed data buffer and copy bytes out of it back to the front

0 is straightforward and doesn't need much further explanation. 1 is where things get a little bit complicated. The next bytes in the compressed stream are an indicator value that will tell you how far back to seek in the decompressed data buffer and how much data to read out of them. The value will be a different size depending on how much data is needed at any given moment. Read one byte, and check the bottom two bits (0x1 and 0x2); they will tell you how large the indicator value is, and how to use the data in it. It's also important to note that the indicator value is little-endian, even though it has to be read one byte at a time; so the first byte you read is the bottom byte, and the last one is the top byte.

Using these definitions:

Then depending on the value of the bottom two bits, this is the structure of the indicator value: