/* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/**
   @file pitch.c
   @brief Pitch analysis
 */

/*
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
   
   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
   
   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
   
   - Neither the name of the Xiph.org Foundation nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.
   
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

/*#include "cc6__kiss_fft_guts.h"
#include "cc6_kiss_fftr.h"*/
#include "cc6_kfft_single.h"

#include "cc6_pitch.h"
#include "cc6_psy.h"
#include "cc6_os_support.h"
#include "cc6_mathops.h"
#include "cc6_modes.h"
#include "cc6_stack_alloc.h"

cc6_kiss_fftr_cfg cc6_pitch_state_alloc(int max_lag)
{
   return cc6_real16_fft_alloc(max_lag);
}

void cc6_pitch_state_free(cc6_kiss_fftr_cfg st)
{
   cc6_real16_fft_free(st);
}

#ifdef FIXED_POINT
static void cc6_normalise16(cc6_celt_word16_t *x, int len, cc6_celt_word16_t val)
{
   int i;
   cc6_celt_word16_t maxabs;
   maxabs = cc6_celt_maxabs16(x,len);
   if (maxabs > val)
   {
      int shift = 0;
      while (maxabs > val)
      {
         maxabs >>= 1;
         shift++;
      }
      if (shift==0)
         return;
      i=0;
      do{
         x[i] = cc6_SHR16(x[i], shift);
      } while (++i<len);
   } else {
      int shift=0;
      if (maxabs == 0)
         return;
      val >>= 1;
      while (maxabs < val)
      {
         val >>= 1;
         shift++;
      }
      if (shift==0)
         return;
      i=0;
      do{
         x[i] = cc6_SHL16(x[i], shift);
      } while (++i<len);
   }
}
#else
#define cc6_normalise16(x,len,val)
#endif

#define cc6_INPUT_SHIFT 15

void cc6_find_spectral_pitch(const cc6_CELTMode *m, cc6_kiss_fftr_cfg fft, const struct cc6_PsyDecay *decay, const cc6_celt_sig_t * __restrict x, const cc6_celt_sig_t * __restrict y, const cc6_celt_word16_t * __restrict window, cc6_celt_word16_t * __restrict spectrum, int len, int max_pitch, int *pitch)
{
   int c, i;
   cc6_VARDECL(cc6_celt_word16_t, _X);
   cc6_VARDECL(cc6_celt_word16_t, _Y);
   const cc6_celt_word16_t * __restrict wptr;
#ifndef SHORTCUTS
   cc6_VARDECL(cc6_celt_mask_t, curve);
#endif
   cc6_celt_word16_t * __restrict X, * __restrict Y;
   cc6_celt_word16_t * __restrict Xptr, * __restrict Yptr;
   const cc6_celt_sig_t * __restrict yptr;
   int n2;
   int L2;
   const int C = cc6_CHANNELS(m);
   const int overlap = cc6_OVERLAP(m);
   const int lag = cc6_MAX_PERIOD;
   cc6_SAVE_STACK;
   n2 = lag>>1;
   L2 = len>>1;
   cc6_ALLOC(_X, lag, cc6_celt_word16_t);
   X = _X;
#ifndef SHORTCUTS
   cc6_ALLOC(curve, n2, cc6_celt_mask_t);
#endif
   cc6_CELT_MEMSET(X,0,lag);
   /* Sum all channels of the current frame and copy into X in bit-reverse order */
   for (c=0;c<C;c++)
   {
      const cc6_celt_sig_t * __restrict xptr = &x[c];
      for (i=0;i<L2;i++)
      {
         X[2*cc6_BITREV(fft,i)] += cc6_SHR32(*xptr,cc6_INPUT_SHIFT);
         xptr += C;
         X[2*cc6_BITREV(fft,i)+1] += cc6_SHR32(*xptr,cc6_INPUT_SHIFT);
         xptr += C;
      }
   }
   /* Applying the window in the bit-reverse domain. It's a bit weird, but it
      can help save memory */
   wptr = window;
   for (i=0;i<overlap>>1;i++)
   {
      X[2*cc6_BITREV(fft,i)]        = cc6_MULT16_16_Q15(wptr[0], X[2*cc6_BITREV(fft,i)]);
      X[2*cc6_BITREV(fft,i)+1]      = cc6_MULT16_16_Q15(wptr[1], X[2*cc6_BITREV(fft,i)+1]);
      X[2*cc6_BITREV(fft,L2-i-1)]   = cc6_MULT16_16_Q15(wptr[1], X[2*cc6_BITREV(fft,L2-i-1)]);
      X[2*cc6_BITREV(fft,L2-i-1)+1] = cc6_MULT16_16_Q15(wptr[0], X[2*cc6_BITREV(fft,L2-i-1)+1]);
      wptr += 2;
   }
   cc6_normalise16(X, lag, 8192);
   /*for (i=0;i<lag;i++) printf ("%d ", X[i]);printf ("\n");*/
   /* Forward real FFT (in-place) */
   cc6_real16_fft_inplace(fft, X, lag);

   if (spectrum)
   {
      for (i=0;i<lag/4;i++)
      {
         spectrum[2*i] = X[4*i];
         spectrum[2*i+1] = X[4*i+1];
      }
   }
#ifndef SHORTCUTS
   cc6_compute_masking(decay, X, curve, lag);
#endif
   
   /* Deferred allocation to reduce peak stack usage */
   cc6_ALLOC(_Y, lag, cc6_celt_word16_t);
   Y = _Y;
   yptr = &y[0];
   /* Copy first channel of the past audio into Y in bit-reverse order */
   for (i=0;i<n2;i++)
   {
      Y[2*cc6_BITREV(fft,i)] = cc6_SHR32(*yptr,cc6_INPUT_SHIFT);
      yptr += C;
      Y[2*cc6_BITREV(fft,i)+1] = cc6_SHR32(*yptr,cc6_INPUT_SHIFT);
      yptr += C;
   }
   /* Add remaining channels into Y in bit-reverse order */
   for (c=1;c<C;c++)
   {
      yptr = &y[c];
      for (i=0;i<n2;i++)
      {
         Y[2*cc6_BITREV(fft,i)] += cc6_SHR32(*yptr,cc6_INPUT_SHIFT);
         yptr += C;
         Y[2*cc6_BITREV(fft,i)+1] += cc6_SHR32(*yptr,cc6_INPUT_SHIFT);
         yptr += C;
      }
   }
   cc6_normalise16(Y, lag, 8192);
   /* Forward real FFT (in-place) */
   cc6_real16_fft_inplace(fft, Y, lag);

   /* Compute cross-spectrum using the inverse masking curve as weighting */
   Xptr = &X[2];
   Yptr = &Y[2];
   for (i=1;i<n2;i++)
   {
      cc6_celt_word16_t Xr, Xi, n;
      /* weight = 1/sqrt(curve) */
      Xr = Xptr[0];
      Xi = Xptr[1];
#ifdef SHORTCUTS
      /*n = cc6_SHR32(32767,(cc6_celt_ilog2(cc6_EPSILON+curve[i])>>1));*/
      n = 1+(8192>>(cc6_celt_ilog2(1+cc6_MULT16_16(Xr,Xr)+cc6_MULT16_16(Xi,Xi))>>1));
      /* Pre-multiply X by n, so we can keep everything in 16 bits */
      Xr = cc6_MULT16_16_16(n, Xr);
      Xi = cc6_MULT16_16_16(n, Xi);
#else
      n = cc6_celt_rsqrt(cc6_EPSILON+curve[i]);
      /* Pre-multiply X by n, so we can keep everything in 16 bits */
      Xr = cc6_EXTRACT16(cc6_SHR32(cc6_MULT16_16(n, Xr),3));
      Xi = cc6_EXTRACT16(cc6_SHR32(cc6_MULT16_16(n, Xi),3));
#endif
      /* Cross-spectrum between X and conj(Y) */
      *Xptr++ = cc6_ADD16(cc6_MULT16_16_Q15(Xr, Yptr[0]), cc6_MULT16_16_Q15(Xi,Yptr[1]));
      *Xptr++ = cc6_SUB16(cc6_MULT16_16_Q15(Xr, Yptr[1]), cc6_MULT16_16_Q15(Xi,Yptr[0]));
      Yptr += 2;
   }
   /*printf ("\n");*/
   X[0] = X[1] = 0;
   /*for (i=0;i<lag;i++) printf ("%d ", X[i]);printf ("\n");*/
   cc6_normalise16(X, lag, 50);
   /* Inverse half-complex to real FFT gives us the correlation */
   cc6_real16_ifft(fft, X, Y, lag);
   
   /* The peak in the correlation gives us the pitch */
   *pitch = cc6_find_max16(Y, max_pitch);
   cc6_RESTORE_STACK;
}