]> Creatis software - gdcm.git/blob - src/jpeg/ljpg/huffd.c
ENH: I am a moron. Fix compilation of gdcm in static mode, I had to add some new...
[gdcm.git] / src / jpeg / ljpg / huffd.c
1 /*
2  * huffd.c --
3  *
4  * Code for JPEG lossless decoding.  Large parts are grabbed from the IJG
5  * software
6  */
7 /*
8  * $Id: huffd.c,v 1.5 2004/09/12 02:48:23 malaterre Exp $
9  */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include "jpeg.h"
14 #include "mcu.h"
15 #include "io.h"
16 #include "proto.h"
17 #include "predict.h"
18
19 #define RST0    0xD0                /* RST0 marker code */
20
21 static long getBuffer;              /* current bit-extraction buffer */
22 static int  bitsLeft;               /* # of unused bits in it */
23
24 /*
25  * The following variables keep track of the input buffer
26  * for the JPEG data, which is read by ReadJpegData.
27  */
28 Uchar *inputBuffer = 0;           /* Input buffer for JPEG data */
29 int inputBufferOffset = 0;        /* Offset of current byte */
30
31 /*
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!
35  *
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
42  * FillBitBuffer.
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.)  
46  */
47
48 #define BITS_PER_LONG (8*sizeof(long))
49 #define MIN_GET_BITS  (BITS_PER_LONG-7) /* max value for long getBuffer */
50
51 /*
52  * bmask[n] is mask for n rightmost bits
53  */
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};
59
60 /*
61  *--------------------------------------------------------------
62  *
63  * FillBitBuffer --
64  *
65  *        Load up the bit buffer with at least nbits
66  *        Process any stuffed bytes at this time.
67  *
68  * Results:
69  *        None
70  *
71  * Side effects:
72  *        The bitwise global variables are updated.
73  *
74  *--------------------------------------------------------------
75  */
76 #define FillBitBuffer(nbits) {                                          \
77     int c, c2;                                                          \
78     while (bitsLeft < MIN_GET_BITS) {                                   \
79         c = GetJpegChar ();                                             \
80         /* If it's 0xFF, check and discard stuffed zero byte */         \
81         if (c == 0xFF) {                                                \
82             c2 = GetJpegChar ();                                        \
83             if (c2 != 0) {                                              \
84                 UnGetJpegChar (c2);                                     \
85                 UnGetJpegChar (c);                                      \
86                 c = 0;                                                  \
87             }                                                           \
88         }/*endif 0xFF*/                                                 \
89         /* OK, load c into getBuffer */                                 \
90         getBuffer = (getBuffer << 8) | c;                               \
91         bitsLeft += 8;                                                  \
92     }/*endwhile*/                                                       \
93 }/*endof FillBitBuffer*/
94
95 /* Macros to make things go at some speed! */
96 /* NB: parameter to get_bits should be simple variable, not expression */
97
98 #define show_bits(nbits,rv) {                                           \
99     if (bitsLeft < nbits) FillBitBuffer(nbits);                         \
100     rv = (getBuffer >> (bitsLeft-(nbits))) & bmask[nbits];              \
101 }
102
103 #define show_bits8(rv) {                                                \
104         if (bitsLeft < 8) FillBitBuffer(8);                             \
105         rv = (getBuffer >> (bitsLeft-8)) & 0xff;                        \
106 }
107
108 #define flush_bits(nbits) {                                             \
109         bitsLeft -= (nbits);                                            \
110 }
111
112 #define get_bits(nbits,rv) {                                            \
113         if (bitsLeft < nbits) FillBitBuffer(nbits);                     \
114         rv = ((getBuffer >> (bitsLeft -= (nbits)))) & bmask[nbits];     \
115 }
116
117 #define get_bit(rv) {                                                   \
118         if (!bitsLeft) FillBitBuffer(1);                                \
119         rv = (getBuffer >> (--bitsLeft)) & 1;                           \
120 }
121
122 /*
123  *--------------------------------------------------------------
124  *
125  * PmPutRow --
126  *
127  *      Output one row of pixels stored in RowBuf.
128  *
129  * Results:
130  *      None
131  *
132  * Side effects:
133  *      One row of pixels are write to file pointed by outFile.
134  *
135  *--------------------------------------------------------------
136  */   
137
138
139 void PmPutRow24(MCU *RowBuf, int numCol, unsigned char **image)
140 {
141         register int col;
142
143         for (col = 0; col < numCol; col++)
144     {
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];
149              (*image)+=3;
150     }
151 }
152
153                                    
154 void PmPutRow16(MCU *RowBuf, int numCol, unsigned short **image)
155 {  
156         register int col;          
157
158         for (col = 0; col < numCol; col++)
159     {                   
160              **image = (unsigned short) RowBuf[col][0];
161              (*image)++;                                        
162     }
163 }   
164
165
166 void PmPutRow8(MCU *RowBuf, int numCol, unsigned char **image)
167 {  
168         register int col;          
169
170         for (col = 0; col < numCol; col++)
171     {                   
172              **image = (unsigned char) RowBuf[col][0];
173              (*image)++;                                        
174     }   
175 }   
176                                                                            
177
178
179
180 /*
181  *--------------------------------------------------------------
182  *
183  * HuffDecode --
184  *
185  *        Taken from Figure F.16: extract next coded symbol from
186  *        input stream.  This should becode a macro.
187  *
188  * Results:
189  *        Next coded symbol
190  *
191  * Side effects:
192  *        Bitstream is parsed.
193  *
194  *--------------------------------------------------------------
195  */
196 #define HuffDecode(htbl,rv)                                             \
197 {                                                                       \
198     int l, code, temp;                                                  \
199                                                                         \
200     /*                                                                  \
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.                                                \
204      */                                                                 \
205     show_bits8(code);                                                   \
206     if (htbl->numbits[code]) {                                          \
207         flush_bits(htbl->numbits[code]);                                \
208         rv=htbl->value[code];                                           \
209     }                                                                   \
210     else {                                                              \
211         flush_bits(8);                                                  \
212         l = 8;                                                          \
213         while (code > htbl->maxcode[l]) {                               \
214             get_bit(temp);                                              \
215             code = (code << 1) | temp;                                  \
216             l++;                                                        \
217         }                                                               \
218                                                                         \
219         /*                                                              \
220          * With garbage input we may reach the sentinel value l = 17.   \
221          */                                                             \
222                                                                         \
223         if (l > 16) {                                                   \
224             fprintf (stderr, "Corrupt JPEG data: bad Huffman code\n");  \
225             rv = 0; /* fake a zero as the safest result */              \
226         } else {                                                        \
227             rv = htbl->huffval[htbl->valptr[l] +                        \
228                 ((int)(code - htbl->mincode[l]))];                      \
229         }                                                               \
230     }/*endelse*/                                                        \
231 }/*HuffDecode*/
232
233 /*
234  *--------------------------------------------------------------
235  *
236  * HuffExtend --
237  *
238  *        Code and table for Figure F.12: extend sign bit
239  *
240  * Results:
241  *        The extended value.
242  *
243  * Side effects:
244  *        None.
245  *
246  *--------------------------------------------------------------
247  */
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};
251
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};
257
258 #define HuffExtend(x,s) {                                               \
259     if ((x) < extendTest[s]) {                                          \
260         (x) += extendOffset[s];                                         \
261     }                                                                   \
262 }
263
264 /*
265  *--------------------------------------------------------------
266  *
267  * HuffDecoderInit --
268  *
269  *        Initialize for a Huffman-compressed scan.
270  *        This is invoked after reading the SOS marker.
271  *
272  * Results:
273  *        None
274  *
275  * Side effects:
276  *        None.
277  *
278  *--------------------------------------------------------------
279  */
280 void HuffDecoderInit (DecompressInfo *dcPtr)
281 {
282     short ci;
283     JpegComponentInfo *compptr;
284     /*
285      * Initialize siv-lyon1.fr
286      tatic variables
287      */
288     bitsLeft = 0;
289
290     for (ci = 0; ci < dcPtr->compsInScan; ci++) {
291         compptr = dcPtr->curCompInfo[ci];
292         /*
293          * Make sure requested tables are present
294          */
295         if (dcPtr->dcHuffTblPtrs[compptr->dcTblNo] == NULL) { 
296             fprintf (stderr, "Error: Use of undefined Huffman table\n");
297             /* exit (1); */
298             dcPtr->error = -1; return;
299         }
300
301         /*
302          * Compute derived values for Huffman tables.
303          * We may do this more than once for same table, but it's not a
304          * big deal
305          */
306         FixHuffTbl (dcPtr->dcHuffTblPtrs[compptr->dcTblNo]);
307     }
308
309     /*
310      * Initialize restart stuff
311      */
312     dcPtr->restartInRows = (dcPtr->restartInterval)/(dcPtr->imageWidth);
313     dcPtr->restartRowsToGo = dcPtr->restartInRows;
314     dcPtr->nextRestartNum = 0;
315 }
316
317 /*
318  *--------------------------------------------------------------
319  *
320  * ProcessRestart --
321  *
322  *        Check for a restart marker & resynchronize decoder.
323  *
324  * Results:
325  *        None.
326  *
327  * Side effects:
328  *        BitStream is parsed, bit buffer is reset, etc.
329  *
330  *--------------------------------------------------------------
331  */
332 static void ProcessRestart(DecompressInfo *dcPtr)
333 {
334     int c, nbytes;
335     /*short ci;*/
336
337     /*
338      * Throw away any unused bits remaining in bit buffer
339      */
340     nbytes = bitsLeft / 8;
341     bitsLeft = 0;
342
343     /*
344      * Scan for next JPEG marker
345      */
346     do 
347         {
348                 do 
349                 {   /* skip any non-FF bytes */
350                     nbytes++;
351                     c = GetJpegChar();
352                 } 
353                 while (c != 0xFF);
354         
355                 do 
356                 {   /* skip any duplicate FFs */
357                     /*
358                      * we don't increment nbytes here since extra FFs are legal
359                      */
360                     c = GetJpegChar ();
361                 } 
362                 while (c == 0xFF);
363     } 
364         while (c == 0); /* repeat if it was a stuffed FF/00 */
365
366     if (c != (RST0 + dcPtr->nextRestartNum)) {
367
368         /*
369          * Uh-oh, the restart markers have been messed up too.
370          * Just bail out.
371          */
372         fprintf (stderr, "Error: Corrupt JPEG data.  Exiting...\n");
373         /* exit(-1); */ 
374         dcPtr->error = -1; return;
375     }
376
377     /*
378      * Update restart state
379      */
380     dcPtr->restartRowsToGo = dcPtr->restartInRows;
381     dcPtr->nextRestartNum = (dcPtr->nextRestartNum + 1) & 7;
382 }
383
384 /*
385  *--------------------------------------------------------------
386  *
387  * DecodeFirstRow --
388  *
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.
393  *
394  * Results:
395  *        None.
396  *
397  * Side effects:
398  *        Bitstream is parsed.
399  *
400  *--------------------------------------------------------------
401  */
402 void DecodeFirstRow (DecompressInfo *dcPtr, MCU *curRowBuf)
403 {
404     register short curComp,ci;
405     register int s,col,compsInScan,numCOL;
406     register JpegComponentInfo *compptr;
407     int Pr,Pt,d;
408     HuffmanTable *dctbl;
409     Pr=dcPtr->dataPrecision;
410     Pt=dcPtr->Pt;
411     compsInScan=dcPtr->compsInScan;
412     numCOL=dcPtr->imageWidth;
413
414     /*
415      * the start of the scan or at the beginning of restart interval.
416      */
417     for (curComp = 0; curComp < compsInScan; curComp++) {
418         ci = dcPtr->MCUmembership[curComp];
419         compptr = dcPtr->curCompInfo[ci];
420         dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];
421
422         /*
423          * Section F.2.2.1: decode the difference
424          */
425         HuffDecode (dctbl,s);
426         if (s) {
427            get_bits(s,d);
428            HuffExtend(d,s);
429            } else {
430            d = 0;
431         }
432
433         /* 
434          * Add the predictor to the difference.
435          */
436         curRowBuf[0][curComp]=d+(1<<(Pr-Pt-1));
437     }
438
439     /*
440      * the rest of the first row
441      */
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];
447
448             /*
449              * Section F.2.2.1: decode the difference
450              */
451             HuffDecode (dctbl,s);
452             if (s) {
453                get_bits(s,d);
454                HuffExtend(d,s);
455                } else {
456                d = 0;
457             }
458
459             /* 
460              * Add the predictor to the difference.
461              */
462             curRowBuf[col][curComp]=d+curRowBuf[col-1][curComp];
463         }
464     }
465
466     if (dcPtr->restartInRows) {
467        (dcPtr->restartRowsToGo)--;
468     }
469 }/*endof DecodeFirstRow*/
470
471 /*
472  *--------------------------------------------------------------
473  *
474  * DecodeImage --
475  *
476  *      Decode the input stream. This includes modifying
477  *      the component value so the real value, not the
478  *      difference is returned.
479  *
480  * Results:
481  *      None.
482  *
483  * Side effects:
484  *      Bitstream is parsed.
485  *
486  *--------------------------------------------------------------
487  */
488 void DecodeImage (DecompressInfo *dcPtr, unsigned short **image, int depth)
489 {
490     register int s, d, col, row;
491     register short curComp, ci;
492     HuffmanTable *dctbl;
493     JpegComponentInfo *compptr;
494     int predictor;
495     int numCOL, numROW, compsInScan;
496     MCU *prevRowBuf, *curRowBuf;
497     int imagewidth, Pt, psv;
498     unsigned short *image16tmp;
499     unsigned char *image8tmp, *image24tmp;
500              
501     numCOL      = imagewidth=dcPtr->imageWidth;
502     numROW      = dcPtr->imageHeight;
503     compsInScan = dcPtr->compsInScan;
504     Pt          = dcPtr->Pt;
505     psv         = dcPtr->Ss;
506     prevRowBuf  = mcuROW2;
507     curRowBuf   = mcuROW1;
508
509     if (depth == 8) 
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;
515     else {
516                 fprintf(stderr,"Unsupported image depth %d\n",depth);
517                 dcPtr->error = -1; return;
518          } 
519
520     /*
521      * Decode the first row of image. Output the row and
522      * turn this row into a previous row for later predictor
523      * calculation.
524      */         
525     row = 0;
526     DecodeFirstRow (dcPtr, curRowBuf);
527  
528     if (depth == 8) 
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);
534
535     gdcmSWAP(MCU *, prevRowBuf, curRowBuf);
536
537     /* optimal case : 8 bit image, one color component, no restartInRows */
538     if ((depth == 8) && (compsInScan == 1) && (dcPtr->restartInRows == 0)) 
539         {
540
541       unsigned char        *curPixelPtr;
542       int                 left,upper,diag;
543       
544       /* initializations */
545  
546       curComp      = 0;
547       ci           = dcPtr->MCUmembership[curComp];
548       compptr      = dcPtr->curCompInfo[ci];
549       dctbl        = dcPtr->dcHuffTblPtrs[compptr->dcTblNo]; 
550       curPixelPtr  = image8tmp;
551
552       for (row=1; row<numROW; row++) 
553           {
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); } 
558           else d = 0;
559           *curPixelPtr = (unsigned char) (d + *(curPixelPtr - numCOL));
560           curPixelPtr++;
561
562           if (psv == 1) {
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); }
567               else d = 0;
568
569               *curPixelPtr = (unsigned char) (d + *(curPixelPtr - 1));
570               curPixelPtr++;
571             }/*endfor col*/
572           }/*endif*/
573           
574           else {
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); }
579               else d = 0;
580
581               /* Predict : All predictors are calculated according to psv */
582               switch (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;
602               }/*endsandwich*/
603
604               *curPixelPtr = (unsigned char) (d + predictor);
605               curPixelPtr++;
606             }/*endfor col*/
607           }/*endelse*/
608           
609       }/*endfor row*/
610     }/*endif fast case*/
611     
612     else { /*normal case with 16 bits or color or ...*/
613       for (row=1; row<numROW; row++) {
614         /*
615          * Account for restart interval, process restart marker if needed.
616          */
617         if (dcPtr->restartInRows) 
618                 {
619            if (dcPtr->restartRowsToGo == 0) 
620                    {
621               ProcessRestart (dcPtr); if (dcPtr->error) return;
622               /*
623                * Reset predictors at restart.
624                */
625               DecodeFirstRow(dcPtr,curRowBuf);
626               if (depth == 8) 
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);
632
633               gdcmSWAP(MCU *,prevRowBuf,curRowBuf);
634               continue;
635            }
636            dcPtr->restartRowsToGo--;
637         }/*endif*/
638
639         /*
640          * For the rest of the column on this row, predictor
641          * calculations are base on PSV. 
642          */
643         
644         /* several color components to decode (RGB colors)*/
645
646         /* The upper neighbors are predictors for the first column. */
647         for (curComp = 0; curComp < compsInScan; curComp++) 
648                 {
649             ci = dcPtr->MCUmembership[curComp];
650             compptr = dcPtr->curCompInfo[ci];
651             dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];
652
653             /* Section F.2.2.1: decode the difference */
654             HuffDecode (dctbl,s);
655             if (s) { get_bits(s,d); HuffExtend(d,s); } 
656             else d = 0;
657             curRowBuf[0][curComp]=d+prevRowBuf[0][curComp];
658         }/*endfor curComp*/
659           
660         for (col=1; col < numCOL; col++) 
661                 {
662             for (curComp = 0; curComp < compsInScan; curComp++) 
663                         {
664                 ci = dcPtr->MCUmembership[curComp];
665                 compptr = dcPtr->curCompInfo[ci];
666                 dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];
667
668                 /* Section F.2.2.1: decode the difference */
669                 HuffDecode (dctbl, s);
670                 if (s) { get_bits (s, d); HuffExtend (d, s); }
671                 else d = 0;
672
673                 QuickPredict (col,curComp,curRowBuf,prevRowBuf,psv,&predictor);
674
675                 curRowBuf[col][curComp]=d+predictor;
676             }/*endfor curComp*/
677         }/*endfor col*/
678         
679               if (depth == 8) 
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);
685
686               gdcmSWAP(MCU *, prevRowBuf, curRowBuf);
687       
688       }/*endfor row*/
689     }/*endelse*/
690 }/*endofmethod DecodeImage*/