/*Copyright (C) 2010-2012 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it 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.

Hikou no mizu 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
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "SoundBuffer.hpp"

SoundBuffer::SoundBuffer()
{
    
}

SoundBuffer::~SoundBuffer()
{
    alDeleteBuffers(1, &m_alBuffer);
}

//Get and set methods
ALuint SoundBuffer::getALBuffer() const
{
    return m_alBuffer;
}

ALenum SoundBuffer::getFormat() const
{
    return m_format;
}

ALsizei SoundBuffer::getFrequency() const
{
    return m_frequency;
}

//Load methods
void SoundBuffer::loadFromOGG(const std::string &path)
{
    //Open file
    FILE *file = fopen(path.c_str(), "rb");
    
    OggVorbis_File oggFile;
    ov_open(file, &oggFile, NULL, 0);
    
    //Read infos
    vorbis_info *oggInfos = ov_info(&oggFile, -1);
    
    ALenum format = AL_FORMAT_MONO16;
    if (oggInfos->channels > 1) format = AL_FORMAT_STEREO16;
    
    ALsizei frequency = oggInfos->rate;
    
    //Get samples
    std::vector<char> samples;
    
    char buffer[4096];
    long bytes;
    do
    {
        bytes = ov_read(&oggFile, buffer, 4096, 0, 2, 1, NULL);
        samples.insert(samples.end(), buffer, buffer + bytes);
    }
    while (bytes > 0);
    
    //Load openAL buffer
    loadFromMemory(&samples[0], static_cast<ALsizei>(samples.size()), format, frequency);
    
    //Close file
    ov_clear(&oggFile);
}

void SoundBuffer::loadFromMemory(const ALvoid *samples, ALsizei size, ALenum format, ALsizei frequency)
{
    //Delete previous resources
    alDeleteBuffers(1, &m_alBuffer);
    
    alGenBuffers(1, &m_alBuffer);
    alBufferData(m_alBuffer, format, samples, size, frequency);
    
    m_format = format;
    m_frequency = frequency;
}
