/*
  Copyright (c) 2024 Alex Diener
  
  This software is provided 'as-is', without any express or implied
  warranty. In no event will the authors be held liable for any damages
  arising from the use of this software.
  
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
  
  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
  
  Alex Diener alex@ludobloom.com
*/

#include "audioplayer/LoopRampAudioStream.h"
#include <math.h>
#include <stdio.h>

#define stemobject_implementation LoopRampAudioStream

v_begin();
v_func(read);
v_func(seek);
v_func(writeAudioFrames);
v_func(updateRamp);
v_func(rampVolume);
v_end();

bool LoopRampAudioStream_init(LoopRampAudioStream * self, AudioFrameIndex startFrameIndex, AudioFrameIndex loopFrameCount, unsigned int bytesPerSample, unsigned int channelCount, unsigned int sampleRate) {
	call_super(init, self, bytesPerSample, channelCount, sampleRate);
	self->frameIndex = startFrameIndex % loopFrameCount;
	self->framePlayedCountTotal = startFrameIndex;
	self->loopFrameCount = loopFrameCount;
	self->looped = startFrameIndex >= loopFrameCount;
	self->rampStartFrameIndex = self->rampEndFrameIndex = 0;
	self->rampQueued = self->rampQueueProcessed = 0;
	self->rampStartVolume = self->rampEndVolume = 1.0f;
	self->lastRampStartVolume = self->lastRampEndVolume = 1.0f;
	return true;
}

AudioFrameIndex LoopRampAudioStream_read(LoopRampAudioStream * self, AudioFrameIndex frameCount, void * outBuffer, bool loop) {
	AudioFrameIndex outFrameIndex = 0;
	AudioFrameIndex loopFrameCount = self->loopFrameCount, framesWritten = 0, remainingFrameCount = frameCount;
	
	call_virtual(updateRamp, self);
	float rampStartVolume = 1.0f, rampEndVolume = 1.0f;
	if (self->rampEndFrameIndex > self->framePlayedCountTotal && self->rampEndFrameIndex > self->rampStartFrameIndex) {
		rampStartVolume = self->rampStartVolume + (self->rampEndVolume - self->rampStartVolume) * (self->framePlayedCountTotal - self->rampStartFrameIndex) / (self->rampEndFrameIndex - self->rampStartFrameIndex);
		rampEndVolume = self->rampStartVolume + (self->rampEndVolume - self->rampStartVolume) * (self->framePlayedCountTotal + frameCount - self->rampStartFrameIndex) / (self->rampEndFrameIndex - self->rampStartFrameIndex);
		
	} else if (self->rampEndVolume == 0.0) {
		return 0;
	}
	
	if (loop) {
		while (remainingFrameCount + self->frameIndex >= loopFrameCount) {
			AudioFrameIndex loopFramesToWrite = loopFrameCount - self->frameIndex;
			call_virtual(writeAudioFrames, self, outBuffer, loopFramesToWrite, &outFrameIndex, rampStartVolume, rampEndVolume, frameCount);
			framesWritten += loopFramesToWrite;
			self->frameIndex = 0;
			remainingFrameCount -= loopFramesToWrite;
			self->looped = true;
		}
	} else if (remainingFrameCount + self->frameIndex >= loopFrameCount) {
		remainingFrameCount = loopFrameCount - self->frameIndex;
	}
	
	call_virtual(writeAudioFrames, self, outBuffer, remainingFrameCount, &outFrameIndex, rampStartVolume, rampEndVolume, frameCount);
	framesWritten += remainingFrameCount;
	self->frameIndex += remainingFrameCount;
	self->framePlayedCountTotal += framesWritten;
	return framesWritten;
}

void LoopRampAudioStream_seek(LoopRampAudioStream * self, AudioFrameIndex offset, int whence) {
	switch (whence) {
		case SEEK_CUR:
			offset += self->framePlayedCountTotal;
			break;
			
		case SEEK_END:
			offset += self->loopFrameCount;
			break;
	}
	self->frameIndex = offset % self->loopFrameCount;
	self->framePlayedCountTotal = offset;
	self->looped = offset >= self->loopFrameCount;
	self->rampStartFrameIndex = self->rampEndFrameIndex = 0;
}

void LoopRampAudioStream_writeAudioFrames(LoopRampAudioStream * self, void * outBuffer, AudioFrameIndex frameCount, AudioFrameIndex * ioOutFrameIndex, float rampStartVolume, float rampEndVolume, AudioFrameIndex rampFrameCountTotal) {
}

void LoopRampAudioStream_updateRamp(LoopRampAudioStream * self) {
	if (self->rampQueued > self->rampQueueProcessed) {
		if (self->rampEndFrameIndex > self->framePlayedCountTotal && self->rampEndFrameIndex > self->rampStartFrameIndex) {
			// A ramp is already in progress; interpolate
			float currentRampValue = fmaxf(0.0f, fminf(1.0f, self->lastRampStartVolume + (self->lastRampEndVolume - self->lastRampStartVolume) * (self->framePlayedCountTotal - self->rampStartFrameIndex) / (self->rampEndFrameIndex - self->rampStartFrameIndex)));
			if (self->rampEndVolume > self->rampStartVolume) {
				if (currentRampValue == 1.0f) {
					self->rampStartFrameIndex = self->rampEndFrameIndex = self->framePlayedCountTotal;
				} else {
					AudioFrameIndex extrapolatedFrameCount = self->queuedRampDuration * currentRampValue * self->sampleRate;
					if (extrapolatedFrameCount > self->framePlayedCountTotal) {
						self->rampStartFrameIndex = 0;
					} else {
						self->rampStartFrameIndex = self->framePlayedCountTotal - extrapolatedFrameCount;
					}
					self->rampEndFrameIndex = self->rampStartFrameIndex + self->queuedRampDuration * self->sampleRate;
				}
			} else {
				if (currentRampValue == 0.0f) {
					self->rampStartFrameIndex = self->rampEndFrameIndex = self->framePlayedCountTotal;
				} else {
					AudioFrameIndex extrapolatedFrameCount = self->queuedRampDuration * (1.0f - currentRampValue) * self->sampleRate;
					if (extrapolatedFrameCount > self->framePlayedCountTotal) {
						self->rampStartFrameIndex = 0;
					} else {
						self->rampStartFrameIndex = self->framePlayedCountTotal - extrapolatedFrameCount;
					}
					self->rampEndFrameIndex = self->rampStartFrameIndex + self->queuedRampDuration * self->sampleRate;
				}
			}
			
		} else {
			// Start new ramp as specified
			self->rampStartFrameIndex = self->framePlayedCountTotal;
			self->rampEndFrameIndex = self->framePlayedCountTotal + self->queuedRampDuration * self->sampleRate;
		}
		self->lastRampStartVolume = self->rampStartVolume;
		self->lastRampEndVolume = self->rampEndVolume;
		self->rampQueueProcessed++;
	}
}

void LoopRampAudioStream_rampVolume(LoopRampAudioStream * self, bool upward, double duration) {
	self->rampStartVolume = upward ? 0.0 : 1.0;
	self->rampEndVolume = upward ? 1.0 : 0.0;
	self->queuedRampDuration = fmax(duration, 0.0);
	self->rampQueued++;
}
