// A true-peak look-ahead limiter for the master submix, implementation.
// Written on the last afternoon of the jam by an engineer agent.
// Shared by BYOK Games under the MIT License
#include "SPLimiter.h"
#include "SPTypes.h"
#include "AudioMixerBlueprintLibrary.h"
#include "Sound/SoundSubmix.h"
#include "Misc/FileHelper.h"
#include "Misc/CommandLine.h"
#include "Misc/Parse.h"
#include "HAL/PlatformTime.h"

// ---------------------------------------------------------------- the DSP

void FSPPeakLimiter::Init(int32 InChannels, float InSampleRate, float InCeilingDb, float InLookMs, float InReleaseMs)
{
	Ch = FMath::Clamp(InChannels, 1, 16);
	L = FMath::Max(8, FMath::RoundToInt(InLookMs * 0.001f * InSampleRate));
	D = L + 6;   // the detector needs 6 frames of future
	Ceil = FMath::Pow(10.f, InCeilingDb / 20.f);
	RelStep = 1.f / FMath::Max(1.f, InReleaseMs * 0.001f * InSampleRate);
	Ring.Init(0.f, (D + 1) * Ch);
	Req.Init(1.f, L + 1);
	Mn.Init(1.f, L + 1);
	Hist.Init(0.f, 12 * Ch);
	for (int32 p = 1; p <= 3; ++p)
		for (int32 k = 0; k < 12; ++k)
		{
			const double Pos = 5.0 + 0.25 * p, X = Pos - k;                              // distance from tap k to the point
			const double Sinc = FMath::Abs(X) < 1e-9 ? 1.0 : FMath::Sin(PI * X) / (PI * X);
			const double Win = 0.5 + 0.5 * FMath::Cos(PI * X / 6.5);                     // Hann over +-6.5 samples
			Taps[p - 1][k] = (float)(Sinc * Win);
		}
	MnSum = (double)(L + 1);
	N = 0; G = 1.f; MinGain = 1.f; NumReduced = 0;
}

void FSPPeakLimiter::Process(float* S, int32 NumFrames)
{
	for (int32 f = 0; f < NumFrames; ++f)
	{
		float* In = S + f * Ch;
		float* Slot = &Ring[(int32)(N % (D + 1)) * Ch];
		for (int32 c = 0; c < Ch; ++c)
		{
			Slot[c] = In[c];
			float* H = &Hist[c * 12];
			FMemory::Memmove(H, H + 1, 11 * sizeof(float));
			H[11] = In[c];   // H[0..11] = x[n-11] .. x[n]
		}
		const int64 J = N - 6;   // the frame whose true peak is known now (H[5] = x[J], H[6] = x[J+1]; the sinc reaches x[J-5] to x[J+6])
		float R = 1.f;
		if (J >= 5)
		{
			float P = 0.f;
			for (int32 c = 0; c < Ch; ++c)
			{
				const float* H = &Hist[c * 12];
				P = FMath::Max(P, FMath::Abs(H[5]));
				for (int32 p = 0; p < 3; ++p)
				{
					float Y = 0.f;
					for (int32 k = 0; k < 12; ++k) Y += H[k] * Taps[p][k];
					P = FMath::Max(P, FMath::Abs(Y));
				}
			}
			if (P > Ceil) R = Ceil / P;
		}
		const int32 Rs = (int32)(((J % (L + 1)) + (L + 1)) % (L + 1));
		Req[Rs] = R;
		float M = 1.f;
		for (int32 i = 0; i <= L; ++i) M = FMath::Min(M, Req[i]);   // the last L+1 requirements
		MnSum += (double)M - (double)Mn[Rs];
		Mn[Rs] = M;
		const float Avg = (float)(MnSum / (double)(L + 1));
		G = FMath::Min(Avg, G + RelStep);
		const int64 T = N - D;
		if (T >= 0)
		{
			const float* Src = &Ring[(int32)(T % (D + 1)) * Ch];
			for (int32 c = 0; c < Ch; ++c) In[c] = Src[c] * G;
			if (G < 0.999f) ++NumReduced;
			MinGain = FMath::Min(MinGain, G);
		}
		else for (int32 c = 0; c < Ch; ++c) In[c] = 0.f;
		++N;
	}
}

// ---------------------------------------------------------------- the effect

void FSPLimiter::Init(const FSoundEffectSubmixInitData& InInitData)
{
	Rate = InInitData.SampleRate > 0.f ? InInitData.SampleRate : 48000.f;
	Chans = 0;
}

void FSPLimiter::OnProcessAudio(const FSoundEffectSubmixInputData& InData, FSoundEffectSubmixOutputData& OutData)
{
	if (!InData.AudioBuffer || !OutData.AudioBuffer || InData.NumChannels <= 0) return;
	if (Chans != InData.NumChannels)
	{
		Chans = InData.NumChannels;
		Lim.Init(Chans, Rate, -1.5f);
		UE_LOG(LogSP, Display, TEXT("SPL LIMITER live ch=%d rate=%.0f ceiling=-1.5 look=5ms latency=%d"), Chans, Rate, Lim.Latency());
	}
	const int32 Num = InData.NumFrames * Chans;
	OutData.AudioBuffer->SetNumUninitialized(Num);
	FMemory::Memcpy(OutData.AudioBuffer->GetData(), InData.AudioBuffer->GetData(), Num * sizeof(float));
	Lim.Process(OutData.AudioBuffer->GetData(), InData.NumFrames);
	if ((++Blocks % 2000) == 0) UE_LOG(LogSP, Display, TEXT("SPL LIMITER blocks=%d reduced_frames=%d min_gain_db=%.1f"), Blocks, Lim.NumReduced, Lim.MinGainDb());
}

// ---------------------------------------------------------------- install and test

void SPLimiter::Install(UObject* WorldContext)
{
	static bool bDone = false;
	int32 V = 1;
	FParse::Value(FCommandLine::Get(), TEXT("SPLimiter="), V);
	if (bDone || V == 0 || !WorldContext) { if (V == 0 && !bDone) { bDone = true; SPL("LIMITER off (-SPLimiter=0)"); } return; }
	bDone = true;
	USoundSubmix* M = LoadObject<USoundSubmix>(nullptr, TEXT("/Game/Shell/Mix/SM_Master.SM_Master"), nullptr, LOAD_NoWarn | LOAD_Quiet);
	USPLimiterPreset* P = NewObject<USPLimiterPreset>(GetTransientPackage());
	P->AddToRoot();
	P->Init();
	const int32 N = M ? UAudioMixerBlueprintLibrary::AddSubmixEffect(WorldContext, M, P) : -1;
	SPL("LIMITER installed master=%d chain=%d", M ? 1 : 0, N);
}

namespace
{
	bool ReadWav16(const FString& Path, TArray<float>& Out, int32& Ch, int32& Rate)
	{
		TArray<uint8> B;
		if (!FFileHelper::LoadFileToArray(B, *Path) || B.Num() < 44) return false;
		int32 Pos = 12; Ch = 2; Rate = 48000; int32 DataAt = -1, DataLen = 0;
		while (Pos + 8 <= B.Num())
		{
			const uint32 Len = *reinterpret_cast<const uint32*>(&B[Pos + 4]);
			if (FMemory::Memcmp(&B[Pos], "fmt ", 4) == 0) { Ch = *reinterpret_cast<const uint16*>(&B[Pos + 10]); Rate = *reinterpret_cast<const int32*>(&B[Pos + 12]); }
			if (FMemory::Memcmp(&B[Pos], "data", 4) == 0) { DataAt = Pos + 8; DataLen = FMath::Min((int32)Len, B.Num() - DataAt); break; }
			Pos += 8 + (int32)Len + (Len & 1);
		}
		if (DataAt < 0) return false;
		const int32 Ns = DataLen / 2;
		Out.SetNumUninitialized(Ns);
		const int16* Pcm = reinterpret_cast<const int16*>(&B[DataAt]);
		for (int32 i = 0; i < Ns; ++i) Out[i] = Pcm[i] / 32768.f;
		return true;
	}
	void WriteWavF32(const FString& Path, const TArray<float>& S, int32 Ch, int32 Rate)
	{
		TArray<uint8> B;
		auto P32 = [&B](uint32 V) { B.Append(reinterpret_cast<const uint8*>(&V), 4); };
		auto P16 = [&B](uint16 V) { B.Append(reinterpret_cast<const uint8*>(&V), 2); };
		const uint32 Bytes = S.Num() * 4;
		B.Append((const uint8*)"RIFF", 4); P32(36 + Bytes); B.Append((const uint8*)"WAVEfmt ", 8);
		P32(16); P16(3); P16(Ch); P32(Rate); P32(Rate * Ch * 4); P16(Ch * 4); P16(32);
		B.Append((const uint8*)"data", 4); P32(Bytes);
		B.Append(reinterpret_cast<const uint8*>(S.GetData()), Bytes);
		FFileHelper::SaveArrayToFile(B, *Path);
	}
	float PeakDb(const TArray<float>& S) { float P = 0.f; for (float X : S) P = FMath::Max(P, FMath::Abs(X)); return 20.f * FMath::LogX(10.f, FMath::Max(P, 1e-9f)); }
}

void SPLimiter::SelfTest()
{
	FString Path;
	if (!FParse::Value(FCommandLine::Get(), TEXT("SPLimiterTest="), Path, false)) return;
	TArray<float> In; int32 Ch = 2, Rate = 48000;
	if (!ReadWav16(Path, In, Ch, Rate)) { SPL("LIMITER test cannot read %s", *Path); return; }
	for (int32 Pass = 0; Pass < 2; ++Pass)
	{
		TArray<float> S = In;
		if (Pass == 1) for (float& X : S) X *= 2.f;   // 6 dB hotter, floats over full scale
		const float InDb = PeakDb(S);
		FSPPeakLimiter L;
		L.Init(Ch, (float)Rate, -1.5f);
		const double T0 = FPlatformTime::Seconds();
		const int32 Block = 480 * Ch;
		for (int32 i = 0; i < S.Num(); i += Block) L.Process(&S[i], FMath::Min(Block, S.Num() - i) / Ch);
		const double Ms = (FPlatformTime::Seconds() - T0) * 1000.0;
		const FString Out = Path + (Pass == 0 ? TEXT(".limited.wav") : TEXT(".limited_hot.wav"));
		WriteWavF32(Out, S, Ch, Rate);
		SPL("LIMITER test pass=%d frames=%d in_sample_peak_db=%.2f out_sample_peak_db=%.2f min_gain_db=%.1f reduced_frames=%d latency=%d dsp_ms=%.0f out=%s",
			Pass, S.Num() / Ch, InDb, PeakDb(S), L.MinGainDb(), L.NumReduced, L.Latency(), Ms, *Out);
	}
}
