sharedbook.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  5. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  6. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009 *
  9. * by the Xiph.Org Foundation http://www.xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function: basic shared codebook operations
  13. last mod: $Id: sharedbook.c 19057 2014-01-22 12:32:31Z xiphmont $
  14. ********************************************************************/
  15. #include <stdlib.h>
  16. #include <math.h>
  17. #include <string.h>
  18. #include <ogg/ogg.h>
  19. #include "os.h"
  20. #include "misc.h"
  21. #include "vorbis/codec.h"
  22. #include "codebook.h"
  23. #include "scales.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(float 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.f)+.001); //+epsilon
  49. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  50. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  51. return(sign|exp|mant);
  52. }
  53. float _float32_unpack(long val){
  54. double mant=val&0x1fffff;
  55. int sign=val&0x80000000;
  56. long exp =(val&0x7fe00000L)>>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. ogg_uint32_t *_make_words(char *l,long n,long sparsecount){
  64. long i,j,count=0;
  65. ogg_uint32_t marker[33];
  66. ogg_uint32_t *r=_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  67. memset(marker,0,sizeof(marker));
  68. for(i=0;i<n;i++){
  69. long length=l[i];
  70. if(length>0){
  71. ogg_uint32_t 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. _ogg_free(r);
  80. return(NULL);
  81. }
  82. r[count++]=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. }else
  109. if(sparsecount==0)count++;
  110. }
  111. /* sanity check the huffman tree; an underpopulated tree must be
  112. rejected. The only exception is the one-node pseudo-nil tree,
  113. which appears to be underpopulated because the tree doesn't
  114. really exist; there's only one possible 'codeword' or zero bits,
  115. but the above tree-gen code doesn't mark that. */
  116. if(sparsecount != 1){
  117. for(i=1;i<33;i++)
  118. if(marker[i] & (0xffffffffUL>>(32-i))){
  119. _ogg_free(r);
  120. return(NULL);
  121. }
  122. }
  123. /* bitreverse the words because our bitwise packer/unpacker is LSb
  124. endian */
  125. for(i=0,count=0;i<n;i++){
  126. ogg_uint32_t temp=0;
  127. for(j=0;j<l[i];j++){
  128. temp<<=1;
  129. temp|=(r[count]>>j)&1;
  130. }
  131. if(sparsecount){
  132. if(l[i])
  133. r[count++]=temp;
  134. }else
  135. r[count++]=temp;
  136. }
  137. return(r);
  138. }
  139. /* there might be a straightforward one-line way to do the below
  140. that's portable and totally safe against roundoff, but I haven't
  141. thought of it. Therefore, we opt on the side of caution */
  142. long _book_maptype1_quantvals(const static_codebook *b){
  143. long vals=floor(pow((float)b->entries,1.f/b->dim));
  144. /* the above *should* be reliable, but we'll not assume that FP is
  145. ever reliable when bitstream sync is at stake; verify via integer
  146. means that vals really is the greatest value of dim for which
  147. vals^b->bim <= b->entries */
  148. /* treat the above as an initial guess */
  149. while(1){
  150. long acc=1;
  151. long acc1=1;
  152. int i;
  153. for(i=0;i<b->dim;i++){
  154. acc*=vals;
  155. acc1*=vals+1;
  156. }
  157. if(acc<=b->entries && acc1>b->entries){
  158. return(vals);
  159. }else{
  160. if(acc>b->entries){
  161. vals--;
  162. }else{
  163. vals++;
  164. }
  165. }
  166. }
  167. }
  168. /* unpack the quantized list of values for encode/decode ***********/
  169. /* we need to deal with two map types: in map type 1, the values are
  170. generated algorithmically (each column of the vector counts through
  171. the values in the quant vector). in map type 2, all the values came
  172. in in an explicit list. Both value lists must be unpacked */
  173. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  174. long j,k,count=0;
  175. if(b->maptype==1 || b->maptype==2){
  176. int quantvals;
  177. float mindel=_float32_unpack(b->q_min);
  178. float delta=_float32_unpack(b->q_delta);
  179. float *r=_ogg_calloc(n*b->dim,sizeof(*r));
  180. /* maptype 1 and 2 both use a quantized value vector, but
  181. different sizes */
  182. switch(b->maptype){
  183. case 1:
  184. /* most of the time, entries%dimensions == 0, but we need to be
  185. well defined. We define that the possible vales at each
  186. scalar is values == entries/dim. If entries%dim != 0, we'll
  187. have 'too few' values (values*dim<entries), which means that
  188. we'll have 'left over' entries; left over entries use zeroed
  189. values (and are wasted). So don't generate codebooks like
  190. that */
  191. quantvals=_book_maptype1_quantvals(b);
  192. for(j=0;j<b->entries;j++){
  193. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  194. float last=0.f;
  195. int indexdiv=1;
  196. for(k=0;k<b->dim;k++){
  197. int index= (j/indexdiv)%quantvals;
  198. float val=b->quantlist[index];
  199. val=fabs(val)*delta+mindel+last;
  200. if(b->q_sequencep)last=val;
  201. if(sparsemap)
  202. r[sparsemap[count]*b->dim+k]=val;
  203. else
  204. r[count*b->dim+k]=val;
  205. indexdiv*=quantvals;
  206. }
  207. count++;
  208. }
  209. }
  210. break;
  211. case 2:
  212. for(j=0;j<b->entries;j++){
  213. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  214. float last=0.f;
  215. for(k=0;k<b->dim;k++){
  216. float val=b->quantlist[j*b->dim+k];
  217. val=fabs(val)*delta+mindel+last;
  218. if(b->q_sequencep)last=val;
  219. if(sparsemap)
  220. r[sparsemap[count]*b->dim+k]=val;
  221. else
  222. r[count*b->dim+k]=val;
  223. }
  224. count++;
  225. }
  226. }
  227. break;
  228. }
  229. return(r);
  230. }
  231. return(NULL);
  232. }
  233. void vorbis_staticbook_destroy(static_codebook *b){
  234. if(b->allocedp){
  235. if(b->quantlist)_ogg_free(b->quantlist);
  236. if(b->lengthlist)_ogg_free(b->lengthlist);
  237. memset(b,0,sizeof(*b));
  238. _ogg_free(b);
  239. } /* otherwise, it is in static memory */
  240. }
  241. void vorbis_book_clear(codebook *b){
  242. /* static book is not cleared; we're likely called on the lookup and
  243. the static codebook belongs to the info struct */
  244. if(b->valuelist)_ogg_free(b->valuelist);
  245. if(b->codelist)_ogg_free(b->codelist);
  246. if(b->dec_index)_ogg_free(b->dec_index);
  247. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  248. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  249. memset(b,0,sizeof(*b));
  250. }
  251. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  252. memset(c,0,sizeof(*c));
  253. c->c=s;
  254. c->entries=s->entries;
  255. c->used_entries=s->entries;
  256. c->dim=s->dim;
  257. c->codelist=_make_words(s->lengthlist,s->entries,0);
  258. //c->valuelist=_book_unquantize(s,s->entries,NULL);
  259. c->quantvals=_book_maptype1_quantvals(s);
  260. c->minval=(int)rint(_float32_unpack(s->q_min));
  261. c->delta=(int)rint(_float32_unpack(s->q_delta));
  262. return(0);
  263. }
  264. static ogg_uint32_t bitreverse(ogg_uint32_t x){
  265. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  266. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  267. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  268. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  269. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  270. }
  271. static int sort32a(const void *a,const void *b){
  272. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  273. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  274. }
  275. /* decode codebook arrangement is more heavily optimized than encode */
  276. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  277. int i,j,n=0,tabn;
  278. int *sortindex;
  279. memset(c,0,sizeof(*c));
  280. /* count actually used entries */
  281. for(i=0;i<s->entries;i++)
  282. if(s->lengthlist[i]>0)
  283. n++;
  284. c->entries=s->entries;
  285. c->used_entries=n;
  286. c->dim=s->dim;
  287. if(n>0){
  288. /* two different remappings go on here.
  289. First, we collapse the likely sparse codebook down only to
  290. actually represented values/words. This collapsing needs to be
  291. indexed as map-valueless books are used to encode original entry
  292. positions as integers.
  293. Second, we reorder all vectors, including the entry index above,
  294. by sorted bitreversed codeword to allow treeless decode. */
  295. /* perform sort */
  296. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  297. ogg_uint32_t **codep=alloca(sizeof(*codep)*n);
  298. if(codes==NULL)goto err_out;
  299. for(i=0;i<n;i++){
  300. codes[i]=bitreverse(codes[i]);
  301. codep[i]=codes+i;
  302. }
  303. qsort(codep,n,sizeof(*codep),sort32a);
  304. sortindex=alloca(n*sizeof(*sortindex));
  305. c->codelist=_ogg_malloc(n*sizeof(*c->codelist));
  306. /* the index is a reverse index */
  307. for(i=0;i<n;i++){
  308. int position=codep[i]-codes;
  309. sortindex[position]=i;
  310. }
  311. for(i=0;i<n;i++)
  312. c->codelist[sortindex[i]]=codes[i];
  313. _ogg_free(codes);
  314. c->valuelist=_book_unquantize(s,n,sortindex);
  315. c->dec_index=_ogg_malloc(n*sizeof(*c->dec_index));
  316. for(n=0,i=0;i<s->entries;i++)
  317. if(s->lengthlist[i]>0)
  318. c->dec_index[sortindex[n++]]=i;
  319. c->dec_codelengths=_ogg_malloc(n*sizeof(*c->dec_codelengths));
  320. for(n=0,i=0;i<s->entries;i++)
  321. if(s->lengthlist[i]>0)
  322. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  323. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  324. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  325. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  326. tabn=1<<c->dec_firsttablen;
  327. c->dec_firsttable=_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  328. c->dec_maxlength=0;
  329. for(i=0;i<n;i++){
  330. if(c->dec_maxlength<c->dec_codelengths[i])
  331. c->dec_maxlength=c->dec_codelengths[i];
  332. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  333. ogg_uint32_t orig=bitreverse(c->codelist[i]);
  334. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  335. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  336. }
  337. }
  338. /* now fill in 'unused' entries in the firsttable with hi/lo search
  339. hints for the non-direct-hits */
  340. {
  341. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  342. long lo=0,hi=0;
  343. for(i=0;i<tabn;i++){
  344. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  345. if(c->dec_firsttable[bitreverse(word)]==0){
  346. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  347. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  348. /* we only actually have 15 bits per hint to play with here.
  349. In order to overflow gracefully (nothing breaks, efficiency
  350. just drops), encode as the difference from the extremes. */
  351. {
  352. unsigned long loval=lo;
  353. unsigned long hival=n-hi;
  354. if(loval>0x7fff)loval=0x7fff;
  355. if(hival>0x7fff)hival=0x7fff;
  356. c->dec_firsttable[bitreverse(word)]=
  357. 0x80000000UL | (loval<<15) | hival;
  358. }
  359. }
  360. }
  361. }
  362. }
  363. return(0);
  364. err_out:
  365. vorbis_book_clear(c);
  366. return(-1);
  367. }
  368. long vorbis_book_codeword(codebook *book,int entry){
  369. if(book->c) /* only use with encode; decode optimizations are
  370. allowed to break this */
  371. return book->codelist[entry];
  372. return -1;
  373. }
  374. long vorbis_book_codelen(codebook *book,int entry){
  375. if(book->c) /* only use with encode; decode optimizations are
  376. allowed to break this */
  377. return book->c->lengthlist[entry];
  378. return -1;
  379. }
  380. #ifdef _V_SELFTEST
  381. /* Unit tests of the dequantizer; this stuff will be OK
  382. cross-platform, I simply want to be sure that special mapping cases
  383. actually work properly; a bug could go unnoticed for a while */
  384. #include <stdio.h>
  385. /* cases:
  386. no mapping
  387. full, explicit mapping
  388. algorithmic mapping
  389. nonsequential
  390. sequential
  391. */
  392. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  393. static long partial_quantlist1[]={0,7,2};
  394. /* no mapping */
  395. static_codebook test1={
  396. 4,16,
  397. NULL,
  398. 0,
  399. 0,0,0,0,
  400. NULL,
  401. 0
  402. };
  403. static float *test1_result=NULL;
  404. /* linear, full mapping, nonsequential */
  405. static_codebook test2={
  406. 4,3,
  407. NULL,
  408. 2,
  409. -533200896,1611661312,4,0,
  410. full_quantlist1,
  411. 0
  412. };
  413. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  414. /* linear, full mapping, sequential */
  415. static_codebook test3={
  416. 4,3,
  417. NULL,
  418. 2,
  419. -533200896,1611661312,4,1,
  420. full_quantlist1,
  421. 0
  422. };
  423. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  424. /* linear, algorithmic mapping, nonsequential */
  425. static_codebook test4={
  426. 3,27,
  427. NULL,
  428. 1,
  429. -533200896,1611661312,4,0,
  430. partial_quantlist1,
  431. 0
  432. };
  433. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  434. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  435. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  436. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  437. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  438. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  439. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  440. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  441. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  442. /* linear, algorithmic mapping, sequential */
  443. static_codebook test5={
  444. 3,27,
  445. NULL,
  446. 1,
  447. -533200896,1611661312,4,1,
  448. partial_quantlist1,
  449. 0
  450. };
  451. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  452. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  453. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  454. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  455. -3, 1, 5, 4, 8,12, -1, 3, 7,
  456. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  457. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  458. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  459. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  460. void run_test(static_codebook *b,float *comp){
  461. float *out=_book_unquantize(b,b->entries,NULL);
  462. int i;
  463. if(comp){
  464. if(!out){
  465. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  466. exit(1);
  467. }
  468. for(i=0;i<b->entries*b->dim;i++)
  469. if(fabs(out[i]-comp[i])>.0001){
  470. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  471. "position %d, %g != %g\n",i,out[i],comp[i]);
  472. exit(1);
  473. }
  474. }else{
  475. if(out){
  476. fprintf(stderr,"_book_unquantize returned a value array: \n"
  477. " correct result should have been NULL\n");
  478. exit(1);
  479. }
  480. }
  481. }
  482. int main(){
  483. /* run the nine dequant tests, and compare to the hand-rolled results */
  484. fprintf(stderr,"Dequant test 1... ");
  485. run_test(&test1,test1_result);
  486. fprintf(stderr,"OK\nDequant test 2... ");
  487. run_test(&test2,test2_result);
  488. fprintf(stderr,"OK\nDequant test 3... ");
  489. run_test(&test3,test3_result);
  490. fprintf(stderr,"OK\nDequant test 4... ");
  491. run_test(&test4,test4_result);
  492. fprintf(stderr,"OK\nDequant test 5... ");
  493. run_test(&test5,test5_result);
  494. fprintf(stderr,"OK\n\n");
  495. return(0);
  496. }
  497. #endif