// A true-peak look-ahead limiter for the master submix, header.
// Written on the last afternoon of the jam by an engineer agent.
// Shared by BYOK Games under the MIT License
// A true-peak brick-wall look-ahead limiter for the master submix (eng8, Sun 16:4x; audio director: the take clipped at +2.0 to +2.5 dBTP
// with the stock Dynamics Processor limiters loaded). It holds every output sample, and the 4x inter-sample peaks between them, under
// the ceiling by construction: the delayed audio is multiplied by a gain that is never above the gain the loudest nearby peak needs.
// Added at the end of SM_Master's effect chain at run time by SPLimiter::Install (-SPLimiter=0 turns it off). -SPLimiterTest=<file.wav>
// runs a 16-bit WAV through it offline and logs the true peaks before and after.
#pragma once

#include "CoreMinimal.h"
#include "Sound/SoundEffectSubmix.h"
#include "SPLimiter.generated.h"

// The DSP, free of any engine audio type, so the offline test and the effect run the same code.
struct SPOILED_API FSPPeakLimiter
{
	void Init(int32 InChannels, float InSampleRate, float InCeilingDb = -1.5f, float InLookMs = 5.f, float InReleaseMs = 90.f);
	// interleaved in place; the output is delayed by Latency() frames
	void Process(float* Samples, int32 NumFrames);
	int32 Latency() const { return D; }
	float MinGainDb() const { return 20.f * FMath::LogX(10.f, FMath::Max(MinGain, 1e-6f)); }
	int32 NumReduced = 0;
private:
	int32 Ch = 2, L = 240, D = 246;
	float Ceil = 0.84f, RelStep = 0.f, MinGain = 1.f, G = 1.f;
	TArray<float> Ring;        // input history, [D+1][Ch]
	TArray<float> Req;         // required gain per frame, ring of L+1
	TArray<float> Mn;          // window-min of Req, ring of L+1
	TArray<int32> Dq;          // monotonic deque of frame indices (window min)
	TArray<float> Hist;        // last 12 samples per channel for the 4x inter-sample estimate
	float Taps[3][12];         // windowed-sinc phases 1/4, 2/4, 3/4 between Hist[5] and Hist[6]
	int64 N = 0;               // frames seen
	double MnSum = 0.0;
};

USTRUCT(BlueprintType)
struct FSPLimiterSettings
{
	GENERATED_BODY()
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Limiter")
	float CeilingDb = -1.5f;
};

class SPOILED_API FSPLimiter : public FSoundEffectSubmix
{
public:
	virtual void Init(const FSoundEffectSubmixInitData& InInitData) override;
	virtual void OnProcessAudio(const FSoundEffectSubmixInputData& InData, FSoundEffectSubmixOutputData& OutData) override;
	virtual void OnPresetChanged() override {}
private:
	FSPPeakLimiter Lim;
	int32 Chans = 0;
	float Rate = 48000.f;
	int32 Blocks = 0;
};

UCLASS()
class SPOILED_API USPLimiterPreset : public USoundEffectSubmixPreset
{
	GENERATED_BODY()
public:
	EFFECT_PRESET_METHODS(SPLimiter)
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Limiter")
	FSPLimiterSettings Settings;
};

namespace SPLimiter
{
	// adds the limiter after SM_Master's own effects (once per run)
	SPOILED_API void Install(UObject* WorldContext);
	// -SPLimiterTest=<wav>: offline, logs "SPL LIMITER test ..." lines
	SPOILED_API void SelfTest();
}
