sharedbook.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. *
  4. * *
  5. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  6. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  7. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  8. * *
  9. * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  10. * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ *
  11. * *
  12. ********************************************************************
  13. function: basic shared codebook operations
  14. ********************************************************************/
  15. #include <stdlib.h>
  16. #include <math.h>
  17. #include <string.h>
  18. #include "ogg/ogg.h"
  19. #include "misc.h"
  20. #include "ivorbiscodec.h"
  21. #include "codebook.h"
  22. /**** pack/unpack helpers ******************************************/
  23. int _ilog(unsigned int v){
  24. int ret=0;
  25. while(v){
  26. ret++;
  27. v>>=1;
  28. }
  29. return(ret);
  30. }
  31. /* 32 bit float (not IEEE; nonnormalized mantissa +
  32. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  33. Why not IEEE? It's just not that important here. */
  34. #define VQ_FEXP 10
  35. #define VQ_FMAN 21
  36. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  37. static ogg_int32_t _float32_unpack(long val,int *point){
  38. long mant=val&0x1fffff;
  39. int sign=val&0x80000000;
  40. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  41. exp-=(VQ_FMAN-1)+VQ_FEXP_BIAS;
  42. if(mant){
  43. while(!(mant&0x40000000)){
  44. mant<<=1;
  45. exp-=1;
  46. }
  47. if(sign)mant= -mant;
  48. }else{
  49. sign=0;
  50. exp=-9999;
  51. }
  52. *point=exp;
  53. return mant;
  54. }
  55. /* given a list of word lengths, generate a list of codewords. Works
  56. for length ordered or unordered, always assigns the lowest valued
  57. codewords first. Extended to handle unused entries (length 0) */
  58. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  59. long i,j,count=0;
  60. ogg_uint32_t marker[33];
  61. ogg_uint32_t *r=(ogg_uint32_t *)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  62. memset(marker,0,sizeof(marker));
  63. for(i=0;i<n;i++){
  64. long length=l[i];
  65. if(length>0){
  66. ogg_uint32_t entry=marker[length];
  67. /* when we claim a node for an entry, we also claim the nodes
  68. below it (pruning off the imagined tree that may have dangled
  69. from it) as well as blocking the use of any nodes directly
  70. above for leaves */
  71. /* update ourself */
  72. if(length<32 && (entry>>length)){
  73. /* error condition; the lengths must specify an overpopulated tree */
  74. _ogg_free(r);
  75. return(NULL);
  76. }
  77. r[count++]=entry;
  78. /* Look to see if the next shorter marker points to the node
  79. above. if so, update it and repeat. */
  80. {
  81. for(j=length;j>0;j--){
  82. if(marker[j]&1){
  83. /* have to jump branches */
  84. if(j==1)
  85. marker[1]++;
  86. else
  87. marker[j]=marker[j-1]<<1;
  88. break; /* invariant says next upper marker would already
  89. have been moved if it was on the same path */
  90. }
  91. marker[j]++;
  92. }
  93. }
  94. /* prune the tree; the implicit invariant says all the longer
  95. markers were dangling from our just-taken node. Dangle them
  96. from our *new* node. */
  97. for(j=length+1;j<33;j++)
  98. if((marker[j]>>1) == entry){
  99. entry=marker[j];
  100. marker[j]=marker[j-1]<<1;
  101. }else
  102. break;
  103. }else
  104. if(sparsecount==0)count++;
  105. }
  106. /* sanity check the huffman tree; an underpopulated tree must be
  107. rejected. The only exception is the one-node pseudo-nil tree,
  108. which appears to be underpopulated because the tree doesn't
  109. really exist; there's only one possible 'codeword' or zero bits,
  110. but the above tree-gen code doesn't mark that. */
  111. if(sparsecount != 1){
  112. for(i=1;i<33;i++)
  113. if(marker[i] & (0xffffffffUL>>(32-i))){
  114. _ogg_free(r);
  115. return(NULL);
  116. }
  117. }
  118. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119. endian */
  120. for(i=0,count=0;i<n;i++){
  121. ogg_uint32_t temp=0;
  122. for(j=0;j<l[i];j++){
  123. temp<<=1;
  124. temp|=(r[count]>>j)&1;
  125. }
  126. if(sparsecount){
  127. if(l[i])
  128. r[count++]=temp;
  129. }else
  130. r[count++]=temp;
  131. }
  132. return(r);
  133. }
  134. /* there might be a straightforward one-line way to do the below
  135. that's portable and totally safe against roundoff, but I haven't
  136. thought of it. Therefore, we opt on the side of caution */
  137. long _book_maptype1_quantvals(const static_codebook *b){
  138. /* get us a starting hint, we'll polish it below */
  139. int bits=_ilog(b->entries);
  140. int vals=b->entries>>((bits-1)*(b->dim-1)/b->dim);
  141. while(1){
  142. long acc=1;
  143. long acc1=1;
  144. int i;
  145. for(i=0;i<b->dim;i++){
  146. acc*=vals;
  147. acc1*=vals+1;
  148. }
  149. if(acc<=b->entries && acc1>b->entries){
  150. return(vals);
  151. }else{
  152. if(acc>b->entries){
  153. vals--;
  154. }else{
  155. vals++;
  156. }
  157. }
  158. }
  159. }
  160. /* different than what _book_unquantize does for mainline:
  161. we repack the book in a fixed point format that shares the same
  162. binary point. Upon first use, we can shift point if needed */
  163. /* we need to deal with two map types: in map type 1, the values are
  164. generated algorithmically (each column of the vector counts through
  165. the values in the quant vector). in map type 2, all the values came
  166. in in an explicit list. Both value lists must be unpacked */
  167. ogg_int32_t *_book_unquantize(const static_codebook *b,int n,int *sparsemap,
  168. int *maxpoint){
  169. long j,k,count=0;
  170. if(b->maptype==1 || b->maptype==2){
  171. int quantvals;
  172. int minpoint,delpoint;
  173. ogg_int32_t mindel=_float32_unpack(b->q_min,&minpoint);
  174. ogg_int32_t delta=_float32_unpack(b->q_delta,&delpoint);
  175. ogg_int32_t *r=(ogg_int32_t *)_ogg_calloc(n*b->dim,sizeof(*r));
  176. int *rp=(int *)_ogg_calloc(n*b->dim,sizeof(*rp));
  177. *maxpoint=minpoint;
  178. /* maptype 1 and 2 both use a quantized value vector, but
  179. different sizes */
  180. switch(b->maptype){
  181. case 1:
  182. /* most of the time, entries%dimensions == 0, but we need to be
  183. well defined. We define that the possible vales at each
  184. scalar is values == entries/dim. If entries%dim != 0, we'll
  185. have 'too few' values (values*dim<entries), which means that
  186. we'll have 'left over' entries; left over entries use zeroed
  187. values (and are wasted). So don't generate codebooks like
  188. that */
  189. quantvals=_book_maptype1_quantvals(b);
  190. for(j=0;j<b->entries;j++){
  191. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  192. ogg_int32_t last=0;
  193. int lastpoint=0;
  194. int indexdiv=1;
  195. for(k=0;k<b->dim;k++){
  196. int index= (j/indexdiv)%quantvals;
  197. int point=0;
  198. int val=VFLOAT_MULTI(delta,delpoint,
  199. abs(b->quantlist[index]),&point);
  200. val=VFLOAT_ADD(mindel,minpoint,val,point,&point);
  201. val=VFLOAT_ADD(last,lastpoint,val,point,&point);
  202. if(b->q_sequencep){
  203. last=val;
  204. lastpoint=point;
  205. }
  206. if(sparsemap){
  207. r[sparsemap[count]*b->dim+k]=val;
  208. rp[sparsemap[count]*b->dim+k]=point;
  209. }else{
  210. r[count*b->dim+k]=val;
  211. rp[count*b->dim+k]=point;
  212. }
  213. if(*maxpoint<point)*maxpoint=point;
  214. indexdiv*=quantvals;
  215. }
  216. count++;
  217. }
  218. }
  219. break;
  220. case 2:
  221. for(j=0;j<b->entries;j++){
  222. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  223. ogg_int32_t last=0;
  224. int lastpoint=0;
  225. for(k=0;k<b->dim;k++){
  226. int point=0;
  227. int val=VFLOAT_MULTI(delta,delpoint,
  228. abs(b->quantlist[j*b->dim+k]),&point);
  229. val=VFLOAT_ADD(mindel,minpoint,val,point,&point);
  230. val=VFLOAT_ADD(last,lastpoint,val,point,&point);
  231. if(b->q_sequencep){
  232. last=val;
  233. lastpoint=point;
  234. }
  235. if(sparsemap){
  236. r[sparsemap[count]*b->dim+k]=val;
  237. rp[sparsemap[count]*b->dim+k]=point;
  238. }else{
  239. r[count*b->dim+k]=val;
  240. rp[count*b->dim+k]=point;
  241. }
  242. if(*maxpoint<point)*maxpoint=point;
  243. }
  244. count++;
  245. }
  246. }
  247. break;
  248. }
  249. for(j=0;j<n*b->dim;j++)
  250. if(rp[j]<*maxpoint)
  251. r[j]>>=*maxpoint-rp[j];
  252. _ogg_free(rp);
  253. return(r);
  254. }
  255. return(NULL);
  256. }
  257. void vorbis_staticbook_destroy(static_codebook *b){
  258. if(b->quantlist)_ogg_free(b->quantlist);
  259. if(b->lengthlist)_ogg_free(b->lengthlist);
  260. memset(b,0,sizeof(*b));
  261. _ogg_free(b);
  262. }
  263. void vorbis_book_clear(codebook *b){
  264. /* static book is not cleared; we're likely called on the lookup and
  265. the static codebook belongs to the info struct */
  266. if(b->valuelist)_ogg_free(b->valuelist);
  267. if(b->codelist)_ogg_free(b->codelist);
  268. if(b->dec_index)_ogg_free(b->dec_index);
  269. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  270. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  271. memset(b,0,sizeof(*b));
  272. }
  273. static ogg_uint32_t bitreverse(ogg_uint32_t x){
  274. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  275. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  276. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  277. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  278. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  279. }
  280. static int sort32a(const void *a,const void *b){
  281. return (**(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  282. (**(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  283. }
  284. /* decode codebook arrangement is more heavily optimized than encode */
  285. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  286. int i,j,n=0,tabn;
  287. int *sortindex;
  288. memset(c,0,sizeof(*c));
  289. /* count actually used entries */
  290. for(i=0;i<s->entries;i++)
  291. if(s->lengthlist[i]>0)
  292. n++;
  293. c->entries=s->entries;
  294. c->used_entries=n;
  295. c->dim=s->dim;
  296. if(n>0){
  297. /* two different remappings go on here.
  298. First, we collapse the likely sparse codebook down only to
  299. actually represented values/words. This collapsing needs to be
  300. indexed as map-valueless books are used to encode original entry
  301. positions as integers.
  302. Second, we reorder all vectors, including the entry index above,
  303. by sorted bitreversed codeword to allow treeless decode. */
  304. /* perform sort */
  305. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  306. ogg_uint32_t **codep=(ogg_uint32_t **)alloca(sizeof(*codep)*n);
  307. if(codes==NULL)goto err_out;
  308. for(i=0;i<n;i++){
  309. codes[i]=bitreverse(codes[i]);
  310. codep[i]=codes+i;
  311. }
  312. qsort(codep,n,sizeof(*codep),sort32a);
  313. sortindex=(int *)alloca(n*sizeof(*sortindex));
  314. c->codelist=(ogg_uint32_t *)_ogg_malloc(n*sizeof(*c->codelist));
  315. /* the index is a reverse index */
  316. for(i=0;i<n;i++){
  317. int position=codep[i]-codes;
  318. sortindex[position]=i;
  319. }
  320. for(i=0;i<n;i++)
  321. c->codelist[sortindex[i]]=codes[i];
  322. _ogg_free(codes);
  323. c->valuelist=_book_unquantize(s,n,sortindex,&c->binarypoint);
  324. c->dec_index=(int *)_ogg_malloc(n*sizeof(*c->dec_index));
  325. for(n=0,i=0;i<s->entries;i++)
  326. if(s->lengthlist[i]>0)
  327. c->dec_index[sortindex[n++]]=i;
  328. c->dec_codelengths=(char *)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  329. for(n=0,i=0;i<s->entries;i++)
  330. if(s->lengthlist[i]>0)
  331. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  332. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  333. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  334. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  335. tabn=1<<c->dec_firsttablen;
  336. c->dec_firsttable=(ogg_uint32_t *)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  337. c->dec_maxlength=0;
  338. for(i=0;i<n;i++){
  339. if(c->dec_maxlength<c->dec_codelengths[i])
  340. c->dec_maxlength=c->dec_codelengths[i];
  341. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  342. ogg_uint32_t orig=bitreverse(c->codelist[i]);
  343. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  344. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  345. }
  346. }
  347. /* now fill in 'unused' entries in the firsttable with hi/lo search
  348. hints for the non-direct-hits */
  349. {
  350. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  351. long lo=0,hi=0;
  352. for(i=0;i<tabn;i++){
  353. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  354. if(c->dec_firsttable[bitreverse(word)]==0){
  355. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  356. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  357. /* we only actually have 15 bits per hint to play with here.
  358. In order to overflow gracefully (nothing breaks, efficiency
  359. just drops), encode as the difference from the extremes. */
  360. {
  361. unsigned long loval=lo;
  362. unsigned long hival=n-hi;
  363. if(loval>0x7fff)loval=0x7fff;
  364. if(hival>0x7fff)hival=0x7fff;
  365. c->dec_firsttable[bitreverse(word)]=
  366. 0x80000000UL | (loval<<15) | hival;
  367. }
  368. }
  369. }
  370. }
  371. }
  372. return(0);
  373. err_out:
  374. vorbis_book_clear(c);
  375. return(-1);
  376. }