sharedbook.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. /********************************************************************
  2. * *
  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. *
  7. * *
  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/ *
  11. * *
  12. ********************************************************************
  13. function: basic shared codebook operations
  14. last mod: $Id: sharedbook.c,v 1.7.4.3.2.1 2000/09/03 08:34:52 jack Exp $
  15. ********************************************************************/
  16. #include <stdlib.h>
  17. #include <math.h>
  18. #include <string.h>
  19. #include <ogg/ogg.h>
  20. #include "os.h"
  21. #include "vorbis/codec.h"
  22. #include "vorbis/codebook.h"
  23. #include "scales.h"
  24. #include "sharedbook.h"
  25. /**** pack/unpack helpers ******************************************/
  26. int _ilog(unsigned int v){
  27. int ret=0;
  28. while(v){
  29. ret++;
  30. v>>=1;
  31. }
  32. return(ret);
  33. }
  34. /* 32 bit float (not IEEE; nonnormalized mantissa +
  35. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  36. Why not IEEE? It's just not that important here. */
  37. #define VQ_FEXP 10
  38. #define VQ_FMAN 21
  39. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  40. /* doesn't currently guard under/overflow */
  41. long _float32_pack(float val){
  42. int sign=0;
  43. long exp;
  44. long mant;
  45. if(val<0){
  46. sign=0x80000000;
  47. val= -val;
  48. }
  49. exp= floor(log(val)/log(2));
  50. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  51. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  52. return(sign|exp|mant);
  53. }
  54. float _float32_unpack(long val){
  55. float mant=val&0x1fffff;
  56. float sign=val&0x80000000;
  57. float exp =(val&0x7fe00000)>>VQ_FMAN;
  58. if(sign)mant= -mant;
  59. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  60. }
  61. /* given a list of word lengths, generate a list of codewords. Works
  62. for length ordered or unordered, always assigns the lowest valued
  63. codewords first. Extended to handle unused entries (length 0) */
  64. long *_make_words(long *l,long n){
  65. long i,j;
  66. long marker[33];
  67. long *r=malloc(n*sizeof(long));
  68. memset(marker,0,sizeof(marker));
  69. for(i=0;i<n;i++){
  70. long length=l[i];
  71. if(length>0){
  72. long entry=marker[length];
  73. /* when we claim a node for an entry, we also claim the nodes
  74. below it (pruning off the imagined tree that may have dangled
  75. from it) as well as blocking the use of any nodes directly
  76. above for leaves */
  77. /* update ourself */
  78. if(length<32 && (entry>>length)){
  79. /* error condition; the lengths must specify an overpopulated tree */
  80. free(r);
  81. return(NULL);
  82. }
  83. r[i]=entry;
  84. /* Look to see if the next shorter marker points to the node
  85. above. if so, update it and repeat. */
  86. {
  87. for(j=length;j>0;j--){
  88. if(marker[j]&1){
  89. /* have to jump branches */
  90. if(j==1)
  91. marker[1]++;
  92. else
  93. marker[j]=marker[j-1]<<1;
  94. break; /* invariant says next upper marker would already
  95. have been moved if it was on the same path */
  96. }
  97. marker[j]++;
  98. }
  99. }
  100. /* prune the tree; the implicit invariant says all the longer
  101. markers were dangling from our just-taken node. Dangle them
  102. from our *new* node. */
  103. for(j=length+1;j<33;j++)
  104. if((marker[j]>>1) == entry){
  105. entry=marker[j];
  106. marker[j]=marker[j-1]<<1;
  107. }else
  108. break;
  109. }
  110. }
  111. /* bitreverse the words because our bitwise packer/unpacker is LSb
  112. endian */
  113. for(i=0;i<n;i++){
  114. long temp=0;
  115. for(j=0;j<l[i];j++){
  116. temp<<=1;
  117. temp|=(r[i]>>j)&1;
  118. }
  119. r[i]=temp;
  120. }
  121. return(r);
  122. }
  123. /* build the decode helper tree from the codewords */
  124. decode_aux *_make_decode_tree(codebook *c){
  125. const static_codebook *s=c->c;
  126. long top=0,i,j,n;
  127. decode_aux *t=malloc(sizeof(decode_aux));
  128. long *ptr0=t->ptr0=calloc(c->entries*2,sizeof(long));
  129. long *ptr1=t->ptr1=calloc(c->entries*2,sizeof(long));
  130. long *codelist=_make_words(s->lengthlist,s->entries);
  131. if(codelist==NULL)return(NULL);
  132. t->aux=c->entries*2;
  133. for(i=0;i<c->entries;i++){
  134. if(s->lengthlist[i]>0){
  135. long ptr=0;
  136. for(j=0;j<s->lengthlist[i]-1;j++){
  137. int bit=(codelist[i]>>j)&1;
  138. if(!bit){
  139. if(!ptr0[ptr])
  140. ptr0[ptr]= ++top;
  141. ptr=ptr0[ptr];
  142. }else{
  143. if(!ptr1[ptr])
  144. ptr1[ptr]= ++top;
  145. ptr=ptr1[ptr];
  146. }
  147. }
  148. if(!((codelist[i]>>j)&1))
  149. ptr0[ptr]=-i;
  150. else
  151. ptr1[ptr]=-i;
  152. }
  153. }
  154. free(codelist);
  155. t->tabn = _ilog(c->entries)-4; /* this is magic */
  156. if(t->tabn<5)t->tabn=5;
  157. n = 1<<t->tabn;
  158. t->tab = malloc(n*sizeof(long));
  159. t->tabl = malloc(n*sizeof(int));
  160. for (i = 0; i < n; i++) {
  161. long p = 0;
  162. for (j = 0; j < t->tabn && (p > 0 || j == 0); j++) {
  163. if (i & (1 << j))
  164. p = ptr1[p];
  165. else
  166. p = ptr0[p];
  167. }
  168. /* now j == length, and p == -code */
  169. t->tab[i] = p;
  170. t->tabl[i] = j;
  171. }
  172. return(t);
  173. }
  174. /* there might be a straightforward one-line way to do the below
  175. that's portable and totally safe against roundoff, but I haven't
  176. thought of it. Therefore, we opt on the side of caution */
  177. long _book_maptype1_quantvals(const static_codebook *b){
  178. long vals=floor(pow(b->entries,1./b->dim));
  179. /* the above *should* be reliable, but we'll not assume that FP is
  180. ever reliable when bitstream sync is at stake; verify via integer
  181. means that vals really is the greatest value of dim for which
  182. vals^b->bim <= b->entries */
  183. /* treat the above as an initial guess */
  184. while(1){
  185. long acc=1;
  186. long acc1=1;
  187. int i;
  188. for(i=0;i<b->dim;i++){
  189. acc*=vals;
  190. acc1*=vals+1;
  191. }
  192. if(acc<=b->entries && acc1>b->entries){
  193. return(vals);
  194. }else{
  195. if(acc>b->entries){
  196. vals--;
  197. }else{
  198. vals++;
  199. }
  200. }
  201. }
  202. }
  203. /* unpack the quantized list of values for encode/decode ***********/
  204. /* we need to deal with two map types: in map type 1, the values are
  205. generated algorithmically (each column of the vector counts through
  206. the values in the quant vector). in map type 2, all the values came
  207. in in an explicit list. Both value lists must be unpacked */
  208. float *_book_unquantize(const static_codebook *b){
  209. long j,k;
  210. if(b->maptype==1 || b->maptype==2){
  211. int quantvals;
  212. float mindel=_float32_unpack(b->q_min);
  213. float delta=_float32_unpack(b->q_delta);
  214. float *r=calloc(b->entries*b->dim,sizeof(float));
  215. /* maptype 1 and 2 both use a quantized value vector, but
  216. different sizes */
  217. switch(b->maptype){
  218. case 1:
  219. /* most of the time, entries%dimensions == 0, but we need to be
  220. well defined. We define that the possible vales at each
  221. scalar is values == entries/dim. If entries%dim != 0, we'll
  222. have 'too few' values (values*dim<entries), which means that
  223. we'll have 'left over' entries; left over entries use zeroed
  224. values (and are wasted). So don't generate codebooks like
  225. that */
  226. quantvals=_book_maptype1_quantvals(b);
  227. for(j=0;j<b->entries;j++){
  228. float last=0.;
  229. int indexdiv=1;
  230. for(k=0;k<b->dim;k++){
  231. int index= (j/indexdiv)%quantvals;
  232. float val=b->quantlist[index];
  233. val=fabs(val)*delta+mindel+last;
  234. if(b->q_sequencep)last=val;
  235. r[j*b->dim+k]=val;
  236. indexdiv*=quantvals;
  237. }
  238. }
  239. break;
  240. case 2:
  241. for(j=0;j<b->entries;j++){
  242. float last=0.;
  243. for(k=0;k<b->dim;k++){
  244. float val=b->quantlist[j*b->dim+k];
  245. val=fabs(val)*delta+mindel+last;
  246. if(b->q_sequencep)last=val;
  247. r[j*b->dim+k]=val;
  248. }
  249. }
  250. }
  251. return(r);
  252. }
  253. return(NULL);
  254. }
  255. void vorbis_staticbook_clear(static_codebook *b){
  256. if(b->quantlist)free(b->quantlist);
  257. if(b->lengthlist)free(b->lengthlist);
  258. if(b->nearest_tree){
  259. free(b->nearest_tree->ptr0);
  260. free(b->nearest_tree->ptr1);
  261. free(b->nearest_tree->p);
  262. free(b->nearest_tree->q);
  263. memset(b->nearest_tree,0,sizeof(encode_aux_nearestmatch));
  264. free(b->nearest_tree);
  265. }
  266. if(b->thresh_tree){
  267. free(b->thresh_tree->quantthresh);
  268. free(b->thresh_tree->quantmap);
  269. memset(b->thresh_tree,0,sizeof(encode_aux_threshmatch));
  270. free(b->thresh_tree);
  271. }
  272. memset(b,0,sizeof(static_codebook));
  273. }
  274. void vorbis_book_clear(codebook *b){
  275. /* static book is not cleared; we're likely called on the lookup and
  276. the static codebook belongs to the info struct */
  277. if(b->decode_tree){
  278. free(b->decode_tree->ptr0);
  279. free(b->decode_tree->ptr1);
  280. memset(b->decode_tree,0,sizeof(decode_aux));
  281. free(b->decode_tree);
  282. }
  283. if(b->valuelist)free(b->valuelist);
  284. if(b->codelist)free(b->codelist);
  285. memset(b,0,sizeof(codebook));
  286. }
  287. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  288. memset(c,0,sizeof(codebook));
  289. c->c=s;
  290. c->entries=s->entries;
  291. c->dim=s->dim;
  292. c->codelist=_make_words(s->lengthlist,s->entries);
  293. c->valuelist=_book_unquantize(s);
  294. return(0);
  295. }
  296. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  297. memset(c,0,sizeof(codebook));
  298. c->c=s;
  299. c->entries=s->entries;
  300. c->dim=s->dim;
  301. c->valuelist=_book_unquantize(s);
  302. c->decode_tree=_make_decode_tree(c);
  303. if(c->decode_tree==NULL)goto err_out;
  304. return(0);
  305. err_out:
  306. vorbis_book_clear(c);
  307. return(-1);
  308. }
  309. static float _dist(int el,float *ref, float *b,int step){
  310. int i;
  311. float acc=0.;
  312. for(i=0;i<el;i++){
  313. float val=(ref[i]-b[i*step]);
  314. acc+=val*val;
  315. }
  316. return(acc);
  317. }
  318. #include <stdio.h>
  319. int _best(codebook *book, float *a, int step){
  320. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  321. encode_aux_threshmatch *tt=book->c->thresh_tree;
  322. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  323. int dim=book->dim;
  324. int ptr=0,k,o;
  325. /*int savebest=-1;
  326. float saverr;*/
  327. /* do we have a threshhold encode hint? */
  328. if(tt){
  329. int index=0;
  330. /* find the quant val of each scalar */
  331. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  332. int i;
  333. /* linear search the quant list for now; it's small and although
  334. with > 8 entries, it would be faster to bisect, this would be
  335. a misplaced optimization for now */
  336. for(i=0;i<tt->threshvals-1;i++)
  337. if(a[o]<tt->quantthresh[i])break;
  338. index=(index*tt->quantvals)+tt->quantmap[i];
  339. }
  340. /* regular lattices are easy :-) */
  341. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  342. use a decision tree after all
  343. and fall through*/
  344. return(index);
  345. }
  346. /* do we have a pigeonhole encode hint? */
  347. if(pt){
  348. const static_codebook *c=book->c;
  349. int i,besti=-1;
  350. float best;
  351. int entry=0;
  352. /* dealing with sequentialness is a pain in the ass */
  353. if(c->q_sequencep){
  354. int pv;
  355. long mul=1;
  356. float qlast=0;
  357. for(k=0,o=0;k<dim;k++,o+=step){
  358. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  359. if(pv<0 || pv>=pt->mapentries)break;
  360. entry+=pt->pigeonmap[pv]*mul;
  361. mul*=pt->quantvals;
  362. qlast+=pv*pt->del+pt->min;
  363. }
  364. }else{
  365. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  366. int pv=(int)((a[o]-pt->min)/pt->del);
  367. if(pv<0 || pv>=pt->mapentries)break;
  368. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  369. }
  370. }
  371. /* must be within the pigeonholable range; if we quant outside (or
  372. in an entry that we define no list for), brute force it */
  373. if(k==dim && pt->fitlength[entry]){
  374. /* search the abbreviated list */
  375. long *list=pt->fitlist+pt->fitmap[entry];
  376. for(i=0;i<pt->fitlength[entry];i++){
  377. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  378. if(besti==-1 || this<best){
  379. best=this;
  380. besti=list[i];
  381. }
  382. }
  383. return(besti);
  384. }
  385. }
  386. if(nt){
  387. /* optimized using the decision tree */
  388. while(1){
  389. float c=0.;
  390. float *p=book->valuelist+nt->p[ptr];
  391. float *q=book->valuelist+nt->q[ptr];
  392. for(k=0,o=0;k<dim;k++,o+=step)
  393. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  394. if(c>0.) /* in A */
  395. ptr= -nt->ptr0[ptr];
  396. else /* in B */
  397. ptr= -nt->ptr1[ptr];
  398. if(ptr<=0)break;
  399. }
  400. return(-ptr);
  401. }
  402. /* brute force it! */
  403. {
  404. const static_codebook *c=book->c;
  405. int i,besti=-1;
  406. float best;
  407. float *e=book->valuelist;
  408. for(i=0;i<book->entries;i++){
  409. if(c->lengthlist[i]>0){
  410. float this=_dist(dim,e,a,step);
  411. if(besti==-1 || this<best){
  412. best=this;
  413. besti=i;
  414. }
  415. }
  416. e+=dim;
  417. }
  418. /*if(savebest!=-1 && savebest!=besti){
  419. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  420. "original:");
  421. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  422. fprintf(stderr,"\n"
  423. "pigeonhole (entry %d, err %g):",savebest,saverr);
  424. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  425. (book->valuelist+savebest*dim)[i]);
  426. fprintf(stderr,"\n"
  427. "bruteforce (entry %d, err %g):",besti,best);
  428. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  429. (book->valuelist+besti*dim)[i]);
  430. fprintf(stderr,"\n");
  431. }*/
  432. return(besti);
  433. }
  434. }
  435. /* returns the entry number and *modifies a* to the remainder value ********/
  436. int vorbis_book_besterror(codebook *book,float *a,int step,int addmul){
  437. int dim=book->dim,i,o;
  438. int best=_best(book,a,step);
  439. switch(addmul){
  440. case 0:
  441. for(i=0,o=0;i<dim;i++,o+=step)
  442. a[o]-=(book->valuelist+best*dim)[i];
  443. break;
  444. case 1:
  445. for(i=0,o=0;i<dim;i++,o+=step){
  446. float val=(book->valuelist+best*dim)[i];
  447. if(val==0){
  448. a[o]=0;
  449. }else{
  450. a[o]/=val;
  451. }
  452. }
  453. break;
  454. }
  455. return(best);
  456. }
  457. long vorbis_book_codeword(codebook *book,int entry){
  458. return book->codelist[entry];
  459. }
  460. long vorbis_book_codelen(codebook *book,int entry){
  461. return book->c->lengthlist[entry];
  462. }
  463. #ifdef _V_SELFTEST
  464. /* Unit tests of the dequantizer; this stuff will be OK
  465. cross-platform, I simply want to be sure that special mapping cases
  466. actually work properly; a bug could go unnoticed for a while */
  467. #include <stdio.h>
  468. /* cases:
  469. no mapping
  470. full, explicit mapping
  471. algorithmic mapping
  472. nonsequential
  473. sequential
  474. */
  475. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  476. static long partial_quantlist1[]={0,7,2};
  477. /* no mapping */
  478. static_codebook test1={
  479. 4,16,
  480. NULL,
  481. 0,
  482. 0,0,0,0,
  483. NULL,
  484. NULL,NULL
  485. };
  486. static float *test1_result=NULL;
  487. /* linear, full mapping, nonsequential */
  488. static_codebook test2={
  489. 4,3,
  490. NULL,
  491. 2,
  492. -533200896,1611661312,4,0,
  493. full_quantlist1,
  494. NULL,NULL
  495. };
  496. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  497. /* linear, full mapping, sequential */
  498. static_codebook test3={
  499. 4,3,
  500. NULL,
  501. 2,
  502. -533200896,1611661312,4,1,
  503. full_quantlist1,
  504. NULL,NULL
  505. };
  506. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  507. /* linear, algorithmic mapping, nonsequential */
  508. static_codebook test4={
  509. 3,27,
  510. NULL,
  511. 1,
  512. -533200896,1611661312,4,0,
  513. partial_quantlist1,
  514. NULL,NULL
  515. };
  516. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  517. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  518. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  519. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  520. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  521. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  522. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  523. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  524. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  525. /* linear, algorithmic mapping, sequential */
  526. static_codebook test5={
  527. 3,27,
  528. NULL,
  529. 1,
  530. -533200896,1611661312,4,1,
  531. partial_quantlist1,
  532. NULL,NULL
  533. };
  534. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  535. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  536. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  537. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  538. -3, 1, 5, 4, 8,12, -1, 3, 7,
  539. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  540. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  541. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  542. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  543. void run_test(static_codebook *b,float *comp){
  544. float *out=_book_unquantize(b);
  545. int i;
  546. if(comp){
  547. if(!out){
  548. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  549. exit(1);
  550. }
  551. for(i=0;i<b->entries*b->dim;i++)
  552. if(fabs(out[i]-comp[i])>.0001){
  553. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  554. "position %d, %g != %g\n",i,out[i],comp[i]);
  555. exit(1);
  556. }
  557. }else{
  558. if(out){
  559. fprintf(stderr,"_book_unquantize returned a value array: \n"
  560. " correct result should have been NULL\n");
  561. exit(1);
  562. }
  563. }
  564. }
  565. int main(){
  566. /* run the nine dequant tests, and compare to the hand-rolled results */
  567. fprintf(stderr,"Dequant test 1... ");
  568. run_test(&test1,test1_result);
  569. fprintf(stderr,"OK\nDequant test 2... ");
  570. run_test(&test2,test2_result);
  571. fprintf(stderr,"OK\nDequant test 3... ");
  572. run_test(&test3,test3_result);
  573. fprintf(stderr,"OK\nDequant test 4... ");
  574. run_test(&test4,test4_result);
  575. fprintf(stderr,"OK\nDequant test 5... ");
  576. run_test(&test5,test5_result);
  577. fprintf(stderr,"OK\n\n");
  578. return(0);
  579. }
  580. #endif