Path: blob/a-new-beginning/SharedDependencies/Sources/libchdr/huffman.c
2 views
/* license:BSD-3-Clause1* copyright-holders:Aaron Giles2****************************************************************************34huffman.c56Static Huffman compression and decompression helpers.78****************************************************************************910Maximum codelength is officially (alphabetsize - 1). This would be 255 bits11(since we use 1 byte values). However, it is also dependent upon the number12of samples used, as follows:13142 bits -> 3..4 samples153 bits -> 5..7 samples164 bits -> 8..12 samples175 bits -> 13..20 samples186 bits -> 21..33 samples197 bits -> 34..54 samples208 bits -> 55..88 samples219 bits -> 89..143 samples2210 bits -> 144..232 samples2311 bits -> 233..376 samples2412 bits -> 377..609 samples2513 bits -> 610..986 samples2614 bits -> 987..1596 samples2715 bits -> 1597..2583 samples2816 bits -> 2584..4180 samples -> note that a 4k data size guarantees codelength <= 16 bits2917 bits -> 4181..6764 samples3018 bits -> 6765..10945 samples3119 bits -> 10946..17710 samples3220 bits -> 17711..28656 samples3321 bits -> 28657..46367 samples3422 bits -> 46368..75024 samples3523 bits -> 75025..121392 samples3624 bits -> 121393..196417 samples3725 bits -> 196418..317810 samples3826 bits -> 317811..514228 samples3927 bits -> 514229..832039 samples4028 bits -> 832040..1346268 samples4129 bits -> 1346269..2178308 samples4230 bits -> 2178309..3524577 samples4331 bits -> 3524578..5702886 samples4432 bits -> 5702887..9227464 samples4546Looking at it differently, here is where powers of 2 fall into these buckets:4748256 samples -> 11 bits max49512 samples -> 12 bits max501k samples -> 14 bits max512k samples -> 15 bits max524k samples -> 16 bits max538k samples -> 18 bits max5416k samples -> 19 bits max5532k samples -> 21 bits max5664k samples -> 22 bits max57128k samples -> 24 bits max58256k samples -> 25 bits max59512k samples -> 27 bits max601M samples -> 28 bits max612M samples -> 29 bits max624M samples -> 31 bits max638M samples -> 32 bits max6465****************************************************************************6667Delta-RLE encoding works as follows:6869Starting value is assumed to be 0. All data is encoded as a delta70from the previous value, such that final[i] = final[i - 1] + delta.71Long runs of 0s are RLE-encoded as follows:72730x100 = repeat count of 8740x101 = repeat count of 9750x102 = repeat count of 10760x103 = repeat count of 11770x104 = repeat count of 12780x105 = repeat count of 13790x106 = repeat count of 14800x107 = repeat count of 15810x108 = repeat count of 16820x109 = repeat count of 32830x10a = repeat count of 64840x10b = repeat count of 128850x10c = repeat count of 256860x10d = repeat count of 512870x10e = repeat count of 1024880x10f = repeat count of 20488990Note that repeat counts are reset at the end of a row, so if a 0 run91extends to the end of a row, a large repeat count may be used.9293The reason for starting the run counts at 8 is that 0 is expected to94be the most common symbol, and is typically encoded in 1 or 2 bits.9596***************************************************************************/9798#include <stdlib.h>99#include <assert.h>100#include <stdio.h>101#include <string.h>102103#include "huffman.h"104105#define MAX(x,y) ((x) > (y) ? (x) : (y))106107/***************************************************************************108* MACROS109***************************************************************************110*/111112#define MAKE_LOOKUP(code,bits) (((code) << 5) | ((bits) & 0x1f))113114/***************************************************************************115* IMPLEMENTATION116***************************************************************************117*/118119/*-------------------------------------------------120* huffman_context_base - create an encoding/121* decoding context122*-------------------------------------------------123*/124125struct huffman_decoder* create_huffman_decoder(int numcodes, int maxbits)126{127/* limit to 24 bits */128if (maxbits > 24)129return NULL;130131struct huffman_decoder* decoder = (struct huffman_decoder*)malloc(sizeof(struct huffman_decoder));132decoder->numcodes = numcodes;133decoder->maxbits = maxbits;134decoder->lookup = (lookup_value*)malloc(sizeof(lookup_value) * (1 << maxbits));135decoder->huffnode = (struct node_t*)malloc(sizeof(struct node_t) * numcodes);136decoder->datahisto = NULL;137decoder->prevdata = 0;138decoder->rleremaining = 0;139return decoder;140}141142/*-------------------------------------------------143* decode_one - decode a single code from the144* huffman stream145*-------------------------------------------------146*/147148uint32_t huffman_decode_one(struct huffman_decoder* decoder, struct bitstream* bitbuf)149{150/* peek ahead to get maxbits worth of data */151uint32_t bits = bitstream_peek(bitbuf, decoder->maxbits);152153/* look it up, then remove the actual number of bits for this code */154lookup_value lookup = decoder->lookup[bits];155bitstream_remove(bitbuf, lookup & 0x1f);156157/* return the value */158return lookup >> 5;159}160161/*-------------------------------------------------162* import_tree_rle - import an RLE-encoded163* huffman tree from a source data stream164*-------------------------------------------------165*/166167enum huffman_error huffman_import_tree_rle(struct huffman_decoder* decoder, struct bitstream* bitbuf)168{169/* bits per entry depends on the maxbits */170int numbits;171if (decoder->maxbits >= 16)172numbits = 5;173else if (decoder->maxbits >= 8)174numbits = 4;175else176numbits = 3;177178/* loop until we read all the nodes */179int curnode;180for (curnode = 0; curnode < decoder->numcodes; )181{182/* a non-one value is just raw */183int nodebits = bitstream_read(bitbuf, numbits);184if (nodebits != 1)185decoder->huffnode[curnode++].numbits = nodebits;186187/* a one value is an escape code */188else189{190/* a double 1 is just a single 1 */191nodebits = bitstream_read(bitbuf, numbits);192if (nodebits == 1)193decoder->huffnode[curnode++].numbits = nodebits;194195/* otherwise, we need one for value for the repeat count */196else197{198int repcount = bitstream_read(bitbuf, numbits) + 3;199while (repcount--)200decoder->huffnode[curnode++].numbits = nodebits;201}202}203}204205/* make sure we ended up with the right number */206if (curnode != decoder->numcodes)207return HUFFERR_INVALID_DATA;208209/* assign canonical codes for all nodes based on their code lengths */210enum huffman_error error = huffman_assign_canonical_codes(decoder);211if (error != HUFFERR_NONE)212return error;213214/* build the lookup table */215huffman_build_lookup_table(decoder);216217/* determine final input length and report errors */218return bitstream_overflow(bitbuf) ? HUFFERR_INPUT_BUFFER_TOO_SMALL : HUFFERR_NONE;219}220221222/*-------------------------------------------------223* import_tree_huffman - import a huffman-encoded224* huffman tree from a source data stream225*-------------------------------------------------226*/227228enum huffman_error huffman_import_tree_huffman(struct huffman_decoder* decoder, struct bitstream* bitbuf)229{230/* start by parsing the lengths for the small tree */231struct huffman_decoder* smallhuff = create_huffman_decoder(24, 6);232smallhuff->huffnode[0].numbits = bitstream_read(bitbuf, 3);233int start = bitstream_read(bitbuf, 3) + 1;234int count = 0;235for (int index = 1; index < 24; index++)236{237if (index < start || count == 7)238smallhuff->huffnode[index].numbits = 0;239else240{241count = bitstream_read(bitbuf, 3);242smallhuff->huffnode[index].numbits = (count == 7) ? 0 : count;243}244}245246/* then regenerate the tree */247enum huffman_error error = huffman_assign_canonical_codes(smallhuff);248if (error != HUFFERR_NONE)249return error;250huffman_build_lookup_table(smallhuff);251252/* determine the maximum length of an RLE count */253uint32_t temp = decoder->numcodes - 9;254uint8_t rlefullbits = 0;255while (temp != 0)256temp >>= 1, rlefullbits++;257258/* now process the rest of the data */259int last = 0;260int curcode;261for (curcode = 0; curcode < decoder->numcodes; )262{263int value = huffman_decode_one(smallhuff, bitbuf);264if (value != 0)265decoder->huffnode[curcode++].numbits = last = value - 1;266else267{268int count = bitstream_read(bitbuf, 3) + 2;269if (count == 7+2)270count += bitstream_read(bitbuf, rlefullbits);271for ( ; count != 0 && curcode < decoder->numcodes; count--)272decoder->huffnode[curcode++].numbits = last;273}274}275276/* make sure we ended up with the right number */277if (curcode != decoder->numcodes)278return HUFFERR_INVALID_DATA;279280/* assign canonical codes for all nodes based on their code lengths */281error = huffman_assign_canonical_codes(decoder);282if (error != HUFFERR_NONE)283return error;284285/* build the lookup table */286huffman_build_lookup_table(decoder);287288/* determine final input length and report errors */289return bitstream_overflow(bitbuf) ? HUFFERR_INPUT_BUFFER_TOO_SMALL : HUFFERR_NONE;290}291292/*-------------------------------------------------293* compute_tree_from_histo - common backend for294* computing a tree based on the data histogram295*-------------------------------------------------296*/297298enum huffman_error huffman_compute_tree_from_histo(struct huffman_decoder* decoder)299{300/* compute the number of data items in the histogram */301uint32_t sdatacount = 0;302for (int i = 0; i < decoder->numcodes; i++)303sdatacount += decoder->datahisto[i];304305/* binary search to achieve the optimum encoding */306uint32_t lowerweight = 0;307uint32_t upperweight = sdatacount * 2;308while (1)309{310/* build a tree using the current weight */311uint32_t curweight = (upperweight + lowerweight) / 2;312int curmaxbits = huffman_build_tree(decoder, sdatacount, curweight);313314/* apply binary search here */315if (curmaxbits <= decoder->maxbits)316{317lowerweight = curweight;318319/* early out if it worked with the raw weights, or if we're done searching */320if (curweight == sdatacount || (upperweight - lowerweight) <= 1)321break;322}323else324upperweight = curweight;325}326327/* assign canonical codes for all nodes based on their code lengths */328return huffman_assign_canonical_codes(decoder);329}330331/***************************************************************************332* INTERNAL FUNCTIONS333***************************************************************************334*/335336/*-------------------------------------------------337* tree_node_compare - compare two tree nodes338* by weight339*-------------------------------------------------340*/341342static int huffman_tree_node_compare(const void *item1, const void *item2)343{344const struct node_t *node1 = *(const struct node_t **)item1;345const struct node_t *node2 = *(const struct node_t **)item2;346if (node2->weight != node1->weight)347return node2->weight - node1->weight;348if (node2->bits - node1->bits == 0)349fprintf(stderr, "identical node sort keys, should not happen!\n");350return (int)node1->bits - (int)node2->bits;351}352353/*-------------------------------------------------354* build_tree - build a huffman tree based on the355* data distribution356*-------------------------------------------------357*/358359int huffman_build_tree(struct huffman_decoder* decoder, uint32_t totaldata, uint32_t totalweight)360{361/* make a list of all non-zero nodes */362struct node_t** list = (struct node_t**)malloc(sizeof(struct node_t*) * decoder->numcodes * 2);363int listitems = 0;364memset(decoder->huffnode, 0, decoder->numcodes * sizeof(decoder->huffnode[0]));365for (int curcode = 0; curcode < decoder->numcodes; curcode++)366if (decoder->datahisto[curcode] != 0)367{368list[listitems++] = &decoder->huffnode[curcode];369decoder->huffnode[curcode].count = decoder->datahisto[curcode];370decoder->huffnode[curcode].bits = curcode;371372/* scale the weight by the current effective length, ensuring we don't go to 0 */373decoder->huffnode[curcode].weight = ((uint64_t)decoder->datahisto[curcode]) * ((uint64_t)totalweight) / ((uint64_t)totaldata);374if (decoder->huffnode[curcode].weight == 0)375decoder->huffnode[curcode].weight = 1;376}377378#if 0379fprintf(stderr, "Pre-sort:\n");380for (int i = 0; i < listitems; i++) {381fprintf(stderr, "weight: %d code: %d\n", list[i]->m_weight, list[i]->m_bits);382}383#endif384385/* sort the list by weight, largest weight first */386qsort(&list[0], listitems, sizeof(list[0]), huffman_tree_node_compare);387388#if 0389fprintf(stderr, "Post-sort:\n");390for (int i = 0; i < listitems; i++) {391fprintf(stderr, "weight: %d code: %d\n", list[i]->m_weight, list[i]->m_bits);392}393fprintf(stderr, "===================\n");394#endif395396/* now build the tree */397int nextalloc = decoder->numcodes;398while (listitems > 1)399{400/* remove lowest two items */401struct node_t* node1 = &(*list[--listitems]);402struct node_t* node0 = &(*list[--listitems]);403404/* create new node */405struct node_t* newnode = &decoder->huffnode[nextalloc++];406newnode->parent = NULL;407node0->parent = node1->parent = newnode;408newnode->weight = node0->weight + node1->weight;409410/* insert into list at appropriate location */411int curitem;412for (curitem = 0; curitem < listitems; curitem++)413if (newnode->weight > list[curitem]->weight)414{415memmove(&list[curitem+1], &list[curitem], (listitems - curitem) * sizeof(list[0]));416break;417}418list[curitem] = newnode;419listitems++;420}421422/* compute the number of bits in each code, and fill in another histogram */423int maxbits = 0;424for (int curcode = 0; curcode < decoder->numcodes; curcode++)425{426struct node_t* node = &decoder->huffnode[curcode];427node->numbits = 0;428node->bits = 0;429430/* if we have a non-zero weight, compute the number of bits */431if (node->weight > 0)432{433/* determine the number of bits for this node */434for (struct node_t *curnode = node; curnode->parent != NULL; curnode = curnode->parent)435node->numbits++;436if (node->numbits == 0)437node->numbits = 1;438439/* keep track of the max */440maxbits = MAX(maxbits, ((int)node->numbits));441}442}443return maxbits;444}445446/*-------------------------------------------------447* assign_canonical_codes - assign canonical codes448* to all the nodes based on the number of bits449* in each450*-------------------------------------------------451*/452453enum huffman_error huffman_assign_canonical_codes(struct huffman_decoder* decoder)454{455/* build up a histogram of bit lengths */456uint32_t bithisto[33] = { 0 };457for (int curcode = 0; curcode < decoder->numcodes; curcode++)458{459struct node_t* node = &decoder->huffnode[curcode];460if (node->numbits > decoder->maxbits)461return HUFFERR_INTERNAL_INCONSISTENCY;462if (node->numbits <= 32)463bithisto[node->numbits]++;464}465466/* for each code length, determine the starting code number */467uint32_t curstart = 0;468for (int codelen = 32; codelen > 0; codelen--)469{470uint32_t nextstart = (curstart + bithisto[codelen]) >> 1;471if (codelen != 1 && nextstart * 2 != (curstart + bithisto[codelen]))472return HUFFERR_INTERNAL_INCONSISTENCY;473bithisto[codelen] = curstart;474curstart = nextstart;475}476477/* now assign canonical codes */478for (int curcode = 0; curcode < decoder->numcodes; curcode++)479{480struct node_t* node = &decoder->huffnode[curcode];481if (node->numbits > 0)482node->bits = bithisto[node->numbits]++;483}484return HUFFERR_NONE;485}486487/*-------------------------------------------------488* build_lookup_table - build a lookup table for489* fast decoding490*-------------------------------------------------491*/492493void huffman_build_lookup_table(struct huffman_decoder* decoder)494{495/* iterate over all codes */496for (int curcode = 0; curcode < decoder->numcodes; curcode++)497{498/* process all nodes which have non-zero bits */499struct node_t* node = &decoder->huffnode[curcode];500if (node->numbits > 0)501{502/* set up the entry */503lookup_value value = MAKE_LOOKUP(curcode, node->numbits);504505/* fill all matching entries */506int shift = decoder->maxbits - node->numbits;507lookup_value *dest = &decoder->lookup[node->bits << shift];508lookup_value *destend = &decoder->lookup[((node->bits + 1) << shift) - 1];509while (dest <= destend)510*dest++ = value;511}512}513}514515516