{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{- |
Copyright   :  (c) Henning Thielemann 2008-2011
License     :  GPL

Maintainer  :  synthesizer@henning-thielemann.de
Stability   :  provisional
Portability :  requires multi-parameter type classes
-}
module Synthesizer.Dimensional.Causal.Filter (
   -- * Non-recursive

   -- ** Amplification
   amplify,
   amplifyDimension,
   amplifyScalarDimension,
   negate,
   envelope,
   envelopeScalarDimension,
   envelopeVector,
   envelopeVectorDimension,

   -- ** Filter operators from calculus
   differentiate,

{-
   -- ** Smooth
   meanStatic,
   mean,

   -- ** Delay
   delay,
   phaseModulation,
   frequencyModulation,
   frequencyModulationDecoupled,
   phaser,
   phaserStereo,
-}


{-
   -- * Recursive

   -- ** Reverb
   comb,
   combProc,
-}

   -- ** Filter operators from calculus
   integrate,
) where

import qualified Synthesizer.Dimensional.Map.Filter as FiltM
import qualified Synthesizer.Dimensional.Process as Proc
import qualified Synthesizer.Dimensional.Sample as Sample
import qualified Synthesizer.Dimensional.Amplitude as Amp
import qualified Synthesizer.Dimensional.Causal.Process as CausalD
import qualified Synthesizer.Causal.Process as Causal
import Control.Arrow ((^<<), (&&&), )

import Synthesizer.Dimensional.Process (DimensionGradient, )

import qualified Synthesizer.State.Filter.Recursive.Integration as Integrate
-- import qualified Synthesizer.State.Filter.Recursive.MovingAverage as MA

-- import qualified Synthesizer.Generic.Filter.Recursive.Comb as Comb
-- import qualified Synthesizer.Dimensional.Causal.Displacement as DispC

import qualified Number.DimensionTerm        as DN
import qualified Algebra.DimensionTerm       as Dim

import Number.DimensionTerm ((&*&), )

-- import qualified Algebra.RealRing      as RealRing
import qualified Algebra.Field          as Field
-- import qualified Algebra.Absolute           as Absolute
import qualified Algebra.Ring           as Ring
import qualified Algebra.Additive       as Additive
-- import qualified Algebra.VectorSpace    as VectorSpace
import qualified Algebra.Module         as Module

import NumericPrelude.Numeric hiding (negate)
import NumericPrelude.Base as P
import Prelude ()


{- | The amplification factor must be positive. -}
{-# INLINE amplify #-}
amplify :: (Module.C y amp) =>
   y ->
   Proc.T s u t (CausalD.Single s (Amp.Numeric amp) (Amp.Numeric amp) yv yv)
amplify :: forall y amp s u t yv.
C y amp =>
y -> T s u t (Single s (Numeric amp) (Numeric amp) yv yv)
amplify y
volume =
   forall a s u t. a -> T s u t a
Proc.pure forall a b. (a -> b) -> a -> b
$ forall y amp (arrow :: * -> * -> *) yv.
(C y amp, Arrow arrow) =>
y -> Single arrow (Numeric amp) (Numeric amp) yv yv
FiltM.amplify y
volume

{-# INLINE amplifyDimension #-}
amplifyDimension :: (Ring.C y, Dim.C u, Dim.C v0, Dim.C v1) =>
   DN.T v0 y ->
   Proc.T s u t
      (CausalD.Single s
          (Amp.Dimensional v1 y) (Amp.Dimensional (Dim.Mul v0 v1) y)
          yv yv)
amplifyDimension :: forall y u v0 v1 s t yv.
(C y, C u, C v0, C v1) =>
T v0 y
-> T s
     u
     t
     (Single s (Dimensional v1 y) (Dimensional (Mul v0 v1) y) yv yv)
amplifyDimension T v0 y
volume =
   forall a s u t. a -> T s u t a
Proc.pure forall a b. (a -> b) -> a -> b
$ forall y v0 v1 (arrow :: * -> * -> *) yv.
(C y, C v0, C v1, Arrow arrow) =>
T v0 y
-> Single
     arrow (Dimensional v1 y) (Dimensional (Mul v0 v1) y) yv yv
FiltM.amplifyDimension T v0 y
volume

{-# INLINE amplifyScalarDimension #-}
amplifyScalarDimension :: (Ring.C y, Dim.C u, Dim.C v) =>
   DN.T v y ->
   Proc.T s u t
      (CausalD.Single s
          (Amp.Dimensional Dim.Scalar y) (Amp.Dimensional v y)
          yv yv)
amplifyScalarDimension :: forall y u v s t yv.
(C y, C u, C v) =>
T v y
-> T s
     u
     t
     (Single s (Dimensional Scalar y) (Dimensional v y) yv yv)
amplifyScalarDimension T v y
volume =
   forall a s u t. a -> T s u t a
Proc.pure forall a b. (a -> b) -> a -> b
$ forall y v (arrow :: * -> * -> *) yv.
(C y, C v, Arrow arrow) =>
T v y
-> Single arrow (Dimensional Scalar y) (Dimensional v y) yv yv
FiltM.amplifyScalarDimension T v y
volume


{-# INLINE negate #-}
negate :: (Additive.C (Sample.Displacement sample)) =>
   Proc.T s u t (CausalD.T s sample sample)
negate :: forall sample s u t.
C (Displacement sample) =>
T s u t (T s sample sample)
negate =
   forall a s u t. a -> T s u t a
Proc.pure forall a b. (a -> b) -> a -> b
$ forall sample (arrow :: * -> * -> *).
(C (Displacement sample), Arrow arrow) =>
T arrow sample sample
FiltM.negate


{-# INLINE envelope #-}
envelope :: (Ring.C y) =>
   Proc.T s u t (CausalD.T s (Sample.Flat y, Sample.Numeric amp y) (Sample.Numeric amp y))
envelope :: forall y s u t amp.
C y =>
T s u t (T s (Flat y, Numeric amp y) (Numeric amp y))
envelope =
   forall a s u t. a -> T s u t a
Proc.pure forall a b. (a -> b) -> a -> b
$ forall y (arrow :: * -> * -> *) amp.
(C y, Arrow arrow) =>
T arrow (Flat y, Numeric amp y) (Numeric amp y)
FiltM.envelope

{-# INLINE envelopeScalarDimension #-}
envelopeScalarDimension ::
   (Ring.C y, Dim.C u, Dim.C v) =>
   Proc.T s u t
      (CausalD.T s
          (Sample.Dimensional Dim.Scalar y y, Sample.Dimensional v y y)
          (Sample.Dimensional v y y))
envelopeScalarDimension :: forall y u v s t.
(C y, C u, C v) =>
T s
  u
  t
  (T s
     (Dimensional Scalar y y, Dimensional v y y)
     (Dimensional v y y))
envelopeScalarDimension =
   forall a s u t. a -> T s u t a
Proc.pure forall a b. (a -> b) -> a -> b
$ forall y v (arrow :: * -> * -> *).
(C y, C v, Arrow arrow) =>
T arrow
  (Dimensional Scalar y y, Dimensional v y y)
  (Dimensional v y y)
FiltM.envelopeScalarDimension

{-# INLINE envelopeVector #-}
envelopeVector :: (Module.C y (Sample.Displacement sample)) =>
   Proc.T s u t (CausalD.T s (Sample.Flat y, sample) sample)
envelopeVector :: forall y sample s u t.
C y (Displacement sample) =>
T s u t (T s (Flat y, sample) sample)
envelopeVector =
   forall a s u t. a -> T s u t a
Proc.pure forall a b. (a -> b) -> a -> b
$ forall y sample (arrow :: * -> * -> *).
(C y (Displacement sample), Arrow arrow) =>
T arrow (Flat y, sample) sample
FiltM.envelopeVector

{-# INLINE envelopeVectorDimension #-}
envelopeVectorDimension ::
   (Module.C y0 yv, Ring.C y, Dim.C u, Dim.C v0, Dim.C v1) =>
   Proc.T s u t
      (CausalD.T s
          (Sample.Dimensional v0 y y0, Sample.Dimensional v1 y yv)
          (Sample.Dimensional (Dim.Mul v0 v1) y yv))
envelopeVectorDimension :: forall y0 yv y u v0 v1 s t.
(C y0 yv, C y, C u, C v0, C v1) =>
T s
  u
  t
  (T s
     (Dimensional v0 y y0, Dimensional v1 y yv)
     (Dimensional (Mul v0 v1) y yv))
envelopeVectorDimension =
   forall a s u t. a -> T s u t a
Proc.pure forall a b. (a -> b) -> a -> b
$ forall y0 yv y v0 v1 (arrow :: * -> * -> *).
(C y0 yv, C y, C v0, C v1, Arrow arrow) =>
T arrow
  (Dimensional v0 y y0, Dimensional v1 y yv)
  (Dimensional (Mul v0 v1) y yv)
FiltM.envelopeVectorDimension


{-# INLINE differentiate #-}
differentiate :: (Additive.C yv, Ring.C q, Dim.C u, Dim.C v) =>
   Proc.T s u q
      (CausalD.Single s
         (Amp.Dimensional v q) (Amp.Dimensional (DimensionGradient u v) q) yv yv)
differentiate :: forall yv q u v s.
(C yv, C q, C u, C v) =>
T s
  u
  q
  (Single
     s (Dimensional v q) (Dimensional (DimensionGradient u v) q) yv yv)
differentiate =
   forall a b c. (a -> b -> c) -> b -> a -> c
flip forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall u s t. C u => T s u t (T (Recip u) t)
Proc.getSampleRate forall a b. (a -> b) -> a -> b
$ \T (Recip u) q
rate ->
      forall sample0 sample1 s.
(Amplitude sample0
 -> (Amplitude sample1,
     T (Displacement sample0) (Displacement sample1)))
-> T s sample0 sample1
CausalD.consFlip forall a b. (a -> b) -> a -> b
$ \ (Amp.Numeric T v q
amp) ->
         (forall amp. amp -> Numeric amp
Amp.Numeric forall a b. (a -> b) -> a -> b
$ T (Recip u) q
rate forall u v a. (C u, C v, C a) => T u a -> T v a -> T (Mul u v) a
&*& T v q
amp,
          forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry (-) forall (a :: * -> * -> *) c d b.
Arrow a =>
(c -> d) -> a b c -> a b d
^<< forall a. T a a
Causal.id forall (a :: * -> * -> *) b c c'.
Arrow a =>
a b c -> a b c' -> a b (c, c')
&&& forall x. x -> T x x
Causal.consInit forall a. C a => a
zero)
--          Causal.crochetL (\x0 x1 -> Just (x0-x1, x0)) zero)


{-
{- | needs a good handling of boundaries, yet -}
{-# INLINE meanStatic #-}
meanStatic ::
   (RealRing.C q, Module.C q yv, Dim.C u, Dim.C v) =>
      DN.T (Dim.Recip u) q   {- ^ cut-off frequency -}
   -> Proc.T s u q (
        SigA.R s v q yv
     -> SigA.R s v q yv)
meanStatic time =
   FiltR.meanStatic time

meanStaticSeparateTY :: (Additive.C yv, Field.C y, RealRing.C t,
         Module.C y yv, Dim.C u, Dim.C v) =>
      DN.T (Dim.Recip u) t   {- ^ cut-off frequency -}
   -> Proc.T s u t (
        SigA.R s v y yv
     -> SigA.R s v y yv)
meanStaticSeparateTY time =
   -- FiltR.meanStatic time, means that 't' = 'y'
   do f <- toFrequencyScalar time
      return $ \ x ->
         let tInt  = round ((recip f - 1)/2)
             width = tInt*2+1
         in  SigA.processBody
                ((SigA.asTypeOfAmplitude (recip (fromIntegral width)) x *> ) .
                 Delay.staticNeg tInt .
                 MA.sumsStaticInt width) x


{- | needs a better handling of boundaries, yet -}
{-# INLINE mean #-}
mean :: (Additive.C yv, RealRing.C q,
         Module.C q yv, Dim.C u, Dim.C v) =>
      DN.T (Dim.Recip u) q    {- ^ minimum cut-off frequency -}
   -> Proc.T s u q (
        SigA.R s (Dim.Recip u) q q
                              {- v cut-off frequencies -}
     -> SigA.R s v q yv
     -> SigA.R s v q yv)
mean minFreq =
   FiltR.mean minFreq


{-# INLINE delay #-}
delay :: (Additive.C yv, Field.C y, RealRing.C t, Dim.C u, Dim.C v) =>
      DN.T u t
   -> Proc.T s u t (
        SigA.R s v y yv
     -> SigA.R s v y yv)
delay time =
   do t <- toTimeScalar time
      return $ SigA.processBody (Delay.static (round t))


{-# INLINE phaseModulation #-}
phaseModulation ::
   (Additive.C yv, RealRing.C q, Dim.C u, Dim.C v,
    Sample.C q, Sample.C yv) =>
      Interpolation.T q yv
   -> DN.T u q
          {- ^ minDelay, minimal delay, may be negative -}
   -> DN.T u q
          {- ^ maxDelay, maximal delay, it must be @minDelay <= maxDelay@
               and the modulation must always be
               in the range [minDelay,maxDelay]. -}
   -> Proc.T s u q (
        SigA.R s u q q
          {- v delay control, positive numbers meanStatic delay,
               negative numbers meanStatic prefetch -}
     -> SigA.R s v q yv
     -> SigA.R s v q yv)
phaseModulation ip minDelay maxDelay =
   FiltR.phaseModulation ip minDelay maxDelay

{-# INLINE frequencyModulation #-}
frequencyModulation ::
   (Flat.C flat q, Additive.C yv, RealRing.C q, Dim.C u, Dim.C v) =>
      Interpolation.T q yv
   -> Proc.T s u q (
        RP.T s flat q    {- v frequency factors -}
     -> SigA.R s v q yv
     -> SigA.R s v q yv)
frequencyModulation ip =
   Proc.pure $
      \ factors ->
          SigA.processBody
             (FiltR.interpolateMultiRelativeZeroPad ip (Flat.toSamples factors))

{- |
Frequency modulation where the input signal can have a sample rate
different from the output.
(The sample rate values can differ, the unit must be the same.
We could lift that restriction,
but then the unit handling becomes more complicated,
and I didn't have a use for it so far.)

The function can be used for resampling.
-}
{-# INLINE frequencyModulationDecoupled #-}
frequencyModulationDecoupled ::
   (Flat.C flat q, Additive.C yv, RealRing.C q, Dim.C u, Dim.C v) =>
      Interpolation.T q yv
   -> Proc.T s u q (
        RP.T s flat q    {- v frequency factors -}
     -> SigP.T u q (SigA.D v q SigS.S) yv
     -> SigA.R s v q yv)
frequencyModulationDecoupled ip =
   fmap
      (\toFreq factors y ->
         flip SigA.processBody (RP.fromSignal (SigP.signal y)) $
            FiltR.interpolateMultiRelativeZeroPad ip
               (SigA.scalarSamples toFreq
                  (SigA.fromBody (SigA.actualSampleRate y) (Flat.toSamples factors))))
      (Proc.withParam Proc.toFrequencyScalar)


{- | symmetric phaser -}
{-# INLINE phaser #-}
phaser ::
   (Additive.C yv, RealRing.C q,
    Module.C q yv, Dim.C u, Dim.C v,
    Sample.C q, Sample.C yv) =>
      Interpolation.T q yv
   -> DN.T u q  {- ^ maxDelay, must be positive -}
   -> Proc.T s u q (
        SigA.R s u q q
                {- v delay control -}
     -> SigA.R s v q yv
     -> SigA.R s v q yv)
phaser = FiltR.phaser

{-# INLINE phaserStereo #-}
phaserStereo ::
   (Additive.C yv, RealRing.C q,
    Module.C q yv, Dim.C u, Dim.C v,
    Sample.C q, Sample.C yv) =>
      Interpolation.T q yv
   -> DN.T u q   {- ^ maxDelay, must be positive -}
   -> Proc.T s u q (
        SigA.R s u q q
                 {- v delay control -}
     -> SigA.R s v q yv
     -> SigA.R s v q (Stereo.T yv))
phaserStereo = FiltR.phaserStereo
-}



{-
The handling of amplitudes is not efficient and the results may surprise.
Due to rounding errors the output amplitude may differ from input amplitude.
This problem can only be overcome by a specialised low-level routine.

allpassPhaser :: (Trans.C q, Module.C q yv, Dim.C u) =>
      NonNeg.Int  {- ^ order, number of filters in the cascade -}
   -> q           {- ^ mixing ratio @x@ means:
                       amplify input by @x@ and
                       amplify delayed signal by @1-x@.
                       Maximum effect is achieved for @x=0.5@. -}
   -> FrequencyFilter s u q (Allpass.Parameter q) amp yv yv
allpassPhaser order r =
-- incomplete
   fmap
      (fmap $ \ap ->
         mix CausalD.<<<
         CausalD.fanout
            (amplify r)
            (amplify (1-r) CausalD.<<< ap))
      (Filt.allpassCascade 20 Filt.allpassFlangerPhase)
-}


{-
{- | Infinitely many equi-delayed exponentially decaying echos. -}
{-# INLINE comb #-}
comb :: (RealRing.C t, Module.C y yv, Dim.C u, Dim.C v, Sample.C yv) =>
   DN.T u t -> y -> Proc.T s u t (SigA.R s v y yv -> SigA.R s v y yv)
comb = FiltR.comb


{- | Infinitely many equi-delayed echos processed by an arbitrary time-preserving signal processor. -}
{-# INLINE combProc #-}
combProc ::
   (RealRing.C t, Absolute.C y, Field.C y, Module.C y yv, Sample.C yv,
    Dim.C u, Dim.C v) =>
   DN.T u t ->
   Proc.T s u t (SigA.R s v y yv -> SigA.R s v y yv) ->
   Proc.T s u t (SigA.R s v y yv -> SigA.R s v y yv)
combProc time proc =
   do f <- proc
      t <- fmap round $ toTimeScalar time
      let chunkSize = SigSt.chunkSize t
      return $ \x ->
         SigA.processBody
            (Sig.fromStorableSignal .
             Comb.runProc t
                (Sig.toStorableSignal chunkSize .
                 SigA.vectorSamples (SigA.toAmplitudeScalar x) .
                 f .
                 SigA.fromBody (SigA.actualAmplitude x) .
                 Sig.fromStorableSignal) .
             Sig.toStorableSignal chunkSize) x
-}


{-# INLINE integrate #-}
integrate :: (Additive.C yv, Field.C q, Dim.C u, Dim.C v) =>
   Proc.T s u q
      (CausalD.T s (Sample.Dimensional v q yv) (Sample.Dimensional (Dim.Mul u v) q yv))
integrate :: forall yv q u v s.
(C yv, C q, C u, C v) =>
T s u q (T s (Dimensional v q yv) (Dimensional (Mul u v) q yv))
integrate =
   forall a b c. (a -> b -> c) -> b -> a -> c
flip forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall u s t. C u => T s u t (T (Recip u) t)
Proc.getSampleRate forall a b. (a -> b) -> a -> b
$ \T (Recip u) q
rate ->
      forall sample0 sample1 s.
(Amplitude sample0
 -> (Amplitude sample1,
     T (Displacement sample0) (Displacement sample1)))
-> T s sample0 sample1
CausalD.consFlip forall a b. (a -> b) -> a -> b
$ \ (Amp.Numeric T v q
amp) ->
         (forall amp. amp -> Numeric amp
Amp.Numeric forall a b. (a -> b) -> a -> b
$
          forall u a. (C u, C a) => T (Recip u) a -> T u a
DN.unrecip T (Recip u) q
rate forall u v a. (C u, C v, C a) => T u a -> T v a -> T (Mul u v) a
&*& T v q
amp,
          forall v. C v => T v v
Integrate.causal)