1 /*
2  * Small jpeg decoder library
3  *
4  * Copyright (c) 2006, Luc Saillard <luc@saillard.org>
5  * All rights reserved.
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * - Redistributions of source code must retain the above copyright notice,
10  *  this list of conditions and the following disclaimer.
11  *
12  * - Redistributions in binary form must reproduce the above copyright notice,
13  *  this list of conditions and the following disclaimer in the documentation
14  *  and/or other materials provided with the distribution.
15  *
16  * - Neither the name of the author nor the names of its contributors may be
17  *  used to endorse or promote products derived from this software without
18  *  specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33 
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <stdint.h>
38 #include <errno.h>
39 
40 #include "tinyjpeg.h"
41 #include "tinyjpeg-internal.h"
42 
43 /* Global variable to return the last error found while deconding */
44 static char error_string[256];
45 
46 static const unsigned char zigzag[64] =
47 {
48    0,  1,  5,  6, 14, 15, 27, 28,
49    2,  4,  7, 13, 16, 26, 29, 42,
50    3,  8, 12, 17, 25, 30, 41, 43,
51    9, 11, 18, 24, 31, 40, 44, 53,
52   10, 19, 23, 32, 39, 45, 52, 54,
53   20, 22, 33, 38, 46, 51, 55, 60,
54   21, 34, 37, 47, 50, 56, 59, 61,
55   35, 36, 48, 49, 57, 58, 62, 63
56 };
57 
58 /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
59 /* IMPORTANT: these are only valid for 8-bit data precision! */
60 static const unsigned char bits_dc_luminance[17] =
61 {
62   0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0
63 };
64 static const unsigned char val_dc_luminance[] =
65 {
66   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
67 };
68 
69 static const unsigned char bits_dc_chrominance[17] =
70 {
71   0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
72 };
73 static const unsigned char val_dc_chrominance[] =
74 {
75   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
76 };
77 
78 static const unsigned char bits_ac_luminance[17] =
79 {
80   0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d
81 };
82 static const unsigned char val_ac_luminance[] =
83 {
84   0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
85   0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
86   0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
87   0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
88   0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
89   0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
90   0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
91   0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
92   0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
93   0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
94   0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
95   0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
96   0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
97   0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
98   0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
99   0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
100   0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
101   0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
102   0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
103   0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
104   0xf9, 0xfa
105 };
106 
107 static const unsigned char bits_ac_chrominance[17] =
108 {
109   0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77
110 };
111 
112 static const unsigned char val_ac_chrominance[] =
113 {
114   0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
115   0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
116   0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
117   0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
118   0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
119   0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
120   0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
121   0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
122   0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
123   0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
124   0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
125   0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
126   0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
127   0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
128   0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
129   0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
130   0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
131   0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
132   0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
133   0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
134   0xf9, 0xfa
135 };
136 
137 
138 /*
139  * 4 functions to manage the stream
140  *
141  *  fill_nbits: put at least nbits in the reservoir of bits.
142  *              But convert any 0xff,0x00 into 0xff
143  *  get_nbits: read nbits from the stream, and put it in result,
144  *             bits is removed from the stream and the reservoir is filled
145  *             automaticaly. The result is signed according to the number of
146  *             bits.
147  *  look_nbits: read nbits from the stream without marking as read.
148  *  skip_nbits: read nbits from the stream but do not return the result.
149  *
150  * stream: current pointer in the jpeg data (read bytes per bytes)
151  * nbits_in_reservoir: number of bits filled into the reservoir
152  * reservoir: register that contains bits information. Only nbits_in_reservoir
153  *            is valid.
154  *                          nbits_in_reservoir
155  *                        <--    17 bits    -->
156  *            Ex: 0000 0000 1010 0000 1111 0000   <== reservoir
157  *                        ^
158  *                        bit 1
159  *            To get two bits from this example
160  *                 result = (reservoir >> 15) & 3
161  *
162  */
163 #define fill_nbits(reservoir,nbits_in_reservoir,stream,nbits_wanted) do { \
164    while (nbits_in_reservoir<nbits_wanted) \
165     { \
166       unsigned char c; \
167       if (stream >= priv->stream_end) \
168         longjmp(priv->jump_state, -EIO); \
169       c = *stream++; \
170       reservoir <<= 8; \
171       if (c == 0xff && *stream == 0x00) \
172         stream++; \
173       reservoir |= c; \
174       nbits_in_reservoir+=8; \
175     } \
176 }  while(0);
177 
178 /* Signed version !!!! */
179 #define get_nbits(reservoir,nbits_in_reservoir,stream,nbits_wanted,result) do { \
180    fill_nbits(reservoir,nbits_in_reservoir,stream,(nbits_wanted)); \
181    result = ((reservoir)>>(nbits_in_reservoir-(nbits_wanted))); \
182    nbits_in_reservoir -= (nbits_wanted);  \
183    reservoir &= ((1U<<nbits_in_reservoir)-1); \
184    if ((unsigned int)result < (1UL<<((nbits_wanted)-1))) \
185        result += (0xFFFFFFFFUL<<(nbits_wanted))+1; \
186 }  while(0);
187 
188 #define look_nbits(reservoir,nbits_in_reservoir,stream,nbits_wanted,result) do { \
189    fill_nbits(reservoir,nbits_in_reservoir,stream,(nbits_wanted)); \
190    result = ((reservoir)>>(nbits_in_reservoir-(nbits_wanted))); \
191 }  while(0);
192 
193 /* To speed up the decoding, we assume that the reservoir have enough bit
194  * slow version:
195  * #define skip_nbits(reservoir,nbits_in_reservoir,stream,nbits_wanted) do { \
196  *   fill_nbits(reservoir,nbits_in_reservoir,stream,(nbits_wanted)); \
197  *   nbits_in_reservoir -= (nbits_wanted); \
198  *   reservoir &= ((1U<<nbits_in_reservoir)-1); \
199  * }  while(0);
200  */
201 #define skip_nbits(reservoir,nbits_in_reservoir,stream,nbits_wanted) do { \
202    nbits_in_reservoir -= (nbits_wanted); \
203    reservoir &= ((1U<<nbits_in_reservoir)-1); \
204 }  while(0);
205 
206 
207 #define be16_to_cpu(x) (((x)[0]<<8)|(x)[1])
208 
209 static void resync(struct jdec_private *priv);
210 
211 /**
212  * Get the next (valid) huffman code in the stream.
213  *
214  * To speedup the procedure, we look HUFFMAN_HASH_NBITS bits and the code is
215  * lower than HUFFMAN_HASH_NBITS we have automaticaly the length of the code
216  * and the value by using two lookup table.
217  * Else if the value is not found, just search (linear) into an array for each
218  * bits is the code is present.
219  *
220  * If the code is not present for any reason, -1 is return.
221  */
get_next_huffman_code(struct jdec_private * priv,struct huffman_table * huffman_table)222 static int get_next_huffman_code(struct jdec_private *priv, struct huffman_table *huffman_table)
223 {
224   int value, hcode;
225   unsigned int extra_nbits, nbits;
226   uint16_t *slowtable;
227 
228   look_nbits(priv->reservoir, priv->nbits_in_reservoir, priv->stream, HUFFMAN_HASH_NBITS, hcode);
229   value = huffman_table->lookup[hcode];
230   if (__likely(value >= 0))
231   {
232      unsigned int code_size = huffman_table->code_size[value];
233      skip_nbits(priv->reservoir, priv->nbits_in_reservoir, priv->stream, code_size);
234      return value;
235   }
236 
237   /* Decode more bits each time ... */
238   for (extra_nbits=0; extra_nbits<16-HUFFMAN_HASH_NBITS; extra_nbits++)
239    {
240      nbits = HUFFMAN_HASH_NBITS + 1 + extra_nbits;
241 
242      look_nbits(priv->reservoir, priv->nbits_in_reservoir, priv->stream, nbits, hcode);
243      slowtable = huffman_table->slowtable[extra_nbits];
244      /* Search if the code is in this array */
245      while (slowtable[0]) {
246 	if (slowtable[0] == hcode) {
247 	   skip_nbits(priv->reservoir, priv->nbits_in_reservoir, priv->stream, nbits);
248 	   return slowtable[1];
249 	}
250 	slowtable+=2;
251      }
252    }
253   return 0;
254 }
255 
256 
257 
258 
259 /**
260  *
261  * Decode a single block that contains the DCT coefficients.
262  * The table coefficients is already dezigzaged at the end of the operation.
263  *
264  */
tinyjpeg_process_Huffman_data_unit(struct jdec_private * priv,int component)265 void tinyjpeg_process_Huffman_data_unit(struct jdec_private *priv, int component)
266 {
267   unsigned char j;
268   unsigned int huff_code;
269   unsigned char size_val, count_0;
270 
271   struct component *c = &priv->component_infos[component];
272   short int DCT[64];
273 
274 
275   /* Initialize the DCT coef table */
276   memset(DCT, 0, sizeof(DCT));
277 
278   /* DC coefficient decoding */
279   huff_code = get_next_huffman_code(priv, c->DC_table);
280   //trace("+ %x\n", huff_code);
281   if (huff_code) {
282      get_nbits(priv->reservoir, priv->nbits_in_reservoir, priv->stream, huff_code, DCT[0]);
283      DCT[0] += c->previous_DC;
284      c->previous_DC = DCT[0];
285   } else {
286      DCT[0] = c->previous_DC;
287   }
288 
289   /* AC coefficient decoding */
290   j = 1;
291   while (j<64)
292    {
293      huff_code = get_next_huffman_code(priv, c->AC_table);
294      //trace("- %x\n", huff_code);
295 
296      size_val = huff_code & 0xF;
297      count_0 = huff_code >> 4;
298 
299      if (size_val == 0)
300       { /* RLE */
301 	if (count_0 == 0)
302 	  break;	/* EOB found, go out */
303 	else if (count_0 == 0xF)
304 	  j += 16;	/* skip 16 zeros */
305       }
306      else
307       {
308 	j += count_0;	/* skip count_0 zeroes */
309 	if (__unlikely(j >= 64))
310 	 {
311 	   snprintf(error_string, sizeof(error_string), "Bad huffman data (buffer overflow)");
312 	   break;
313 	 }
314 	get_nbits(priv->reservoir, priv->nbits_in_reservoir, priv->stream, size_val, DCT[j]);
315 	j++;
316       }
317    }
318 
319   for (j = 0; j < 64; j++)
320     c->DCT[j] = DCT[zigzag[j]];
321 }
322 
323 /*
324  * Takes two array of bits, and build the huffman table for size, and code
325  *
326  * lookup will return the symbol if the code is less or equal than HUFFMAN_HASH_NBITS.
327  * code_size will be used to known how many bits this symbol is encoded.
328  * slowtable will be used when the first lookup didn't give the result.
329  */
build_huffman_table(const unsigned char * bits,const unsigned char * vals,struct huffman_table * table)330 static void build_huffman_table(const unsigned char *bits, const unsigned char *vals, struct huffman_table *table)
331 {
332   unsigned int i, j, code, code_size, val, nbits;
333   unsigned char huffsize[HUFFMAN_BITS_SIZE+1], *hz;
334   unsigned int huffcode[HUFFMAN_BITS_SIZE+1], *hc;
335 
336   /*
337    * Build a temp array
338    *   huffsize[X] => numbers of bits to write vals[X]
339    */
340   hz = huffsize;
341   for (i=1; i<=16; i++)
342    {
343      for (j=1; j<=bits[i]; j++)
344        *hz++ = i;
345    }
346   *hz = 0;
347 
348   memset(table->lookup, 0xff, sizeof(table->lookup));
349   for (i=0; i<(16-HUFFMAN_HASH_NBITS); i++)
350     table->slowtable[i][0] = 0;
351 
352   /* Build a temp array
353    *   huffcode[X] => code used to write vals[X]
354    */
355   code = 0;
356   hc = huffcode;
357   hz = huffsize;
358   nbits = *hz;
359   while (*hz)
360    {
361      while (*hz == nbits)
362       {
363 	*hc++ = code++;
364 	hz++;
365       }
366      code <<= 1;
367      nbits++;
368    }
369 
370   /*
371    * Build the lookup table, and the slowtable if needed.
372    */
373   for (i=0; huffsize[i]; i++)
374    {
375      val = vals[i];
376      code = huffcode[i];
377      code_size = huffsize[i];
378 
379      trace("val=%2.2x code=%8.8x codesize=%2.2d\n", val, code, code_size);
380 
381      table->code_size[val] = code_size;
382      if (code_size <= HUFFMAN_HASH_NBITS)
383       {
384 	/*
385 	 * Good: val can be put in the lookup table, so fill all value of this
386 	 * column with value val
387 	 */
388 	int repeat = 1UL<<(HUFFMAN_HASH_NBITS - code_size);
389 	code <<= HUFFMAN_HASH_NBITS - code_size;
390 	while ( repeat-- )
391 	  table->lookup[code++] = val;
392 
393       }
394      else
395       {
396 	/* Perhaps sorting the array will be an optimization */
397 	uint16_t *slowtable = table->slowtable[code_size-HUFFMAN_HASH_NBITS-1];
398 	while(slowtable[0])
399 	  slowtable+=2;
400 	slowtable[0] = code;
401 	slowtable[1] = val;
402 	slowtable[2] = 0;
403 	/* TODO: NEED TO CHECK FOR AN OVERFLOW OF THE TABLE */
404       }
405 
406    }
407 }
408 
build_default_huffman_tables(struct jdec_private * priv)409 static void build_default_huffman_tables(struct jdec_private *priv)
410 {
411   if (   (priv->flags & TINYJPEG_FLAGS_MJPEG_TABLE)
412       && priv->default_huffman_table_initialized)
413     return;
414 
415   build_huffman_table(bits_dc_luminance, val_dc_luminance, &priv->HTDC[0]);
416   build_huffman_table(bits_ac_luminance, val_ac_luminance, &priv->HTAC[0]);
417 
418   build_huffman_table(bits_dc_chrominance, val_dc_chrominance, &priv->HTDC[1]);
419   build_huffman_table(bits_ac_chrominance, val_ac_chrominance, &priv->HTAC[1]);
420 
421   priv->default_huffman_table_initialized = 1;
422 }
423 
424 
425 
426 /*******************************************************************************
427  *
428  * Colorspace conversion routine
429  *
430  *
431  * Note:
432  * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
433  * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
434  * The conversion equations to be implemented are therefore
435  *      R = Y                + 1.40200 * Cr
436  *      G = Y - 0.34414 * Cb - 0.71414 * Cr
437  *      B = Y + 1.77200 * Cb
438  *
439  ******************************************************************************/
440 
print_SOF(const unsigned char * stream)441 static void print_SOF(const unsigned char *stream)
442 {
443 #if JPEG_DEBUG
444   int width, height, nr_components, precision;
445   const char *nr_components_to_string[] = {
446      "????",
447      "Grayscale",
448      "????",
449      "YCbCr",
450      "CYMK"
451   };
452 
453   precision = stream[2];
454   height = be16_to_cpu(stream+3);
455   width  = be16_to_cpu(stream+5);
456   nr_components = stream[7];
457 
458   trace("> SOF marker\n");
459   trace("Size:%dx%d nr_components:%d (%s)  precision:%d\n",
460       width, height,
461       nr_components, nr_components_to_string[nr_components],
462       precision);
463 #endif
464   (void)stream;
465 }
466 
467 /*******************************************************************************
468  *
469  * JPEG/JFIF Parsing functions
470  *
471  * Note: only a small subset of the jpeg file format is supported. No markers,
472  * nor progressive stream is supported.
473  *
474  ******************************************************************************/
475 
build_quantization_table(float * qtable,const unsigned char * ref_table)476 static void build_quantization_table(float *qtable, const unsigned char *ref_table)
477 {
478   /* Taken from libjpeg. Copyright Independent JPEG Group's LLM idct.
479    * For float AA&N IDCT method, divisors are equal to quantization
480    * coefficients scaled by scalefactor[row]*scalefactor[col], where
481    *   scalefactor[0] = 1
482    *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
483    * We apply a further scale factor of 8.
484    * What's actually stored is 1/divisor so that the inner loop can
485    * use a multiplication rather than a division.
486    */
487   int i, j;
488   static const double aanscalefactor[8] = {
489      1.0, 1.387039845, 1.306562965, 1.175875602,
490      1.0, 0.785694958, 0.541196100, 0.275899379
491   };
492   const unsigned char *zz = zigzag;
493 
494   for (i=0; i<8; i++) {
495      for (j=0; j<8; j++) {
496        *qtable++ = ref_table[*zz++] * aanscalefactor[i] * aanscalefactor[j];
497      }
498    }
499 
500 }
501 
parse_DQT(struct jdec_private * priv,const unsigned char * stream)502 static int parse_DQT(struct jdec_private *priv, const unsigned char *stream)
503 {
504   int qi;
505   float *table;
506   const unsigned char *dqt_block_end;
507 
508   trace("> DQT marker\n");
509   dqt_block_end = stream + be16_to_cpu(stream);
510   stream += 2;	/* Skip length */
511 
512   while (stream < dqt_block_end)
513    {
514      qi = *stream++;
515 #if SANITY_CHECK
516      if (qi>>4)
517        error("16 bits quantization table is not supported\n");
518      if (qi>4)
519        error("No more 4 quantization table is supported (got %d)\n", qi);
520 #endif
521      table = priv->Q_tables[qi];
522      build_quantization_table(table, stream);
523      stream += 64;
524    }
525   trace("< DQT marker\n");
526   return 0;
527 }
528 
parse_SOF(struct jdec_private * priv,const unsigned char * stream)529 static int parse_SOF(struct jdec_private *priv, const unsigned char *stream)
530 {
531   int i, width, height, nr_components, cid, sampling_factor;
532   int Q_table;
533   struct component *c;
534 
535   trace("> SOF marker\n");
536   print_SOF(stream);
537 
538   height = be16_to_cpu(stream+3);
539   width  = be16_to_cpu(stream+5);
540   nr_components = stream[7];
541 #if SANITY_CHECK
542   if (stream[2] != 8)
543     error("Precision other than 8 is not supported\n");
544   if (width>JPEG_MAX_WIDTH || height>JPEG_MAX_HEIGHT)
545     error("Width and Height (%dx%d) seems suspicious\n", width, height);
546   if (nr_components != 3)
547     error("We only support YUV images\n");
548 #endif
549   stream += 8;
550   for (i=0; i<nr_components; i++) {
551      cid = *stream++;
552      sampling_factor = *stream++;
553      Q_table = *stream++;
554      c = &priv->component_infos[i];
555 #if SANITY_CHECK
556      c->cid = cid;
557      if (Q_table >= COMPONENTS)
558        error("Bad Quantization table index (got %d, max allowed %d)\n", Q_table, COMPONENTS-1);
559 #endif
560      c->Vfactor = sampling_factor&0xf;
561      c->Hfactor = sampling_factor>>4;
562      c->Q_table = priv->Q_tables[Q_table];
563      trace("Component:%d  factor:%dx%d  Quantization table:%d\n",
564            cid, c->Hfactor, c->Hfactor, Q_table );
565 
566   }
567   priv->width = width;
568   priv->height = height;
569 
570   trace("< SOF marker\n");
571 
572   return 0;
573 }
574 
parse_SOS(struct jdec_private * priv,const unsigned char * stream)575 static int parse_SOS(struct jdec_private *priv, const unsigned char *stream)
576 {
577   unsigned int i, cid, table;
578   unsigned int nr_components = stream[2];
579 
580   trace("> SOS marker\n");
581 
582 #if SANITY_CHECK
583   if (nr_components != 3)
584     error("We only support YCbCr image\n");
585 #endif
586 
587   stream += 3;
588   for (i=0;i<nr_components;i++) {
589      cid = *stream++;
590      table = *stream++;
591 #if SANITY_CHECK
592      if ((table&0xf)>=4)
593 	error("We do not support more than 2 AC Huffman table\n");
594      if ((table>>4)>=4)
595 	error("We do not support more than 2 DC Huffman table\n");
596      if (cid != priv->component_infos[i].cid)
597         error("SOS cid order (%d:%d) isn't compatible with the SOF marker (%d:%d)\n",
598 	      i, cid, i, priv->component_infos[i].cid);
599      trace("ComponentId:%d  tableAC:%d tableDC:%d\n", cid, table&0xf, table>>4);
600 #endif
601      priv->component_infos[i].AC_table = &priv->HTAC[table&0xf];
602      priv->component_infos[i].DC_table = &priv->HTDC[table>>4];
603   }
604   priv->stream = stream+3;
605   trace("< SOS marker\n");
606   return 0;
607 }
608 
parse_DHT(struct jdec_private * priv,const unsigned char * stream)609 static int parse_DHT(struct jdec_private *priv, const unsigned char *stream)
610 {
611   unsigned int count, i;
612   unsigned char huff_bits[17];
613   int length, index;
614 
615   length = be16_to_cpu(stream) - 2;
616   stream += 2;	/* Skip length */
617 
618   trace("> DHT marker (length=%d)\n", length);
619 
620   while (length>0) {
621      index = *stream++;
622 
623      /* We need to calculate the number of bytes 'vals' will takes */
624      huff_bits[0] = 0;
625      count = 0;
626      for (i=1; i<17; i++) {
627 	huff_bits[i] = *stream++;
628 	count += huff_bits[i];
629      }
630 #if SANITY_CHECK
631      if (count >= HUFFMAN_BITS_SIZE)
632        error("No more than %d bytes is allowed to describe a huffman table", HUFFMAN_BITS_SIZE);
633      if ( (index &0xf) >= HUFFMAN_TABLES)
634        error("No more than %d Huffman tables is supported (got %d)\n", HUFFMAN_TABLES, index&0xf);
635      trace("Huffman table %s[%d] length=%d\n", (index&0xf0)?"AC":"DC", index&0xf, count);
636 #endif
637 
638      if (index & 0xf0 )
639        build_huffman_table(huff_bits, stream, &priv->HTAC[index&0xf]);
640      else
641        build_huffman_table(huff_bits, stream, &priv->HTDC[index&0xf]);
642 
643      length -= 1;
644      length -= 16;
645      length -= count;
646      stream += count;
647   }
648   trace("< DHT marker\n");
649   return 0;
650 }
651 
parse_DRI(struct jdec_private * priv,const unsigned char * stream)652 static int parse_DRI(struct jdec_private *priv, const unsigned char *stream)
653 {
654   unsigned int length;
655 
656   trace("> DRI marker\n");
657 
658   length = be16_to_cpu(stream);
659 
660 #if SANITY_CHECK
661   if (length != 4)
662     error("Length of DRI marker need to be 4\n");
663 #endif
664 
665   priv->restart_interval = be16_to_cpu(stream+2);
666 
667 #if JPEG_DEBUG
668   trace("Restart interval = %d\n", priv->restart_interval);
669 #endif
670 
671   trace("< DRI marker\n");
672 
673   return 0;
674 }
675 
676 
677 
resync(struct jdec_private * priv)678 static void resync(struct jdec_private *priv)
679 {
680   int i;
681 
682   /* Init DC coefficients */
683   for (i=0; i<COMPONENTS; i++)
684      priv->component_infos[i].previous_DC = 0;
685 
686   priv->reservoir = 0;
687   priv->nbits_in_reservoir = 0;
688   if (priv->restart_interval > 0)
689     priv->restarts_to_go = priv->restart_interval;
690   else
691     priv->restarts_to_go = -1;
692 }
693 
find_next_rst_marker(struct jdec_private * priv)694 static int find_next_rst_marker(struct jdec_private *priv)
695 {
696   int rst_marker_found = 0;
697   int marker;
698   const unsigned char *stream = priv->stream;
699 
700   /* Parse marker */
701   while (!rst_marker_found)
702    {
703      while (*stream++ != 0xff)
704       {
705 	if (stream >= priv->stream_end)
706 	  error("EOF while search for a RST marker.");
707       }
708      /* Skip any padding ff byte (this is normal) */
709      while (*stream == 0xff)
710        stream++;
711 
712      marker = *stream++;
713      if ((RST+priv->last_rst_marker_seen) == marker)
714        rst_marker_found = 1;
715      else if (marker >= RST && marker <= RST7)
716        error("Wrong Reset marker found, abording");
717      else if (marker == EOI)
718        return 0;
719    }
720   trace("RST Marker %d found at offset %d\n", priv->last_rst_marker_seen, stream - priv->stream_begin);
721 
722   priv->stream = stream;
723   priv->last_rst_marker_seen++;
724   priv->last_rst_marker_seen &= 7;
725 
726   return 0;
727 }
728 
parse_JFIF(struct jdec_private * priv,const unsigned char * stream)729 static int parse_JFIF(struct jdec_private *priv, const unsigned char *stream)
730 {
731   int chuck_len;
732   int marker;
733   int sos_marker_found = 0;
734   int dht_marker_found = 0;
735   const unsigned char *next_chunck;
736 
737   /* Parse marker */
738   while (!sos_marker_found)
739    {
740      if (*stream++ != 0xff)
741        goto bogus_jpeg_format;
742      /* Skip any padding ff byte (this is normal) */
743      while (*stream == 0xff)
744        stream++;
745 
746      marker = *stream++;
747      chuck_len = be16_to_cpu(stream);
748      next_chunck = stream + chuck_len;
749      switch (marker)
750       {
751        case SOF:
752 	 if (parse_SOF(priv, stream) < 0)
753 	   return -1;
754 	 break;
755        case DQT:
756 	 if (parse_DQT(priv, stream) < 0)
757 	   return -1;
758 	 break;
759        case SOS:
760 	 if (parse_SOS(priv, stream) < 0)
761 	   return -1;
762 	 sos_marker_found = 1;
763 	 break;
764        case DHT:
765 	 if (parse_DHT(priv, stream) < 0)
766 	   return -1;
767 	 dht_marker_found = 1;
768 	 break;
769        case DRI:
770 	 if (parse_DRI(priv, stream) < 0)
771 	   return -1;
772 	 break;
773        default:
774 	 trace("> Unknown marker %2.2x\n", marker);
775 	 break;
776       }
777 
778      stream = next_chunck;
779    }
780 
781   if (!dht_marker_found) {
782     trace("No Huffman table loaded, using the default one\n");
783     build_default_huffman_tables(priv);
784   }
785 
786 #ifdef SANITY_CHECK
787   if (   (priv->component_infos[cY].Hfactor < priv->component_infos[cCb].Hfactor)
788       || (priv->component_infos[cY].Hfactor < priv->component_infos[cCr].Hfactor))
789     error("Horizontal sampling factor for Y should be greater than horitontal sampling factor for Cb or Cr\n");
790   if (   (priv->component_infos[cY].Vfactor < priv->component_infos[cCb].Vfactor)
791       || (priv->component_infos[cY].Vfactor < priv->component_infos[cCr].Vfactor))
792     error("Vertical sampling factor for Y should be greater than vertical sampling factor for Cb or Cr\n");
793   if (   (priv->component_infos[cCb].Hfactor!=1)
794       || (priv->component_infos[cCr].Hfactor!=1)
795       || (priv->component_infos[cCb].Vfactor!=1)
796       || (priv->component_infos[cCr].Vfactor!=1))
797     error("Sampling other than 1x1 for Cr and Cb is not supported");
798 #endif
799 
800   return 0;
801 bogus_jpeg_format:
802   trace("Bogus jpeg format\n");
803   return -1;
804 }
805 
806 /*******************************************************************************
807  *
808  * Functions exported of the library.
809  *
810  * Note: Some applications can access directly to internal pointer of the
811  * structure. It's is not recommended, but if you have many images to
812  * uncompress with the same parameters, some functions can be called to speedup
813  * the decoding.
814  *
815  ******************************************************************************/
816 
817 /**
818  * Allocate a new tinyjpeg decoder object.
819  *
820  * Before calling any other functions, an object need to be called.
821  */
tinyjpeg_init(void)822 struct jdec_private *tinyjpeg_init(void)
823 {
824   struct jdec_private *priv;
825 
826   priv = (struct jdec_private *)calloc(1, sizeof(struct jdec_private));
827   if (priv == NULL)
828     return NULL;
829   return priv;
830 }
831 
832 /**
833  * Free a tinyjpeg object.
834  *
835  * No others function can be called after this one.
836  */
tinyjpeg_free(struct jdec_private * priv)837 void tinyjpeg_free(struct jdec_private *priv)
838 {
839   int i;
840   for (i=0; i<COMPONENTS; i++) {
841      if (priv->components[i])
842        free(priv->components[i]);
843      priv->components[i] = NULL;
844   }
845   free(priv);
846 }
847 
848 /**
849  * Initialize the tinyjpeg object and prepare the decoding of the stream.
850  *
851  * Check if the jpeg can be decoded with this jpeg decoder.
852  * Fill some table used for preprocessing.
853  */
tinyjpeg_parse_header(struct jdec_private * priv,const unsigned char * buf,unsigned int size)854 int tinyjpeg_parse_header(struct jdec_private *priv, const unsigned char *buf, unsigned int size)
855 {
856   int ret;
857 
858   /* Identify the file */
859   if ((buf[0] != 0xFF) || (buf[1] != SOI))
860     error("Not a JPG file ?\n");
861 
862   priv->stream_begin = buf+2;
863   priv->stream_length = size-2;
864   priv->stream_end = priv->stream_begin + priv->stream_length;
865 
866   ret = parse_JFIF(priv, priv->stream_begin);
867 
868   return ret;
869 }
870 
871 /**
872  * Decode and convert the jpeg image into @pixfmt@ image
873  *
874  * Note: components will be automaticaly allocated if no memory is attached.
875  */
tinyjpeg_decode(struct jdec_private * priv,const struct tinyjpeg_colorspace * pixfmt)876 int tinyjpeg_decode(struct jdec_private *priv,
877 		    const struct tinyjpeg_colorspace *pixfmt)
878 {
879   int x, y, sx, sy;
880   int xshift_by_mcu, yshift_by_mcu;
881   int xstride_by_mcu, ystride_by_mcu;
882   unsigned int bytes_per_blocklines[3], bytes_per_mcu[3];
883   decode_MCU_fct decode_MCU;
884   const decode_MCU_fct *decode_mcu_table;
885   convert_colorspace_fct convert_to_pixfmt;
886   uint8_t *pptr[3];
887 
888   decode_mcu_table = pixfmt->decode_mcu_table;
889 
890   /* Fix: check return value */
891   pixfmt->initialize(priv, bytes_per_blocklines, bytes_per_mcu);
892 
893   xshift_by_mcu = yshift_by_mcu = 3;
894   if ((priv->component_infos[cY].Hfactor | priv->component_infos[cY].Vfactor) == 1) {
895      decode_MCU = decode_mcu_table[0];
896      convert_to_pixfmt = pixfmt->convert_colorspace[0];
897      trace("Use decode 1x1 sampling\n");
898   } else if (priv->component_infos[cY].Hfactor == 1) {
899      decode_MCU = decode_mcu_table[1];
900      convert_to_pixfmt = pixfmt->convert_colorspace[1];
901      yshift_by_mcu = 4;
902      trace("Use decode 1x2 sampling (not supported)\n");
903   } else if (priv->component_infos[cY].Vfactor == 2) {
904      decode_MCU = decode_mcu_table[3];
905      convert_to_pixfmt = pixfmt->convert_colorspace[3];
906      xshift_by_mcu = 4;
907      yshift_by_mcu = 4;
908      trace("Use decode 2x2 sampling\n");
909   } else {
910      decode_MCU = decode_mcu_table[2];
911      convert_to_pixfmt = pixfmt->convert_colorspace[2];
912      xshift_by_mcu = 4;
913      trace("Use decode 2x1 sampling\n");
914   }
915 
916   resync(priv);
917 
918   /* Don't forget to that block can be either 8 or 16 lines */
919   bytes_per_blocklines[0] <<= yshift_by_mcu-3;
920   bytes_per_blocklines[1] <<= yshift_by_mcu-3;
921   bytes_per_blocklines[2] <<= yshift_by_mcu-3;
922 
923   bytes_per_mcu[0] <<= xshift_by_mcu-3;
924   bytes_per_mcu[1] <<= xshift_by_mcu-3;
925   bytes_per_mcu[2] <<= xshift_by_mcu-3;
926 
927   xstride_by_mcu = 1 << xshift_by_mcu;
928   ystride_by_mcu = 1 << yshift_by_mcu;
929 
930   pptr[0] = priv->components[0];
931   pptr[1] = priv->components[1];
932   pptr[2] = priv->components[2];
933 
934   trace("bpbl = %d, bpmcu = %d\n",
935 	bytes_per_blocklines[0], bytes_per_mcu[0]);
936 
937   for (y = priv->height; y > 0; y -= ystride_by_mcu)
938    {
939      trace("Decoding row %d\n", priv->height-y);
940      priv->plane[0] = pptr[0];  pptr[0] += bytes_per_blocklines[0];
941      priv->plane[1] = pptr[1];  pptr[1] += bytes_per_blocklines[1];
942      priv->plane[2] = pptr[2];  pptr[2] += bytes_per_blocklines[2];
943 
944      sy = min(y, ystride_by_mcu);
945 
946      for (x = priv->width; x > 0; x -= xstride_by_mcu)
947       {
948 	sx = min(x, xstride_by_mcu);
949 	trace("Block size: %dx%d\n", sx, sy);
950 
951 	decode_MCU(priv);
952 	convert_to_pixfmt(priv, sx, sy);
953 	priv->plane[0] += bytes_per_mcu[0];
954 	priv->plane[1] += bytes_per_mcu[1];
955 	priv->plane[2] += bytes_per_mcu[2];
956 	if (priv->restarts_to_go>0)
957 	 {
958 	   priv->restarts_to_go--;
959 	   if (priv->restarts_to_go == 0)
960 	    {
961 	      priv->stream -= (priv->nbits_in_reservoir/8);
962 	      resync(priv);
963 	      if (find_next_rst_marker(priv) < 0)
964 		return -1;
965 	    }
966 	 }
967       }
968    }
969 
970   trace("Input file size: %d\n", priv->stream_length+2);
971   trace("Input bytes actually read: %d\n", priv->stream - priv->stream_begin + 2);
972 
973   return 0;
974 }
975 
tinyjpeg_get_errorstring(struct jdec_private * priv)976 const char *tinyjpeg_get_errorstring(struct jdec_private *priv)
977 {
978   /* FIXME: the error string must be store in the context */
979   priv = priv;
980   return error_string;
981 }
982 
tinyjpeg_get_size(struct jdec_private * priv,unsigned int * width,unsigned int * height)983 void tinyjpeg_get_size(struct jdec_private *priv, unsigned int *width, unsigned int *height)
984 {
985   *width = priv->width;
986   *height = priv->height;
987 }
988 
tinyjpeg_get_components(struct jdec_private * priv,unsigned char ** components,unsigned int ncomponents)989 int tinyjpeg_get_components(struct jdec_private *priv, unsigned char **components, unsigned int ncomponents)
990 {
991   unsigned int i;
992   if (ncomponents > COMPONENTS)
993     ncomponents = COMPONENTS;
994   for (i=0; i<ncomponents; i++)
995     components[i] = priv->components[i];
996   return 0;
997 }
998 
tinyjpeg_set_components(struct jdec_private * priv,unsigned char * const * components,unsigned int ncomponents)999 int tinyjpeg_set_components(struct jdec_private *priv, unsigned char * const *components, unsigned int ncomponents)
1000 {
1001   unsigned int i;
1002   if (ncomponents > COMPONENTS)
1003     ncomponents = COMPONENTS;
1004   for (i=0; i<ncomponents; i++)
1005     priv->components[i] = components[i];
1006   return 0;
1007 }
1008 
tinyjpeg_get_bytes_per_row(struct jdec_private * priv,unsigned int * bytes,unsigned int ncomponents)1009 int tinyjpeg_get_bytes_per_row(struct jdec_private *priv,
1010 			       unsigned int *bytes,
1011 			       unsigned int ncomponents)
1012 {
1013   unsigned int i;
1014   if (ncomponents > COMPONENTS)
1015     ncomponents = COMPONENTS;
1016   for (i=0; i<ncomponents; i++)
1017     bytes[i] = priv->bytes_per_row[i];
1018   return 0;
1019 }
1020 
tinyjpeg_set_bytes_per_row(struct jdec_private * priv,const unsigned int * bytes,unsigned int ncomponents)1021 int tinyjpeg_set_bytes_per_row(struct jdec_private *priv,
1022 			       const unsigned int *bytes,
1023 			       unsigned int ncomponents)
1024 {
1025   unsigned int i;
1026   if (ncomponents > COMPONENTS)
1027     ncomponents = COMPONENTS;
1028   for (i=0; i<ncomponents; i++)
1029     priv->bytes_per_row[i] = bytes[i];
1030   return 0;
1031 }
1032 
tinyjpeg_set_flags(struct jdec_private * priv,int flags)1033 int tinyjpeg_set_flags(struct jdec_private *priv, int flags)
1034 {
1035   int oldflags = priv->flags;
1036   priv->flags = flags;
1037   return oldflags;
1038 }
1039