/********************************************************************
 *                                                                  *
 * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.   *
 * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
 * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
 * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
 *                                                                  *
 * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002             *
 * by the XIPHOPHORUS Company http://www.xiph.org/                  *
 *                                                                  *
 ********************************************************************

 function: floor backend 0 implementation
 last mod: $Id: floor0.c,v 1.49 2001/12/21 14:52:35 segher Exp $

 ********************************************************************/

#include <string.h>
#include "registry.h"
#include "lsp.h"
#include "os.h"
#include "misc.h"

extern int32_t vorbis_coslook_i(int32_t a);

static const int32_t barklook[28]={
  0,100,200,301,          405,516,635,766,
  912,1077,1263,1476,     1720,2003,2333,2721,
  3184,3742,4428,5285,    6376,7791,9662,12181,
  15624,20397,27087,36554
};

/* used in init only; interpolate the long way */
static int32_t toBARK(int n){
  int i;
  for(i=0;i<27;i++)
    if(n>=barklook[i] && n<barklook[i+1])break;

  if(i==27){
    return 27<<15;
  }else{
    int gap=barklook[i+1]-barklook[i];
    int del=n-barklook[i];

    return((i<<15)+((del<<15)/gap));
  }
}

typedef struct{
	int     ln;
	int     m;
	int*    linearmap[2];
	int     n[2];
	int     channels;
	bint**  plsp;

	vorbis_info_floor0*	vi;
} vorbis_look_floor0;

static void floor0_free_info(vorbis_info_floor* i){
	vorbis_info_floor0* info = (vorbis_info_floor0*) i;
	if (info) _ogg_free(info);
}

static void floor0_free_look(vorbis_look_floor* i){
	vorbis_look_floor0* look = (vorbis_look_floor0*) i;
	if (look){
		if (look->linearmap[0]) _ogg_free(look->linearmap[0]);
		if (look->linearmap[1]) _ogg_free(look->linearmap[1]);
		if (look->plsp){
			int j;

			for (j = 0; j < look->channels; j++)
				_ogg_free(look->plsp[j]);
			_ogg_free(look->plsp);
		}
		_ogg_free(look);
	}
}

static vorbis_info_floor* floor0_unpack(vorbis_info* vi, oggpack_buffer* opb){
	codec_setup_info* ci = vi->codec_setup;
	int j;

	vorbis_info_floor0* info = _ogg_malloc(sizeof(*info));
	if (!info) return NULL;

	info->order=oggpack_read(opb,8);
	info->rate=oggpack_read(opb,16);
	info->barkmap=oggpack_read(opb,16);
	info->ampbits=oggpack_read(opb,6);
	info->ampdB=oggpack_read(opb,8);
	info->numbooks=oggpack_read(opb,4)+1;

  if(info->order<1)goto err_out;
  if(info->rate<1)goto err_out;
  if(info->barkmap<1)goto err_out;
  if(info->numbooks<1)goto err_out;

  for(j=0;j<info->numbooks;j++){
    info->books[j]=oggpack_read(opb,8);
    if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  }
  return(info);

 err_out:
  floor0_free_info(info);
  return(NULL);
}

/* initialize Bark scale and normalization lookups.  We could do this
   with static tables, but Vorbis allows a number of possible
   combinations, so it's best to do it computationally.

   The below is authoritative in terms of defining scale mapping.
   Note that the scale depends on the sampling rate as well as the
   linear block and mapping sizes */
static int floor0_map_lazy_init(vorbis_block      *vb,
                                vorbis_info_floor *infoX,
                                vorbis_look_floor0 *look){
  if(!look->linearmap[vb->W]){
    vorbis_dsp_state   *vd=vb->vd;
    vorbis_info        *vi=vd->vi;
    codec_setup_info   *ci=vi->codec_setup;
    vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
    int W=vb->W;
    int n=ci->blocksizes[W]/2,j;
    int div;

    /* we choose a scaling constant so that:
       floor(bark(rate/2-1)*C)=mapped-1
       floor(bark(rate/2)*C)=mapped */
    div = toBARK(info->rate/2);

    /* the mapping from a linear scale to a smaller bark scale is
       straightforward.  We do *not* make sure that the linear mapping
       does not skip bark-scale bins; the decoder simply skips them and
       the encoder may do what it wishes in filling them.  They're
       necessary in some mapping combinations to keep the scale spacing
       accurate */
    look->linearmap[W]=_ogg_malloc((n+1)*sizeof(*look->linearmap));
    if (!look->linearmap[W]) return 1;
    for(j=0;j<n;j++){
      int val=(look->ln*((toBARK(info->rate/2*j/n)<<11)/div))>>11;
		   /* bark numbers represent band edges */
      if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
      //do cos convertion here instead of in lsp
      look->linearmap[W][j]=vorbis_coslook_i(0x10000*val/look->ln);
    }
    look->linearmap[W][j]=-0x100000; // special val
    look->n[W]=n;
  }

  return 0;
}

static vorbis_look_floor* floor0_look(vorbis_dsp_state* vd,
					                  vorbis_info_floor* i){
  vorbis_info        *vi=vd->vi;
  vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  vorbis_look_floor0 *look=_ogg_calloc(1,sizeof(*look));
  if (!look) return NULL;

  look->m=info->order;
  look->ln=info->barkmap;
  look->vi=info;
  look->channels = vi->channels;

  look->plsp = _ogg_malloc(look->channels*sizeof(*look->plsp));
  if (!look->plsp) goto err_out;
  memset(look->plsp,0,look->channels*sizeof(*look->plsp));
  for (int j = 0; j < look->channels; j++)
  {
    look->plsp[j] = _ogg_malloc(sizeof(*look->plsp[j])*(look->m+1));
    if (!look->plsp[j]) goto err_out;
  }

  return look;

err_out:
  floor0_free_look(look);
  return(NULL);
}

static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i, int ch){
  vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  vorbis_info_floor0 *info=look->vi;
  int j,k;
  int ampraw=oggpack_read(&vb->opb,info->ampbits);

  if(ampraw>0){ /* also handles the -1 out of data case */
    bint amp;
    int shift = info->ampbits - BISHIFT;
    int booknum=oggpack_read(&vb->opb,ilog(info->numbooks));

    if (shift > 0)
    	amp = (ampraw >> shift) * info->ampdB;
    else
    	amp = (ampraw << -shift) * info->ampdB;

    if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
      codec_setup_info *ci=vb->vd->vi->codec_setup;
      codebook *b=ci->fullbooks+info->books[booknum];
      bint last=BIZERO;
      bint* lsp=look->plsp[ch];

      for(j=0;j<look->m;j+=b->dim)
	if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
      for(j=0;j<look->m;){
	for(k=0;j<look->m && k<b->dim;k++,j++)lsp[j]+=last;
	last=lsp[j-1];
      }

      lsp[look->m]=amp;
      return(lsp);
    }
  }
 eop:
  return(NULL);
}

static int floor0_inverse2(vorbis_block* vb, vorbis_look_floor* i,
			   void* memo, xint* out){
  vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  vorbis_info_floor0 *info=look->vi;

  if (floor0_map_lazy_init(vb,info,look))
  	return 1;

  if(memo){
    bint* lsp=(bint*) memo;
    bint  amp=lsp[look->m];

    /* take the coefficients back to a spectral envelope curve */
    vorbis_lsp_to_curve(out,
    		look->linearmap[vb->W],
    		look->n[vb->W],
			lsp,look->m, amp, info->ampdB);
    return(1);
  }
  memset(out,0,sizeof(*out)*look->n[vb->W]);
  return(0);
}

/* export hooks */
const vorbis_func_floor floor0_exportbundle={
  &floor0_unpack,&floor0_look,&floor0_free_info,
  &floor0_free_look,&floor0_inverse1,&floor0_inverse2
};


