/*
NAME
  pcm-to-wav.js

AUTHOR
  Trek Hopton <trek@ausocean.org>

LICENSE
  This file is Copyright (C) 2018 the Australian Ocean Lab (AusOcean)

  It is free software: you can redistribute it and/or modify them
  under the terms of the GNU General Public License as published by the
  Free Software Foundation, either version 3 of the License, or (at your
  option) any later version.

  It is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  for more details.

  You should have received a copy of the GNU General Public License in gpl.txt.
  If not, see [GNU licenses](http://www.gnu.org/licenses).
*/

// pcmToWav takes raw pcm data along with the sample rate, number of channels and bit-depth, 
// and adds a WAV header to it so that it can be read and played by common players.
// input and output data bytes are represented as arrays of 8 bit integers.
// WAV spec.: http://soundfile.sapp.org/doc/WaveFormat/
function pcmToWav(data, rate, channels, bitdepth) {
    subChunk2ID = [100, 97, 116, 97]; // "data"
    subChunk2Size = int32ToBytes(data.length);

    subChunk1ID = [102, 109, 116, 32]; // "fmt "
    subChunk1Size = int32ToBytes(16);
    audioFmt = int16ToBytes(1); // 1 = PCM
    numChannels = int16ToBytes(channels);
    sampleRate = int32ToBytes(rate);
    byteRate = int32ToBytes(rate * channels * bitdepth / 8);
    blockAlign = int16ToBytes(channels * bitdepth / 8);
    bitsPerSample = int16ToBytes(bitdepth)

    chunkID = [82, 73, 70, 70]; // "RIFF"
    chunkSize = int32ToBytes(36 + data.length);
    format = [87, 65, 86, 69]; // "WAVE"

    result = chunkID;
    result.push(...chunkSize, ...format, ...subChunk1ID, ...subChunk1Size, ...audioFmt, ...numChannels, ...sampleRate, ...byteRate, ...blockAlign, ...bitsPerSample, ...subChunk2ID, ...subChunk2Size);
    return result.concat(data);
}

// int32ToBytes takes a number assumed to be an int 32 and converts it to an array containing bytes (Little Endian).
function int32ToBytes(num) {
    return [
        (num & 0x000000ff),
        (num & 0x0000ff00) >> 8,
        (num & 0x00ff0000) >> 16,
        (num & 0xff000000) >> 24
    ];
}

// int16ToBytes takes a number assumed to be an int 16 and converts it to an array containing bytes (Little Endian).
function int16ToBytes(num) {
    return [(num & 0x00ff), (num & 0xff00) >> 8];
}