#### RemiAudio
#### Copyright (C) 2022-2024 Remilia Scarlet <remilia@posteo.jp>
####   Based on Zita-Rev1
####   Copyright (C) 2003-2017 Fons Adriaensen <fons@linuxaudio.org>
####
#### This program is free software; you can redistribute it and/or modify it
#### under the terms of the GNU General Public License as published by the Free
#### Software Foundation; either version 3 of the License, or (at your option)
#### any later version.
####
#### This program is distributed in the hope that it will be useful, but WITHOUT
#### ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#### FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#### more details.
####
#### You should have received a copy of the GNU General Public License along
#### with this program.  If not, see <http://www.gnu.org/licenses/>.
require "math"
require "../../common"
require "./zita"

module RemiAudio::DSP
  # Implements a Hall-like reverb effect.
  #
  # This is a port of Zita-Rev1, a mostly-a-hall-partially-a-plate reverb based
  # on a feedback delay network and allpass comb filters.
  #
  # The original Zita-Rev1 supports an "ambisonic" mode, which allows for two
  # inputs and four outputs.  This implementation does not support the
  # calculations for ambisonic mode, however, so it's strictly a reverb with
  # stereo output.
  #
  # This particular variation is simplified to save on CPU time.
  class ZitaReverbSimple < ZitaReverb
    def initialize(newSampleRate : Int32, numFrames : Int32)
      @sampleRate = newSampleRate.to_f64
      @invSampleRate = 1.0f64 / @sampleRate

      # Create pre-delays
      @vdelay0 = VDelay.new((0.1f64 * @sampleRate).to_i32!)
      @vdelay1 = VDelay.new((0.1f64 * @sampleRate).to_i32!)

      # Create main delay network
      @diff1 = [] of Diff
      @delay = [] of Delay
      NUM_DIFFS.times do |i|
        k1 = (TDIFF[i] * @sampleRate + 0.5).floor.to_i64!
        k2 = (TDELAY[i] * @sampleRate + 0.5).floor.to_i64!
        @diff1 << Diff.new(k1, ((i & 1) != 0 ? -0.6f64 : 0.6f64))
        @delay << Delay.new(k2 - k1)
      end

      # Prepare internal values
      prepare(numFrames)
    end

    private def prepare(numFrames : Int32) : Nil
      a : Int32 = @cntA1
      b : Int32 = @cntB1
      c : Int32 = @cntC1
      @d0 = 0.0
      @d1 = 0.0

      k : Int32 = (((@ipdel - 0.02) * @sampleRate) + 0.5).trunc.to_i32!
      @vdelay0.setDelay(k)
      @vdelay1.setDelay(k)
      @cntA2 = a

      wlo : Float64 = 6.2832 * @xover * @invSampleRate
      chi : Float64 = if @damping > (0.49 * @sampleRate)
                        2.0
                      else
                        1 - RemiMath.fastCos(6.2832 * @damping * @invSampleRate)
                      end
      halfRtMid : Float64 = 0.5 * @rtmid
      8.times do |i|
        @filt1.unsafe_fetch(i).setParams(TDELAY.unsafe_fetch(i), @rtmid, @rtlow, wlo, halfRtMid, chi)
      end
      @cntB2 = b

      t1 : Float64 = 0.7 / Math.sqrt(@rtmid)
      @d0 = (-@g0) / numFrames
      @d1 = (t1 - @g1) / numFrames
      @cntC2 = c
    end

    def damping : Float64
      raise "Not supported by this class"
    end

    def damping=(value : Float64)
      raise "Not supported by this class"
    end

    def predelay : Float64
      raise "Not supported by this class"
    end

    def predelay=(value : Float64)
      raise "Not supported by this class"
    end

    def crossover : Float64
      raise "Not supported by this class"
    end

    def crossover=(value : Float64)
      raise "Not supported by this class"
    end

    def timeLow : Float64
      raise "Not supported by this class"
    end

    def timeLow=(value : Float64)
      raise "Not supported by this class"
    end

    def timeHigh : Float64
      raise "Not supported by this class"
    end

    def timeHigh=(value : Float64)
      raise "Not supported by this class"
    end

    def eq(number : Int) : Tuple(Float64, Float64)
      raise "Not supported by this class"
    end

    def setEq(number : Int, frequency : Float64, gain : Float64)
      raise "Not supported by this class"
    end

    def mute
      @vdelay0.mute
      @vdelay1.mute
      @diff1.each &.mute
      @delay.each &.mute
      @filt1.each &.reset
    end

    macro processZ(z, x0, x1)
      {{z}} = {{x0}} - {{x1}}
      {{x0}} += {{x1}}
      {{x1}} = {{z}}
    end

    # Purposely unhygenic.  Sets up variables for use in the process() methods.
    private macro processCommon
      z : Float64 = 0.0
      x0 : Float64 = 0.0
      x1 : Float64 = 0.0
      x2 : Float64 = 0.0
      x3 : Float64 = 0.0
      x4 : Float64 = 0.0
      x5 : Float64 = 0.0
      x6 : Float64 = 0.0
      x7 : Float64 = 0.0
    end

    private macro processLeftRight(left, right, outLeft, outRight)
      # Write to the pre-delays
      @vdelay0.write({{left}})
      @vdelay1.write({{right}})

      # Pre-Delay -> Diffuser
      z = 0.375f64 * @vdelay0.read # Remi: This was 0.3 in the original Zita-Rev1 code
      x0 = @diff1.unsafe_fetch(0).process(@delay.unsafe_fetch(0).read + z)
      x1 = @diff1.unsafe_fetch(1).process(@delay.unsafe_fetch(1).read + z)
      x2 = @diff1.unsafe_fetch(2).process(@delay.unsafe_fetch(2).read - z)
      x3 = @diff1.unsafe_fetch(3).process(@delay.unsafe_fetch(3).read - z)

      z = 0.375f64 * @vdelay1.read # Remi: This was 0.3 in the original Zita-Rev1 code
      x4 = @diff1.unsafe_fetch(4).process(@delay.unsafe_fetch(4).read + z)
      x5 = @diff1.unsafe_fetch(5).process(@delay.unsafe_fetch(5).read + z)
      x6 = @diff1.unsafe_fetch(6).process(@delay.unsafe_fetch(6).read - z)
      x7 = @diff1.unsafe_fetch(7).process(@delay.unsafe_fetch(7).read - z)

      # Send signals through delay lines
      processZ(z, x0, x1)
      processZ(z, x2, x3)
      processZ(z, x4, x5)
      processZ(z, x6, x7)

      processZ(z, x0, x2)
      processZ(z, x1, x3)
      processZ(z, x4, x6)
      processZ(z, x5, x7)

      processZ(z, x0, x4)
      processZ(z, x1, x5)
      processZ(z, x2, x6)
      processZ(z, x3, x7)

      # Mix
      @g1 += @d1
      {{outLeft}}  = @g1 * (x1 + x2)
      {{outRight}} = @g1 * (x1 - x2)

      # Update FDN
      @delay.unsafe_fetch(0).write(@filt1.unsafe_fetch(0).process(ZITA_G * x0))
      @delay.unsafe_fetch(1).write(@filt1.unsafe_fetch(1).process(ZITA_G * x1))
      @delay.unsafe_fetch(2).write(@filt1.unsafe_fetch(2).process(ZITA_G * x2))
      @delay.unsafe_fetch(3).write(@filt1.unsafe_fetch(3).process(ZITA_G * x3))
      @delay.unsafe_fetch(4).write(@filt1.unsafe_fetch(4).process(ZITA_G * x4))
      @delay.unsafe_fetch(5).write(@filt1.unsafe_fetch(5).process(ZITA_G * x5))
      @delay.unsafe_fetch(6).write(@filt1.unsafe_fetch(6).process(ZITA_G * x6))
      @delay.unsafe_fetch(7).write(@filt1.unsafe_fetch(7).process(ZITA_G * x7))
    end

    def process(inputLeft : Array(Float64)|Slice(Float64), inputRight : Array(Float64)|Slice(Float64),
                outputLeft : Array(Float64)|Slice(Float64), outputRight : Array(Float64)|Slice(Float64)) : Nil
      unless inputLeft.size == outputLeft.size &&
             inputRight.size == outputRight.size &&
             inputLeft.size == inputRight.size
        raise BufferSizeMismatchError.new("The length of the buffers must match")
      end

      prepare(inputLeft.size)
      processCommon

      inputLeft.size.times do |i|
        processLeftRight(inputLeft[i], inputRight[i], outputLeft[i], outputRight[i])
      end
    end

    def process(inputLeft : Array(Float32)|Slice(Float32), inputRight : Array(Float32)|Slice(Float32),
                outputLeft : Array(Float32)|Slice(Float32), outputRight : Array(Float32)|Slice(Float32)) : Nil
      unless inputLeft.size == outputLeft.size &&
             inputRight.size == outputRight.size &&
             inputLeft.size == inputRight.size
        raise BufferSizeMismatchError.new("The length of the buffers must match")
      end

      prepare(inputLeft.size)
      processCommon

      outLeft : Float64 = 0.0
      outRight : Float64 = 0.0

      inputLeft.size.times do |i|
        processLeftRight(inputLeft[i], inputRight[i], outLeft, outRight)
        outputLeft[i] = outLeft.to_f32!
        outputRight[i] = outRight.to_f32!
      end
    end

    def process(input : Array(Float32)|Slice(Float32), output : Array(Float32)|Slice(Float32)) : Nil
      unless input.size == output.size
        raise BufferSizeMismatchError.new("The length of the buffers must match")
      end

      prepare(input.size.tdiv(2))
      processCommon

      outLeft : Float64 = 0.0
      outRight : Float64 = 0.0
      i = 0

      while i < input.size
        processLeftRight(input[i].to_f64!, input[i + 1].to_f64!, outLeft, outRight)
        output[i] = (outLeft * amount).to_f32!
        output[i + 1] = (outRight * amount).to_f32!
        i += 2
      end
    end

    def process(buffer : Array(Float32)|Slice(Float32), amount : Float32|Float64 = 1.0) : Nil
      prepare(buffer.size.tdiv(2))
      processCommon

      outLeft : Float64 = 0.0
      outRight : Float64 = 0.0
      i = 0

      while i < buffer.size
        processLeftRight(buffer[i].to_f64!, buffer[i + 1].to_f64!, outLeft, outRight)
        buffer[i] += (outLeft * amount).to_f32!
        buffer[i + 1] += (outRight * amount).to_f32!
        i += 2
      end
    end

    def updateInternalParams(*, numFrames : Int32 = 0)
      prepare(numFrames)
    end
  end
end
