4 * This file was part of the Independent JPEG Group's software:
5 * Copyright (C) 1991-1998, Thomas G. Lane.
6 * Lossless JPEG Modifications:
7 * Copyright (C) 1999, Ken Murchison.
8 * libjpeg-turbo Modifications:
9 * Copyright (C) 2012, 2015, 2022, D. R. Commander.
10 * For conditions of distribution and use, see the accompanying README.ijg
13 * This file contains routines to decode JPEG datastream markers.
14 * Most of the complexity arises from our desire to support input
15 * suspension: if not all of the data for a marker is available,
16 * we must exit back to the application. On resumption, we reprocess
20 #define JPEG_INTERNALS
25 typedef enum { /* JPEG marker codes */
96 struct jpeg_marker_reader pub; /* public fields */
98 /* Application-overridable marker processing methods */
99 jpeg_marker_parser_method process_COM;
100 jpeg_marker_parser_method process_APPn[16];
102 /* Limit on marker data length to save for each marker type */
103 unsigned int length_limit_COM;
104 unsigned int length_limit_APPn[16];
106 /* Status of COM/APPn marker saving */
107 jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
108 unsigned int bytes_read; /* data bytes read so far in marker */
109 /* Note: cur_marker is not linked into marker_list until it's all read. */
112 typedef my_marker_reader *my_marker_ptr;
116 * Macros for fetching data from the data source module.
118 * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
119 * the current restart point; we update them only when we have reached a
120 * suitable place to restart if a suspension occurs.
123 /* Declare and initialize local copies of input pointer/count */
124 #define INPUT_VARS(cinfo) \
125 struct jpeg_source_mgr *datasrc = (cinfo)->src; \
126 const JOCTET *next_input_byte = datasrc->next_input_byte; \
127 size_t bytes_in_buffer = datasrc->bytes_in_buffer
129 /* Unload the local copies --- do this only at a restart boundary */
130 #define INPUT_SYNC(cinfo) \
131 ( datasrc->next_input_byte = next_input_byte, \
132 datasrc->bytes_in_buffer = bytes_in_buffer )
134 /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
135 #define INPUT_RELOAD(cinfo) \
136 ( next_input_byte = datasrc->next_input_byte, \
137 bytes_in_buffer = datasrc->bytes_in_buffer )
139 /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
140 * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
141 * but we must reload the local copies after a successful fill.
143 #define MAKE_BYTE_AVAIL(cinfo, action) \
144 if (bytes_in_buffer == 0) { \
145 if (!(*datasrc->fill_input_buffer) (cinfo)) \
147 INPUT_RELOAD(cinfo); \
150 /* Read a byte into variable V.
151 * If must suspend, take the specified action (typically "return FALSE").
153 #define INPUT_BYTE(cinfo, V, action) \
154 MAKESTMT( MAKE_BYTE_AVAIL(cinfo, action); \
156 V = *next_input_byte++; )
158 /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
159 * V should be declared unsigned int or perhaps JLONG.
161 #define INPUT_2BYTES(cinfo, V, action) \
162 MAKESTMT( MAKE_BYTE_AVAIL(cinfo, action); \
164 V = ((unsigned int)(*next_input_byte++)) << 8; \
165 MAKE_BYTE_AVAIL(cinfo, action); \
167 V += *next_input_byte++; )
171 * Routines to process JPEG markers.
173 * Entry condition: JPEG marker itself has been read and its code saved
174 * in cinfo->unread_marker; input restart point is just after the marker.
176 * Exit: if return TRUE, have read and processed any parameters, and have
177 * updated the restart point to point after the parameters.
178 * If return FALSE, was forced to suspend before reaching end of
179 * marker parameters; restart point has not been moved. Same routine
180 * will be called again after application supplies more input data.
182 * This approach to suspension assumes that all of a marker's parameters
183 * can fit into a single input bufferload. This should hold for "normal"
184 * markers. Some COM/APPn markers might have large parameter segments
185 * that might not fit. If we are simply dropping such a marker, we use
186 * skip_input_data to get past it, and thereby put the problem on the
187 * source manager's shoulders. If we are saving the marker's contents
188 * into memory, we use a slightly different convention: when forced to
189 * suspend, the marker processor updates the restart point to the end of
190 * what it's consumed (ie, the end of the buffer) before returning FALSE.
191 * On resumption, cinfo->unread_marker still contains the marker code,
192 * but the data source will point to the next chunk of marker data.
193 * The marker processor must retain internal state to deal with this.
195 * Note that we don't bother to avoid duplicate trace messages if a
196 * suspension occurs within marker parameters. Other side effects
202 get_soi(j_decompress_ptr cinfo)
203 /* Process an SOI marker */
207 TRACEMS(cinfo, 1, JTRC_SOI);
209 if (cinfo->marker->saw_SOI)
210 ERREXIT(cinfo, JERR_SOI_DUPLICATE);
212 /* Reset all parameters that are defined to be reset by SOI */
214 for (i = 0; i < NUM_ARITH_TBLS; i++) {
215 cinfo->arith_dc_L[i] = 0;
216 cinfo->arith_dc_U[i] = 1;
217 cinfo->arith_ac_K[i] = 5;
219 cinfo->restart_interval = 0;
221 /* Set initial assumptions for colorspace etc */
223 cinfo->jpeg_color_space = JCS_UNKNOWN;
224 cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
226 cinfo->saw_JFIF_marker = FALSE;
227 cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
228 cinfo->JFIF_minor_version = 1;
229 cinfo->density_unit = 0;
230 cinfo->X_density = 1;
231 cinfo->Y_density = 1;
232 cinfo->saw_Adobe_marker = FALSE;
233 cinfo->Adobe_transform = 0;
235 cinfo->marker->saw_SOI = TRUE;
242 get_sof(j_decompress_ptr cinfo, boolean is_prog, boolean is_lossless,
244 /* Process a SOFn marker */
248 jpeg_component_info *compptr;
251 cinfo->progressive_mode = is_prog;
252 cinfo->master->lossless = is_lossless;
253 cinfo->arith_code = is_arith;
255 INPUT_2BYTES(cinfo, length, return FALSE);
257 INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
258 INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
259 INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
260 INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
264 TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
265 (int)cinfo->image_width, (int)cinfo->image_height,
266 cinfo->num_components);
268 if (cinfo->marker->saw_SOF)
269 ERREXIT(cinfo, JERR_SOF_DUPLICATE);
271 /* We don't support files in which the image height is initially specified */
272 /* as 0 and is later redefined by DNL. As long as we have to check that, */
273 /* might as well have a general sanity check. */
274 if (cinfo->image_height <= 0 || cinfo->image_width <= 0 ||
275 cinfo->num_components <= 0)
276 ERREXIT(cinfo, JERR_EMPTY_IMAGE);
278 if (length != (cinfo->num_components * 3))
279 ERREXIT(cinfo, JERR_BAD_LENGTH);
281 if (cinfo->comp_info == NULL) /* do only once, even if suspend */
282 cinfo->comp_info = (jpeg_component_info *)(*cinfo->mem->alloc_small)
283 ((j_common_ptr)cinfo, JPOOL_IMAGE,
284 cinfo->num_components * sizeof(jpeg_component_info));
286 for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
288 compptr->component_index = ci;
289 INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
290 INPUT_BYTE(cinfo, c, return FALSE);
291 compptr->h_samp_factor = (c >> 4) & 15;
292 compptr->v_samp_factor = (c ) & 15;
293 INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
295 TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
296 compptr->component_id, compptr->h_samp_factor,
297 compptr->v_samp_factor, compptr->quant_tbl_no);
300 cinfo->marker->saw_SOF = TRUE;
308 get_sos(j_decompress_ptr cinfo)
309 /* Process a SOS marker */
312 int i, ci, n, c, cc, pi;
313 jpeg_component_info *compptr;
316 if (!cinfo->marker->saw_SOF)
317 ERREXIT(cinfo, JERR_SOS_NO_SOF);
319 INPUT_2BYTES(cinfo, length, return FALSE);
321 INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
323 TRACEMS1(cinfo, 1, JTRC_SOS, n);
325 if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
326 ERREXIT(cinfo, JERR_BAD_LENGTH);
328 cinfo->comps_in_scan = n;
330 /* Collect the component-spec parameters */
332 for (i = 0; i < MAX_COMPS_IN_SCAN; i++)
333 cinfo->cur_comp_info[i] = NULL;
335 for (i = 0; i < n; i++) {
336 INPUT_BYTE(cinfo, cc, return FALSE);
337 INPUT_BYTE(cinfo, c, return FALSE);
339 for (ci = 0, compptr = cinfo->comp_info;
340 ci < cinfo->num_components && ci < MAX_COMPS_IN_SCAN;
342 if (cc == compptr->component_id && !cinfo->cur_comp_info[ci])
346 ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
350 cinfo->cur_comp_info[i] = compptr;
351 compptr->dc_tbl_no = (c >> 4) & 15;
352 compptr->ac_tbl_no = (c ) & 15;
354 TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
355 compptr->dc_tbl_no, compptr->ac_tbl_no);
357 /* This CSi (cc) should differ from the previous CSi */
358 for (pi = 0; pi < i; pi++) {
359 if (cinfo->cur_comp_info[pi] == compptr) {
360 ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
365 /* Collect the additional scan parameters Ss, Se, Ah/Al. */
366 INPUT_BYTE(cinfo, c, return FALSE);
368 INPUT_BYTE(cinfo, c, return FALSE);
370 INPUT_BYTE(cinfo, c, return FALSE);
371 cinfo->Ah = (c >> 4) & 15;
372 cinfo->Al = (c ) & 15;
374 TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
375 cinfo->Ah, cinfo->Al);
377 /* Prepare to scan data & restart markers */
378 cinfo->marker->next_restart_num = 0;
380 /* Count another SOS marker */
381 cinfo->input_scan_number++;
388 #ifdef D_ARITH_CODING_SUPPORTED
391 get_dac(j_decompress_ptr cinfo)
392 /* Process a DAC marker */
398 INPUT_2BYTES(cinfo, length, return FALSE);
402 INPUT_BYTE(cinfo, index, return FALSE);
403 INPUT_BYTE(cinfo, val, return FALSE);
407 TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
409 if (index < 0 || index >= (2 * NUM_ARITH_TBLS))
410 ERREXIT1(cinfo, JERR_DAC_INDEX, index);
412 if (index >= NUM_ARITH_TBLS) { /* define AC table */
413 cinfo->arith_ac_K[index - NUM_ARITH_TBLS] = (UINT8)val;
414 } else { /* define DC table */
415 cinfo->arith_dc_L[index] = (UINT8)(val & 0x0F);
416 cinfo->arith_dc_U[index] = (UINT8)(val >> 4);
417 if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
418 ERREXIT1(cinfo, JERR_DAC_VALUE, val);
423 ERREXIT(cinfo, JERR_BAD_LENGTH);
429 #else /* !D_ARITH_CODING_SUPPORTED */
431 #define get_dac(cinfo) skip_variable(cinfo)
433 #endif /* D_ARITH_CODING_SUPPORTED */
437 get_dht(j_decompress_ptr cinfo)
438 /* Process a DHT marker */
447 INPUT_2BYTES(cinfo, length, return FALSE);
450 while (length > 16) {
451 INPUT_BYTE(cinfo, index, return FALSE);
453 TRACEMS1(cinfo, 1, JTRC_DHT, index);
457 for (i = 1; i <= 16; i++) {
458 INPUT_BYTE(cinfo, bits[i], return FALSE);
464 TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
465 bits[1], bits[2], bits[3], bits[4],
466 bits[5], bits[6], bits[7], bits[8]);
467 TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
468 bits[9], bits[10], bits[11], bits[12],
469 bits[13], bits[14], bits[15], bits[16]);
471 /* Here we just do minimal validation of the counts to avoid walking
472 * off the end of our table space. jdhuff.c will check more carefully.
474 if (count > 256 || ((JLONG)count) > length)
475 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
477 for (i = 0; i < count; i++)
478 INPUT_BYTE(cinfo, huffval[i], return FALSE);
480 memset(&huffval[count], 0, (256 - count) * sizeof(UINT8));
484 if (index & 0x10) { /* AC table definition */
486 if (index < 0 || index >= NUM_HUFF_TBLS)
487 ERREXIT1(cinfo, JERR_DHT_INDEX, index);
488 htblptr = &cinfo->ac_huff_tbl_ptrs[index];
489 } else { /* DC table definition */
490 if (index < 0 || index >= NUM_HUFF_TBLS)
491 ERREXIT1(cinfo, JERR_DHT_INDEX, index);
492 htblptr = &cinfo->dc_huff_tbl_ptrs[index];
495 if (*htblptr == NULL)
496 *htblptr = jpeg_alloc_huff_table((j_common_ptr)cinfo);
498 memcpy((*htblptr)->bits, bits, sizeof((*htblptr)->bits));
499 memcpy((*htblptr)->huffval, huffval, sizeof((*htblptr)->huffval));
503 ERREXIT(cinfo, JERR_BAD_LENGTH);
511 get_dqt(j_decompress_ptr cinfo)
512 /* Process a DQT marker */
517 JQUANT_TBL *quant_ptr;
520 INPUT_2BYTES(cinfo, length, return FALSE);
524 INPUT_BYTE(cinfo, n, return FALSE);
528 TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
530 if (n >= NUM_QUANT_TBLS)
531 ERREXIT1(cinfo, JERR_DQT_INDEX, n);
533 if (cinfo->quant_tbl_ptrs[n] == NULL)
534 cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr)cinfo);
535 quant_ptr = cinfo->quant_tbl_ptrs[n];
537 for (i = 0; i < DCTSIZE2; i++) {
539 INPUT_2BYTES(cinfo, tmp, return FALSE);
541 INPUT_BYTE(cinfo, tmp, return FALSE);
542 /* We convert the zigzag-order table to natural array order. */
543 quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16)tmp;
546 if (cinfo->err->trace_level >= 2) {
547 for (i = 0; i < DCTSIZE2; i += 8) {
548 TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
549 quant_ptr->quantval[i], quant_ptr->quantval[i + 1],
550 quant_ptr->quantval[i + 2], quant_ptr->quantval[i + 3],
551 quant_ptr->quantval[i + 4], quant_ptr->quantval[i + 5],
552 quant_ptr->quantval[i + 6], quant_ptr->quantval[i + 7]);
556 length -= DCTSIZE2 + 1;
557 if (prec) length -= DCTSIZE2;
561 ERREXIT(cinfo, JERR_BAD_LENGTH);
569 get_dri(j_decompress_ptr cinfo)
570 /* Process a DRI marker */
576 INPUT_2BYTES(cinfo, length, return FALSE);
579 ERREXIT(cinfo, JERR_BAD_LENGTH);
581 INPUT_2BYTES(cinfo, tmp, return FALSE);
583 TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
585 cinfo->restart_interval = tmp;
593 * Routines for processing APPn and COM markers.
594 * These are either saved in memory or discarded, per application request.
595 * APP0 and APP14 are specially checked to see if they are
596 * JFIF and Adobe markers, respectively.
599 #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
600 #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
601 #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
605 examine_app0(j_decompress_ptr cinfo, JOCTET *data, unsigned int datalen,
607 /* Examine first few bytes from an APP0.
608 * Take appropriate action if it is a JFIF marker.
609 * datalen is # of bytes at data[], remaining is length of rest of marker data.
612 JLONG totallen = (JLONG)datalen + remaining;
614 if (datalen >= APP0_DATA_LEN &&
620 /* Found JFIF APP0 marker: save info */
621 cinfo->saw_JFIF_marker = TRUE;
622 cinfo->JFIF_major_version = data[5];
623 cinfo->JFIF_minor_version = data[6];
624 cinfo->density_unit = data[7];
625 cinfo->X_density = (data[8] << 8) + data[9];
626 cinfo->Y_density = (data[10] << 8) + data[11];
628 * Major version must be 1, anything else signals an incompatible change.
629 * (We used to treat this as an error, but now it's a nonfatal warning,
630 * because some bozo at Hijaak couldn't read the spec.)
631 * Minor version should be 0..2, but process anyway if newer.
633 if (cinfo->JFIF_major_version != 1)
634 WARNMS2(cinfo, JWRN_JFIF_MAJOR,
635 cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
636 /* Generate trace messages */
637 TRACEMS5(cinfo, 1, JTRC_JFIF,
638 cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
639 cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
640 /* Validate thumbnail dimensions and issue appropriate messages */
641 if (data[12] | data[13])
642 TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, data[12], data[13]);
643 totallen -= APP0_DATA_LEN;
644 if (totallen != ((JLONG)data[12] * (JLONG)data[13] * (JLONG)3))
645 TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int)totallen);
646 } else if (datalen >= 6 &&
652 /* Found JFIF "JFXX" extension APP0 marker */
653 /* The library doesn't actually do anything with these,
654 * but we try to produce a helpful trace message.
658 TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int)totallen);
661 TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int)totallen);
664 TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int)totallen);
667 TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION, data[5], (int)totallen);
671 /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
672 TRACEMS1(cinfo, 1, JTRC_APP0, (int)totallen);
678 examine_app14(j_decompress_ptr cinfo, JOCTET *data, unsigned int datalen,
680 /* Examine first few bytes from an APP14.
681 * Take appropriate action if it is an Adobe marker.
682 * datalen is # of bytes at data[], remaining is length of rest of marker data.
685 unsigned int version, flags0, flags1, transform;
687 if (datalen >= APP14_DATA_LEN &&
693 /* Found Adobe APP14 marker */
694 version = (data[5] << 8) + data[6];
695 flags0 = (data[7] << 8) + data[8];
696 flags1 = (data[9] << 8) + data[10];
697 transform = data[11];
698 TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
699 cinfo->saw_Adobe_marker = TRUE;
700 cinfo->Adobe_transform = (UINT8)transform;
702 /* Start of APP14 does not match "Adobe", or too short */
703 TRACEMS1(cinfo, 1, JTRC_APP14, (int)(datalen + remaining));
709 get_interesting_appn(j_decompress_ptr cinfo)
710 /* Process an APP0 or APP14 marker without saving it */
713 JOCTET b[APPN_DATA_LEN];
714 unsigned int i, numtoread;
717 INPUT_2BYTES(cinfo, length, return FALSE);
720 /* get the interesting part of the marker data */
721 if (length >= APPN_DATA_LEN)
722 numtoread = APPN_DATA_LEN;
724 numtoread = (unsigned int)length;
727 for (i = 0; i < numtoread; i++)
728 INPUT_BYTE(cinfo, b[i], return FALSE);
732 switch (cinfo->unread_marker) {
734 examine_app0(cinfo, (JOCTET *)b, numtoread, length);
737 examine_app14(cinfo, (JOCTET *)b, numtoread, length);
740 /* can't get here unless jpeg_save_markers chooses wrong processor */
741 ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
745 /* skip any remaining data -- could be lots */
748 (*cinfo->src->skip_input_data) (cinfo, (long)length);
754 #ifdef SAVE_MARKERS_SUPPORTED
757 save_marker(j_decompress_ptr cinfo)
758 /* Save an APPn or COM marker into the marker list */
760 my_marker_ptr marker = (my_marker_ptr)cinfo->marker;
761 jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
762 unsigned int bytes_read, data_length;
767 if (cur_marker == NULL) {
768 /* begin reading a marker */
769 INPUT_2BYTES(cinfo, length, return FALSE);
771 if (length >= 0) { /* watch out for bogus length word */
772 /* figure out how much we want to save */
774 if (cinfo->unread_marker == (int)M_COM)
775 limit = marker->length_limit_COM;
777 limit = marker->length_limit_APPn[cinfo->unread_marker - (int)M_APP0];
778 if ((unsigned int)length < limit)
779 limit = (unsigned int)length;
780 /* allocate and initialize the marker item */
781 cur_marker = (jpeg_saved_marker_ptr)
782 (*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,
783 sizeof(struct jpeg_marker_struct) + limit);
784 cur_marker->next = NULL;
785 cur_marker->marker = (UINT8)cinfo->unread_marker;
786 cur_marker->original_length = (unsigned int)length;
787 cur_marker->data_length = limit;
788 /* data area is just beyond the jpeg_marker_struct */
789 data = cur_marker->data = (JOCTET *)(cur_marker + 1);
790 marker->cur_marker = cur_marker;
791 marker->bytes_read = 0;
795 /* deal with bogus length word */
796 bytes_read = data_length = 0;
800 /* resume reading a marker */
801 bytes_read = marker->bytes_read;
802 data_length = cur_marker->data_length;
803 data = cur_marker->data + bytes_read;
806 while (bytes_read < data_length) {
807 INPUT_SYNC(cinfo); /* move the restart point to here */
808 marker->bytes_read = bytes_read;
809 /* If there's not at least one byte in buffer, suspend */
810 MAKE_BYTE_AVAIL(cinfo, return FALSE);
811 /* Copy bytes with reasonable rapidity */
812 while (bytes_read < data_length && bytes_in_buffer > 0) {
813 *data++ = *next_input_byte++;
819 /* Done reading what we want to read */
820 if (cur_marker != NULL) { /* will be NULL if bogus length word */
821 /* Add new marker to end of list */
822 if (cinfo->marker_list == NULL) {
823 cinfo->marker_list = cur_marker;
825 jpeg_saved_marker_ptr prev = cinfo->marker_list;
826 while (prev->next != NULL)
828 prev->next = cur_marker;
830 /* Reset pointer & calc remaining data length */
831 data = cur_marker->data;
832 length = cur_marker->original_length - data_length;
834 /* Reset to initial state for next marker */
835 marker->cur_marker = NULL;
837 /* Process the marker if interesting; else just make a generic trace msg */
838 switch (cinfo->unread_marker) {
840 examine_app0(cinfo, data, data_length, length);
843 examine_app14(cinfo, data, data_length, length);
846 TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
847 (int)(data_length + length));
851 /* skip any remaining data -- could be lots */
852 INPUT_SYNC(cinfo); /* do before skip_input_data */
854 (*cinfo->src->skip_input_data) (cinfo, (long)length);
859 #endif /* SAVE_MARKERS_SUPPORTED */
863 skip_variable(j_decompress_ptr cinfo)
864 /* Skip over an unknown or uninteresting variable-length marker */
869 INPUT_2BYTES(cinfo, length, return FALSE);
872 TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int)length);
874 INPUT_SYNC(cinfo); /* do before skip_input_data */
876 (*cinfo->src->skip_input_data) (cinfo, (long)length);
883 * Find the next JPEG marker, save it in cinfo->unread_marker.
884 * Returns FALSE if had to suspend before reaching a marker;
885 * in that case cinfo->unread_marker is unchanged.
887 * Note that the result might not be a valid marker code,
888 * but it will never be 0 or FF.
892 next_marker(j_decompress_ptr cinfo)
898 INPUT_BYTE(cinfo, c, return FALSE);
899 /* Skip any non-FF bytes.
900 * This may look a bit inefficient, but it will not occur in a valid file.
901 * We sync after each discarded byte so that a suspending data source
902 * can discard the byte from its buffer.
905 cinfo->marker->discarded_bytes++;
907 INPUT_BYTE(cinfo, c, return FALSE);
909 /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
910 * pad bytes, so don't count them in discarded_bytes. We assume there
911 * will not be so many consecutive FF bytes as to overflow a suspending
912 * data source's input buffer.
915 INPUT_BYTE(cinfo, c, return FALSE);
918 break; /* found a valid marker, exit loop */
919 /* Reach here if we found a stuffed-zero data sequence (FF/00).
920 * Discard it and loop back to try again.
922 cinfo->marker->discarded_bytes += 2;
926 if (cinfo->marker->discarded_bytes != 0) {
927 WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
928 cinfo->marker->discarded_bytes = 0;
931 cinfo->unread_marker = c;
939 first_marker(j_decompress_ptr cinfo)
940 /* Like next_marker, but used to obtain the initial SOI marker. */
941 /* For this marker, we do not allow preceding garbage or fill; otherwise,
942 * we might well scan an entire input file before realizing it ain't JPEG.
943 * If an application wants to process non-JFIF files, it must seek to the
944 * SOI before calling the JPEG library.
950 INPUT_BYTE(cinfo, c, return FALSE);
951 INPUT_BYTE(cinfo, c2, return FALSE);
952 if (c != 0xFF || c2 != (int)M_SOI)
953 ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
955 cinfo->unread_marker = c2;
963 * Read markers until SOS or EOI.
965 * Returns same codes as are defined for jpeg_consume_input:
966 * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
970 read_markers(j_decompress_ptr cinfo)
972 /* Outer loop repeats once for each marker. */
974 /* Collect the marker proper, unless we already did. */
975 /* NB: first_marker() enforces the requirement that SOI appear first. */
976 if (cinfo->unread_marker == 0) {
977 if (!cinfo->marker->saw_SOI) {
978 if (!first_marker(cinfo))
979 return JPEG_SUSPENDED;
981 if (!next_marker(cinfo))
982 return JPEG_SUSPENDED;
985 /* At this point cinfo->unread_marker contains the marker code and the
986 * input point is just past the marker proper, but before any parameters.
987 * A suspension will cause us to return with this state still true.
989 switch (cinfo->unread_marker) {
992 return JPEG_SUSPENDED;
995 case M_SOF0: /* Baseline */
996 case M_SOF1: /* Extended sequential, Huffman */
997 if (!get_sof(cinfo, FALSE, FALSE, FALSE))
998 return JPEG_SUSPENDED;
1001 case M_SOF2: /* Progressive, Huffman */
1002 if (!get_sof(cinfo, TRUE, FALSE, FALSE))
1003 return JPEG_SUSPENDED;
1006 case M_SOF3: /* Lossless, Huffman */
1007 if (!get_sof(cinfo, FALSE, TRUE, FALSE))
1008 return JPEG_SUSPENDED;
1011 case M_SOF9: /* Extended sequential, arithmetic */
1012 if (!get_sof(cinfo, FALSE, FALSE, TRUE))
1013 return JPEG_SUSPENDED;
1016 case M_SOF10: /* Progressive, arithmetic */
1017 if (!get_sof(cinfo, TRUE, FALSE, TRUE))
1018 return JPEG_SUSPENDED;
1021 case M_SOF11: /* Lossless, arithmetic */
1022 if (!get_sof(cinfo, FALSE, TRUE, TRUE))
1023 return JPEG_SUSPENDED;
1026 /* Currently unsupported SOFn types */
1027 case M_SOF5: /* Differential sequential, Huffman */
1028 case M_SOF6: /* Differential progressive, Huffman */
1029 case M_SOF7: /* Differential lossless, Huffman */
1030 case M_JPG: /* Reserved for JPEG extensions */
1031 case M_SOF13: /* Differential sequential, arithmetic */
1032 case M_SOF14: /* Differential progressive, arithmetic */
1033 case M_SOF15: /* Differential lossless, arithmetic */
1034 ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
1038 if (!get_sos(cinfo))
1039 return JPEG_SUSPENDED;
1040 cinfo->unread_marker = 0; /* processed the marker */
1041 return JPEG_REACHED_SOS;
1044 TRACEMS(cinfo, 1, JTRC_EOI);
1045 cinfo->unread_marker = 0; /* processed the marker */
1046 return JPEG_REACHED_EOI;
1049 if (!get_dac(cinfo))
1050 return JPEG_SUSPENDED;
1054 if (!get_dht(cinfo))
1055 return JPEG_SUSPENDED;
1059 if (!get_dqt(cinfo))
1060 return JPEG_SUSPENDED;
1064 if (!get_dri(cinfo))
1065 return JPEG_SUSPENDED;
1084 if (!(*((my_marker_ptr)cinfo->marker)->process_APPn[
1085 cinfo->unread_marker - (int)M_APP0]) (cinfo))
1086 return JPEG_SUSPENDED;
1090 if (!(*((my_marker_ptr)cinfo->marker)->process_COM) (cinfo))
1091 return JPEG_SUSPENDED;
1094 case M_RST0: /* these are all parameterless */
1103 TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
1106 case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
1107 if (!skip_variable(cinfo))
1108 return JPEG_SUSPENDED;
1111 default: /* must be DHP, EXP, JPGn, or RESn */
1112 /* For now, we treat the reserved markers as fatal errors since they are
1113 * likely to be used to signal incompatible JPEG Part 3 extensions.
1114 * Once the JPEG 3 version-number marker is well defined, this code
1117 ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
1120 /* Successfully processed marker, so reset state variable */
1121 cinfo->unread_marker = 0;
1127 * Read a restart marker, which is expected to appear next in the datastream;
1128 * if the marker is not there, take appropriate recovery action.
1129 * Returns FALSE if suspension is required.
1131 * This is called by the entropy decoder after it has read an appropriate
1132 * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
1133 * has already read a marker from the data source. Under normal conditions
1134 * cinfo->unread_marker will be reset to 0 before returning; if not reset,
1135 * it holds a marker which the decoder will be unable to read past.
1139 read_restart_marker(j_decompress_ptr cinfo)
1141 /* Obtain a marker unless we already did. */
1142 /* Note that next_marker will complain if it skips any data. */
1143 if (cinfo->unread_marker == 0) {
1144 if (!next_marker(cinfo))
1148 if (cinfo->unread_marker ==
1149 ((int)M_RST0 + cinfo->marker->next_restart_num)) {
1150 /* Normal case --- swallow the marker and let entropy decoder continue */
1151 TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
1152 cinfo->unread_marker = 0;
1154 /* Uh-oh, the restart markers have been messed up. */
1155 /* Let the data source manager determine how to resync. */
1156 if (!(*cinfo->src->resync_to_restart) (cinfo,
1157 cinfo->marker->next_restart_num))
1161 /* Update next-restart state */
1162 cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
1169 * This is the default resync_to_restart method for data source managers
1170 * to use if they don't have any better approach. Some data source managers
1171 * may be able to back up, or may have additional knowledge about the data
1172 * which permits a more intelligent recovery strategy; such managers would
1173 * presumably supply their own resync method.
1175 * read_restart_marker calls resync_to_restart if it finds a marker other than
1176 * the restart marker it was expecting. (This code is *not* used unless
1177 * a nonzero restart interval has been declared.) cinfo->unread_marker is
1178 * the marker code actually found (might be anything, except 0 or FF).
1179 * The desired restart marker number (0..7) is passed as a parameter.
1180 * This routine is supposed to apply whatever error recovery strategy seems
1181 * appropriate in order to position the input stream to the next data segment.
1182 * Note that cinfo->unread_marker is treated as a marker appearing before
1183 * the current data-source input point; usually it should be reset to zero
1185 * Returns FALSE if suspension is required.
1187 * This implementation is substantially constrained by wanting to treat the
1188 * input as a data stream; this means we can't back up. Therefore, we have
1189 * only the following actions to work with:
1190 * 1. Simply discard the marker and let the entropy decoder resume at next
1192 * 2. Read forward until we find another marker, discarding intervening
1193 * data. (In theory we could look ahead within the current bufferload,
1194 * without having to discard data if we don't find the desired marker.
1195 * This idea is not implemented here, in part because it makes behavior
1196 * dependent on buffer size and chance buffer-boundary positions.)
1197 * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
1198 * This will cause the entropy decoder to process an empty data segment,
1199 * inserting dummy zeroes, and then we will reprocess the marker.
1201 * #2 is appropriate if we think the desired marker lies ahead, while #3 is
1202 * appropriate if the found marker is a future restart marker (indicating
1203 * that we have missed the desired restart marker, probably because it got
1205 * We apply #2 or #3 if the found marker is a restart marker no more than
1206 * two counts behind or ahead of the expected one. We also apply #2 if the
1207 * found marker is not a legal JPEG marker code (it's certainly bogus data).
1208 * If the found marker is a restart marker more than 2 counts away, we do #1
1209 * (too much risk that the marker is erroneous; with luck we will be able to
1210 * resync at some future point).
1211 * For any valid non-restart JPEG marker, we apply #3. This keeps us from
1212 * overrunning the end of a scan. An implementation limited to single-scan
1213 * files might find it better to apply #2 for markers other than EOI, since
1214 * any other marker would have to be bogus data in that case.
1218 jpeg_resync_to_restart(j_decompress_ptr cinfo, int desired)
1220 int marker = cinfo->unread_marker;
1223 /* Always put up a warning. */
1224 WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
1226 /* Outer loop handles repeated decision after scanning forward. */
1228 if (marker < (int)M_SOF0)
1229 action = 2; /* invalid marker */
1230 else if (marker < (int)M_RST0 || marker > (int)M_RST7)
1231 action = 3; /* valid non-restart marker */
1233 if (marker == ((int)M_RST0 + ((desired + 1) & 7)) ||
1234 marker == ((int)M_RST0 + ((desired + 2) & 7)))
1235 action = 3; /* one of the next two expected restarts */
1236 else if (marker == ((int)M_RST0 + ((desired - 1) & 7)) ||
1237 marker == ((int)M_RST0 + ((desired - 2) & 7)))
1238 action = 2; /* a prior restart, so advance */
1240 action = 1; /* desired restart or too far away */
1242 TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
1245 /* Discard marker and let entropy decoder resume processing. */
1246 cinfo->unread_marker = 0;
1249 /* Scan to the next marker, and repeat the decision loop. */
1250 if (!next_marker(cinfo))
1252 marker = cinfo->unread_marker;
1255 /* Return without advancing past this marker. */
1256 /* Entropy decoder will be forced to process an empty segment. */
1264 * Reset marker processing state to begin a fresh datastream.
1268 reset_marker_reader(j_decompress_ptr cinfo)
1270 my_marker_ptr marker = (my_marker_ptr)cinfo->marker;
1272 cinfo->comp_info = NULL; /* until allocated by get_sof */
1273 cinfo->input_scan_number = 0; /* no SOS seen yet */
1274 cinfo->unread_marker = 0; /* no pending marker */
1275 marker->pub.saw_SOI = FALSE; /* set internal state too */
1276 marker->pub.saw_SOF = FALSE;
1277 marker->pub.discarded_bytes = 0;
1278 marker->cur_marker = NULL;
1283 * Initialize the marker reader module.
1284 * This is called only once, when the decompression object is created.
1288 jinit_marker_reader(j_decompress_ptr cinfo)
1290 my_marker_ptr marker;
1293 /* Create subobject in permanent pool */
1294 marker = (my_marker_ptr)
1295 (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
1296 sizeof(my_marker_reader));
1297 cinfo->marker = (struct jpeg_marker_reader *)marker;
1298 /* Initialize public method pointers */
1299 marker->pub.reset_marker_reader = reset_marker_reader;
1300 marker->pub.read_markers = read_markers;
1301 marker->pub.read_restart_marker = read_restart_marker;
1302 /* Initialize COM/APPn processing.
1303 * By default, we examine and then discard APP0 and APP14,
1304 * but simply discard COM and all other APPn.
1306 marker->process_COM = skip_variable;
1307 marker->length_limit_COM = 0;
1308 for (i = 0; i < 16; i++) {
1309 marker->process_APPn[i] = skip_variable;
1310 marker->length_limit_APPn[i] = 0;
1312 marker->process_APPn[0] = get_interesting_appn;
1313 marker->process_APPn[14] = get_interesting_appn;
1314 /* Reset marker processing state */
1315 reset_marker_reader(cinfo);
1320 * Control saving of COM and APPn markers into marker_list.
1323 #ifdef SAVE_MARKERS_SUPPORTED
1326 jpeg_save_markers(j_decompress_ptr cinfo, int marker_code,
1327 unsigned int length_limit)
1329 my_marker_ptr marker = (my_marker_ptr)cinfo->marker;
1331 jpeg_marker_parser_method processor;
1333 /* Length limit mustn't be larger than what we can allocate
1334 * (should only be a concern in a 16-bit environment).
1336 maxlength = cinfo->mem->max_alloc_chunk - sizeof(struct jpeg_marker_struct);
1337 if (((long)length_limit) > maxlength)
1338 length_limit = (unsigned int)maxlength;
1340 /* Choose processor routine to use.
1341 * APP0/APP14 have special requirements.
1344 processor = save_marker;
1345 /* If saving APP0/APP14, save at least enough for our internal use. */
1346 if (marker_code == (int)M_APP0 && length_limit < APP0_DATA_LEN)
1347 length_limit = APP0_DATA_LEN;
1348 else if (marker_code == (int)M_APP14 && length_limit < APP14_DATA_LEN)
1349 length_limit = APP14_DATA_LEN;
1351 processor = skip_variable;
1352 /* If discarding APP0/APP14, use our regular on-the-fly processor. */
1353 if (marker_code == (int)M_APP0 || marker_code == (int)M_APP14)
1354 processor = get_interesting_appn;
1357 if (marker_code == (int)M_COM) {
1358 marker->process_COM = processor;
1359 marker->length_limit_COM = length_limit;
1360 } else if (marker_code >= (int)M_APP0 && marker_code <= (int)M_APP15) {
1361 marker->process_APPn[marker_code - (int)M_APP0] = processor;
1362 marker->length_limit_APPn[marker_code - (int)M_APP0] = length_limit;
1364 ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
1367 #endif /* SAVE_MARKERS_SUPPORTED */
1371 * Install a special processing method for COM or APPn markers.
1375 jpeg_set_marker_processor(j_decompress_ptr cinfo, int marker_code,
1376 jpeg_marker_parser_method routine)
1378 my_marker_ptr marker = (my_marker_ptr)cinfo->marker;
1380 if (marker_code == (int)M_COM)
1381 marker->process_COM = routine;
1382 else if (marker_code >= (int)M_APP0 && marker_code <= (int)M_APP15)
1383 marker->process_APPn[marker_code - (int)M_APP0] = routine;
1385 ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);