/********************************************************************
 *                                                                  *
 * 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 1 implementation
 last mod: $Id: floor1.c,v 1.19 2001/12/19 23:13:33 segher Exp $

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "registry.h"
#include "os.h"
#include "misc.h"

#define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */

typedef struct{
	int forward_index[VIF_POSIT+2];

	int hineighbor[VIF_POSIT];
	int loneighbor[VIF_POSIT];
	int posts;

	int n;
	int quant_q;
	vorbis_info_floor1 *vi;
	int	channels;
	int32_t**	pfits;

} vorbis_look_floor1;

static void floor1_free_info(vorbis_info_floor *i){
	vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;

	if(info){
		_ogg_free(info);
	}
}

static void floor1_free_look(vorbis_look_floor *i){
	vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
	if(look){
		if (look->pfits)
		{
			int j;

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

static int icomp(const void *a,const void *b){
  return(**(int **)a-**(int **)b);
}

static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  codec_setup_info     *ci=vi->codec_setup;
  int j,k,count=0,maxclass=-1,rangebits;

  vorbis_info_floor1 *info=_ogg_calloc(1,sizeof(*info));
  if (!info) return NULL;
  /* read partitions */
  info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  for(j=0;j<info->partitions;j++){
    info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
    if(info->partitionclass[j]<0)goto err_out;
    if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  }

  /* read partition classes */
  for(j=0;j<maxclass+1;j++){
    info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
    info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
    if(info->class_subs[j]<0)
      goto err_out;
    if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
    if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
      goto err_out;
    for(k=0;k<(1<<info->class_subs[j]);k++){
      info->class_subbook[j][k]=oggpack_read(opb,8)-1;
      if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
	goto err_out;
    }
  }

  /* read the post list */
  info->mult=oggpack_read(opb,2)+1;     /* only 1,2,3,4 legal now */
  rangebits=oggpack_read(opb,4);
  if(rangebits<0)goto err_out;

  for(j=0,k=0;j<info->partitions;j++){
    count+=info->class_dim[info->partitionclass[j]];
    if(count>VIF_POSIT) goto err_out;
    for(;k<count;k++){
      int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
      if(t<0 || t>=(1<<rangebits))
	goto err_out;
    }
  }
  info->postlist[0]=0;
  info->postlist[1]=1<<rangebits;

  /* don't allow repeated values in post list as they'd result in
     zero-length segments */
  {
    int *sortpointer[VIF_POSIT+2];
    for(j=0;j<count+2;j++)sortpointer[j]=info->postlist+j;
    qsort(sortpointer,count+2,sizeof(*sortpointer),icomp);

    for(j=1;j<count+2;j++)
      if(*sortpointer[j-1]==*sortpointer[j])goto err_out;
  }

  return(info);

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

static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
					vorbis_info_floor *in){
  int *sortpointer[VIF_POSIT+2];
  vorbis_info_floor1 *info=(vorbis_info_floor1 *)in;
  vorbis_look_floor1 *look=_ogg_calloc(1,sizeof(*look));
  int i,j,n=0;
  if (!look) return NULL;

  look->vi=info;
  look->n=info->postlist[1];

  /* we drop each position value in-between already decoded values,
     and use linear interpolation to predict each new value past the
     edges.  The positions are read in the order of the position
     list... we precompute the bounding positions in the lookup.  Of
     course, the neighbors can change (if a position is declined), but
     this is an initial mapping */

  for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  n+=2;
  look->posts=n;

  /* also store a sorted position index */
  for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  qsort(sortpointer,n,sizeof(*sortpointer),icomp);

  /* points from sort order back to range number */
  for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;

  /* quantize values to multiplier spec */
  switch(info->mult){
  case 1: /* 1024 -> 256 */
    look->quant_q=256;
    break;
  case 2: /* 1024 -> 128 */
    look->quant_q=128;
    break;
  case 3: /* 1024 -> 86 */
    look->quant_q=86;
    break;
  case 4: /* 1024 -> 64 */
    look->quant_q=64;
    break;
  }

  /* discover our neighbors for decode where we don't use fit flags
     (that would push the neighbors outward) */
  for(i=0;i<n-2;i++){
    int lo=0;
    int hi=1;
    int lx=0;
    int hx=look->n;
    int currentx=info->postlist[i+2];
    for(j=0;j<i+2;j++){
      int x=info->postlist[j];
      if(x>lx && x<currentx){
	lo=j;
	lx=x;
      }
      if(x<hx && x>currentx){
	hi=j;
	hx=x;
      }
    }
    look->loneighbor[i]=lo;
    look->hineighbor[i]=hi;
  }

  look->channels = vd->vi->channels;
  look->pfits = _ogg_malloc(look->channels*sizeof(*look->pfits));
  if (!look->pfits) goto err_out;
  memset(look->pfits,0,look->channels*sizeof(*look->pfits));
  for (j = 0; j < look->channels; j++)
  {
    look->pfits[j] = _ogg_malloc((look->posts)*sizeof(*look->pfits[0]));
    if (!look->pfits[j]) goto err_out;
  }

  return(look);

err_out:
  floor1_free_look(look);
  return NULL;
}

static int render_point(int x0,int x1,int y0,int y1,int x){
  y0&=0x7fff; /* mask off flag */
  y1&=0x7fff;

  {
    int dy=y1-y0;
    int adx=x1-x0;
    int ady=abs(dy);
    int err=ady*(x-x0);

    int off=err/adx;
    if(dy<0)return(y0-off);
    return(y0+off);
  }
}

#include "floor1_table.h"

static void render_line(int x0,int x1,int y0,int y1, xint* d){
	int dy = y1 - y0;
	int adx = x1 - x0;
	int ady = abs(dy);
	int base = dy/adx;
	int sy = (dy < 0 ? base-1:base+1);
	int err = 0;
	const fromdB_look* p;

	ady -= abs(base*adx);
	d += x0;

	p = FLOOR_fromdB_LOOKUP + y0;
	*d = LMULSHR(*d, p->val, p->shift + (BISHIFT - XISHIFT));
	while(++x0 < x1){
		err += ady;
		if(err >= adx){
			err -= adx;
			p += sy;
		}
		else{
			p += base;
		}
		d++;
		*d = LMULSHR(*d, p->val, p->shift + (BISHIFT - XISHIFT));
	}
}

static void* floor1_inverse1(vorbis_block* vb, vorbis_look_floor* in, int ch){
	vorbis_look_floor1* look = (vorbis_look_floor1*) in;
	vorbis_info_floor1* info = look->vi;
    codec_setup_info *ci=vb->vd->vi->codec_setup;

	int i,j,k;
	codebook* books = ci->fullbooks;

	/* unpack wrapped/predicted values from stream */
	if(oggpack_read(&vb->opb, 1) == 1){
		int32_t* fit_value = look->pfits[ch];

		fit_value[0] = oggpack_read(&vb->opb, ilog(look->quant_q-1));
		fit_value[1] = oggpack_read(&vb->opb, ilog(look->quant_q-1));

		/* partition by partition */
		for(i = 0, j = 2; i < info->partitions; i++){
			int class=info->partitionclass[i];
			int cdim=info->class_dim[class];
			int csubbits=info->class_subs[class];
			int csub=1<<csubbits;
			int cval=0;

			/* decode the partition's first stage cascade value */
			if(csubbits){
				cval = vorbis_book_decode(books+info->class_book[class], &vb->opb);

				if(cval == -1) goto eop;
			}

			for(k = 0; k < cdim; k++){
				int book = info->class_subbook[class][cval&(csub-1)];
				cval >>= csubbits;
				if(book >= 0){
					if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
						goto eop;
				}else{
					fit_value[j+k]=0;
				}
			}
			j += cdim;
		}

		/* unwrap positive values and reconsitute via linear interpolation */
		for(i = 2; i < look->posts; i++){
			int predicted = render_point(info->postlist[look->loneighbor[i-2]],
							info->postlist[look->hineighbor[i-2]],
							fit_value[look->loneighbor[i-2]],
							fit_value[look->hineighbor[i-2]],
							info->postlist[i]);
			int hiroom = look->quant_q - predicted;
			int loroom = predicted;
			int room = (hiroom < loroom ? hiroom:loroom)<<1;
			int val = fit_value[i];

			if(val){
				if(val >= room){
					if(hiroom > loroom){
						val = val-loroom;
					}else{
						val = -1-(val-hiroom);
					}
				}else{
					if(val & 1){
						val= -((val+1)>>1);
					}else{
						val>>=1;
					}
				}

				fit_value[i] = (val + predicted) & 0x7fff;
				fit_value[look->loneighbor[i-2]] &= 0x7fff;
				fit_value[look->hineighbor[i-2]] &= 0x7fff;
			}else{
				fit_value[i] = predicted|0x8000;
			}
		}

		return(fit_value);
	}
eop:
	return(NULL);
}

static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
			  xint* out){
  vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  vorbis_info_floor1 *info=look->vi;

  codec_setup_info   *ci=vb->vd->vi->codec_setup;
  int                  n=ci->blocksizes[vb->W]/2;
  int j;

  if(memo){
    /* render the lines */
    int *fit_value=(int *)memo;
    int hx=0;
    int lx=0;
    int ly=fit_value[0]*info->mult;
    /* guard lookup against out-of-range values */
    ly=(ly<0?0:ly>255?255:ly);

    for(j=1;j<look->posts;j++){
      int current=look->forward_index[j];
      int hy=fit_value[current]&0x7fff;
      if(hy==fit_value[current]){

	hx=info->postlist[current];
    hy*=info->mult;
    /* guard lookup against out-of-range values */
    hy=(hy<0?0:hy>255?255:hy);

	render_line(lx,hx,ly,hy,out);

	lx=hx;
	ly=hy;
      }
    }
    for(j=hx;j<n;j++)
    {
	/* be certain */
	const fromdB_look* p = FLOOR_fromdB_LOOKUP + ly;
	out[j] = LMULSHR(out[j], p->val, p->shift + (BISHIFT - XISHIFT));
    }

    return(1);
  }
  memset(out,0,sizeof(*out)*n);
  return(0);
}

/* export hooks */
const vorbis_func_floor floor1_exportbundle={
  &floor1_unpack,&floor1_look,&floor1_free_info,
  &floor1_free_look,&floor1_inverse1,&floor1_inverse2
};

