1 /********************************************************************
3 * THIS FILE IS PART OF THE Ogg Vorbis SOFTWARE CODEC SOURCE CODE. *
4 * USE, DISTRIBUTION AND REPRODUCTION OF THIS SOURCE IS GOVERNED BY *
5 * THE GNU PUBLIC LICENSE 2, WHICH IS INCLUDED WITH THIS SOURCE. *
6 * PLEASE READ THESE TERMS DISTRIBUTING. *
8 * THE OggSQUISH SOURCE CODE IS (C) COPYRIGHT 1994-2000 *
9 * by Monty <monty@xiph.org> and The XIPHOPHORUS Company *
10 * http://www.xiph.org/ *
12 ********************************************************************
14 function: basic shared codebook operations
15 last mod: $Id: sharedbook.c,v 1.9 2000/10/12 03:12:54 xiphmont Exp $
17 ********************************************************************/
24 #include "vorbis/codec.h"
25 #include "vorbis/codebook.h"
27 #include "sharedbook.h"
29 /**** pack/unpack helpers ******************************************/
30 int _ilog(unsigned int v){
39 /* 32 bit float (not IEEE; nonnormalized mantissa +
40 biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
41 Why not IEEE? It's just not that important here. */
45 #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
47 /* doesn't currently guard under/overflow */
48 long _float32_pack(float val){
56 exp= floor(log(val)/log(2));
57 mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
58 exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
60 return(sign|exp|mant);
63 float _float32_unpack(long val){
64 float mant=val&0x1fffff;
65 float sign=val&0x80000000;
66 float exp =(val&0x7fe00000)>>VQ_FMAN;
68 return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
71 /* given a list of word lengths, generate a list of codewords. Works
72 for length ordered or unordered, always assigns the lowest valued
73 codewords first. Extended to handle unused entries (length 0) */
74 long *_make_words(long *l,long n){
77 long *r=malloc(n*sizeof(long));
78 memset(marker,0,sizeof(marker));
83 long entry=marker[length];
85 /* when we claim a node for an entry, we also claim the nodes
86 below it (pruning off the imagined tree that may have dangled
87 from it) as well as blocking the use of any nodes directly
91 if(length<32 && (entry>>length)){
92 /* error condition; the lengths must specify an overpopulated tree */
98 /* Look to see if the next shorter marker points to the node
99 above. if so, update it and repeat. */
101 for(j=length;j>0;j--){
104 /* have to jump branches */
108 marker[j]=marker[j-1]<<1;
109 break; /* invariant says next upper marker would already
110 have been moved if it was on the same path */
116 /* prune the tree; the implicit invariant says all the longer
117 markers were dangling from our just-taken node. Dangle them
118 from our *new* node. */
119 for(j=length+1;j<33;j++)
120 if((marker[j]>>1) == entry){
122 marker[j]=marker[j-1]<<1;
128 /* bitreverse the words because our bitwise packer/unpacker is LSb
142 /* build the decode helper tree from the codewords */
143 decode_aux *_make_decode_tree(codebook *c){
144 const static_codebook *s=c->c;
146 decode_aux *t=malloc(sizeof(decode_aux));
147 long *ptr0=t->ptr0=calloc(c->entries*2,sizeof(long));
148 long *ptr1=t->ptr1=calloc(c->entries*2,sizeof(long));
149 long *codelist=_make_words(s->lengthlist,s->entries);
151 if(codelist==NULL)return(NULL);
154 for(i=0;i<c->entries;i++){
155 if(s->lengthlist[i]>0){
157 for(j=0;j<s->lengthlist[i]-1;j++){
158 int bit=(codelist[i]>>j)&1;
169 if(!((codelist[i]>>j)&1))
177 t->tabn = _ilog(c->entries)-4; /* this is magic */
178 if(t->tabn<5)t->tabn=5;
180 t->tab = malloc(n*sizeof(long));
181 t->tabl = malloc(n*sizeof(int));
182 for (i = 0; i < n; i++) {
184 for (j = 0; j < t->tabn && (p > 0 || j == 0); j++) {
190 /* now j == length, and p == -code */
198 /* there might be a straightforward one-line way to do the below
199 that's portable and totally safe against roundoff, but I haven't
200 thought of it. Therefore, we opt on the side of caution */
201 long _book_maptype1_quantvals(const static_codebook *b){
202 long vals=floor(pow(b->entries,1./b->dim));
204 /* the above *should* be reliable, but we'll not assume that FP is
205 ever reliable when bitstream sync is at stake; verify via integer
206 means that vals really is the greatest value of dim for which
207 vals^b->bim <= b->entries */
208 /* treat the above as an initial guess */
213 for(i=0;i<b->dim;i++){
217 if(acc<=b->entries && acc1>b->entries){
229 /* unpack the quantized list of values for encode/decode ***********/
230 /* we need to deal with two map types: in map type 1, the values are
231 generated algorithmically (each column of the vector counts through
232 the values in the quant vector). in map type 2, all the values came
233 in in an explicit list. Both value lists must be unpacked */
234 float *_book_unquantize(const static_codebook *b){
236 if(b->maptype==1 || b->maptype==2){
238 float mindel=_float32_unpack(b->q_min);
239 float delta=_float32_unpack(b->q_delta);
240 float *r=calloc(b->entries*b->dim,sizeof(float));
242 /* maptype 1 and 2 both use a quantized value vector, but
246 /* most of the time, entries%dimensions == 0, but we need to be
247 well defined. We define that the possible vales at each
248 scalar is values == entries/dim. If entries%dim != 0, we'll
249 have 'too few' values (values*dim<entries), which means that
250 we'll have 'left over' entries; left over entries use zeroed
251 values (and are wasted). So don't generate codebooks like
253 quantvals=_book_maptype1_quantvals(b);
254 for(j=0;j<b->entries;j++){
257 for(k=0;k<b->dim;k++){
258 int index= (j/indexdiv)%quantvals;
259 float val=b->quantlist[index];
260 val=fabs(val)*delta+mindel+last;
261 if(b->q_sequencep)last=val;
268 for(j=0;j<b->entries;j++){
270 for(k=0;k<b->dim;k++){
271 float val=b->quantlist[j*b->dim+k];
272 val=fabs(val)*delta+mindel+last;
273 if(b->q_sequencep)last=val;
283 void vorbis_staticbook_clear(static_codebook *b){
284 if(b->quantlist)free(b->quantlist);
285 if(b->lengthlist)free(b->lengthlist);
287 free(b->nearest_tree->ptr0);
288 free(b->nearest_tree->ptr1);
289 free(b->nearest_tree->p);
290 free(b->nearest_tree->q);
291 memset(b->nearest_tree,0,sizeof(encode_aux_nearestmatch));
292 free(b->nearest_tree);
295 free(b->thresh_tree->quantthresh);
296 free(b->thresh_tree->quantmap);
297 memset(b->thresh_tree,0,sizeof(encode_aux_threshmatch));
298 free(b->thresh_tree);
300 memset(b,0,sizeof(static_codebook));
303 void vorbis_book_clear(codebook *b){
304 /* static book is not cleared; we're likely called on the lookup and
305 the static codebook belongs to the info struct */
307 free(b->decode_tree->ptr0);
308 free(b->decode_tree->ptr1);
309 memset(b->decode_tree,0,sizeof(decode_aux));
310 free(b->decode_tree);
312 if(b->valuelist)free(b->valuelist);
313 if(b->codelist)free(b->codelist);
314 memset(b,0,sizeof(codebook));
317 int vorbis_book_init_encode(codebook *c,const static_codebook *s){
318 memset(c,0,sizeof(codebook));
320 c->entries=s->entries;
322 c->codelist=_make_words(s->lengthlist,s->entries);
323 c->valuelist=_book_unquantize(s);
327 int vorbis_book_init_decode(codebook *c,const static_codebook *s){
328 memset(c,0,sizeof(codebook));
330 c->entries=s->entries;
332 c->valuelist=_book_unquantize(s);
333 c->decode_tree=_make_decode_tree(c);
334 if(c->decode_tree==NULL)goto err_out;
337 vorbis_book_clear(c);
341 static float _dist(int el,float *ref, float *b,int step){
345 float val=(ref[i]-b[i*step]);
352 int _best(codebook *book, float *a, int step){
353 encode_aux_nearestmatch *nt=book->c->nearest_tree;
354 encode_aux_threshmatch *tt=book->c->thresh_tree;
355 encode_aux_pigeonhole *pt=book->c->pigeon_tree;
361 /* do we have a threshhold encode hint? */
364 /* find the quant val of each scalar */
365 for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
367 /* linear search the quant list for now; it's small and although
368 with > 8 entries, it would be faster to bisect, this would be
369 a misplaced optimization for now */
370 for(i=0;i<tt->threshvals-1;i++)
371 if(a[o]<tt->quantthresh[i])break;
373 index=(index*tt->quantvals)+tt->quantmap[i];
375 /* regular lattices are easy :-) */
376 if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
377 use a decision tree after all
382 /* do we have a pigeonhole encode hint? */
384 const static_codebook *c=book->c;
389 /* dealing with sequentialness is a pain in the ass */
394 for(k=0,o=0;k<dim;k++,o+=step){
395 pv=(int)((a[o]-qlast-pt->min)/pt->del);
396 if(pv<0 || pv>=pt->mapentries)break;
397 entry+=pt->pigeonmap[pv]*mul;
399 qlast+=pv*pt->del+pt->min;
402 for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
403 int pv=(int)((a[o]-pt->min)/pt->del);
404 if(pv<0 || pv>=pt->mapentries)break;
405 entry=entry*pt->quantvals+pt->pigeonmap[pv];
409 /* must be within the pigeonholable range; if we quant outside (or
410 in an entry that we define no list for), brute force it */
411 if(k==dim && pt->fitlength[entry]){
412 /* search the abbreviated list */
413 long *list=pt->fitlist+pt->fitmap[entry];
414 for(i=0;i<pt->fitlength[entry];i++){
415 float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
416 if(besti==-1 || this<best){
427 /* optimized using the decision tree */
430 float *p=book->valuelist+nt->p[ptr];
431 float *q=book->valuelist+nt->q[ptr];
433 for(k=0,o=0;k<dim;k++,o+=step)
434 c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
445 /* brute force it! */
447 const static_codebook *c=book->c;
450 float *e=book->valuelist;
451 for(i=0;i<book->entries;i++){
452 if(c->lengthlist[i]>0){
453 float this=_dist(dim,e,a,step);
454 if(besti==-1 || this<best){
462 /*if(savebest!=-1 && savebest!=besti){
463 fprintf(stderr,"brute force/pigeonhole disagreement:\n"
465 for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
467 "pigeonhole (entry %d, err %g):",savebest,saverr);
468 for(i=0;i<dim;i++)fprintf(stderr,"%g,",
469 (book->valuelist+savebest*dim)[i]);
471 "bruteforce (entry %d, err %g):",besti,best);
472 for(i=0;i<dim;i++)fprintf(stderr,"%g,",
473 (book->valuelist+besti*dim)[i]);
474 fprintf(stderr,"\n");
480 /* returns the entry number and *modifies a* to the remainder value ********/
481 int vorbis_book_besterror(codebook *book,float *a,int step,int addmul){
482 int dim=book->dim,i,o;
483 int best=_best(book,a,step);
486 for(i=0,o=0;i<dim;i++,o+=step)
487 a[o]-=(book->valuelist+best*dim)[i];
490 for(i=0,o=0;i<dim;i++,o+=step){
491 float val=(book->valuelist+best*dim)[i];
503 long vorbis_book_codeword(codebook *book,int entry){
504 return book->codelist[entry];
507 long vorbis_book_codelen(codebook *book,int entry){
508 return book->c->lengthlist[entry];
513 /* Unit tests of the dequantizer; this stuff will be OK
514 cross-platform, I simply want to be sure that special mapping cases
515 actually work properly; a bug could go unnoticed for a while */
522 full, explicit mapping
529 static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
530 static long partial_quantlist1[]={0,7,2};
533 static_codebook test1={
541 static float *test1_result=NULL;
543 /* linear, full mapping, nonsequential */
544 static_codebook test2={
548 -533200896,1611661312,4,0,
552 static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
554 /* linear, full mapping, sequential */
555 static_codebook test3={
559 -533200896,1611661312,4,1,
563 static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
565 /* linear, algorithmic mapping, nonsequential */
566 static_codebook test4={
570 -533200896,1611661312,4,0,
574 static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
575 -3, 4,-3, 4, 4,-3, -1, 4,-3,
576 -3,-1,-3, 4,-1,-3, -1,-1,-3,
577 -3,-3, 4, 4,-3, 4, -1,-3, 4,
578 -3, 4, 4, 4, 4, 4, -1, 4, 4,
579 -3,-1, 4, 4,-1, 4, -1,-1, 4,
580 -3,-3,-1, 4,-3,-1, -1,-3,-1,
581 -3, 4,-1, 4, 4,-1, -1, 4,-1,
582 -3,-1,-1, 4,-1,-1, -1,-1,-1};
584 /* linear, algorithmic mapping, sequential */
585 static_codebook test5={
589 -533200896,1611661312,4,1,
593 static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
594 -3, 1,-2, 4, 8, 5, -1, 3, 0,
595 -3,-4,-7, 4, 3, 0, -1,-2,-5,
596 -3,-6,-2, 4, 1, 5, -1,-4, 0,
597 -3, 1, 5, 4, 8,12, -1, 3, 7,
598 -3,-4, 0, 4, 3, 7, -1,-2, 2,
599 -3,-6,-7, 4, 1, 0, -1,-4,-5,
600 -3, 1, 0, 4, 8, 7, -1, 3, 2,
601 -3,-4,-5, 4, 3, 2, -1,-2,-3};
603 void run_test(static_codebook *b,float *comp){
604 float *out=_book_unquantize(b);
609 fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
613 for(i=0;i<b->entries*b->dim;i++)
614 if(fabs(out[i]-comp[i])>.0001){
615 fprintf(stderr,"disagreement in unquantized and reference data:\n"
616 "position %d, %g != %g\n",i,out[i],comp[i]);
622 fprintf(stderr,"_book_unquantize returned a value array: \n"
623 " correct result should have been NULL\n");
630 /* run the nine dequant tests, and compare to the hand-rolled results */
631 fprintf(stderr,"Dequant test 1... ");
632 run_test(&test1,test1_result);
633 fprintf(stderr,"OK\nDequant test 2... ");
634 run_test(&test2,test2_result);
635 fprintf(stderr,"OK\nDequant test 3... ");
636 run_test(&test3,test3_result);
637 fprintf(stderr,"OK\nDequant test 4... ");
638 run_test(&test4,test4_result);
639 fprintf(stderr,"OK\nDequant test 5... ");
640 run_test(&test5,test5_result);
641 fprintf(stderr,"OK\n\n");