/*
This software module was originally developed by
Toshiyuki Nomura (NEC Corporation)
and edited by

in the course of development of the
MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and 3.
This software module is an implementation of a part of one or more
MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4 Audio
standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio standards
free license to this software module or modifications thereof for use in
hardware or software products claiming conformance to the MPEG-2 NBC/
MPEG-4 Audio  standards. Those intending to use this software module in
hardware or software products are advised that this use may infringe
existing patents. The original developer of this software module and
his/her company, the subsequent editors and their companies, and ISO/IEC
have no liability for use of this software module or modifications
thereof in an implementation. Copyright is not released for non
MPEG-2 NBC/MPEG-4 Audio conforming products. The original developer
retains full right to use the code for his/her  own purpose, assign or
donate the code to a third party and to inhibit third party from using
the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
This copyright notice must be included in all copies or derivative works.
Copyright (c)1996.
*/
/*
 *	MPEG-4 Audio Verification Model (LPC-ABS Core)
 *	
 *	Mode Decision Subroutines
 *
 *	Ver1.0	96.12.16	T.Nomura(NEC)
 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include	"nec_abs_const.h"
#include	"nec_exc_proto.h"

#define NEC_LAG_RNG		8
#define	NEC_LEN_PITCH_ANALYSIS	80

void nec_mode_decision(
		       float	input_signal[],	/* input */
		       float	wn_alpha[],	/* input */
		       float	wd_alpha[],	/* input */
		       long	lpc_order,	/* configuration input */
		       long	frame_size,	/* configuration input */
		       long	sbfrm_size,	/* configuration input */
		       long	lag_idx_cand[],	/* output */
		       long	*vu_flag	/* output */
		       )
{
   long		i, j, k;
   long		can, frame, sample, num_sf;
   long		*lag_path, *lag_sf;
   long		org_frame, max_lag, idx, lag;
   long		lag_lmt0, lag_lmt1;
   float	dist;
   float	*cur_wsp, *dly_wsp;
   float	cWc, cWx, xWx, *cr2ar;
   float	frms, gain_pitch_p, gain_pitch_total;
   static long	flag=0, int_to_indx[NEC_PITCH_MAX+1];
   static float	pmn[NEC_LPC_ORDER], pmd[NEC_LPC_ORDER];
   static float pst_wsp[NEC_PITCH_MAX];
   static float	lag_priority;
   static float	thr_spurms, thr_gain[3], rms_m01;
   long		len_pitch_ana;
   long		n_pitch;

   num_sf = frame_size/sbfrm_size;
   len_pitch_ana = sbfrm_size;
   if ( len_pitch_ana < (long)NEC_LEN_PITCH_ANALYSIS )
      len_pitch_ana = (long)NEC_LEN_PITCH_ANALYSIS;
   n_pitch = frame_size/len_pitch_ana;

   /*------ memory initialization ------*/
   if ( flag == 0 ) {
      flag = 1;
      for ( i = 0; i < NEC_LPC_ORDER; i++ ) pmn[i] = pmd[i] = 0.0;
      for ( i = 0; i < NEC_PITCH_MAX; i++ ) pst_wsp[i] = 0.0;
      /* INTEGER DELAY TO INDEX 17-144 */
      int_to_indx[0] = 255;
      for (i = 17; i <= 70; i++) {
	 int_to_indx[i] = (i - 17) * 3;
      }
      for (i = 71; i <= 89; i++) {
	 int_to_indx[i] = 162 + (i - 71) * 2;
      }
      for (i = 90; i <= 144; i++) {
	 int_to_indx[i] = 200 + (i - 90);
      }
      lag_priority = 0.85;
      rms_m01 = 250.0;
      thr_spurms = 10.0;
      thr_gain[0] = 9.0;
      thr_gain[1] = 3.5;
      thr_gain[2] = 1.5;
   }

   /*------ memory allocation ----------*/
   if ((lag_sf = (long *)calloc(n_pitch, sizeof(long))) == NULL) {
      printf("\n Memory allocation error in nec_mode_decision \n");
      exit(1);
   }
   if ((lag_path = (long *)calloc(n_pitch, sizeof(long))) == NULL) {
      printf("\n Memory allocation error in nec_mode_decision \n");
      exit(1);
   }
   if ((cur_wsp = (float *)calloc(frame_size, sizeof(float))) == NULL) {
      printf("\n Memory allocation error in nec_mode_decision \n");
      exit(1);
   }
   if ((dly_wsp = (float *)calloc(len_pitch_ana, sizeof(float))) == NULL) {
      printf("\n Memory allocation error in nec_mode_decision \n");
      exit(1);
   }
   if ((cr2ar = (float *)calloc(n_pitch*(NEC_PITCH_MAX+1), sizeof(float))) == NULL) {
      printf("\n Memory allocation error in nec_mode_decision \n");
      exit(1);
   }

   /*------- open-loop pitch search subframe by subframe -------*/
   for ( frame = 0; frame < n_pitch; frame++ ) {
      nec_pw_filt(&cur_wsp[frame*len_pitch_ana],
		  &input_signal[frame*len_pitch_ana],
		  lpc_order,
		  &wd_alpha[frame*lpc_order], &wn_alpha[frame*lpc_order],
		  pmn, pmd, len_pitch_ana);
   }

   for ( frame = 0; frame < n_pitch; frame++ ) {
      for ( lag = NEC_PITCH_MIN; lag <= NEC_PITCH_MAX; lag++ ) {
	 for ( sample = 0, k = NEC_PITCH_MAX - lag;
	      k < NEC_PITCH_MAX && sample < len_pitch_ana; k++, sample++) {
	    dly_wsp[sample] = pst_wsp[k];
	 }
	 for ( k = 0; sample < len_pitch_ana; k++, sample++) {
	    dly_wsp[sample] = cur_wsp[len_pitch_ana * frame + k];
	 }
	 cWc = 0.0;
	 cWx = 0.0;
	 for ( k = 0; k < len_pitch_ana; k++) {
	    cWc += dly_wsp[k] * dly_wsp[k];
	    cWx += dly_wsp[k] * cur_wsp[len_pitch_ana * frame + k];
	 }
	 
	 idx = (NEC_PITCH_MAX+1)*frame+lag;
	 if (cWc == 0.0 || cWx == 0.0) {
	    cr2ar[idx] = 0.0;
	 } else {
	    cr2ar[idx] = cWx / sqrt( cWc );
	 }
      }

      /*--- MEMORY UPDATE ---*/
      for ( i = 0; i < NEC_PITCH_MAX - len_pitch_ana; i++ ) {
	 pst_wsp[i] = pst_wsp[len_pitch_ana+i];
      }
      for ( i = 0; i < len_pitch_ana; i++ ) {
	 pst_wsp[(NEC_PITCH_MAX-len_pitch_ana)+i] =
	    cur_wsp[len_pitch_ana*frame+i];
      }
   }

   for ( frame = 0; frame < n_pitch; frame++ ) {
      dist = cr2ar[(NEC_PITCH_MAX+1)*frame+NEC_PITCH_MIN];
      max_lag = NEC_PITCH_MIN;
      for ( lag = NEC_PITCH_MIN+1; lag <= NEC_PITCH_MAX; lag++ ) {
	 idx = (NEC_PITCH_MAX+1)*frame+lag;
	 if ( (lag-max_lag) > NEC_PITCH_MIN ) lag_priority = 0.85;
	 else				      lag_priority = 1.0;
	 if ( lag_priority * cr2ar[idx] > dist ) {
	    max_lag = lag;
	    dist = cr2ar[idx];
	 }
	 lag_sf[frame] = max_lag;
      }
   }

   /*----------- U/V DECISION ---------------*/
   gain_pitch_total = 0.0;
   frms = 0.0;
   for ( frame = 0; frame < n_pitch; frame++ ) {
      idx = (NEC_PITCH_MAX+1)*frame + lag_sf[frame];
      xWx = 0.0;
      for (i = 0; i < len_pitch_ana; i++) {
	 xWx += cur_wsp[frame * len_pitch_ana + i]
	    * cur_wsp[frame * len_pitch_ana + i];
	 frms += input_signal[frame * len_pitch_ana + i]
	    * input_signal[frame * len_pitch_ana + i];
      }
      gain_pitch_p = ((xWx == 0.0 || xWx - cr2ar[idx]*cr2ar[idx] <= 0.0 )
		      ? 1.0
		      : xWx / (xWx - cr2ar[idx]*cr2ar[idx]));
      gain_pitch_total += 10.0 * log10(gain_pitch_p);
   }
   gain_pitch_total = gain_pitch_total / n_pitch;
   frms = sqrt(frms / frame_size);
   if (frms < thr_spurms || gain_pitch_total < thr_gain[2]) {
      if (frms * gain_pitch_total > rms_m01 * thr_gain[2]) {
	 *vu_flag = 1;
      } else {
	 *vu_flag = 0;
      }
   } else {
      if (thr_gain[2] <= gain_pitch_total && gain_pitch_total < thr_gain[1]) {
	 *vu_flag = 1;
      }
      if (thr_gain[1] <= gain_pitch_total && gain_pitch_total < thr_gain[0]) {
	 *vu_flag = 2;
      }
      if (thr_gain[0] <= gain_pitch_total) {
	 *vu_flag = 3;
      }
   }

   if ( *vu_flag > 1 ) {
      /*------- open-loop pitch trackng -------*/
      dist = -1.0e30;
      for ( frame = 0; frame < n_pitch; frame++ ) {
	 idx = (NEC_PITCH_MAX+1)*frame+lag_sf[frame];
	 if ( cr2ar[idx] > dist ) {
	    dist = cr2ar[idx];
	    org_frame = frame;
	 }
      }
      lag_lmt0 = lag_sf[org_frame] - NEC_LAG_RNG;
      lag_lmt1 = lag_sf[org_frame] + NEC_LAG_RNG;
      if ( lag_lmt0 < NEC_PITCH_MIN ) lag_lmt0 = NEC_PITCH_MIN;
      if ( lag_lmt1 > NEC_PITCH_MAX ) lag_lmt1 = NEC_PITCH_MAX;

      for ( frame = 0; frame < n_pitch; frame++ ) {
	 dist = -1.0e30;
	 lag_path[frame] = -1;
	 for ( lag = lag_lmt0; lag <= lag_lmt1; lag++) {
	    idx = (NEC_PITCH_MAX+1)*frame + lag;
	    if (cr2ar[idx] > dist) {
	       dist = cr2ar[idx];
	       lag_path[frame] = lag;
	    }
	 }
      }
   } else {
      /*------- open-loop pitch search -------*/
      for ( frame = 0; frame < n_pitch; frame++ ) {
	 lag_path[frame] = lag_sf[frame];
      }
   }

   for ( i = 0; i < n_pitch; i++ ) {
      for ( j = 0; j < num_sf/n_pitch; j++ ) {
	 lag_idx_cand[i*num_sf/n_pitch+j] = int_to_indx[lag_path[i]];
      }
   }

   free( lag_sf );
   free( lag_path );
   free( cur_wsp );
   free( dly_wsp );
   free( cr2ar );

}
