sharedbook.c 14 KB

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