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