1
///////////////////////////////////////////////////////////////////////////
3
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
6
// All rights reserved.
8
// Redistribution and use in source and binary forms, with or without
9
// modification, are permitted provided that the following conditions are
11
// * Redistributions of source code must retain the above copyright
12
// notice, this list of conditions and the following disclaimer.
13
// * Redistributions in binary form must reproduce the above
14
// copyright notice, this list of conditions and the following disclaimer
15
// in the documentation and/or other materials provided with the
17
// * Neither the name of Industrial Light & Magic nor the names of
18
// its contributors may be used to endorse or promote products derived
19
// from this software without specific prior written permission.
21
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
///////////////////////////////////////////////////////////////////////////
38
//-----------------------------------------------------------------------------
40
// 16-bit Huffman compression and decompression.
42
// The source code in this file is derived from the 8-bit
43
// Huffman compression and decompression routines written
44
// by Christian Rouet for his PIZ image file format.
46
//-----------------------------------------------------------------------------
50
#include <ImfAutoArray.h>
64
const int HUF_ENCBITS = 16; // literal (value) bit length
65
const int HUF_DECBITS = 14; // decoding bit size (>= 8)
67
const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
68
const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
69
const int HUF_DECMASK = HUF_DECSIZE - 1;
73
{ // short code long code
74
//-------------------------------
75
int len:8; // code length 0
76
int lit:24; // lit p size
84
throw InputExc ("Error in header for Huffman-encoded data "
85
"(invalid number of bits).");
92
throw InputExc ("Error in Huffman-encoded data "
93
"(decoded data are longer than expected).");
100
throw InputExc ("Error in Huffman-encoded data "
101
"(decoded data are shorter than expected).");
108
throw InputExc ("Error in Huffman-encoded data "
116
throw InputExc ("Error in Huffman-encoded data "
117
"(invalid code table size).");
122
unexpectedEndOfTable ()
124
throw InputExc ("Error in Huffman-encoded data "
125
"(unexpected end of code table data).");
132
throw InputExc ("Error in Huffman-encoded data "
133
"(code table is longer than expected).");
140
throw InputExc ("Error in Huffman-encoded data "
141
"(invalid code table entry).");
146
hufLength (Int64 code)
160
outputBits (int nBits, Int64 bits, Int64 &c, int &lc, char *&out)
168
*out++ = (c >> (lc -= 8));
173
getBits (int nBits, Int64 &c, int &lc, const char *&in)
177
c = (c << 8) | *(unsigned char *)(in++);
182
return (c >> lc) & ((1 << nBits) - 1);
187
// ENCODING TABLE BUILDING & (UN)PACKING
191
// Build a "canonical" Huffman code table:
192
// - for each (uncompressed) symbol, hcode contains the length
193
// of the corresponding code (in the compressed data)
194
// - canonical codes are computed and stored in hcode
195
// - the rules for constructing canonical codes are as follows:
196
// * shorter codes (if filled with zeroes to the right)
197
// have a numerically higher value than longer codes
198
// * for codes with the same length, numerical values
199
// increase with numerical symbol values
200
// - because the canonical code table can be constructed from
201
// symbol lengths alone, the code table can be transmitted
202
// without sending the actual code values
203
// - see http://www.compressconsult.com/huffman/
207
hufCanonicalCodeTable (Int64 hcode[HUF_ENCSIZE])
212
// For each i from 0 through 58, count the
213
// number of different codes of length i, and
214
// store the count in n[i].
217
for (int i = 0; i <= 58; ++i)
220
for (int i = 0; i < HUF_ENCSIZE; ++i)
224
// For each i from 58 through 1, compute the
225
// numerically lowest code with length i, and
226
// store that code in n[i].
231
for (int i = 58; i > 0; --i)
233
Int64 nc = ((c + n[i]) >> 1);
239
// hcode[i] contains the length, l, of the
240
// code for symbol i. Assign the next available
241
// code of length l to the symbol and store both
242
// l and the code in hcode[i].
245
for (int i = 0; i < HUF_ENCSIZE; ++i)
250
hcode[i] = l | (n[l]++ << 6);
256
// Compute Huffman codes (based on frq input) and store them in frq:
257
// - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
258
// - max code length is 58 bits;
259
// - codes outside the range [im-iM] have a null length (unused values);
260
// - original frequencies are destroyed;
261
// - encoding tables are used by hufEncode() and hufBuildDecTable();
267
bool operator () (Int64 *a, Int64 *b) {return *a > *b;}
273
(Int64* frq, // io: input frequencies [HUF_ENCSIZE], output table
274
int* im, // o: min frq index
275
int* iM) // o: max frq index
278
// This function assumes that when it is called, array frq
279
// indicates the frequency of all possible symbols in the data
280
// that are to be Huffman-encoded. (frq[i] contains the number
281
// of occurrences of symbol i in the data.)
283
// The loop below does three things:
285
// 1) Finds the minimum and maximum indices that point
286
// to non-zero entries in frq:
288
// frq[im] != 0, and frq[i] == 0 for all i < im
289
// frq[iM] != 0, and frq[i] == 0 for all i > iM
291
// 2) Fills array fHeap with pointers to all non-zero
294
// 3) Initializes array hlink such that hlink[i] == i
295
// for all array entries.
298
AutoArray <int, HUF_ENCSIZE> hlink;
299
AutoArray <Int64 *, HUF_ENCSIZE> fHeap;
308
for (int i = *im; i < HUF_ENCSIZE; i++)
321
// Add a pseudo-symbol, with a frequency count of 1, to frq;
322
// adjust the fHeap and hlink array accordingly. Function
323
// hufEncode() uses the pseudo-symbol for run-length encoding.
328
fHeap[nf] = &frq[*iM];
332
// Build an array, scode, such that scode[i] contains the number
333
// of bits assigned to symbol i. Conceptually this is done by
334
// constructing a tree whose leaves are the symbols with non-zero
337
// Make a heap that contains all symbols with a non-zero frequency,
338
// with the least frequent symbol on top.
340
// Repeat until only one symbol is left on the heap:
342
// Take the two least frequent symbols off the top of the heap.
343
// Create a new node that has first two nodes as children, and
344
// whose frequency is the sum of the frequencies of the first
345
// two nodes. Put the new node back into the heap.
347
// The last node left on the heap is the root of the tree. For each
348
// leaf node, the distance between the root and the leaf is the length
349
// of the code for the corresponding symbol.
351
// The loop below doesn't actually build the tree; instead we compute
352
// the distances of the leaves from the root on the fly. When a new
353
// node is added to the heap, then that node's descendants are linked
354
// into a single linear list that starts at the new node, and the code
355
// lengths of the descendants (that is, their distance from the root
356
// of the tree) are incremented by one.
359
make_heap (&fHeap[0], &fHeap[nf], FHeapCompare());
361
AutoArray <Int64, HUF_ENCSIZE> scode;
362
memset (scode, 0, sizeof (Int64) * HUF_ENCSIZE);
367
// Find the indices, mm and m, of the two smallest non-zero frq
368
// values in fHeap, add the smallest frq to the second-smallest
369
// frq, and remove the smallest frq value from fHeap.
372
int mm = fHeap[0] - frq;
373
pop_heap (&fHeap[0], &fHeap[nf], FHeapCompare());
376
int m = fHeap[0] - frq;
377
pop_heap (&fHeap[0], &fHeap[nf], FHeapCompare());
380
push_heap (&fHeap[0], &fHeap[nf], FHeapCompare());
383
// The entries in scode are linked into lists with the
384
// entries in hlink serving as "next" pointers and with
385
// the end of a list marked by hlink[j] == j.
387
// Traverse the lists that start at scode[m] and scode[mm].
388
// For each element visited, increment the length of the
389
// corresponding code by one bit. (If we visit scode[j]
390
// during the traversal, then the code for symbol j becomes
393
// Merge the lists that start at scode[m] and scode[mm]
394
// into a single list that starts at scode[m].
398
// Add a bit to all codes in the first list.
401
for (int j = m; true; j = hlink[j])
405
assert (scode[j] <= 58);
410
// Merge the two lists.
419
// Add a bit to all codes in the second list
422
for (int j = mm; true; j = hlink[j])
426
assert (scode[j] <= 58);
434
// Build a canonical Huffman code table, replacing the code
435
// lengths in scode with (code, code length) pairs. Copy the
436
// code table from scode into frq.
439
hufCanonicalCodeTable (scode);
440
memcpy (frq, scode, sizeof (Int64) * HUF_ENCSIZE);
445
// Pack an encoding table:
446
// - only code lengths, not actual codes, are stored
447
// - runs of zeroes are compressed as follows:
450
// --------------------------------
456
// n zeroes (6 or more) 63 n-6 (6 + 8 bits)
459
const int SHORT_ZEROCODE_RUN = 59;
460
const int LONG_ZEROCODE_RUN = 63;
461
const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
462
const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
467
(const Int64* hcode, // i : encoding table [HUF_ENCSIZE]
468
int im, // i : min hcode index
469
int iM, // i : max hcode index
470
char** pcode) // o: ptr to packed table (updated)
476
for (; im <= iM; im++)
478
int l = hufLength (hcode[im]);
484
while ((im < iM) && (zerun < LONGEST_LONG_RUN))
486
if (hufLength (hcode[im+1]) > 0 )
494
if (zerun >= SHORTEST_LONG_RUN)
496
outputBits (6, LONG_ZEROCODE_RUN, c, lc, p);
497
outputBits (8, zerun - SHORTEST_LONG_RUN, c, lc, p);
501
outputBits (6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
507
outputBits (6, l, c, lc, p);
511
*p++ = (unsigned char) (c << (8 - lc));
518
// Unpack an encoding table packed by hufPackEncTable():
523
(const char** pcode, // io: ptr to packed table (updated)
524
int ni, // i : input size (in bytes)
525
int im, // i : min hcode index
526
int iM, // i : max hcode index
527
Int64* hcode) // o: encoding table [HUF_ENCSIZE]
529
memset (hcode, 0, sizeof (Int64) * HUF_ENCSIZE);
531
const char *p = *pcode;
535
for (; im <= iM; im++)
538
unexpectedEndOfTable();
540
Int64 l = hcode[im] = getBits (6, c, lc, p); // code length
542
if (l == (Int64) LONG_ZEROCODE_RUN)
545
unexpectedEndOfTable();
547
int zerun = getBits (8, c, lc, p) + SHORTEST_LONG_RUN;
549
if (im + zerun > iM + 1)
557
else if (l >= (Int64) SHORT_ZEROCODE_RUN)
559
int zerun = l - SHORT_ZEROCODE_RUN + 2;
561
if (im + zerun > iM + 1)
573
hufCanonicalCodeTable (hcode);
578
// DECODING TABLE BUILDING
582
// Clear a newly allocated decoding table so that it contains only zeroes.
587
(HufDec * hdecod) // io: (allocated by caller)
588
// decoding table [HUF_DECSIZE]
590
memset (hdecod, 0, sizeof (HufDec) * HUF_DECSIZE);
595
// Build a decoding hash table based on the encoding table hcode:
596
// - short codes (<= HUF_DECBITS) are resolved with a single table access;
597
// - long code entry allocations are not optimized, because long codes are
599
// - decoding tables are used by hufDecode();
604
(const Int64* hcode, // i : encoding table
605
int im, // i : min index in hcode
606
int iM, // i : max index in hcode
607
HufDec * hdecod) // o: (allocated by caller)
608
// decoding table [HUF_DECSIZE]
611
// Init hashtable & loop on all codes.
612
// Assumes that hufClearDecTable(hdecod) has already been called.
615
for (; im <= iM; im++)
617
Int64 c = hufCode (hcode[im]);
618
int l = hufLength (hcode[im]);
623
// Error: c is supposed to be an l-bit code,
624
// but c contains a value that is greater
625
// than the largest l-bit number.
634
// Long code: add a secondary entry
637
HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
642
// Error: a short code has already
643
// been stored in table entry *pl.
654
pl->p = new int [pl->lit];
656
for (int i = 0; i < pl->lit - 1; ++i)
666
pl->p[pl->lit - 1]= im;
671
// Short code: init all primary entries
674
HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
676
for (Int64 i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++)
678
if (pl->len || pl->p)
681
// Error: a short code or a long code has
682
// already been stored in table entry *pl.
697
// Free the long code entries of a decoding table built by hufBuildDecTable()
701
hufFreeDecTable (HufDec *hdecod) // io: Decoding table
703
for (int i = 0; i < HUF_DECSIZE; i++)
707
delete [] hdecod[i].p;
719
outputCode (Int64 code, Int64 &c, int &lc, char *&out)
721
outputBits (hufLength (code), hufCode (code), c, lc, out);
726
sendCode (Int64 sCode, int runCount, Int64 runCode,
727
Int64 &c, int &lc, char *&out)
729
static const int RLMIN = 32; // min count to activate run-length coding
731
if (runCount > RLMIN)
733
outputCode (sCode, c, lc, out);
734
outputCode (runCode, c, lc, out);
735
outputBits (8, runCount, c, lc, out);
739
while (runCount-- >= 0)
740
outputCode (sCode, c, lc, out);
746
// Encode (compress) ni values based on the Huffman encoding table hcode:
750
hufEncode // return: output size (in bits)
751
(const Int64* hcode, // i : encoding table
752
const unsigned short* in, // i : uncompressed input buffer
753
const int ni, // i : input buffer size (in bytes)
754
int rlc, // i : rl code
755
char* out) // o: compressed output buffer
757
char *outStart = out;
758
Int64 c = 0; // bits not yet written to out
759
int lc = 0; // number of valid bits in c (LSB)
764
// Loop on input values
767
for (int i = 1; i < ni; i++)
770
// Count same values or send code
773
if (s == in[i] && cs < 255)
779
sendCode (hcode[s], cs, hcode[rlc], c, lc, out);
787
// Send remaining code
790
sendCode (hcode[s], cs, hcode[rlc], c, lc, out);
793
*out = (c << (8 - lc)) & 0xff;
795
return (out - outStart) * 8 + lc;
804
// In order to force the compiler to inline them,
805
// getChar() and getCode() are implemented as macros
806
// instead of "inline" functions.
809
#define getChar(c, lc, in) \
811
c = (c << 8) | *(unsigned char *)(in++); \
816
#define getCode(po, rlc, c, lc, in, out, oe) \
821
getChar(c, lc, in); \
825
unsigned char cs = (c >> lc); \
830
unsigned short s = out[-1]; \
847
// Decode (uncompress) ni bits based on encoding & decoding tables:
852
(const Int64 * hcode, // i : encoding table
853
const HufDec * hdecod, // i : decoding table
854
const char* in, // i : compressed input buffer
855
int ni, // i : input size (in bits)
856
int rlc, // i : run-length code
857
int no, // i : expected output size (in bytes)
858
unsigned short* out) // o: uncompressed output buffer
862
unsigned short * outb = out;
863
unsigned short * oe = out + no;
864
const char * ie = in + (ni + 7) / 8; // input byte size
867
// Loop on input bytes
875
// Access decoding table
878
while (lc >= HUF_DECBITS)
880
const HufDec pl = hdecod[(c >> (lc-HUF_DECBITS)) & HUF_DECMASK];
889
getCode (pl.lit, rlc, c, lc, in, out, oe);
894
invalidCode(); // wrong code
902
for (j = 0; j < pl.lit; j++)
904
int l = hufLength (hcode[pl.p[j]]);
906
while (lc < l && in < ie) // get more bits
911
if (hufCode (hcode[pl.p[j]]) ==
912
((c >> (lc - l)) & ((Int64(1) << l) - 1)))
915
// Found : get long code
919
getCode (pl.p[j], rlc, c, lc, in, out, oe);
926
invalidCode(); // Not found
932
// Get remaining (short) codes
935
int i = (8 - ni) & 7;
941
const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
946
getCode (pl.lit, rlc, c, lc, in, out, oe);
950
invalidCode(); // wrong (long) code
954
if (out - outb != no)
960
countFrequencies (Int64 freq[HUF_ENCSIZE],
961
const unsigned short data[/*n*/],
964
for (int i = 0; i < HUF_ENCSIZE; ++i)
967
for (int i = 0; i < n; ++i)
973
writeUInt (char buf[4], unsigned int i)
975
unsigned char *b = (unsigned char *) buf;
985
readUInt (const char buf[4])
987
const unsigned char *b = (const unsigned char *) buf;
989
return ( b[0] & 0x000000ff) |
990
((b[1] << 8) & 0x0000ff00) |
991
((b[2] << 16) & 0x00ff0000) |
992
((b[3] << 24) & 0xff000000);
999
// EXTERNAL INTERFACE
1004
hufCompress (const unsigned short raw[],
1011
AutoArray <Int64, HUF_ENCSIZE> freq;
1013
countFrequencies (freq, raw, nRaw);
1016
hufBuildEncTable (freq, &im, &iM);
1018
char *tableStart = compressed + 20;
1019
char *tableEnd = tableStart;
1020
hufPackEncTable (freq, im, iM, &tableEnd);
1021
int tableLength = tableEnd - tableStart;
1023
char *dataStart = tableEnd;
1024
int nBits = hufEncode (freq, raw, nRaw, iM, dataStart);
1025
int dataLength = (nBits + 7) / 8;
1027
writeUInt (compressed, im);
1028
writeUInt (compressed + 4, iM);
1029
writeUInt (compressed + 8, tableLength);
1030
writeUInt (compressed + 12, nBits);
1031
writeUInt (compressed + 16, 0); // room for future extensions
1033
return dataStart + dataLength - compressed;
1038
hufUncompress (const char compressed[],
1040
unsigned short raw[],
1043
if (nCompressed == 0)
1051
int im = readUInt (compressed);
1052
int iM = readUInt (compressed + 4);
1053
// int tableLength = readUInt (compressed + 8);
1054
int nBits = readUInt (compressed + 12);
1056
if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE)
1059
const char *ptr = compressed + 20;
1061
AutoArray <Int64, HUF_ENCSIZE> freq;
1062
AutoArray <HufDec, HUF_DECSIZE> hdec;
1064
hufClearDecTable (hdec);
1066
hufUnpackEncTable (&ptr, nCompressed - (ptr - compressed), im, iM, freq);
1070
if (nBits > 8 * (nCompressed - (ptr - compressed)))
1073
hufBuildDecTable (freq, im, iM, hdec);
1074
hufDecode (freq, hdec, ptr, nBits, iM, nRaw, raw);
1078
hufFreeDecTable (hdec);
1082
hufFreeDecTable (hdec);