the tree representation used by the decoder. return value is error*/
| 521 | |
| 522 | /*the tree representation used by the decoder. return value is error*/ |
| 523 | static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) |
| 524 | { |
| 525 | unsigned nodefilled = 0; /*up to which node it is filled*/ |
| 526 | unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ |
| 527 | unsigned n, i; |
| 528 | |
| 529 | tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned)); |
| 530 | if(!tree->tree2d) return 83; /*alloc fail*/ |
| 531 | |
| 532 | /* |
| 533 | convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means |
| 534 | uninited, a value >= numcodes is an address to another bit, a value < numcodes |
| 535 | is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as |
| 536 | many columns as codes - 1. |
| 537 | A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. |
| 538 | Here, the internal nodes are stored (what their 0 and 1 option point to). |
| 539 | There is only memory for such good tree currently, if there are more nodes |
| 540 | (due to too long length codes), error 55 will happen |
| 541 | */ |
| 542 | for(n = 0; n < tree->numcodes * 2; n++) |
| 543 | { |
| 544 | tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ |
| 545 | } |
| 546 | |
| 547 | for(n = 0; n < tree->numcodes; n++) /*the codes*/ |
| 548 | { |
| 549 | for(i = 0; i < tree->lengths[n]; i++) /*the bits for this code*/ |
| 550 | { |
| 551 | unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); |
| 552 | if(treepos > tree->numcodes - 2) return 55; /*oversubscribed, see comment in lodepng_error_text*/ |
| 553 | if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ |
| 554 | { |
| 555 | if(i + 1 == tree->lengths[n]) /*last bit*/ |
| 556 | { |
| 557 | tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ |
| 558 | treepos = 0; |
| 559 | } |
| 560 | else |
| 561 | { |
| 562 | /*put address of the next step in here, first that address has to be found of course |
| 563 | (it's just nodefilled + 1)...*/ |
| 564 | nodefilled++; |
| 565 | /*addresses encoded with numcodes added to it*/ |
| 566 | tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; |
| 567 | treepos = nodefilled; |
| 568 | } |
| 569 | } |
| 570 | else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes; |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | for(n = 0; n < tree->numcodes * 2; n++) |
| 575 | { |
| 576 | if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ |
| 577 | } |
| 578 | |
| 579 | return 0; |
| 580 | } |
no test coverage detected