]> Creatis software - gdcm.git/blob - src/gdcmjpegls/Decoder/bitio.c
The bad hack I made to bypass illegal images where undefined length UN data
[gdcm.git] / src / gdcmjpegls / Decoder / bitio.c
1 /* SPMG/JPEG-LS IMPLEMENTATION V.2.1
2    =====================================
3    These programs are Copyright (c) University of British Columbia. All rights reserved.
4    They may be freely redistributed in their entirety provided that this copyright
5    notice is not removed. THEY MAY NOT BE SOLD FOR PROFIT OR INCORPORATED IN
6    COMMERCIAL PROGRAMS WITHOUT THE WRITTEN PERMISSION OF THE COPYRIGHT HOLDER.
7    Each program is provided as is, without any express or implied warranty,
8    without even the warranty of fitness for a particular purpose.
9
10    =========================================================
11    THIS SOFTWARE IS BASED ON HP's implementation of jpeg-ls:
12    =========================================================
13
14    LOCO-I/JPEG-LS IMPLEMENTATION V.0.90
15    -------------------------------------------------------------------------------
16    (c) COPYRIGHT HEWLETT-PACKARD COMPANY, 1995-1999.
17         HEWLETT-PACKARD COMPANY ("HP") DOES NOT WARRANT THE ACCURACY OR
18    COMPLETENESS OF THE INFORMATION GIVEN HERE.  ANY USE MADE OF, OR
19    RELIANCE ON, SUCH INFORMATION IS ENTIRELY AT USER'S OWN RISK.
20         BY DOWNLOADING THE LOCO-I/JPEG-LS COMPRESSORS/DECOMPRESSORS
21    ("THE SOFTWARE") YOU AGREE TO BE BOUND BY THE TERMS AND CONDITIONS
22    OF THIS LICENSING AGREEMENT.
23         YOU MAY DOWNLOAD AND USE THE SOFTWARE FOR NON-COMMERCIAL PURPOSES
24    FREE OF CHARGE OR FURTHER OBLIGATION.  YOU MAY NOT, DIRECTLY OR
25    INDIRECTLY, DISTRIBUTE THE SOFTWARE FOR A FEE, INCORPORATE THIS
26    SOFTWARE INTO ANY PRODUCT OFFERED FOR SALE, OR USE THE SOFTWARE
27    TO PROVIDE A SERVICE FOR WHICH A FEE IS CHARGED.
28         YOU MAY MAKE COPIES OF THE SOFTWARE AND DISTRIBUTE SUCH COPIES TO
29    OTHER PERSONS PROVIDED THAT SUCH COPIES ARE ACCOMPANIED BY
30    HEWLETT-PACKARD'S COPYRIGHT NOTICE AND THIS AGREEMENT AND THAT
31    SUCH OTHER PERSONS AGREE TO BE BOUND BY THE TERMS OF THIS AGREEMENT.
32         THE SOFTWARE IS NOT OF PRODUCT QUALITY AND MAY HAVE ERRORS OR DEFECTS.
33    THE JPEG-LS STANDARD IS STILL UNDER DEVELOPMENT. THE SOFTWARE IS NOT A
34    FINAL OR FULL IMPLEMENTATION OF THE STANDARD.  HP GIVES NO EXPRESS OR
35    IMPLIED WARRANTY OF ANY KIND AND ANY IMPLIED WARRANTIES OF
36    MERCHANTABILITY AND FITNESS FOR PURPOSE ARE DISCLAIMED.
37         HP SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
38    OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE.
39    -------------------------------------------------------------------------------
40 */
41
42 /*
43  *
44  * Initial code by Alex Jakulin,  Aug. 1995
45  *
46  * Modified and optimized: Gadiel Seroussi, October 1995
47  *
48  * Modified and added Restart marker and input tables by:
49  * David Cheng-Hsiu Chu, and Ismail R. Ismail march 1999
50  */
51
52 #include "global.h"
53 #include "bitio.h"
54 #include <string.h> /* for memset */
55
56
57 /*extern int zeroLUT[];  */   /* lookup table to find number of leading zeroes */
58
59 /*extern FILE *in, *out; */
60
61 byte negbuff[BUFSIZE+4];    /* byte I/O buffer, allowing for 4 "negative" 
62                    locations  */
63
64 /*
65  'buff' is defined as 'rawbuff+4' in bitio.h, so that buff[-4]..buff[-1]
66  are well defined. Those locations are used to "return" data to
67  the byte buffer when flushing the input bit buffer .
68  */
69
70
71 int fp;          /* index into byte buffer */
72 int truebufsize;       /* true size of byte buffer ( <= BUFSIZE) */
73 int foundeof;
74
75 int zeroLUT[256];      /* table to find out number of leading zeros */
76
77
78 /* BIT I/O variables */
79 dword reg; /* BIT buffer for input/output */
80 int bits;  /* number of bits free in bit buffer (on output) */
81            /* (number of bits free)-8 in bit buffer (on input)*/
82
83
84 /****************************************************************************
85  *  INPUT ROUTINES
86  *  note: some routines are implemented as preprocessor macros. See bitio.h.
87  ****************************************************************************/
88
89
90 void bufiinit(FILE *fil) {
91     /* argument is ignored */
92     (void)fil;
93     fp = BUFSIZE;
94     truebufsize = 0;
95     foundeof = 0;
96 }
97
98
99 byte fillinbuff(FILE *fil)
100 {
101   int i;
102
103   /* remember 4 last bytes of current buffer (for "undo") */
104   for ( i=-4; i<0; i++ )
105     buff[i] = buff[fp+i];
106         truebufsize = fread(buff, 1, BUFSIZE, fil);
107   if ( truebufsize < BUFSIZE ) 
108   {
109       if ( truebufsize <= 0 ) 
110     {
111       if ( foundeof ) 
112       {  /* second attempt to read past EOF */
113         fprintf(stderr,"*** Premature EOF in compressed file\n");
114         exit(10);
115       }
116       else 
117       {
118         /* One attempt to read past EOF is OK  */
119         foundeof = 1;
120       }
121       }
122       /* fill buffer with zeros */
123       memset(buff+truebufsize, 0, (BUFSIZE-truebufsize)*sizeof(*buff));
124   }
125
126   fp = 1;
127     return buff[0];
128 }
129
130
131 /* Initializes the bit input routines */
132 void bitiinit() {
133         bits = reg = 0;
134         fillbuffer(24);
135 }
136
137
138 /* 
139    Flush the input bit buffer TO A BYTE BOUNDARY. Return unused whole
140    bytes to the byte buffer
141  */
142 void bitiflush()  {
143     int filled,
144   discard, 
145   dbytes,
146   i, k;
147   unsigned int treg;
148     byte *bp;
149
150     filled = 24 - bits;    /* how many bits at the MS part of reg 
151             have unused data. These correspond to 
152             at most filled+2 bits from the input
153             stream, as at most 2 '0' bits might have
154             been dropped by marker processing */
155
156     dbytes = (filled+2)/8;  /* the coorrect number of bytes we need to
157         "unget" is either dbytes or dbytes-1 */
158     /* this solution is more general than what is required here: it 
159        will work correctly even if the end of a scan is not followed
160        by a marker, as will necessarily be the case with the standard JPEG
161        format */
162     for ( ; ; dbytes-- ) 
163   {
164     bp = buff + fp - dbytes;  /* back-in the buffer */
165     treg = k = 0;
166     for ( i=0; i<dbytes; i++ ) 
167     {
168       if ( bp[i-1]==0xff && (bp[i]&0x80)==0 ) 
169       {
170         treg |= bp[i] << (BITBUFSIZE-7-k);
171         k += 7;
172       }
173       else 
174       {
175         treg |= bp[i] << (BITBUFSIZE-8-k);
176         k += 8;
177       }
178     }
179
180     if ( k <= filled )
181     break;
182     }
183     /* check consistency */
184     if ( filled-k > 7 ) {
185       fprintf(stderr,"bitiflush: inconsistent bits=%d filled=%d k=%d\n",bits,filled,k);
186       exit(10);
187     }
188     discard = filled-k;
189     if ( treg != (reg<<discard) ) {
190       fprintf(stderr,"bitiflush: inconsistent bits=%d discard=%d reg=%08lx treg=%08x\n",bits, discard, reg, treg);
191       exit(10);
192     }
193     if ( reg & (((1<<discard)-1)<<(BITBUFSIZE-discard)) )
194       fprintf(stderr,"bitiflush: Warning: discarding nonzero bits; reg=%08lx bits=%d discard=%d\n",reg,bits,discard);
195
196     fp -= dbytes;  /* do the unget */
197     if ( buff[fp-1]==0xff && buff[fp]==0 ) fp++;
198
199     bits = 0;
200     reg = 0;
201 }
202
203
204
205
206 /* Unpad zeros from byte length */
207 void unpadzeros()
208 {
209   int z;
210
211   z = bits % 8;
212   
213   if (bits!=24)
214   {
215     reg = (reg << z);
216     bits = bits + z;
217   }
218
219
220 }
221   
222   
223
224
225 /* creates the bit counting look-up table. */
226 void createzeroLUT()
227 {
228         int i, j, k, l;
229
230         j = k = 1; l = 8;
231         for (i = 0; i < 256; ++i) {
232                 zeroLUT[i] = l;
233                 --k;
234                 if (k == 0) {
235                         k = j;
236                         --l;
237                         j *= 2;
238                 }
239         }
240 }
241
242
243
244 #ifdef IOFXNS
245 /* if using functions instead of macros */
246 dword
247 getbits(int no) 
248 {
249         register dword temp;
250
251         assert(no > 0 && no <= 18);
252         temp = reg >> (32 - no);
253         fillbuffer(no);
254         return temp;
255 }
256 #  define GETBITS(n)  getbits(n)
257 #else
258 /* see GETBITS(x,n) in bitio.h */
259 #endif