/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "game/audio/buffer.hpp"

#include <al.h>
#include <alc.h>
#include <ogg/ogg.h>
#include <vorbis/codec.h>
#include <fstream>
#include <limits>
#include <vector>
#include <cstring>
#include <map>

#include "common/logger.hpp"

using namespace polygun::audio;

AudioBuffer::AudioBuffer() :
	m_buffer_id(0),
	m_valid(false)
{
	alGenBuffers(1, &m_buffer_id);

	ALCenum error = alGetError();
	if(error!=AL_NO_ERROR) {
		LOG_ERROR("Failed to create OpenAL bufferf (OpenAL error: %d)", error);
		return;
	}
	m_valid = true;
}

AudioBuffer::~AudioBuffer() {
	if(m_valid)
		alDeleteBuffers(1,&m_buffer_id);
}

bool AudioBuffer::load_from_file(const std::string& filename) {
	if(!m_valid) {
		LOG_ERROR("Attempt to load sound file to invalid buffer");
		return false;
	}

	std::ifstream file(filename, std::ios::binary);
	if(!file.good()) {
		LOG_ERROR("Failed to open file '%s'", filename.c_str());
		return false;
	}

	char magic[4];
	file.read(magic, 4);
	bool result = false;
	if(strncmp(magic, "OggS", 4)==0) {
		result = load_ogg(file);
		if(!result)
			LOG_ERROR("Failed to load Ogg file '%s'", filename.c_str());
	}
	else
		LOG_ERROR("File '%s' has unsupported format", filename.c_str());

	file.close();
	return result;
}

bool AudioBuffer::load_ogg(std::istream& stream) {
	stream.seekg(0);
	ogg_sync_state state;
	if(ogg_sync_init(&state)!=0) {
		LOG_VERBOSE("Failed to init Ogg sync state");
		return false;
	}

	bool continue_reading = true;
	bool reading_vorbis_header = true;
	bool first_vorbis_header_packet = true;
	unsigned char vorbis_header_page_counter = 0;
	ogg_page page;
	vorbis_info vorb;
	vorbis_comment vorb_comment;
	std::vector<int16_t> decoded_samples;
	vorbis_dsp_state dsp;
	vorbis_block block;
	std::map<int, ogg_stream_state> ogg_streams;
	while(continue_reading) {
		while(ogg_sync_pageout(&state, &page)==0) {
			char* sync_buffer = ogg_sync_buffer(&state, 4096);
			if(!sync_buffer) {
				LOG_VERBOSE("Failed to obtain Ogg buffer");
				ogg_sync_clear(&state);
				return false;
			}
			stream.read(sync_buffer, 4096);
			std::streamsize bytes_read = stream.gcount();
			if(bytes_read==0) {
				continue_reading = false;
				break;
			}
			if(bytes_read>0)
				ogg_sync_wrote(&state, bytes_read);
		}
		if(!continue_reading)
			break;

		int page_serialno = ogg_page_serialno(&page);
		ogg_stream_state* ogg_stream = &ogg_streams[page_serialno];
		if(ogg_page_bos(&page)) {
			if(ogg_stream_init(ogg_stream, page_serialno)!=0) {
				LOG_VERBOSE("Failed to init Ogg stream");
				ogg_sync_clear(&state);
				return false;
			}
		}

		if(ogg_stream_pagein(ogg_stream, &page)==-1) {
			LOG_VERBOSE("Failed to supply page to Ogg stream");
			ogg_stream_clear(ogg_stream);
			ogg_sync_clear(&state);
			return false;
		}

		ogg_packet packet;
		if(reading_vorbis_header) {
			if(ogg_stream_packetout(ogg_stream, &packet)!=1) {
				LOG_VERBOSE("Failed to obtain packet from Ogg stream");
				ogg_sync_clear(&state);
				return false;
			}
			if(first_vorbis_header_packet) {
				if(!vorbis_synthesis_idheader(&packet)) {
					LOG_VERBOSE("Ogg file doesn't contain Vorbis encoded audio");
					ogg_sync_clear(&state);
					return false;
				}
				vorbis_info_init(&vorb);
				vorbis_comment_init(&vorb_comment);
				first_vorbis_header_packet = false;
			}
			if(vorbis_synthesis_headerin(&vorb, &vorb_comment, &packet)!=0) {
				LOG_VERBOSE("Failed to supply Vorbis header part from Ogg packet");
				vorbis_info_clear(&vorb);
				vorbis_comment_clear(&vorb_comment);
				ogg_sync_clear(&state);
				return false;
			}
			vorbis_header_page_counter++;
			if(vorbis_header_page_counter==3) {
				reading_vorbis_header = false;
				if(vorbis_synthesis_init(&dsp, &vorb)!=0) {
					LOG_VERBOSE("Failed to init Vorbis synthesis");
					vorbis_info_clear(&vorb);
					vorbis_comment_clear(&vorb_comment);
					ogg_sync_clear(&state);
					return false;
				}
				if(vorbis_block_init(&dsp, &block)!=0) {
					LOG_VERBOSE("Failed to init Vorbis block");
					vorbis_dsp_clear(&dsp);
					vorbis_info_clear(&vorb);
					vorbis_comment_clear(&vorb_comment);
					ogg_sync_clear(&state);
					return false;
				}
			}
			continue;
		}
		else if(ogg_stream_packetout(ogg_stream, &packet)!=1)
			continue;

		do{
			if(vorbis_synthesis(&block, &packet)!=0) {
				LOG_VERBOSE("Failed to synthesis Ogg packet");
				vorbis_block_clear(&block);
				vorbis_dsp_clear(&dsp);
				vorbis_info_clear(&vorb);
				vorbis_comment_clear(&vorb_comment);
				ogg_sync_clear(&state);
				return false;
			}

			if(vorbis_synthesis_blockin(&dsp, &block)!=0) {
				LOG_VERBOSE("Failed to supply block to Vorbis synthesis");
				vorbis_block_clear(&block);
				vorbis_dsp_clear(&dsp);
				vorbis_info_clear(&vorb);
				vorbis_comment_clear(&vorb_comment);
				ogg_sync_clear(&state);
				return false;
			}

			float** samples;
			int sample_count = vorbis_synthesis_pcmout(&dsp, &samples);
			if(sample_count>0) {
				for(int a = 0; a<sample_count; a++) {
					for(int i = 0; i<(vorb.channels>2?2:vorb.channels); i++) {
						decoded_samples.push_back(samples[i][a]*std::numeric_limits<int16_t>::max());
					}
				}
				vorbis_synthesis_read(&dsp, sample_count);
			}
		}
		while(ogg_stream_packetout(ogg_stream, &packet)==1);
	}

	ALenum al_format = -1;
	if(vorb.channels==1)
		al_format = AL_FORMAT_MONO16;
	else if(vorb.channels>=2)
		al_format = AL_FORMAT_STEREO16;
	alBufferData(m_buffer_id, al_format, decoded_samples.data(), decoded_samples.size()*2, vorb.rate);
	ALCenum error = alGetError();
	if(error!=AL_NO_ERROR)
		LOG_ERROR("Failed to submit decoded Vorbis sound data to OpenAL buffer (OpenAL error: %d)", error);

	vorbis_block_clear(&block);
	vorbis_info_clear(&vorb);
	vorbis_comment_clear(&vorb_comment);
	vorbis_dsp_clear(&dsp);
	for(std::map<int, ogg_stream_state>::iterator it = ogg_streams.begin(); it!=ogg_streams.end(); it++)
		ogg_stream_clear(&it->second);
	ogg_sync_clear(&state);
	return true;
}
