huffdec.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggTheora 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 Theora SOURCE CODE IS COPYRIGHT (C) 2002-2009 *
  9. * by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function:
  13. last mod: $Id$
  14. ********************************************************************/
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <ogg/ogg.h>
  18. #include "huffdec.h"
  19. #include "decint.h"
  20. /*Instead of storing every branching in the tree, subtrees can be collapsed
  21. into one node, with a table of size 1<<nbits pointing directly to its
  22. descedents nbits levels down.
  23. This allows more than one bit to be read at a time, and avoids following all
  24. the intermediate branches with next to no increased code complexity once
  25. the collapsed tree has been built.
  26. We do _not_ require that a subtree be complete to be collapsed, but instead
  27. store duplicate pointers in the table, and record the actual depth of the
  28. node below its parent.
  29. This tells us the number of bits to advance the stream after reaching it.
  30. This turns out to be equivalent to the method described in \cite{Hash95},
  31. without the requirement that codewords be sorted by length.
  32. If the codewords were sorted by length (so-called ``canonical-codes''), they
  33. could be decoded much faster via either Lindell and Moffat's approach or
  34. Hashemian's Condensed Huffman Code approach, the latter of which has an
  35. extremely small memory footprint.
  36. We can't use Choueka et al.'s finite state machine approach, which is
  37. extremely fast, because we can't allow multiple symbols to be output at a
  38. time; the codebook can and does change between symbols.
  39. It also has very large memory requirements, which impairs cache coherency.
  40. We store the tree packed in an array of 16-bit integers (words).
  41. Each node consists of a single word, followed consecutively by two or more
  42. indices of its children.
  43. Let n be the value of this first word.
  44. This is the number of bits that need to be read to traverse the node, and
  45. must be positive.
  46. 1<<n entries follow in the array, each an index to a child node.
  47. If the child is positive, then it is the index of another internal node in
  48. the table.
  49. If the child is negative or zero, then it is a leaf node.
  50. These are stored directly in the child pointer to save space, since they only
  51. require a single word.
  52. If a leaf node would have been encountered before reading n bits, then it is
  53. duplicated the necessary number of times in this table.
  54. Leaf nodes pack both a token value and their actual depth in the tree.
  55. The token in the leaf node is (-leaf&255).
  56. The number of bits that need to be consumed to reach the leaf, starting from
  57. the current node, is (-leaf>>8).
  58. @ARTICLE{Hash95,
  59. author="Reza Hashemian",
  60. title="Memory Efficient and High-Speed Search {Huffman} Coding",
  61. journal="{IEEE} Transactions on Communications",
  62. volume=43,
  63. number=10,
  64. pages="2576--2581",
  65. month=Oct,
  66. year=1995
  67. }*/
  68. /*The map from external spec-defined tokens to internal tokens.
  69. This is constructed so that any extra bits read with the original token value
  70. can be masked off the least significant bits of its internal token index.
  71. In addition, all of the tokens which require additional extra bits are placed
  72. at the start of the list, and grouped by type.
  73. OC_DCT_REPEAT_RUN3_TOKEN is placed first, as it is an extra-special case, so
  74. giving it index 0 may simplify comparisons on some architectures.
  75. These requirements require some substantial reordering.*/
  76. static const unsigned char OC_DCT_TOKEN_MAP[TH_NDCT_TOKENS]={
  77. /*OC_DCT_EOB1_TOKEN (0 extra bits)*/
  78. 15,
  79. /*OC_DCT_EOB2_TOKEN (0 extra bits)*/
  80. 16,
  81. /*OC_DCT_EOB3_TOKEN (0 extra bits)*/
  82. 17,
  83. /*OC_DCT_REPEAT_RUN0_TOKEN (2 extra bits)*/
  84. 88,
  85. /*OC_DCT_REPEAT_RUN1_TOKEN (3 extra bits)*/
  86. 80,
  87. /*OC_DCT_REPEAT_RUN2_TOKEN (4 extra bits)*/
  88. 1,
  89. /*OC_DCT_REPEAT_RUN3_TOKEN (12 extra bits)*/
  90. 0,
  91. /*OC_DCT_SHORT_ZRL_TOKEN (3 extra bits)*/
  92. 48,
  93. /*OC_DCT_ZRL_TOKEN (6 extra bits)*/
  94. 14,
  95. /*OC_ONE_TOKEN (0 extra bits)*/
  96. 56,
  97. /*OC_MINUS_ONE_TOKEN (0 extra bits)*/
  98. 57,
  99. /*OC_TWO_TOKEN (0 extra bits)*/
  100. 58,
  101. /*OC_MINUS_TWO_TOKEN (0 extra bits)*/
  102. 59,
  103. /*OC_DCT_VAL_CAT2 (1 extra bit)*/
  104. 60,
  105. 62,
  106. 64,
  107. 66,
  108. /*OC_DCT_VAL_CAT3 (2 extra bits)*/
  109. 68,
  110. /*OC_DCT_VAL_CAT4 (3 extra bits)*/
  111. 72,
  112. /*OC_DCT_VAL_CAT5 (4 extra bits)*/
  113. 2,
  114. /*OC_DCT_VAL_CAT6 (5 extra bits)*/
  115. 4,
  116. /*OC_DCT_VAL_CAT7 (6 extra bits)*/
  117. 6,
  118. /*OC_DCT_VAL_CAT8 (10 extra bits)*/
  119. 8,
  120. /*OC_DCT_RUN_CAT1A (1 extra bit)*/
  121. 18,
  122. 20,
  123. 22,
  124. 24,
  125. 26,
  126. /*OC_DCT_RUN_CAT1B (3 extra bits)*/
  127. 32,
  128. /*OC_DCT_RUN_CAT1C (4 extra bits)*/
  129. 12,
  130. /*OC_DCT_RUN_CAT2A (2 extra bits)*/
  131. 28,
  132. /*OC_DCT_RUN_CAT2B (3 extra bits)*/
  133. 40
  134. };
  135. /*The log base 2 of number of internal tokens associated with each of the spec
  136. tokens (i.e., how many of the extra bits are folded into the token value).
  137. Increasing the maximum value beyond 3 will enlarge the amount of stack
  138. required for tree construction.*/
  139. static const unsigned char OC_DCT_TOKEN_MAP_LOG_NENTRIES[TH_NDCT_TOKENS]={
  140. 0,0,0,2,3,0,0,3,0,0,0,0,0,1,1,1,1,2,3,1,1,1,2,1,1,1,1,1,3,1,2,3
  141. };
  142. /*The size a lookup table is allowed to grow to relative to the number of
  143. unique nodes it contains.
  144. E.g., if OC_HUFF_SLUSH is 4, then at most 75% of the space in the tree is
  145. wasted (1/4 of the space must be used).
  146. Larger numbers can decode tokens with fewer read operations, while smaller
  147. numbers may save more space.
  148. With a sample file:
  149. 32233473 read calls are required when no tree collapsing is done (100.0%).
  150. 19269269 read calls are required when OC_HUFF_SLUSH is 1 (59.8%).
  151. 11144969 read calls are required when OC_HUFF_SLUSH is 2 (34.6%).
  152. 10538563 read calls are required when OC_HUFF_SLUSH is 4 (32.7%).
  153. 10192578 read calls are required when OC_HUFF_SLUSH is 8 (31.6%).
  154. Since a value of 2 gets us the vast majority of the speed-up with only a
  155. small amount of wasted memory, this is what we use.
  156. This value must be less than 128, or you could create a tree with more than
  157. 32767 entries, which would overflow the 16-bit words used to index it.*/
  158. #define OC_HUFF_SLUSH (2)
  159. /*The root of the tree is on the fast path, and a larger value here is more
  160. beneficial than elsewhere in the tree.
  161. 7 appears to give the best performance, trading off between increased use of
  162. the single-read fast path and cache footprint for the tables, though
  163. obviously this will depend on your cache size.
  164. Using 7 here, the VP3 tables are about twice as large compared to using 2.*/
  165. #define OC_ROOT_HUFF_SLUSH (7)
  166. /*Unpacks a Huffman codebook.
  167. _opb: The buffer to unpack from.
  168. _tokens: Stores a list of internal tokens, in the order they were found in
  169. the codebook, and the lengths of their corresponding codewords.
  170. This is enough to completely define the codebook, while minimizing
  171. stack usage and avoiding temporary allocations (for platforms
  172. where free() is a no-op).
  173. Return: The number of internal tokens in the codebook, or a negative value
  174. on error.*/
  175. int oc_huff_tree_unpack(oc_pack_buf *_opb,unsigned char _tokens[256][2]){
  176. ogg_uint32_t code;
  177. int len;
  178. int ntokens;
  179. int nleaves;
  180. code=0;
  181. len=ntokens=nleaves=0;
  182. for(;;){
  183. long bits;
  184. bits=oc_pack_read1(_opb);
  185. /*Only process nodes so long as there's more bits in the buffer.*/
  186. if(oc_pack_bytes_left(_opb)<0)return TH_EBADHEADER;
  187. /*Read an internal node:*/
  188. if(!bits){
  189. len++;
  190. /*Don't allow codewords longer than 32 bits.*/
  191. if(len>32)return TH_EBADHEADER;
  192. }
  193. /*Read a leaf node:*/
  194. else{
  195. ogg_uint32_t code_bit;
  196. int neb;
  197. int nentries;
  198. int token;
  199. /*Don't allow more than 32 spec-tokens per codebook.*/
  200. if(++nleaves>32)return TH_EBADHEADER;
  201. bits=oc_pack_read(_opb,OC_NDCT_TOKEN_BITS);
  202. neb=OC_DCT_TOKEN_MAP_LOG_NENTRIES[bits];
  203. token=OC_DCT_TOKEN_MAP[bits];
  204. nentries=1<<neb;
  205. while(nentries-->0){
  206. _tokens[ntokens][0]=(unsigned char)token++;
  207. _tokens[ntokens][1]=(unsigned char)(len+neb);
  208. ntokens++;
  209. }
  210. code_bit=0x80000000U>>len-1;
  211. while(len>0&&(code&code_bit)){
  212. code^=code_bit;
  213. code_bit<<=1;
  214. len--;
  215. }
  216. if(len<=0)break;
  217. code|=code_bit;
  218. }
  219. }
  220. return ntokens;
  221. }
  222. /*Count how many tokens would be required to fill a subtree at depth _depth.
  223. _tokens: A list of internal tokens, in the order they are found in the
  224. codebook, and the lengths of their corresponding codewords.
  225. _depth: The depth of the desired node in the corresponding tree structure.
  226. Return: The number of tokens that belong to that subtree.*/
  227. static int oc_huff_subtree_tokens(unsigned char _tokens[][2],int _depth){
  228. ogg_uint32_t code;
  229. int ti;
  230. code=0;
  231. ti=0;
  232. do{
  233. if(_tokens[ti][1]-_depth<32)code+=0x80000000U>>_tokens[ti++][1]-_depth;
  234. else{
  235. /*Because of the expanded internal tokens, we can have codewords as long
  236. as 35 bits.
  237. A single recursion here is enough to advance past them.*/
  238. code++;
  239. ti+=oc_huff_subtree_tokens(_tokens+ti,_depth+31);
  240. }
  241. }
  242. while(code<0x80000000U);
  243. return ti;
  244. }
  245. /*Compute the number of bits to use for a collapsed tree node at the given
  246. depth.
  247. _tokens: A list of internal tokens, in the order they are found in the
  248. codebook, and the lengths of their corresponding codewords.
  249. _ntokens: The number of tokens corresponding to this tree node.
  250. _depth: The depth of this tree node.
  251. Return: The number of bits to use for a collapsed tree node rooted here.
  252. This is always at least one, even if this was a leaf node.*/
  253. static int oc_huff_tree_collapse_depth(unsigned char _tokens[][2],
  254. int _ntokens,int _depth){
  255. int got_leaves;
  256. int loccupancy;
  257. int occupancy;
  258. int slush;
  259. int nbits;
  260. int best_nbits;
  261. slush=_depth>0?OC_HUFF_SLUSH:OC_ROOT_HUFF_SLUSH;
  262. /*It's legal to have a tree with just a single node, which requires no bits
  263. to decode and always returns the same token.
  264. However, no encoder actually does this (yet).
  265. To avoid a special case in oc_huff_token_decode(), we force the number of
  266. lookahead bits to be at least one.
  267. This will produce a tree that looks ahead one bit and then advances the
  268. stream zero bits.*/
  269. nbits=1;
  270. occupancy=2;
  271. got_leaves=1;
  272. do{
  273. int ti;
  274. if(got_leaves)best_nbits=nbits;
  275. nbits++;
  276. got_leaves=0;
  277. loccupancy=occupancy;
  278. for(occupancy=ti=0;ti<_ntokens;occupancy++){
  279. if(_tokens[ti][1]<_depth+nbits)ti++;
  280. else if(_tokens[ti][1]==_depth+nbits){
  281. got_leaves=1;
  282. ti++;
  283. }
  284. else ti+=oc_huff_subtree_tokens(_tokens+ti,_depth+nbits);
  285. }
  286. }
  287. while(occupancy>loccupancy&&occupancy*slush>=1<<nbits);
  288. return best_nbits;
  289. }
  290. /*Determines the size in words of a Huffman tree node that represents a
  291. subtree of depth _nbits.
  292. _nbits: The depth of the subtree.
  293. This must be greater than zero.
  294. Return: The number of words required to store the node.*/
  295. static size_t oc_huff_node_size(int _nbits){
  296. return 1+(1<<_nbits);
  297. }
  298. /*Produces a collapsed-tree representation of the given token list.
  299. _tree: The storage for the collapsed Huffman tree.
  300. This may be NULL to compute the required storage size instead of
  301. constructing the tree.
  302. _tokens: A list of internal tokens, in the order they are found in the
  303. codebook, and the lengths of their corresponding codewords.
  304. _ntokens: The number of tokens corresponding to this tree node.
  305. Return: The number of words required to store the tree.*/
  306. static size_t oc_huff_tree_collapse(ogg_int16_t *_tree,
  307. unsigned char _tokens[][2],int _ntokens){
  308. ogg_int16_t node[34];
  309. unsigned char depth[34];
  310. unsigned char last[34];
  311. size_t ntree;
  312. int ti;
  313. int l;
  314. depth[0]=0;
  315. last[0]=(unsigned char)(_ntokens-1);
  316. ntree=0;
  317. ti=0;
  318. l=0;
  319. do{
  320. int nbits;
  321. nbits=oc_huff_tree_collapse_depth(_tokens+ti,last[l]+1-ti,depth[l]);
  322. node[l]=(ogg_int16_t)ntree;
  323. ntree+=oc_huff_node_size(nbits);
  324. if(_tree!=NULL)_tree[node[l]++]=(ogg_int16_t)nbits;
  325. do{
  326. while(ti<=last[l]&&_tokens[ti][1]<=depth[l]+nbits){
  327. if(_tree!=NULL){
  328. ogg_int16_t leaf;
  329. int nentries;
  330. nentries=1<<depth[l]+nbits-_tokens[ti][1];
  331. leaf=(ogg_int16_t)-(_tokens[ti][1]-depth[l]<<8|_tokens[ti][0]);
  332. while(nentries-->0)_tree[node[l]++]=leaf;
  333. }
  334. ti++;
  335. }
  336. if(ti<=last[l]){
  337. /*We need to recurse*/
  338. depth[l+1]=(unsigned char)(depth[l]+nbits);
  339. if(_tree!=NULL)_tree[node[l]++]=(ogg_int16_t)ntree;
  340. l++;
  341. last[l]=
  342. (unsigned char)(ti+oc_huff_subtree_tokens(_tokens+ti,depth[l])-1);
  343. break;
  344. }
  345. /*Pop back up a level of recursion.*/
  346. else if(l-->0)nbits=depth[l+1]-depth[l];
  347. }
  348. while(l>=0);
  349. }
  350. while(l>=0);
  351. return ntree;
  352. }
  353. /*Unpacks a set of Huffman trees, and reduces them to a collapsed
  354. representation.
  355. _opb: The buffer to unpack the trees from.
  356. _nodes: The table to fill with the Huffman trees.
  357. Return: 0 on success, or a negative value on error.
  358. The caller is responsible for cleaning up any partially initialized
  359. _nodes on failure.*/
  360. int oc_huff_trees_unpack(oc_pack_buf *_opb,
  361. ogg_int16_t *_nodes[TH_NHUFFMAN_TABLES]){
  362. int i;
  363. for(i=0;i<TH_NHUFFMAN_TABLES;i++){
  364. unsigned char tokens[256][2];
  365. int ntokens;
  366. ogg_int16_t *tree;
  367. size_t size;
  368. /*Unpack the full tree into a temporary buffer.*/
  369. ntokens=oc_huff_tree_unpack(_opb,tokens);
  370. if(ntokens<0)return ntokens;
  371. /*Figure out how big the collapsed tree will be and allocate space for it.*/
  372. size=oc_huff_tree_collapse(NULL,tokens,ntokens);
  373. /*This should never happen; if it does it means you set OC_HUFF_SLUSH or
  374. OC_ROOT_HUFF_SLUSH too large.*/
  375. if(size>32767)return TH_EIMPL;
  376. tree=(ogg_int16_t *)_ogg_malloc(size*sizeof(*tree));
  377. if(tree==NULL)return TH_EFAULT;
  378. /*Construct the collapsed the tree.*/
  379. oc_huff_tree_collapse(tree,tokens,ntokens);
  380. _nodes[i]=tree;
  381. }
  382. return 0;
  383. }
  384. /*Determines the size in words of a Huffman subtree.
  385. _tree: The complete Huffman tree.
  386. _node: The index of the root of the desired subtree.
  387. Return: The number of words required to store the tree.*/
  388. static size_t oc_huff_tree_size(const ogg_int16_t *_tree,int _node){
  389. size_t size;
  390. int nchildren;
  391. int n;
  392. int i;
  393. n=_tree[_node];
  394. size=oc_huff_node_size(n);
  395. nchildren=1<<n;
  396. i=0;
  397. do{
  398. int child;
  399. child=_tree[_node+i+1];
  400. if(child<=0)i+=1<<n-(-child>>8);
  401. else{
  402. size+=oc_huff_tree_size(_tree,child);
  403. i++;
  404. }
  405. }
  406. while(i<nchildren);
  407. return size;
  408. }
  409. /*Makes a copy of the given set of Huffman trees.
  410. _dst: The array to store the copy in.
  411. _src: The array of trees to copy.*/
  412. int oc_huff_trees_copy(ogg_int16_t *_dst[TH_NHUFFMAN_TABLES],
  413. const ogg_int16_t *const _src[TH_NHUFFMAN_TABLES]){
  414. int total;
  415. int i;
  416. total=0;
  417. for(i=0;i<TH_NHUFFMAN_TABLES;i++){
  418. size_t size;
  419. size=oc_huff_tree_size(_src[i],0);
  420. total+=size;
  421. _dst[i]=(ogg_int16_t *)_ogg_malloc(size*sizeof(*_dst[i]));
  422. if(_dst[i]==NULL){
  423. while(i-->0)_ogg_free(_dst[i]);
  424. return TH_EFAULT;
  425. }
  426. memcpy(_dst[i],_src[i],size*sizeof(*_dst[i]));
  427. }
  428. return 0;
  429. }
  430. /*Frees the memory used by a set of Huffman trees.
  431. _nodes: The array of trees to free.*/
  432. void oc_huff_trees_clear(ogg_int16_t *_nodes[TH_NHUFFMAN_TABLES]){
  433. int i;
  434. for(i=0;i<TH_NHUFFMAN_TABLES;i++)_ogg_free(_nodes[i]);
  435. }
  436. /*Unpacks a single token using the given Huffman tree.
  437. _opb: The buffer to unpack the token from.
  438. _node: The tree to unpack the token with.
  439. Return: The token value.*/
  440. int oc_huff_token_decode_c(oc_pack_buf *_opb,const ogg_int16_t *_tree){
  441. const unsigned char *ptr;
  442. const unsigned char *stop;
  443. oc_pb_window window;
  444. int available;
  445. long bits;
  446. int node;
  447. int n;
  448. ptr=_opb->ptr;
  449. window=_opb->window;
  450. stop=_opb->stop;
  451. available=_opb->bits;
  452. node=0;
  453. for(;;){
  454. n=_tree[node];
  455. if(n>available){
  456. unsigned shift;
  457. shift=OC_PB_WINDOW_SIZE-available;
  458. do{
  459. /*We don't bother setting eof because we won't check for it after we've
  460. started decoding DCT tokens.*/
  461. if(ptr>=stop){
  462. shift=(unsigned)-OC_LOTS_OF_BITS;
  463. break;
  464. }
  465. shift-=8;
  466. window|=(oc_pb_window)*ptr++<<shift;
  467. }
  468. while(shift>=8);
  469. /*Note: We never request more than 24 bits, so there's no need to fill in
  470. the last partial byte here.*/
  471. available=OC_PB_WINDOW_SIZE-shift;
  472. }
  473. bits=window>>OC_PB_WINDOW_SIZE-n;
  474. node=_tree[node+1+bits];
  475. if(node<=0)break;
  476. window<<=n;
  477. available-=n;
  478. }
  479. node=-node;
  480. n=node>>8;
  481. window<<=n;
  482. available-=n;
  483. _opb->ptr=ptr;
  484. _opb->window=window;
  485. _opb->bits=available;
  486. return node&255;
  487. }