4 * Code for JPEG lossless decoding. Large parts are grabbed from the IJG
8 * $Id: huffd.c,v 1.5 2004/09/12 02:48:23 malaterre Exp $
19 #define RST0 0xD0 /* RST0 marker code */
21 static long getBuffer; /* current bit-extraction buffer */
22 static int bitsLeft; /* # of unused bits in it */
25 * The following variables keep track of the input buffer
26 * for the JPEG data, which is read by ReadJpegData.
28 Uchar *inputBuffer = 0; /* Input buffer for JPEG data */
29 int inputBufferOffset = 0; /* Offset of current byte */
32 * Code for extracting the next N bits from the input stream.
33 * (N never exceeds 15 for JPEG data.)
34 * This needs to go as fast as possible!
36 * We read source bytes into getBuffer and dole out bits as needed.
37 * If getBuffer already contains enough bits, they are fetched in-line
38 * by the macros get_bits() and get_bit(). When there aren't enough bits,
39 * FillBitBuffer is called; it will attempt to fill getBuffer to the
40 * "high water mark", then extract the desired number of bits. The idea,
41 * of course, is to minimize the function-call overhead cost of entering
43 * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
44 * of getBuffer to be used. (On machines with wider words, an even larger
45 * buffer could be used.)
48 #define BITS_PER_LONG (8*sizeof(long))
49 #define MIN_GET_BITS (BITS_PER_LONG-7) /* max value for long getBuffer */
52 * bmask[n] is mask for n rightmost bits
54 static int bmask[] = {0x0000,
55 0x0001, 0x0003, 0x0007, 0x000F,
56 0x001F, 0x003F, 0x007F, 0x00FF,
57 0x01FF, 0x03FF, 0x07FF, 0x0FFF,
58 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
61 *--------------------------------------------------------------
65 * Load up the bit buffer with at least nbits
66 * Process any stuffed bytes at this time.
72 * The bitwise global variables are updated.
74 *--------------------------------------------------------------
76 #define FillBitBuffer(nbits) { \
78 while (bitsLeft < MIN_GET_BITS) { \
80 /* If it's 0xFF, check and discard stuffed zero byte */ \
82 c2 = GetJpegChar (); \
89 /* OK, load c into getBuffer */ \
90 getBuffer = (getBuffer << 8) | c; \
93 }/*endof FillBitBuffer*/
95 /* Macros to make things go at some speed! */
96 /* NB: parameter to get_bits should be simple variable, not expression */
98 #define show_bits(nbits,rv) { \
99 if (bitsLeft < nbits) FillBitBuffer(nbits); \
100 rv = (getBuffer >> (bitsLeft-(nbits))) & bmask[nbits]; \
103 #define show_bits8(rv) { \
104 if (bitsLeft < 8) FillBitBuffer(8); \
105 rv = (getBuffer >> (bitsLeft-8)) & 0xff; \
108 #define flush_bits(nbits) { \
109 bitsLeft -= (nbits); \
112 #define get_bits(nbits,rv) { \
113 if (bitsLeft < nbits) FillBitBuffer(nbits); \
114 rv = ((getBuffer >> (bitsLeft -= (nbits)))) & bmask[nbits]; \
117 #define get_bit(rv) { \
118 if (!bitsLeft) FillBitBuffer(1); \
119 rv = (getBuffer >> (--bitsLeft)) & 1; \
123 *--------------------------------------------------------------
127 * Output one row of pixels stored in RowBuf.
133 * One row of pixels are write to file pointed by outFile.
135 *--------------------------------------------------------------
139 void PmPutRow24(MCU *RowBuf, int numCol, unsigned char **image)
143 for (col = 0; col < numCol; col++)
145 /* take each RGB column */
146 **image = (unsigned char) RowBuf[col][0];
147 *(*image+1) = (unsigned char) RowBuf[col][1];
148 *(*image+2) = (unsigned char) RowBuf[col][2];
154 void PmPutRow16(MCU *RowBuf, int numCol, unsigned short **image)
158 for (col = 0; col < numCol; col++)
160 **image = (unsigned short) RowBuf[col][0];
166 void PmPutRow8(MCU *RowBuf, int numCol, unsigned char **image)
170 for (col = 0; col < numCol; col++)
172 **image = (unsigned char) RowBuf[col][0];
181 *--------------------------------------------------------------
185 * Taken from Figure F.16: extract next coded symbol from
186 * input stream. This should becode a macro.
192 * Bitstream is parsed.
194 *--------------------------------------------------------------
196 #define HuffDecode(htbl,rv) \
201 * If the huffman code is less than 8 bits, we can use the fast \
202 * table lookup to get its value. It's more than 8 bits about \
203 * 3-4% of the time. \
206 if (htbl->numbits[code]) { \
207 flush_bits(htbl->numbits[code]); \
208 rv=htbl->value[code]; \
213 while (code > htbl->maxcode[l]) { \
215 code = (code << 1) | temp; \
220 * With garbage input we may reach the sentinel value l = 17. \
224 fprintf (stderr, "Corrupt JPEG data: bad Huffman code\n"); \
225 rv = 0; /* fake a zero as the safest result */ \
227 rv = htbl->huffval[htbl->valptr[l] + \
228 ((int)(code - htbl->mincode[l]))]; \
234 *--------------------------------------------------------------
238 * Code and table for Figure F.12: extend sign bit
241 * The extended value.
246 *--------------------------------------------------------------
248 static int extendTest[16] = /* entry n is 2**(n-1) */
249 {0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
250 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000};
252 static int extendOffset[16] = /* entry n is (-1 << n) + 1 */
253 {0, ((-1) << 1) + 1, ((-1) << 2) + 1, ((-1) << 3) + 1, ((-1) << 4) + 1,
254 ((-1) << 5) + 1, ((-1) << 6) + 1, ((-1) << 7) + 1, ((-1) << 8) + 1,
255 ((-1) << 9) + 1, ((-1) << 10) + 1, ((-1) << 11) + 1, ((-1) << 12) + 1,
256 ((-1) << 13) + 1, ((-1) << 14) + 1, ((-1) << 15) + 1};
258 #define HuffExtend(x,s) { \
259 if ((x) < extendTest[s]) { \
260 (x) += extendOffset[s]; \
265 *--------------------------------------------------------------
269 * Initialize for a Huffman-compressed scan.
270 * This is invoked after reading the SOS marker.
278 *--------------------------------------------------------------
280 void HuffDecoderInit (DecompressInfo *dcPtr)
283 JpegComponentInfo *compptr;
285 * Initialize siv-lyon1.fr
290 for (ci = 0; ci < dcPtr->compsInScan; ci++) {
291 compptr = dcPtr->curCompInfo[ci];
293 * Make sure requested tables are present
295 if (dcPtr->dcHuffTblPtrs[compptr->dcTblNo] == NULL) {
296 fprintf (stderr, "Error: Use of undefined Huffman table\n");
298 dcPtr->error = -1; return;
302 * Compute derived values for Huffman tables.
303 * We may do this more than once for same table, but it's not a
306 FixHuffTbl (dcPtr->dcHuffTblPtrs[compptr->dcTblNo]);
310 * Initialize restart stuff
312 dcPtr->restartInRows = (dcPtr->restartInterval)/(dcPtr->imageWidth);
313 dcPtr->restartRowsToGo = dcPtr->restartInRows;
314 dcPtr->nextRestartNum = 0;
318 *--------------------------------------------------------------
322 * Check for a restart marker & resynchronize decoder.
328 * BitStream is parsed, bit buffer is reset, etc.
330 *--------------------------------------------------------------
332 static void ProcessRestart(DecompressInfo *dcPtr)
338 * Throw away any unused bits remaining in bit buffer
340 nbytes = bitsLeft / 8;
344 * Scan for next JPEG marker
349 { /* skip any non-FF bytes */
356 { /* skip any duplicate FFs */
358 * we don't increment nbytes here since extra FFs are legal
364 while (c == 0); /* repeat if it was a stuffed FF/00 */
366 if (c != (RST0 + dcPtr->nextRestartNum)) {
369 * Uh-oh, the restart markers have been messed up too.
372 fprintf (stderr, "Error: Corrupt JPEG data. Exiting...\n");
374 dcPtr->error = -1; return;
378 * Update restart state
380 dcPtr->restartRowsToGo = dcPtr->restartInRows;
381 dcPtr->nextRestartNum = (dcPtr->nextRestartNum + 1) & 7;
385 *--------------------------------------------------------------
389 * Decode the first raster line of samples at the start of
390 * the scan and at the beginning of each restart interval.
391 * This includes modifying the component value so the real
392 * value, not the difference is returned.
398 * Bitstream is parsed.
400 *--------------------------------------------------------------
402 void DecodeFirstRow (DecompressInfo *dcPtr, MCU *curRowBuf)
404 register short curComp,ci;
405 register int s,col,compsInScan,numCOL;
406 register JpegComponentInfo *compptr;
409 Pr=dcPtr->dataPrecision;
411 compsInScan=dcPtr->compsInScan;
412 numCOL=dcPtr->imageWidth;
415 * the start of the scan or at the beginning of restart interval.
417 for (curComp = 0; curComp < compsInScan; curComp++) {
418 ci = dcPtr->MCUmembership[curComp];
419 compptr = dcPtr->curCompInfo[ci];
420 dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];
423 * Section F.2.2.1: decode the difference
425 HuffDecode (dctbl,s);
434 * Add the predictor to the difference.
436 curRowBuf[0][curComp]=d+(1<<(Pr-Pt-1));
440 * the rest of the first row
442 for (col=1; col<numCOL; col++) {
443 for (curComp = 0; curComp < compsInScan; curComp++) {
444 ci = dcPtr->MCUmembership[curComp];
445 compptr = dcPtr->curCompInfo[ci];
446 dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];
449 * Section F.2.2.1: decode the difference
451 HuffDecode (dctbl,s);
460 * Add the predictor to the difference.
462 curRowBuf[col][curComp]=d+curRowBuf[col-1][curComp];
466 if (dcPtr->restartInRows) {
467 (dcPtr->restartRowsToGo)--;
469 }/*endof DecodeFirstRow*/
472 *--------------------------------------------------------------
476 * Decode the input stream. This includes modifying
477 * the component value so the real value, not the
478 * difference is returned.
484 * Bitstream is parsed.
486 *--------------------------------------------------------------
488 void DecodeImage (DecompressInfo *dcPtr, unsigned short **image, int depth)
490 register int s, d, col, row;
491 register short curComp, ci;
493 JpegComponentInfo *compptr;
495 int numCOL, numROW, compsInScan;
496 MCU *prevRowBuf, *curRowBuf;
497 int imagewidth, Pt, psv;
498 unsigned short *image16tmp;
499 unsigned char *image8tmp, *image24tmp;
501 numCOL = imagewidth=dcPtr->imageWidth;
502 numROW = dcPtr->imageHeight;
503 compsInScan = dcPtr->compsInScan;
506 prevRowBuf = mcuROW2;
510 image8tmp = (unsigned char *) *image;
511 else if (depth == 16)
512 image16tmp = (unsigned short *) *image;
513 else if (depth == 24)
514 image24tmp = (unsigned char *) *image;
516 fprintf(stderr,"Unsupported image depth %d\n",depth);
517 dcPtr->error = -1; return;
521 * Decode the first row of image. Output the row and
522 * turn this row into a previous row for later predictor
526 DecodeFirstRow (dcPtr, curRowBuf);
529 PmPutRow8 (curRowBuf, numCOL, &image8tmp);
530 else if (depth == 16)
531 PmPutRow16 (curRowBuf, numCOL, &image16tmp);
532 else if (depth == 24)
533 PmPutRow24 (curRowBuf, numCOL, &image24tmp);
535 gdcmSWAP(MCU *, prevRowBuf, curRowBuf);
537 /* optimal case : 8 bit image, one color component, no restartInRows */
538 if ((depth == 8) && (compsInScan == 1) && (dcPtr->restartInRows == 0))
541 unsigned char *curPixelPtr;
544 /* initializations */
547 ci = dcPtr->MCUmembership[curComp];
548 compptr = dcPtr->curCompInfo[ci];
549 dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];
550 curPixelPtr = image8tmp;
552 for (row=1; row<numROW; row++)
554 /* Upper neighbor is predictor for the first column */
555 /* Section F.2.2.1: decode the difference */
556 HuffDecode (dctbl,s);
557 if (s) { get_bits(s,d); HuffExtend(d,s); }
559 *curPixelPtr = (unsigned char) (d + *(curPixelPtr - numCOL));
563 for (col=1; col < numCOL; col++) {
564 /* Section F.2.2.1: decode the difference */
565 HuffDecode (dctbl, s);
566 if (s) { get_bits (s, d); HuffExtend (d, s); }
569 *curPixelPtr = (unsigned char) (d + *(curPixelPtr - 1));
575 for (col=1; col < numCOL; col++) {
576 /* Section F.2.2.1: decode the difference */
577 HuffDecode (dctbl, s);
578 if (s) { get_bits (s, d); HuffExtend (d, s); }
581 /* Predict : All predictors are calculated according to psv */
583 case 0: predictor = 0; break;
584 case 2: predictor = *(curPixelPtr - numCOL); break;
585 case 3: predictor = *(curPixelPtr - numCOL - 1); break;
586 case 4: upper = *(curPixelPtr - numCOL);
587 left = *(curPixelPtr - 1);
588 diag = *(curPixelPtr - numCOL - 1);
589 predictor = left + upper - diag; break;
590 case 5: upper = *(curPixelPtr - numCOL);
591 left = *(curPixelPtr - 1);
592 diag = *(curPixelPtr - numCOL - 1);
593 predictor = left+((upper-diag)>>1); break;
594 case 6: upper = *(curPixelPtr - numCOL);
595 left = *(curPixelPtr - 1);
596 diag = *(curPixelPtr - numCOL - 1);
597 predictor = upper+((left-diag)>>1); break;
598 case 7: upper = *(curPixelPtr - numCOL);
599 left = *(curPixelPtr - 1);
600 predictor = (left+upper)>>1; break;
601 default : predictor = 0;
604 *curPixelPtr = (unsigned char) (d + predictor);
612 else { /*normal case with 16 bits or color or ...*/
613 for (row=1; row<numROW; row++) {
615 * Account for restart interval, process restart marker if needed.
617 if (dcPtr->restartInRows)
619 if (dcPtr->restartRowsToGo == 0)
621 ProcessRestart (dcPtr); if (dcPtr->error) return;
623 * Reset predictors at restart.
625 DecodeFirstRow(dcPtr,curRowBuf);
627 PmPutRow8 (curRowBuf, numCOL, &image8tmp);
628 else if (depth == 16)
629 PmPutRow16 (curRowBuf, numCOL, &image16tmp);
630 else if (depth == 24)
631 PmPutRow24 (curRowBuf, numCOL, &image24tmp);
633 gdcmSWAP(MCU *,prevRowBuf,curRowBuf);
636 dcPtr->restartRowsToGo--;
640 * For the rest of the column on this row, predictor
641 * calculations are base on PSV.
644 /* several color components to decode (RGB colors)*/
646 /* The upper neighbors are predictors for the first column. */
647 for (curComp = 0; curComp < compsInScan; curComp++)
649 ci = dcPtr->MCUmembership[curComp];
650 compptr = dcPtr->curCompInfo[ci];
651 dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];
653 /* Section F.2.2.1: decode the difference */
654 HuffDecode (dctbl,s);
655 if (s) { get_bits(s,d); HuffExtend(d,s); }
657 curRowBuf[0][curComp]=d+prevRowBuf[0][curComp];
660 for (col=1; col < numCOL; col++)
662 for (curComp = 0; curComp < compsInScan; curComp++)
664 ci = dcPtr->MCUmembership[curComp];
665 compptr = dcPtr->curCompInfo[ci];
666 dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];
668 /* Section F.2.2.1: decode the difference */
669 HuffDecode (dctbl, s);
670 if (s) { get_bits (s, d); HuffExtend (d, s); }
673 QuickPredict (col,curComp,curRowBuf,prevRowBuf,psv,&predictor);
675 curRowBuf[col][curComp]=d+predictor;
680 PmPutRow8 (curRowBuf, numCOL, &image8tmp);
681 else if (depth == 16)
682 PmPutRow16 (curRowBuf, numCOL, &image16tmp);
683 else if (depth == 24)
684 PmPutRow24 (curRowBuf, numCOL, &image24tmp);
686 gdcmSWAP(MCU *, prevRowBuf, curRowBuf);
690 }/*endofmethod DecodeImage*/