/********************************************************************
 *                                                                  *
 * 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-2015             *
 * by the Xiph.Org Foundation http://www.xiph.org/                  *
 *                                                                  *
 ********************************************************************

 function: basic shared codebook operations
 last mod: $Id: sharedbook.c 19457 2015-03-03 00:15:29Z giles $

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

#ifdef MAKEABS
#include <stdio.h>
#endif
#include <stdlib.h>
#include <string.h>
#include "os.h"
#include "codebook.h"
#include "codec.h"
#include "Log.h"

/**** pack/unpack helpers ******************************************/
int32_t ilog(uint32_t v){
	int32_t ret = 0;

	while(v){
		ret++;
		v >>= 1;
	}

	return(ret);
}

/* 32 bit float (not IEEE; nonnormalized mantissa +
   biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
   Why not IEEE?  It's just not that important here. */

#define VQ_FMAN 21
#define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */

static bint _mindel_unpack(int32_t val){
	int32_t mant, exp;
	mant = val &  0x001fffff;
	exp  = (val & 0x7fe00000) >> VQ_FMAN;

	exp += BISHIFT - (VQ_FMAN-1) - VQ_FEXP_BIAS;
#ifdef MAKEABS
	if ((exp + ilog(mant)) > 31)
		printf("mindel, big exp %d %x %d\n", exp, mant, ilog(mant));
#endif

	if(val & 0x80000000) mant = -mant;

	if (exp < 0)
		return mant >> (-exp);
	else
		return mant << exp;
}

static void _float32_unpack(int32_t val, int32_t* mant, int32_t* exp)
{
	*mant = val &  0x001fffff;
	*exp  = (val & 0x7fe00000) >> VQ_FMAN;

	// +32 below because it will be used by LMULSH(val, mant, exp)
	*exp += 32 + BISHIFT - (VQ_FMAN-1) - VQ_FEXP_BIAS;
#ifdef MAKEABS
	// for LMULSH ilog(val*mant)+exp must fit in 64 bits,  and ilog(val) <= 17
	// so
	if ((*exp + ilog(*mant)) > 63)
		printf("big exp %d %x %d\n", *exp, *mant, ilog(*mant));
#endif

	if(val & 0x80000000) *mant = -*mant;

	*exp = -*exp;
}

/* given a list of word lengths, generate a list of codewords.  Works
   for length ordered or unordered, always assigns the lowest valued
   codewords first.  Extended to handle unused entries (length 0) */
static uint32_t *_make_words(const uint8_t *l,int32_t n, int32_t sparsecount){
	int32_t i,j, count=0;
	uint32_t marker[33];
	uint32_t *r=_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
	if (!r) return NULL;
	memset(marker,0,sizeof(marker));

	for(i=0;i<n;i++){
		int32_t length=l[i];
		if(length>0){
			uint32_t entry=marker[length];

			/* when we claim a node for an entry, we also claim the nodes
			   below it (pruning off the imagined tree that may have dangled
			   from it) as well as blocking the use of any nodes directly
			   above for leaves */

			/* update ourself */
			if(length<32 && (entry>>length)){
				/* error condition; the lengths must specify an overpopulated tree */
				_ogg_free(r);
				return(NULL);
			}
			r[count++]=entry;

			/* Look to see if the next shorter marker points to the node
			   above. if so, update it and repeat.  */
			{
				for(j=length;j>0;j--){

					if(marker[j]&1){
						/* have to jump branches */
						if(j==1)
							marker[1]++;
						else
							marker[j]=marker[j-1]<<1;
						break; /* invariant says next upper marker would already
								  have been moved if it was on the same path */
					}
					marker[j]++;
				}
			}

			/* prune the tree; the implicit invariant says all the longer
			   markers were dangling from our just-taken node.  Dangle them
			   from our *new* node. */
			for(j=length+1;j<33;j++)
				if((marker[j]>>1) == entry){
					entry=marker[j];
					marker[j]=marker[j-1]<<1;
				}else
					break;
		}else
			if(sparsecount==0)count++;
	}

	/* any underpopulated tree must be rejected. */
	/* Single-entry codebooks are a retconned extension to the spec.
	   They have a single codeword '0' of length 1 that results in an
	   underpopulated tree.  Shield that case from the underformed tree check. */
	if(!(count==1 && marker[2]==2)){
		for(i=1;i<33;i++)
			if(marker[i] & (0xffffffffU>>(32-i))){
				_ogg_free(r);
				return(NULL);
			}
	}

  /* bitreverse the words because our bitwise packer/unpacker is LSb
     endian */
  for(i=0,count=0;i<n;i++){
    uint32_t temp=0;
    for(j=0;j<l[i];j++){
      temp<<=1;
      temp|=(r[count]>>j)&1;
    }

    if(sparsecount){
      if(l[i])
	r[count++]=temp;
    }else
      r[count++]=temp;
  }

  return(r);
}

/* there might be a straightforward one-line way to do the below
   that's portable and totally safe against roundoff, but I haven't
   thought of it.  Therefore, we opt on the side of caution */
int32_t _book_maptype1_quantvals(const static_codebook *b){
  /* get us a starting hint, we'll polish it below */
  int32_t bits=ilog(b->entries);
  int32_t vals=b->entries>>((bits-1)*(b->dim-1)/b->dim);

  while(1){
    int32_t acc=1;
    int32_t acc1=1;
    int i;
    for(i=0;i<b->dim;i++){
      acc*=vals;
      acc1*=vals+1;
    }
    if(acc<=b->entries && acc1>b->entries){
      return(vals);
    }else{
      if(acc>b->entries){
	vals--;
      }else{
	vals++;
      }
    }
  }
}

/* unpack the quantized list of values for encode/decode ***********/
/* we need to deal with two map types: in map type 1, the values are
   generated algorithmically (each column of the vector counts through
   the values in the quant vector). in map type 2, all the values came
   in in an explicit list.  Both value lists must be unpacked */
static bint* _book_unquantize(const static_codebook* b,int n,const int *sparsemap){
	int32_t j,k,count=0;

	if(b->maptype==1 || b->maptype==2){
		int quantvals;
		bint mindel;
		int32_t dmant, dexp;
		bint* r = _ogg_calloc(n*b->dim,sizeof(*r));

		if (!r) return NULL;

		mindel = _mindel_unpack(b->q_min);
		_float32_unpack(b->q_delta, &dmant, &dexp);

		/* maptype 1 and 2 both use a quantized value vector, but
		   different sizes */
		switch(b->maptype){
			case 1:
			{
	/* most of the time, entries%dimensions == 0, but we need to be
	 well defined.  We define that the possible vales at each
	 scalar is values == entries/dim.  If entries%dim != 0, we'll
	 have 'too few' values (values*dim<entries), which means that
	 we'll have 'left over' entries; left over entries use zeroed
	 values (and are wasted).  So don't generate codebooks like
	 that */
				quantvals = _book_maptype1_quantvals(b);
				for(j = 0; j < b->entries; j++){
					if((sparsemap && b->lengthlist[j]) || !sparsemap){
						bint last = BIZERO;
						int indexdiv = 1;
						bint* rp;
						if (sparsemap)
							rp = &r[sparsemap[count]*b->dim];
						else
							rp = &r[count*b->dim];

						for(k = 0; k < b->dim; k++){
							int index = (j/indexdiv)%quantvals;
							int32_t val = b->quantlist[index];

							if (val < 0) val = -val;

#ifdef MAKEABS
	// for LMULSH ilog(val*mant)+exp must fit in 64 bits
	// so
	if ((dexp + ilog(abs(dmant)) + ilog(val)) > 63)
		printf("big val %d %x %x\n", dexp, abs(dmant), val);
#endif

							val = LMULSH(val, dmant, dexp);
							val += mindel + last;
							if(b->q_sequencep)last=val;
							*rp++=val;
							indexdiv*=quantvals;
						}
						count++;
					}
				}
			}
			break;
			case 2:
			{
				for(j = 0; j < b->entries; j++){
					if((sparsemap && b->lengthlist[j]) || !sparsemap){
						bint last = BIZERO;
						bint* rp;
						if (sparsemap)
							rp = &r[sparsemap[count]*b->dim];
						else
							rp = &r[count*b->dim];

						for(k = 0; k < b->dim; k++){
							int32_t val = b->quantlist[j*b->dim+k];

							if (val < 0) val = -val;

#ifdef MAKEABS
	// for LMULSH ilog(val*mant)+exp must fit in 64 bits
	// so
	if ((dexp + ilog(abs(dmant)) + ilog(val)) > 63)
		printf("big val %d %x %x\n", dexp, abs(dmant), val);
#endif

							val = LMULSH(val, dmant, dexp);
							val += mindel + last;
							if(b->q_sequencep)last=val;
							*rp++=val;
						}
						count++;
					}
				}
			}
			break;
		}

		return(r);
	}

	return(NULL);
}

void vorbis_staticbook_destroy(static_codebook *b){
  if(b->quantlist)_ogg_free(b->quantlist);
  if(b->lengthlist)_ogg_free(b->lengthlist);
  _ogg_free(b);
}

void vorbis_book_clear(codebook *b){
  /* static book is not cleared; we're likely called on the lookup and
     the static codebook belongs to the info struct */
  if(b->valuelist)_ogg_free(b->valuelist);
  if(b->codelist)_ogg_free(b->codelist);

  if(b->dec_index)_ogg_free(b->dec_index);
  if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  if(b->dec_firsttable)_ogg_free(b->dec_firsttable);

  memset(b,0,sizeof(*b));
}

static uint32_t bitreverse(uint32_t x){
  x=    ((x>>16)&0x0000ffffU) | ((x<<16)&0xffff0000U);
  x=    ((x>> 8)&0x00ff00ffU) | ((x<< 8)&0xff00ff00U);
  x=    ((x>> 4)&0x0f0f0f0fU) | ((x<< 4)&0xf0f0f0f0U);
  x=    ((x>> 2)&0x33333333U) | ((x<< 2)&0xccccccccU);
  return((x>> 1)&0x55555555U) | ((x<< 1)&0xaaaaaaaaU);
}

static int sort32a(const void *a,const void *b){
  return (**(uint32_t**)a>**(uint32_t**)b)-
  		(**(uint32_t**)a<**(uint32_t**)b);
}

/* decode codebook arrangement is more heavily optimized than encode */
int vorbis_book_init_decode(codebook *c,const static_codebook *s){
	int i,j,n=0,tabn;
	int *sortindex = NULL;
	memset(c,0,sizeof(*c));

	/* count actually used entries and find max length */
	for(i=0;i<s->entries;i++)
		if(s->lengthlist[i]>0)
			n++;

	c->entries=s->entries;
	c->used_entries=n;
	c->dim=s->dim;

	if (n>0){

		/* two different remappings go on here.

		   First, we collapse the likely sparse codebook down only to
		   actually represented values/words.  This collapsing needs to be
		   indexed as map-valueless books are used to encode original entry
		   positions as integers.

		   Second, we reorder all vectors, including the entry index above,
		   by sorted bitreversed codeword to allow treeless decode. */

		/* perform sort */
	    uint32_t*  codes=_make_words(s->lengthlist,s->entries,c->used_entries);
    	uint32_t** codep=_ogg_malloc(sizeof(*codep)*n);
	    sortindex=_ogg_malloc(n*sizeof(*sortindex));
    	c->codelist=_ogg_malloc(n*sizeof(*c->codelist));
	    c->dec_index=_ogg_malloc(n*sizeof(*c->dec_index));
    	c->dec_codelengths=_ogg_malloc(n*sizeof(*c->dec_codelengths));

	    if ((codes==NULL)
    	||  (codep==NULL)
	    ||  (sortindex==NULL)
    	||  (c->codelist==NULL)
	    ||  (c->dec_index==NULL)
    	||  (c->dec_codelengths==NULL))
	    {
    		if(codes)_ogg_free(codes);
    		if(codep)_ogg_free(codep);
	    	goto err_mem_out;
    	}

		for(i=0;i<n;i++){
			codes[i]=bitreverse(codes[i]);
			codep[i]=codes+i;
		}

		qsort(codep,n,sizeof(*codep),sort32a);

		/* the index is a reverse index */
		for(i=0;i<n;i++){
			int position=codep[i]-codes;
			sortindex[position]=i;
		}

		for(i=0;i<n;i++)
			c->codelist[sortindex[i]]=codes[i];

		_ogg_free(codes);
		_ogg_free(codep);

		c->valuelist=_book_unquantize(s,n,sortindex);
		//if (c->valuelist==NULL)goto err_out;

	    c->dec_maxlength=0;
		for(n=0,i=0;i<s->entries;i++)
			if(s->lengthlist[i]>0){
				int si = sortindex[n++];
				c->dec_index[si]=i;
				c->dec_codelengths[si]=s->lengthlist[i];
				if(s->lengthlist[i]>c->dec_maxlength)
					c->dec_maxlength=s->lengthlist[i];
			}

		if(n==1 && c->dec_maxlength==1){
			/* special case the 'single entry codebook' with a single bit
			   fastpath table (that always returns entry 0 )in order to use
			   unmodified decode paths. */
			c->dec_firsttablen=1;
			c->dec_firsttable=_ogg_calloc(2,sizeof(*c->dec_firsttable));
			if(c->dec_firsttable==NULL)goto err_mem_out;
			c->dec_firsttable[0]=c->dec_firsttable[1]=1;
		}else{
			c->dec_firsttablen=ilog(c->used_entries)-4; /* this is magic */
			if(c->dec_firsttablen<5)c->dec_firsttablen=5;
			if(c->dec_firsttablen>8)c->dec_firsttablen=8;

			tabn=1<<c->dec_firsttablen;
			c->dec_firsttable=_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
			if(c->dec_firsttable==NULL)goto err_mem_out;

			for(i=0;i<n;i++){
				if(c->dec_codelengths[i]<=c->dec_firsttablen){
					uint32_t orig=bitreverse(c->codelist[i]);
					for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
						c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
				}
			}

			/* now fill in 'unused' entries in the firsttable with hi/lo search
			   hints for the non-direct-hits */
			{
				uint32_t mask=0xfffffffeU<<(31-c->dec_firsttablen);
				int32_t lo=0,hi=0;

				for(i=0;i<tabn;i++){
					uint32_t word=i<<(32-c->dec_firsttablen);
					if(c->dec_firsttable[bitreverse(word)]==0){
						while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
						while(    hi<n && word>=(c->codelist[hi]&mask))hi++;

						/* we only actually have 15 bits per hint to play with here.
						   In order to overflow gracefully (nothing breaks, efficiency
						   just drops), encode as the difference from the extremes. */
						{
							uint32_t loval=lo;
							uint32_t hival=n-hi;

							if(loval>0x7fff)loval=0x7fff;
							if(hival>0x7fff)hival=0x7fff;
							c->dec_firsttable[bitreverse(word)]=
							   0x80000000U | (loval<<15) | hival;
						}
					}
				}
			}
		}
	}

	if(sortindex)_ogg_free(sortindex);

	return(0);
err_mem_out:
	if(sortindex)_ogg_free(sortindex);
	vorbis_book_clear(c);
    return OV_EMEMORY;
}
