#include <iostream>
#include <stdexcept>
#include "WavSource.h"

#define FORMAT_DEPTH_MASK   0xFFFF

WavSource::WavSource(std::string path) {
	_info.format = 0;
	_file = sf_open(path.c_str(), SFM_READ, &_info);
	if(!_file) {
		throw std::runtime_error(sf_strerror(nullptr));
	}


}

WavSource::~WavSource() {
	int err = sf_close(_file);
	if(err) {
		std::cout << "close sound file error: " << err << std::endl;
	}

	std::cout << "WavSource::~WavSource()" << std::endl;
}

int WavSource::getChannelCount() const {
	return _info.channels;
}

int WavSource::getSampleRate() const {
	return _info.samplerate;
}

std::size_t WavSource::getSampleDepth() const {
	switch(_info.format & FORMAT_DEPTH_MASK) {
		case SF_FORMAT_PCM_S8:
		case SF_FORMAT_PCM_U8:
			return 8;
		case SF_FORMAT_PCM_16:
			return 16;
		case SF_FORMAT_PCM_24:
			return 24;
		case SF_FORMAT_PCM_32:
			return 32;
		default:
			throw std::runtime_error("unknown sample depth");
	}
}


void WavSource::readData(unsigned long frameCount, void *output) const {
	sf_read_float(_file, (float*)output, frameCount*_info.channels);
}
