#This work is licensed under the
#Creative Commons Attribution-Share Alike 3.0 United States License.
#To view a copy of this license, visit
#http://creativecommons.org/licenses/by-sa/3.0/us/ or send a letter to
#Creative Commons,
#171 Second Street, Suite 300,
#San Francisco, California, 94105, USA.

INPUT "a TTA encoded file";
OUTPUT "signed PCM samples";
VAR signature "signature";
VAR format "format";
VAR channels "channels";
VAR bits_per_sample "bits-per-sample";
VAR sample_rate "sample rate";
VAR total_pcm_frames "total PCM frames";
VAR header_crc "header CRC";
VAR tta_frame_size "TTA frame size";
VAR seektable_crc "seektable CRC";
VAR block_size "block size";
VAR pcm_frames "PCM frames";
FUNC decode_frame "decode frame" "tta:decode_frame";
/*read header*/;
signature <- read 4 bytes;
assert signature == bytes(84, 84, 65, 49);
format <- read 16 unsigned;
channels <- read 16 unsigned;
bits_per_sample <- read 16 unsigned;
sample_rate <- read 32 unsigned;
total_pcm_frames <- read 32 unsigned;
header_crc <- read 32 unsigned /*don't process with CRC*/;
validate_crc(header_crc);
;
/*read seektable*/;
for i <- 0 to ceil((total_pcm_frames * 245) / (sample_rate * 256)) {
    tta_frame_size[i] <- read 32 unsigned;
}
seektable_crc <- read 32 unsigned /*don't process with CRC*/;
validate_crc(seektable_crc);
;
/*decode frames*/;
while total_pcm_frames > 0 {
    block_size <- floor((sample_rate * 256) / 245);
    if block_size > total_pcm_frames {
        block_size <- total_pcm_frames;
    }
    pcm_frames <- decode_frame(bits_per_sample, channels, block_size);
    total_pcm_frames <- total_pcm_frames - block_size;
    return pcm_frames;
}
