Remove 'oldcode'
[oweals/cde.git] / cde / lib / DtHelp / jpeg / jdmarker.c
1 /*
2  * CDE - Common Desktop Environment
3  *
4  * Copyright (c) 1993-2012, The Open Group. All rights reserved.
5  *
6  * These libraries and programs are free software; you can
7  * redistribute them and/or modify them under the terms of the GNU
8  * Lesser General Public License as published by the Free Software
9  * Foundation; either version 2 of the License, or (at your option)
10  * any later version.
11  *
12  * These libraries and programs are distributed in the hope that
13  * they will be useful, but WITHOUT ANY WARRANTY; without even the
14  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15  * PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with these libraries and programs; if not, write
20  * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
21  * Floor, Boston, MA 02110-1301 USA
22  */
23 /* $XConsortium: jdmarker.c /main/2 1996/05/09 03:48:44 drk $ */
24 /*
25  * jdmarker.c
26  *
27  * Copyright (C) 1991-1996, Thomas G. Lane.
28  * This file is part of the Independent JPEG Group's software.
29  * For conditions of distribution and use, see the accompanying README file.
30  *
31  * This file contains routines to decode JPEG datastream markers.
32  * Most of the complexity arises from our desire to support input
33  * suspension: if not all of the data for a marker is available,
34  * we must exit back to the application.  On resumption, we reprocess
35  * the marker.
36  */
37
38 #define JPEG_INTERNALS
39 #include "jinclude.h"
40 #include "jpeglib.h"
41
42
43 typedef enum {                  /* JPEG marker codes */
44   M_SOF0  = 0xc0,
45   M_SOF1  = 0xc1,
46   M_SOF2  = 0xc2,
47   M_SOF3  = 0xc3,
48   
49   M_SOF5  = 0xc5,
50   M_SOF6  = 0xc6,
51   M_SOF7  = 0xc7,
52   
53   M_JPG   = 0xc8,
54   M_SOF9  = 0xc9,
55   M_SOF10 = 0xca,
56   M_SOF11 = 0xcb,
57   
58   M_SOF13 = 0xcd,
59   M_SOF14 = 0xce,
60   M_SOF15 = 0xcf,
61   
62   M_DHT   = 0xc4,
63   
64   M_DAC   = 0xcc,
65   
66   M_RST0  = 0xd0,
67   M_RST1  = 0xd1,
68   M_RST2  = 0xd2,
69   M_RST3  = 0xd3,
70   M_RST4  = 0xd4,
71   M_RST5  = 0xd5,
72   M_RST6  = 0xd6,
73   M_RST7  = 0xd7,
74   
75   M_SOI   = 0xd8,
76   M_EOI   = 0xd9,
77   M_SOS   = 0xda,
78   M_DQT   = 0xdb,
79   M_DNL   = 0xdc,
80   M_DRI   = 0xdd,
81   M_DHP   = 0xde,
82   M_EXP   = 0xdf,
83   
84   M_APP0  = 0xe0,
85   M_APP1  = 0xe1,
86   M_APP2  = 0xe2,
87   M_APP3  = 0xe3,
88   M_APP4  = 0xe4,
89   M_APP5  = 0xe5,
90   M_APP6  = 0xe6,
91   M_APP7  = 0xe7,
92   M_APP8  = 0xe8,
93   M_APP9  = 0xe9,
94   M_APP10 = 0xea,
95   M_APP11 = 0xeb,
96   M_APP12 = 0xec,
97   M_APP13 = 0xed,
98   M_APP14 = 0xee,
99   M_APP15 = 0xef,
100   
101   M_JPG0  = 0xf0,
102   M_JPG13 = 0xfd,
103   M_COM   = 0xfe,
104   
105   M_TEM   = 0x01,
106   
107   M_ERROR = 0x100
108 } JPEG_MARKER;
109
110
111 /*
112  * Macros for fetching data from the data source module.
113  *
114  * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
115  * the current restart point; we update them only when we have reached a
116  * suitable place to restart if a suspension occurs.
117  */
118
119 /* Declare and initialize local copies of input pointer/count */
120 #define INPUT_VARS(cinfo)  \
121         struct jpeg_source_mgr * datasrc = (cinfo)->src;  \
122         const JOCTET * next_input_byte = datasrc->next_input_byte;  \
123         size_t bytes_in_buffer = datasrc->bytes_in_buffer
124
125 /* Unload the local copies --- do this only at a restart boundary */
126 #define INPUT_SYNC(cinfo)  \
127         ( datasrc->next_input_byte = next_input_byte,  \
128           datasrc->bytes_in_buffer = bytes_in_buffer )
129
130 /* Reload the local copies --- seldom used except in MAKE_BYTE_AVAIL */
131 #define INPUT_RELOAD(cinfo)  \
132         ( next_input_byte = datasrc->next_input_byte,  \
133           bytes_in_buffer = datasrc->bytes_in_buffer )
134
135 /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
136  * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
137  * but we must reload the local copies after a successful fill.
138  */
139 #define MAKE_BYTE_AVAIL(cinfo,action)  \
140         if (bytes_in_buffer == 0) {  \
141           if (! (*datasrc->fill_input_buffer) (cinfo))  \
142             { action; }  \
143           INPUT_RELOAD(cinfo);  \
144         }  \
145         bytes_in_buffer--
146
147 /* Read a byte into variable V.
148  * If must suspend, take the specified action (typically "return FALSE").
149  */
150 #define INPUT_BYTE(cinfo,V,action)  \
151         MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
152                   V = GETJOCTET(*next_input_byte++); )
153
154 /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
155  * V should be declared unsigned int or perhaps INT32.
156  */
157 #define INPUT_2BYTES(cinfo,V,action)  \
158         MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
159                   V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
160                   MAKE_BYTE_AVAIL(cinfo,action); \
161                   V += GETJOCTET(*next_input_byte++); )
162
163
164 /*
165  * Routines to process JPEG markers.
166  *
167  * Entry condition: JPEG marker itself has been read and its code saved
168  *   in cinfo->unread_marker; input restart point is just after the marker.
169  *
170  * Exit: if return TRUE, have read and processed any parameters, and have
171  *   updated the restart point to point after the parameters.
172  *   If return FALSE, was forced to suspend before reaching end of
173  *   marker parameters; restart point has not been moved.  Same routine
174  *   will be called again after application supplies more input data.
175  *
176  * This approach to suspension assumes that all of a marker's parameters can
177  * fit into a single input bufferload.  This should hold for "normal"
178  * markers.  Some COM/APPn markers might have large parameter segments,
179  * but we use skip_input_data to get past those, and thereby put the problem
180  * on the source manager's shoulders.
181  *
182  * Note that we don't bother to avoid duplicate trace messages if a
183  * suspension occurs within marker parameters.  Other side effects
184  * require more care.
185  */
186
187
188 LOCAL(boolean)
189 get_soi (j_decompress_ptr cinfo)
190 /* Process an SOI marker */
191 {
192   int i;
193   
194   TRACEMS(cinfo, 1, JTRC_SOI);
195
196   if (cinfo->marker->saw_SOI)
197     ERREXIT(cinfo, JERR_SOI_DUPLICATE);
198
199   /* Reset all parameters that are defined to be reset by SOI */
200
201   for (i = 0; i < NUM_ARITH_TBLS; i++) {
202     cinfo->arith_dc_L[i] = 0;
203     cinfo->arith_dc_U[i] = 1;
204     cinfo->arith_ac_K[i] = 5;
205   }
206   cinfo->restart_interval = 0;
207
208   /* Set initial assumptions for colorspace etc */
209
210   cinfo->jpeg_color_space = JCS_UNKNOWN;
211   cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
212
213   cinfo->saw_JFIF_marker = FALSE;
214   cinfo->density_unit = 0;      /* set default JFIF APP0 values */
215   cinfo->X_density = 1;
216   cinfo->Y_density = 1;
217   cinfo->saw_Adobe_marker = FALSE;
218   cinfo->Adobe_transform = 0;
219
220   cinfo->marker->saw_SOI = TRUE;
221
222   return TRUE;
223 }
224
225
226 LOCAL(boolean)
227 get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
228 /* Process a SOFn marker */
229 {
230   INT32 length;
231   int c, ci;
232   jpeg_component_info * compptr;
233   INPUT_VARS(cinfo);
234
235   cinfo->progressive_mode = is_prog;
236   cinfo->arith_code = is_arith;
237
238   INPUT_2BYTES(cinfo, length, return FALSE);
239
240   INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
241   INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
242   INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
243   INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
244
245   length -= 8;
246
247   TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
248            (int) cinfo->image_width, (int) cinfo->image_height,
249            cinfo->num_components);
250
251   if (cinfo->marker->saw_SOF)
252     ERREXIT(cinfo, JERR_SOF_DUPLICATE);
253
254   /* We don't support files in which the image height is initially specified */
255   /* as 0 and is later redefined by DNL.  As long as we have to check that,  */
256   /* might as well have a general sanity check. */
257   if (cinfo->image_height <= 0 || cinfo->image_width <= 0
258       || cinfo->num_components <= 0)
259     ERREXIT(cinfo, JERR_EMPTY_IMAGE);
260
261   if (length != (cinfo->num_components * 3))
262     ERREXIT(cinfo, JERR_BAD_LENGTH);
263
264   if (cinfo->comp_info == NULL) /* do only once, even if suspend */
265     cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
266                         ((j_common_ptr) cinfo, JPOOL_IMAGE,
267                          cinfo->num_components * SIZEOF(jpeg_component_info));
268   
269   for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
270        ci++, compptr++) {
271     compptr->component_index = ci;
272     INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
273     INPUT_BYTE(cinfo, c, return FALSE);
274     compptr->h_samp_factor = (c >> 4) & 15;
275     compptr->v_samp_factor = (c     ) & 15;
276     INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
277
278     TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
279              compptr->component_id, compptr->h_samp_factor,
280              compptr->v_samp_factor, compptr->quant_tbl_no);
281   }
282
283   cinfo->marker->saw_SOF = TRUE;
284
285   INPUT_SYNC(cinfo);
286   return TRUE;
287 }
288
289
290 LOCAL(boolean)
291 get_sos (j_decompress_ptr cinfo)
292 /* Process a SOS marker */
293 {
294   INT32 length;
295   int i, ci, n, c, cc;
296   jpeg_component_info * compptr;
297   INPUT_VARS(cinfo);
298
299   if (! cinfo->marker->saw_SOF)
300     ERREXIT(cinfo, JERR_SOS_NO_SOF);
301
302   INPUT_2BYTES(cinfo, length, return FALSE);
303
304   INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
305
306   if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
307     ERREXIT(cinfo, JERR_BAD_LENGTH);
308
309   TRACEMS1(cinfo, 1, JTRC_SOS, n);
310
311   cinfo->comps_in_scan = n;
312
313   /* Collect the component-spec parameters */
314
315   for (i = 0; i < n; i++) {
316     INPUT_BYTE(cinfo, cc, return FALSE);
317     INPUT_BYTE(cinfo, c, return FALSE);
318     
319     for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
320          ci++, compptr++) {
321       if (cc == compptr->component_id)
322         goto id_found;
323     }
324
325     ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
326
327   id_found:
328
329     cinfo->cur_comp_info[i] = compptr;
330     compptr->dc_tbl_no = (c >> 4) & 15;
331     compptr->ac_tbl_no = (c     ) & 15;
332     
333     TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
334              compptr->dc_tbl_no, compptr->ac_tbl_no);
335   }
336
337   /* Collect the additional scan parameters Ss, Se, Ah/Al. */
338   INPUT_BYTE(cinfo, c, return FALSE);
339   cinfo->Ss = c;
340   INPUT_BYTE(cinfo, c, return FALSE);
341   cinfo->Se = c;
342   INPUT_BYTE(cinfo, c, return FALSE);
343   cinfo->Ah = (c >> 4) & 15;
344   cinfo->Al = (c     ) & 15;
345
346   TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
347            cinfo->Ah, cinfo->Al);
348
349   /* Prepare to scan data & restart markers */
350   cinfo->marker->next_restart_num = 0;
351
352   /* Count another SOS marker */
353   cinfo->input_scan_number++;
354
355   INPUT_SYNC(cinfo);
356   return TRUE;
357 }
358
359
360 METHODDEF(boolean)
361 get_app0 (j_decompress_ptr cinfo)
362 /* Process an APP0 marker */
363 {
364 #define JFIF_LEN 14
365   INT32 length;
366   UINT8 b[JFIF_LEN];
367   int buffp;
368   INPUT_VARS(cinfo);
369
370   INPUT_2BYTES(cinfo, length, return FALSE);
371   length -= 2;
372
373   /* See if a JFIF APP0 marker is present */
374
375   if (length >= JFIF_LEN) {
376     for (buffp = 0; buffp < JFIF_LEN; buffp++)
377       INPUT_BYTE(cinfo, b[buffp], return FALSE);
378     length -= JFIF_LEN;
379
380     if (b[0]==0x4A && b[1]==0x46 && b[2]==0x49 && b[3]==0x46 && b[4]==0) {
381       /* Found JFIF APP0 marker: check version */
382       /* Major version must be 1, anything else signals an incompatible change.
383        * We used to treat this as an error, but now it's a nonfatal warning,
384        * because some bozo at Hijaak couldn't read the spec.
385        * Minor version should be 0..2, but process anyway if newer.
386        */
387       if (b[5] != 1)
388         WARNMS2(cinfo, JWRN_JFIF_MAJOR, b[5], b[6]);
389       else if (b[6] > 2)
390         TRACEMS2(cinfo, 1, JTRC_JFIF_MINOR, b[5], b[6]);
391       /* Save info */
392       cinfo->saw_JFIF_marker = TRUE;
393       cinfo->density_unit = b[7];
394       cinfo->X_density = (b[8] << 8) + b[9];
395       cinfo->Y_density = (b[10] << 8) + b[11];
396       TRACEMS3(cinfo, 1, JTRC_JFIF,
397                cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
398       if (b[12] | b[13])
399         TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, b[12], b[13]);
400       if (length != ((INT32) b[12] * (INT32) b[13] * (INT32) 3))
401         TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) length);
402     } else {
403       /* Start of APP0 does not match "JFIF" */
404       TRACEMS1(cinfo, 1, JTRC_APP0, (int) length + JFIF_LEN);
405     }
406   } else {
407     /* Too short to be JFIF marker */
408     TRACEMS1(cinfo, 1, JTRC_APP0, (int) length);
409   }
410
411   INPUT_SYNC(cinfo);
412   if (length > 0)               /* skip any remaining data -- could be lots */
413     (*cinfo->src->skip_input_data) (cinfo, (long) length);
414
415   return TRUE;
416 }
417
418
419 METHODDEF(boolean)
420 get_app14 (j_decompress_ptr cinfo)
421 /* Process an APP14 marker */
422 {
423 #define ADOBE_LEN 12
424   INT32 length;
425   UINT8 b[ADOBE_LEN];
426   int buffp;
427   unsigned int version, flags0, flags1, transform;
428   INPUT_VARS(cinfo);
429
430   INPUT_2BYTES(cinfo, length, return FALSE);
431   length -= 2;
432
433   /* See if an Adobe APP14 marker is present */
434
435   if (length >= ADOBE_LEN) {
436     for (buffp = 0; buffp < ADOBE_LEN; buffp++)
437       INPUT_BYTE(cinfo, b[buffp], return FALSE);
438     length -= ADOBE_LEN;
439
440     if (b[0]==0x41 && b[1]==0x64 && b[2]==0x6F && b[3]==0x62 && b[4]==0x65) {
441       /* Found Adobe APP14 marker */
442       version = (b[5] << 8) + b[6];
443       flags0 = (b[7] << 8) + b[8];
444       flags1 = (b[9] << 8) + b[10];
445       transform = b[11];
446       TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
447       cinfo->saw_Adobe_marker = TRUE;
448       cinfo->Adobe_transform = (UINT8) transform;
449     } else {
450       /* Start of APP14 does not match "Adobe" */
451       TRACEMS1(cinfo, 1, JTRC_APP14, (int) length + ADOBE_LEN);
452     }
453   } else {
454     /* Too short to be Adobe marker */
455     TRACEMS1(cinfo, 1, JTRC_APP14, (int) length);
456   }
457
458   INPUT_SYNC(cinfo);
459   if (length > 0)               /* skip any remaining data -- could be lots */
460     (*cinfo->src->skip_input_data) (cinfo, (long) length);
461
462   return TRUE;
463 }
464
465
466 LOCAL(boolean)
467 get_dac (j_decompress_ptr cinfo)
468 /* Process a DAC marker */
469 {
470   INT32 length;
471   int index, val;
472   INPUT_VARS(cinfo);
473
474   INPUT_2BYTES(cinfo, length, return FALSE);
475   length -= 2;
476   
477   while (length > 0) {
478     INPUT_BYTE(cinfo, index, return FALSE);
479     INPUT_BYTE(cinfo, val, return FALSE);
480
481     length -= 2;
482
483     TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
484
485     if (index < 0 || index >= (2*NUM_ARITH_TBLS))
486       ERREXIT1(cinfo, JERR_DAC_INDEX, index);
487
488     if (index >= NUM_ARITH_TBLS) { /* define AC table */
489       cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
490     } else {                    /* define DC table */
491       cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
492       cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
493       if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
494         ERREXIT1(cinfo, JERR_DAC_VALUE, val);
495     }
496   }
497
498   INPUT_SYNC(cinfo);
499   return TRUE;
500 }
501
502
503 LOCAL(boolean)
504 get_dht (j_decompress_ptr cinfo)
505 /* Process a DHT marker */
506 {
507   INT32 length;
508   UINT8 bits[17];
509   UINT8 huffval[256];
510   int i, index, count;
511   JHUFF_TBL **htblptr;
512   INPUT_VARS(cinfo);
513
514   INPUT_2BYTES(cinfo, length, return FALSE);
515   length -= 2;
516   
517   while (length > 0) {
518     INPUT_BYTE(cinfo, index, return FALSE);
519
520     TRACEMS1(cinfo, 1, JTRC_DHT, index);
521       
522     bits[0] = 0;
523     count = 0;
524     for (i = 1; i <= 16; i++) {
525       INPUT_BYTE(cinfo, bits[i], return FALSE);
526       count += bits[i];
527     }
528
529     length -= 1 + 16;
530
531     TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
532              bits[1], bits[2], bits[3], bits[4],
533              bits[5], bits[6], bits[7], bits[8]);
534     TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
535              bits[9], bits[10], bits[11], bits[12],
536              bits[13], bits[14], bits[15], bits[16]);
537
538     if (count > 256 || ((INT32) count) > length)
539       ERREXIT(cinfo, JERR_DHT_COUNTS);
540
541     for (i = 0; i < count; i++)
542       INPUT_BYTE(cinfo, huffval[i], return FALSE);
543
544     length -= count;
545
546     if (index & 0x10) {         /* AC table definition */
547       index -= 0x10;
548       htblptr = &cinfo->ac_huff_tbl_ptrs[index];
549     } else {                    /* DC table definition */
550       htblptr = &cinfo->dc_huff_tbl_ptrs[index];
551     }
552
553     if (index < 0 || index >= NUM_HUFF_TBLS)
554       ERREXIT1(cinfo, JERR_DHT_INDEX, index);
555
556     if (*htblptr == NULL)
557       *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
558   
559     MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
560     MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
561   }
562
563   INPUT_SYNC(cinfo);
564   return TRUE;
565 }
566
567
568 LOCAL(boolean)
569 get_dqt (j_decompress_ptr cinfo)
570 /* Process a DQT marker */
571 {
572   INT32 length;
573   int n, i, prec;
574   unsigned int tmp;
575   JQUANT_TBL *quant_ptr;
576   INPUT_VARS(cinfo);
577
578   INPUT_2BYTES(cinfo, length, return FALSE);
579   length -= 2;
580
581   while (length > 0) {
582     INPUT_BYTE(cinfo, n, return FALSE);
583     prec = n >> 4;
584     n &= 0x0F;
585
586     TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
587
588     if (n >= NUM_QUANT_TBLS)
589       ERREXIT1(cinfo, JERR_DQT_INDEX, n);
590       
591     if (cinfo->quant_tbl_ptrs[n] == NULL)
592       cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
593     quant_ptr = cinfo->quant_tbl_ptrs[n];
594
595     for (i = 0; i < DCTSIZE2; i++) {
596       if (prec)
597         INPUT_2BYTES(cinfo, tmp, return FALSE);
598       else
599         INPUT_BYTE(cinfo, tmp, return FALSE);
600       /* We convert the zigzag-order table to natural array order. */
601       quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
602     }
603
604     if (cinfo->err->trace_level >= 2) {
605       for (i = 0; i < DCTSIZE2; i += 8) {
606         TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
607                  quant_ptr->quantval[i],   quant_ptr->quantval[i+1],
608                  quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
609                  quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
610                  quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
611       }
612     }
613
614     length -= DCTSIZE2+1;
615     if (prec) length -= DCTSIZE2;
616   }
617
618   INPUT_SYNC(cinfo);
619   return TRUE;
620 }
621
622
623 LOCAL(boolean)
624 get_dri (j_decompress_ptr cinfo)
625 /* Process a DRI marker */
626 {
627   INT32 length;
628   unsigned int tmp;
629   INPUT_VARS(cinfo);
630
631   INPUT_2BYTES(cinfo, length, return FALSE);
632   
633   if (length != 4)
634     ERREXIT(cinfo, JERR_BAD_LENGTH);
635
636   INPUT_2BYTES(cinfo, tmp, return FALSE);
637
638   TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
639
640   cinfo->restart_interval = tmp;
641
642   INPUT_SYNC(cinfo);
643   return TRUE;
644 }
645
646
647 METHODDEF(boolean)
648 skip_variable (j_decompress_ptr cinfo)
649 /* Skip over an unknown or uninteresting variable-length marker */
650 {
651   INT32 length;
652   INPUT_VARS(cinfo);
653
654   INPUT_2BYTES(cinfo, length, return FALSE);
655   
656   TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
657
658   INPUT_SYNC(cinfo);            /* do before skip_input_data */
659   (*cinfo->src->skip_input_data) (cinfo, (long) length - 2L);
660
661   return TRUE;
662 }
663
664
665 /*
666  * Find the next JPEG marker, save it in cinfo->unread_marker.
667  * Returns FALSE if had to suspend before reaching a marker;
668  * in that case cinfo->unread_marker is unchanged.
669  *
670  * Note that the result might not be a valid marker code,
671  * but it will never be 0 or FF.
672  */
673
674 LOCAL(boolean)
675 next_marker (j_decompress_ptr cinfo)
676 {
677   int c;
678   INPUT_VARS(cinfo);
679
680   for (;;) {
681     INPUT_BYTE(cinfo, c, return FALSE);
682     /* Skip any non-FF bytes.
683      * This may look a bit inefficient, but it will not occur in a valid file.
684      * We sync after each discarded byte so that a suspending data source
685      * can discard the byte from its buffer.
686      */
687     while (c != 0xFF) {
688       cinfo->marker->discarded_bytes++;
689       INPUT_SYNC(cinfo);
690       INPUT_BYTE(cinfo, c, return FALSE);
691     }
692     /* This loop swallows any duplicate FF bytes.  Extra FFs are legal as
693      * pad bytes, so don't count them in discarded_bytes.  We assume there
694      * will not be so many consecutive FF bytes as to overflow a suspending
695      * data source's input buffer.
696      */
697     do {
698       INPUT_BYTE(cinfo, c, return FALSE);
699     } while (c == 0xFF);
700     if (c != 0)
701       break;                    /* found a valid marker, exit loop */
702     /* Reach here if we found a stuffed-zero data sequence (FF/00).
703      * Discard it and loop back to try again.
704      */
705     cinfo->marker->discarded_bytes += 2;
706     INPUT_SYNC(cinfo);
707   }
708
709   if (cinfo->marker->discarded_bytes != 0) {
710     WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
711     cinfo->marker->discarded_bytes = 0;
712   }
713
714   cinfo->unread_marker = c;
715
716   INPUT_SYNC(cinfo);
717   return TRUE;
718 }
719
720
721 LOCAL(boolean)
722 first_marker (j_decompress_ptr cinfo)
723 /* Like next_marker, but used to obtain the initial SOI marker. */
724 /* For this marker, we do not allow preceding garbage or fill; otherwise,
725  * we might well scan an entire input file before realizing it ain't JPEG.
726  * If an application wants to process non-JFIF files, it must seek to the
727  * SOI before calling the JPEG library.
728  */
729 {
730   int c, c2;
731   INPUT_VARS(cinfo);
732
733   INPUT_BYTE(cinfo, c, return FALSE);
734   INPUT_BYTE(cinfo, c2, return FALSE);
735   if (c != 0xFF || c2 != (int) M_SOI)
736     ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
737
738   cinfo->unread_marker = c2;
739
740   INPUT_SYNC(cinfo);
741   return TRUE;
742 }
743
744
745 /*
746  * Read markers until SOS or EOI.
747  *
748  * Returns same codes as are defined for jpeg_consume_input:
749  * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
750  */
751
752 METHODDEF(int)
753 read_markers (j_decompress_ptr cinfo)
754 {
755   /* Outer loop repeats once for each marker. */
756   for (;;) {
757     /* Collect the marker proper, unless we already did. */
758     /* NB: first_marker() enforces the requirement that SOI appear first. */
759     if (cinfo->unread_marker == 0) {
760       if (! cinfo->marker->saw_SOI) {
761         if (! first_marker(cinfo))
762           return JPEG_SUSPENDED;
763       } else {
764         if (! next_marker(cinfo))
765           return JPEG_SUSPENDED;
766       }
767     }
768     /* At this point cinfo->unread_marker contains the marker code and the
769      * input point is just past the marker proper, but before any parameters.
770      * A suspension will cause us to return with this state still true.
771      */
772     switch (cinfo->unread_marker) {
773     case M_SOI:
774       if (! get_soi(cinfo))
775         return JPEG_SUSPENDED;
776       break;
777
778     case M_SOF0:                /* Baseline */
779     case M_SOF1:                /* Extended sequential, Huffman */
780       if (! get_sof(cinfo, FALSE, FALSE))
781         return JPEG_SUSPENDED;
782       break;
783
784     case M_SOF2:                /* Progressive, Huffman */
785       if (! get_sof(cinfo, TRUE, FALSE))
786         return JPEG_SUSPENDED;
787       break;
788
789     case M_SOF9:                /* Extended sequential, arithmetic */
790       if (! get_sof(cinfo, FALSE, TRUE))
791         return JPEG_SUSPENDED;
792       break;
793
794     case M_SOF10:               /* Progressive, arithmetic */
795       if (! get_sof(cinfo, TRUE, TRUE))
796         return JPEG_SUSPENDED;
797       break;
798
799     /* Currently unsupported SOFn types */
800     case M_SOF3:                /* Lossless, Huffman */
801     case M_SOF5:                /* Differential sequential, Huffman */
802     case M_SOF6:                /* Differential progressive, Huffman */
803     case M_SOF7:                /* Differential lossless, Huffman */
804     case M_JPG:                 /* Reserved for JPEG extensions */
805     case M_SOF11:               /* Lossless, arithmetic */
806     case M_SOF13:               /* Differential sequential, arithmetic */
807     case M_SOF14:               /* Differential progressive, arithmetic */
808     case M_SOF15:               /* Differential lossless, arithmetic */
809       ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
810       break;
811
812     case M_SOS:
813       if (! get_sos(cinfo))
814         return JPEG_SUSPENDED;
815       cinfo->unread_marker = 0; /* processed the marker */
816       return JPEG_REACHED_SOS;
817     
818     case M_EOI:
819       TRACEMS(cinfo, 1, JTRC_EOI);
820       cinfo->unread_marker = 0; /* processed the marker */
821       return JPEG_REACHED_EOI;
822       
823     case M_DAC:
824       if (! get_dac(cinfo))
825         return JPEG_SUSPENDED;
826       break;
827       
828     case M_DHT:
829       if (! get_dht(cinfo))
830         return JPEG_SUSPENDED;
831       break;
832       
833     case M_DQT:
834       if (! get_dqt(cinfo))
835         return JPEG_SUSPENDED;
836       break;
837       
838     case M_DRI:
839       if (! get_dri(cinfo))
840         return JPEG_SUSPENDED;
841       break;
842       
843     case M_APP0:
844     case M_APP1:
845     case M_APP2:
846     case M_APP3:
847     case M_APP4:
848     case M_APP5:
849     case M_APP6:
850     case M_APP7:
851     case M_APP8:
852     case M_APP9:
853     case M_APP10:
854     case M_APP11:
855     case M_APP12:
856     case M_APP13:
857     case M_APP14:
858     case M_APP15:
859       if (! (*cinfo->marker->process_APPn[cinfo->unread_marker - (int) M_APP0]) (cinfo))
860         return JPEG_SUSPENDED;
861       break;
862       
863     case M_COM:
864       if (! (*cinfo->marker->process_COM) (cinfo))
865         return JPEG_SUSPENDED;
866       break;
867
868     case M_RST0:                /* these are all parameterless */
869     case M_RST1:
870     case M_RST2:
871     case M_RST3:
872     case M_RST4:
873     case M_RST5:
874     case M_RST6:
875     case M_RST7:
876     case M_TEM:
877       TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
878       break;
879
880     case M_DNL:                 /* Ignore DNL ... perhaps the wrong thing */
881       if (! skip_variable(cinfo))
882         return JPEG_SUSPENDED;
883       break;
884
885     default:                    /* must be DHP, EXP, JPGn, or RESn */
886       /* For now, we treat the reserved markers as fatal errors since they are
887        * likely to be used to signal incompatible JPEG Part 3 extensions.
888        * Once the JPEG 3 version-number marker is well defined, this code
889        * ought to change!
890        */
891       ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
892       break;
893     }
894     /* Successfully processed marker, so reset state variable */
895     cinfo->unread_marker = 0;
896   } /* end loop */
897 }
898
899
900 /*
901  * Read a restart marker, which is expected to appear next in the datastream;
902  * if the marker is not there, take appropriate recovery action.
903  * Returns FALSE if suspension is required.
904  *
905  * This is called by the entropy decoder after it has read an appropriate
906  * number of MCUs.  cinfo->unread_marker may be nonzero if the entropy decoder
907  * has already read a marker from the data source.  Under normal conditions
908  * cinfo->unread_marker will be reset to 0 before returning; if not reset,
909  * it holds a marker which the decoder will be unable to read past.
910  */
911
912 METHODDEF(boolean)
913 read_restart_marker (j_decompress_ptr cinfo)
914 {
915   /* Obtain a marker unless we already did. */
916   /* Note that next_marker will complain if it skips any data. */
917   if (cinfo->unread_marker == 0) {
918     if (! next_marker(cinfo))
919       return FALSE;
920   }
921
922   if (cinfo->unread_marker ==
923       ((int) M_RST0 + cinfo->marker->next_restart_num)) {
924     /* Normal case --- swallow the marker and let entropy decoder continue */
925     TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
926     cinfo->unread_marker = 0;
927   } else {
928     /* Uh-oh, the restart markers have been messed up. */
929     /* Let the data source manager determine how to resync. */
930     if (! (*cinfo->src->resync_to_restart) (cinfo,
931                                             cinfo->marker->next_restart_num))
932       return FALSE;
933   }
934
935   /* Update next-restart state */
936   cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
937
938   return TRUE;
939 }
940
941
942 /*
943  * This is the default resync_to_restart method for data source managers
944  * to use if they don't have any better approach.  Some data source managers
945  * may be able to back up, or may have additional knowledge about the data
946  * which permits a more intelligent recovery strategy; such managers would
947  * presumably supply their own resync method.
948  *
949  * read_restart_marker calls resync_to_restart if it finds a marker other than
950  * the restart marker it was expecting.  (This code is *not* used unless
951  * a nonzero restart interval has been declared.)  cinfo->unread_marker is
952  * the marker code actually found (might be anything, except 0 or FF).
953  * The desired restart marker number (0..7) is passed as a parameter.
954  * This routine is supposed to apply whatever error recovery strategy seems
955  * appropriate in order to position the input stream to the next data segment.
956  * Note that cinfo->unread_marker is treated as a marker appearing before
957  * the current data-source input point; usually it should be reset to zero
958  * before returning.
959  * Returns FALSE if suspension is required.
960  *
961  * This implementation is substantially constrained by wanting to treat the
962  * input as a data stream; this means we can't back up.  Therefore, we have
963  * only the following actions to work with:
964  *   1. Simply discard the marker and let the entropy decoder resume at next
965  *      byte of file.
966  *   2. Read forward until we find another marker, discarding intervening
967  *      data.  (In theory we could look ahead within the current bufferload,
968  *      without having to discard data if we don't find the desired marker.
969  *      This idea is not implemented here, in part because it makes behavior
970  *      dependent on buffer size and chance buffer-boundary positions.)
971  *   3. Leave the marker unread (by failing to zero cinfo->unread_marker).
972  *      This will cause the entropy decoder to process an empty data segment,
973  *      inserting dummy zeroes, and then we will reprocess the marker.
974  *
975  * #2 is appropriate if we think the desired marker lies ahead, while #3 is
976  * appropriate if the found marker is a future restart marker (indicating
977  * that we have missed the desired restart marker, probably because it got
978  * corrupted).
979  * We apply #2 or #3 if the found marker is a restart marker no more than
980  * two counts behind or ahead of the expected one.  We also apply #2 if the
981  * found marker is not a legal JPEG marker code (it's certainly bogus data).
982  * If the found marker is a restart marker more than 2 counts away, we do #1
983  * (too much risk that the marker is erroneous; with luck we will be able to
984  * resync at some future point).
985  * For any valid non-restart JPEG marker, we apply #3.  This keeps us from
986  * overrunning the end of a scan.  An implementation limited to single-scan
987  * files might find it better to apply #2 for markers other than EOI, since
988  * any other marker would have to be bogus data in that case.
989  */
990
991 GLOBAL(boolean)
992 jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
993 {
994   int marker = cinfo->unread_marker;
995   int action = 1;
996   
997   /* Always put up a warning. */
998   WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
999   
1000   /* Outer loop handles repeated decision after scanning forward. */
1001   for (;;) {
1002     if (marker < (int) M_SOF0)
1003       action = 2;               /* invalid marker */
1004     else if (marker < (int) M_RST0 || marker > (int) M_RST7)
1005       action = 3;               /* valid non-restart marker */
1006     else {
1007       if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
1008           marker == ((int) M_RST0 + ((desired+2) & 7)))
1009         action = 3;             /* one of the next two expected restarts */
1010       else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
1011                marker == ((int) M_RST0 + ((desired-2) & 7)))
1012         action = 2;             /* a prior restart, so advance */
1013       else
1014         action = 1;             /* desired restart or too far away */
1015     }
1016     TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
1017     switch (action) {
1018     case 1:
1019       /* Discard marker and let entropy decoder resume processing. */
1020       cinfo->unread_marker = 0;
1021       return TRUE;
1022     case 2:
1023       /* Scan to the next marker, and repeat the decision loop. */
1024       if (! next_marker(cinfo))
1025         return FALSE;
1026       marker = cinfo->unread_marker;
1027       break;
1028     case 3:
1029       /* Return without advancing past this marker. */
1030       /* Entropy decoder will be forced to process an empty segment. */
1031       return TRUE;
1032     }
1033   } /* end loop */
1034 }
1035
1036
1037 /*
1038  * Reset marker processing state to begin a fresh datastream.
1039  */
1040
1041 METHODDEF(void)
1042 reset_marker_reader (j_decompress_ptr cinfo)
1043 {
1044   cinfo->comp_info = NULL;              /* until allocated by get_sof */
1045   cinfo->input_scan_number = 0;         /* no SOS seen yet */
1046   cinfo->unread_marker = 0;             /* no pending marker */
1047   cinfo->marker->saw_SOI = FALSE;       /* set internal state too */
1048   cinfo->marker->saw_SOF = FALSE;
1049   cinfo->marker->discarded_bytes = 0;
1050 }
1051
1052
1053 /*
1054  * Initialize the marker reader module.
1055  * This is called only once, when the decompression object is created.
1056  */
1057
1058 GLOBAL(void)
1059 jinit_marker_reader (j_decompress_ptr cinfo)
1060 {
1061   int i;
1062
1063   /* Create subobject in permanent pool */
1064   cinfo->marker = (struct jpeg_marker_reader *)
1065     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
1066                                 SIZEOF(struct jpeg_marker_reader));
1067   /* Initialize method pointers */
1068   cinfo->marker->reset_marker_reader = reset_marker_reader;
1069   cinfo->marker->read_markers = read_markers;
1070   cinfo->marker->read_restart_marker = read_restart_marker;
1071   cinfo->marker->process_COM = skip_variable;
1072   for (i = 0; i < 16; i++)
1073     cinfo->marker->process_APPn[i] = skip_variable;
1074   cinfo->marker->process_APPn[0] = get_app0;
1075   cinfo->marker->process_APPn[14] = get_app14;
1076   /* Reset marker processing state */
1077   reset_marker_reader(cinfo);
1078 }