sharedbook.c 17 KB

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