vorbis_sharedbook.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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-2015 *
  9. * by the Xiph.Org Foundation http://www.xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function: basic shared codebook operations
  13. last mod: $Id: sharedbook.c 19457 2015-03-03 00:15:29Z giles $
  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 ov_ilog(ogg_uint32_t v){
  26. int ret;
  27. for(ret=0;v;ret++)v>>=1;
  28. return ret;
  29. }
  30. /* 32 bit float (not IEEE; nonnormalized mantissa +
  31. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  32. Why not IEEE? It's just not that important here. */
  33. #define VQ_FEXP 10
  34. #define VQ_FMAN 21
  35. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  36. /* doesn't currently guard under/overflow */
  37. long _float32_pack(float val){
  38. int sign=0;
  39. long exp;
  40. long mant;
  41. if(val<0){
  42. sign=0x80000000;
  43. val= -val;
  44. }
  45. exp= floor(log(val)/log(2.f)+.001); //+epsilon
  46. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  47. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  48. return(sign|exp|mant);
  49. }
  50. float _float32_unpack(long val){
  51. double mant=val&0x1fffff;
  52. int sign=val&0x80000000;
  53. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  54. if(sign)mant= -mant;
  55. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  56. }
  57. /* given a list of word lengths, generate a list of codewords. Works
  58. for length ordered or unordered, always assigns the lowest valued
  59. codewords first. Extended to handle unused entries (length 0) */
  60. ogg_uint32_t *_make_words(char *l,long n,long sparsecount){
  61. long i,j,count=0;
  62. ogg_uint32_t marker[33];
  63. ogg_uint32_t *r=_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  64. memset(marker,0,sizeof(marker));
  65. for(i=0;i<n;i++){
  66. long length=l[i];
  67. if(length>0){
  68. ogg_uint32_t entry=marker[length];
  69. /* when we claim a node for an entry, we also claim the nodes
  70. below it (pruning off the imagined tree that may have dangled
  71. from it) as well as blocking the use of any nodes directly
  72. above for leaves */
  73. /* update ourself */
  74. if(length<32 && (entry>>length)){
  75. /* error condition; the lengths must specify an overpopulated tree */
  76. _ogg_free(r);
  77. return(NULL);
  78. }
  79. r[count++]=entry;
  80. /* Look to see if the next shorter marker points to the node
  81. above. if so, update it and repeat. */
  82. {
  83. for(j=length;j>0;j--){
  84. if(marker[j]&1){
  85. /* have to jump branches */
  86. if(j==1)
  87. marker[1]++;
  88. else
  89. marker[j]=marker[j-1]<<1;
  90. break; /* invariant says next upper marker would already
  91. have been moved if it was on the same path */
  92. }
  93. marker[j]++;
  94. }
  95. }
  96. /* prune the tree; the implicit invariant says all the longer
  97. markers were dangling from our just-taken node. Dangle them
  98. from our *new* node. */
  99. for(j=length+1;j<33;j++)
  100. if((marker[j]>>1) == entry){
  101. entry=marker[j];
  102. marker[j]=marker[j-1]<<1;
  103. }else
  104. break;
  105. }else
  106. if(sparsecount==0)count++;
  107. }
  108. /* any underpopulated tree must be rejected. */
  109. /* Single-entry codebooks are a retconned extension to the spec.
  110. They have a single codeword '0' of length 1 that results in an
  111. underpopulated tree. Shield that case from the underformed tree check. */
  112. if(!(count==1 && marker[2]==2)){
  113. for(i=1;i<33;i++)
  114. if(marker[i] & (0xffffffffUL>>(32-i))){
  115. _ogg_free(r);
  116. return(NULL);
  117. }
  118. }
  119. /* bitreverse the words because our bitwise packer/unpacker is LSb
  120. endian */
  121. for(i=0,count=0;i<n;i++){
  122. ogg_uint32_t temp=0;
  123. for(j=0;j<l[i];j++){
  124. temp<<=1;
  125. temp|=(r[count]>>j)&1;
  126. }
  127. if(sparsecount){
  128. if(l[i])
  129. r[count++]=temp;
  130. }else
  131. r[count++]=temp;
  132. }
  133. return(r);
  134. }
  135. /* there might be a straightforward one-line way to do the below
  136. that's portable and totally safe against roundoff, but I haven't
  137. thought of it. Therefore, we opt on the side of caution */
  138. long _book_maptype1_quantvals(const static_codebook *b){
  139. long vals=floor(pow((float)b->entries,1.f/b->dim));
  140. /* the above *should* be reliable, but we'll not assume that FP is
  141. ever reliable when bitstream sync is at stake; verify via integer
  142. means that vals really is the greatest value of dim for which
  143. vals^b->bim <= b->entries */
  144. /* treat the above as an initial guess */
  145. while(1){
  146. long acc=1;
  147. long acc1=1;
  148. int i;
  149. for(i=0;i<b->dim;i++){
  150. acc*=vals;
  151. acc1*=vals+1;
  152. }
  153. if(acc<=b->entries && acc1>b->entries){
  154. return(vals);
  155. }else{
  156. if(acc>b->entries){
  157. vals--;
  158. }else{
  159. vals++;
  160. }
  161. }
  162. }
  163. }
  164. /* unpack the quantized list of values for encode/decode ***********/
  165. /* we need to deal with two map types: in map type 1, the values are
  166. generated algorithmically (each column of the vector counts through
  167. the values in the quant vector). in map type 2, all the values came
  168. in in an explicit list. Both value lists must be unpacked */
  169. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  170. long j,k,count=0;
  171. if(b->maptype==1 || b->maptype==2){
  172. int quantvals;
  173. float mindel=_float32_unpack(b->q_min);
  174. float delta=_float32_unpack(b->q_delta);
  175. float *r=_ogg_calloc(n*b->dim,sizeof(*r));
  176. /* maptype 1 and 2 both use a quantized value vector, but
  177. different sizes */
  178. switch(b->maptype){
  179. case 1:
  180. /* most of the time, entries%dimensions == 0, but we need to be
  181. well defined. We define that the possible vales at each
  182. scalar is values == entries/dim. If entries%dim != 0, we'll
  183. have 'too few' values (values*dim<entries), which means that
  184. we'll have 'left over' entries; left over entries use zeroed
  185. values (and are wasted). So don't generate codebooks like
  186. that */
  187. quantvals=_book_maptype1_quantvals(b);
  188. for(j=0;j<b->entries;j++){
  189. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  190. float last=0.f;
  191. int indexdiv=1;
  192. for(k=0;k<b->dim;k++){
  193. int index= (j/indexdiv)%quantvals;
  194. float val=b->quantlist[index];
  195. val=fabs(val)*delta+mindel+last;
  196. if(b->q_sequencep)last=val;
  197. if(sparsemap)
  198. r[sparsemap[count]*b->dim+k]=val;
  199. else
  200. r[count*b->dim+k]=val;
  201. indexdiv*=quantvals;
  202. }
  203. count++;
  204. }
  205. }
  206. break;
  207. case 2:
  208. for(j=0;j<b->entries;j++){
  209. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  210. float last=0.f;
  211. for(k=0;k<b->dim;k++){
  212. float val=b->quantlist[j*b->dim+k];
  213. val=fabs(val)*delta+mindel+last;
  214. if(b->q_sequencep)last=val;
  215. if(sparsemap)
  216. r[sparsemap[count]*b->dim+k]=val;
  217. else
  218. r[count*b->dim+k]=val;
  219. }
  220. count++;
  221. }
  222. }
  223. break;
  224. }
  225. return(r);
  226. }
  227. return(NULL);
  228. }
  229. void vorbis_staticbook_destroy(static_codebook *b){
  230. if(b->allocedp){
  231. if(b->quantlist)_ogg_free(b->quantlist);
  232. if(b->lengthlist)_ogg_free(b->lengthlist);
  233. memset(b,0,sizeof(*b));
  234. _ogg_free(b);
  235. } /* otherwise, it is in static memory */
  236. }
  237. void vorbis_book_clear(codebook *b){
  238. /* static book is not cleared; we're likely called on the lookup and
  239. the static codebook belongs to the info struct */
  240. if(b->valuelist)_ogg_free(b->valuelist);
  241. if(b->codelist)_ogg_free(b->codelist);
  242. if(b->dec_index)_ogg_free(b->dec_index);
  243. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  244. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  245. memset(b,0,sizeof(*b));
  246. }
  247. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  248. memset(c,0,sizeof(*c));
  249. c->c=s;
  250. c->entries=s->entries;
  251. c->used_entries=s->entries;
  252. c->dim=s->dim;
  253. c->codelist=_make_words(s->lengthlist,s->entries,0);
  254. //c->valuelist=_book_unquantize(s,s->entries,NULL);
  255. c->quantvals=_book_maptype1_quantvals(s);
  256. c->minval=(int)rint(_float32_unpack(s->q_min));
  257. c->delta=(int)rint(_float32_unpack(s->q_delta));
  258. return(0);
  259. }
  260. static ogg_uint32_t bitreverse(ogg_uint32_t x){
  261. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  262. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  263. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  264. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  265. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  266. }
  267. static int sort32a(const void *a,const void *b){
  268. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  269. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  270. }
  271. /* decode codebook arrangement is more heavily optimized than encode */
  272. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  273. int i,j,n=0,tabn;
  274. int *sortindex;
  275. memset(c,0,sizeof(*c));
  276. /* count actually used entries and find max length */
  277. for(i=0;i<s->entries;i++)
  278. if(s->lengthlist[i]>0)
  279. n++;
  280. c->entries=s->entries;
  281. c->used_entries=n;
  282. c->dim=s->dim;
  283. if(n>0){
  284. /* two different remappings go on here.
  285. First, we collapse the likely sparse codebook down only to
  286. actually represented values/words. This collapsing needs to be
  287. indexed as map-valueless books are used to encode original entry
  288. positions as integers.
  289. Second, we reorder all vectors, including the entry index above,
  290. by sorted bitreversed codeword to allow treeless decode. */
  291. /* perform sort */
  292. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  293. ogg_uint32_t **codep=alloca(sizeof(*codep)*n);
  294. if(codes==NULL)goto err_out;
  295. for(i=0;i<n;i++){
  296. codes[i]=bitreverse(codes[i]);
  297. codep[i]=codes+i;
  298. }
  299. qsort(codep,n,sizeof(*codep),sort32a);
  300. sortindex=alloca(n*sizeof(*sortindex));
  301. c->codelist=_ogg_malloc(n*sizeof(*c->codelist));
  302. /* the index is a reverse index */
  303. for(i=0;i<n;i++){
  304. int position=codep[i]-codes;
  305. sortindex[position]=i;
  306. }
  307. for(i=0;i<n;i++)
  308. c->codelist[sortindex[i]]=codes[i];
  309. _ogg_free(codes);
  310. c->valuelist=_book_unquantize(s,n,sortindex);
  311. c->dec_index=_ogg_malloc(n*sizeof(*c->dec_index));
  312. for(n=0,i=0;i<s->entries;i++)
  313. if(s->lengthlist[i]>0)
  314. c->dec_index[sortindex[n++]]=i;
  315. c->dec_codelengths=_ogg_malloc(n*sizeof(*c->dec_codelengths));
  316. c->dec_maxlength=0;
  317. for(n=0,i=0;i<s->entries;i++)
  318. if(s->lengthlist[i]>0){
  319. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  320. if(s->lengthlist[i]>c->dec_maxlength)
  321. c->dec_maxlength=s->lengthlist[i];
  322. }
  323. if(n==1 && c->dec_maxlength==1){
  324. /* special case the 'single entry codebook' with a single bit
  325. fastpath table (that always returns entry 0 )in order to use
  326. unmodified decode paths. */
  327. c->dec_firsttablen=1;
  328. c->dec_firsttable=_ogg_calloc(2,sizeof(*c->dec_firsttable));
  329. c->dec_firsttable[0]=c->dec_firsttable[1]=1;
  330. }else{
  331. c->dec_firsttablen=ov_ilog(c->used_entries)-4; /* this is magic */
  332. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  333. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  334. tabn=1<<c->dec_firsttablen;
  335. c->dec_firsttable=_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  336. for(i=0;i<n;i++){
  337. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  338. ogg_uint32_t orig=bitreverse(c->codelist[i]);
  339. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  340. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  341. }
  342. }
  343. /* now fill in 'unused' entries in the firsttable with hi/lo search
  344. hints for the non-direct-hits */
  345. {
  346. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  347. long lo=0,hi=0;
  348. for(i=0;i<tabn;i++){
  349. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  350. if(c->dec_firsttable[bitreverse(word)]==0){
  351. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  352. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  353. /* we only actually have 15 bits per hint to play with here.
  354. In order to overflow gracefully (nothing breaks, efficiency
  355. just drops), encode as the difference from the extremes. */
  356. {
  357. unsigned long loval=lo;
  358. unsigned long hival=n-hi;
  359. if(loval>0x7fff)loval=0x7fff;
  360. if(hival>0x7fff)hival=0x7fff;
  361. c->dec_firsttable[bitreverse(word)]=
  362. 0x80000000UL | (loval<<15) | hival;
  363. }
  364. }
  365. }
  366. }
  367. }
  368. }
  369. return(0);
  370. err_out:
  371. vorbis_book_clear(c);
  372. return(-1);
  373. }
  374. long vorbis_book_codeword(codebook *book,int entry){
  375. if(book->c) /* only use with encode; decode optimizations are
  376. allowed to break this */
  377. return book->codelist[entry];
  378. return -1;
  379. }
  380. long vorbis_book_codelen(codebook *book,int entry){
  381. if(book->c) /* only use with encode; decode optimizations are
  382. allowed to break this */
  383. return book->c->lengthlist[entry];
  384. return -1;
  385. }
  386. #ifdef _V_SELFTEST
  387. /* Unit tests of the dequantizer; this stuff will be OK
  388. cross-platform, I simply want to be sure that special mapping cases
  389. actually work properly; a bug could go unnoticed for a while */
  390. #include <stdio.h>
  391. /* cases:
  392. no mapping
  393. full, explicit mapping
  394. algorithmic mapping
  395. nonsequential
  396. sequential
  397. */
  398. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  399. static long partial_quantlist1[]={0,7,2};
  400. /* no mapping */
  401. static_codebook test1={
  402. 4,16,
  403. NULL,
  404. 0,
  405. 0,0,0,0,
  406. NULL,
  407. 0
  408. };
  409. static float *test1_result=NULL;
  410. /* linear, full mapping, nonsequential */
  411. static_codebook test2={
  412. 4,3,
  413. NULL,
  414. 2,
  415. -533200896,1611661312,4,0,
  416. full_quantlist1,
  417. 0
  418. };
  419. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  420. /* linear, full mapping, sequential */
  421. static_codebook test3={
  422. 4,3,
  423. NULL,
  424. 2,
  425. -533200896,1611661312,4,1,
  426. full_quantlist1,
  427. 0
  428. };
  429. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  430. /* linear, algorithmic mapping, nonsequential */
  431. static_codebook test4={
  432. 3,27,
  433. NULL,
  434. 1,
  435. -533200896,1611661312,4,0,
  436. partial_quantlist1,
  437. 0
  438. };
  439. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  440. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  441. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  442. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  443. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  444. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  445. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  446. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  447. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  448. /* linear, algorithmic mapping, sequential */
  449. static_codebook test5={
  450. 3,27,
  451. NULL,
  452. 1,
  453. -533200896,1611661312,4,1,
  454. partial_quantlist1,
  455. 0
  456. };
  457. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  458. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  459. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  460. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  461. -3, 1, 5, 4, 8,12, -1, 3, 7,
  462. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  463. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  464. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  465. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  466. void run_test(static_codebook *b,float *comp){
  467. float *out=_book_unquantize(b,b->entries,NULL);
  468. int i;
  469. if(comp){
  470. if(!out){
  471. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  472. exit(1);
  473. }
  474. for(i=0;i<b->entries*b->dim;i++)
  475. if(fabs(out[i]-comp[i])>.0001){
  476. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  477. "position %d, %g != %g\n",i,out[i],comp[i]);
  478. exit(1);
  479. }
  480. }else{
  481. if(out){
  482. fprintf(stderr,"_book_unquantize returned a value array: \n"
  483. " correct result should have been NULL\n");
  484. exit(1);
  485. }
  486. }
  487. }
  488. int main(){
  489. /* run the nine dequant tests, and compare to the hand-rolled results */
  490. fprintf(stderr,"Dequant test 1... ");
  491. run_test(&test1,test1_result);
  492. fprintf(stderr,"OK\nDequant test 2... ");
  493. run_test(&test2,test2_result);
  494. fprintf(stderr,"OK\nDequant test 3... ");
  495. run_test(&test3,test3_result);
  496. fprintf(stderr,"OK\nDequant test 4... ");
  497. run_test(&test4,test4_result);
  498. fprintf(stderr,"OK\nDequant test 5... ");
  499. run_test(&test5,test5_result);
  500. fprintf(stderr,"OK\n\n");
  501. return(0);
  502. }
  503. #endif