Merge branch 'upstream' into tizen_base
[platform/upstream/libjpeg-turbo.git] / jdinput.c
1 /*
2  * jdinput.c
3  *
4  * This file was part of the Independent JPEG Group's software:
5  * Copyright (C) 1991-1997, Thomas G. Lane.
6  * Lossless JPEG Modifications:
7  * Copyright (C) 1999, Ken Murchison.
8  * libjpeg-turbo Modifications:
9  * Copyright (C) 2010, 2016, 2018, 2022, D. R. Commander.
10  * Copyright (C) 2015, Google, Inc.
11  * For conditions of distribution and use, see the accompanying README.ijg
12  * file.
13  *
14  * This file contains input control logic for the JPEG decompressor.
15  * These routines are concerned with controlling the decompressor's input
16  * processing (marker reading and coefficient/difference decoding).
17  * The actual input reading is done in jdmarker.c, jdhuff.c, jdphuff.c,
18  * and jdlhuff.c.
19  */
20
21 #define JPEG_INTERNALS
22 #include "jinclude.h"
23 #include "jpeglib.h"
24 #include "jpegapicomp.h"
25
26
27 /* Private state */
28
29 typedef struct {
30   struct jpeg_input_controller pub; /* public fields */
31
32   boolean inheaders;            /* TRUE until first SOS is reached */
33 } my_input_controller;
34
35 typedef my_input_controller *my_inputctl_ptr;
36
37
38 /* Forward declarations */
39 METHODDEF(int) consume_markers(j_decompress_ptr cinfo);
40
41
42 /*
43  * Routines to calculate various quantities related to the size of the image.
44  */
45
46 LOCAL(void)
47 initial_setup(j_decompress_ptr cinfo)
48 /* Called once, when first SOS marker is reached */
49 {
50   int ci;
51   jpeg_component_info *compptr;
52   int data_unit = cinfo->master->lossless ? 1 : DCTSIZE;
53
54   /* Make sure image isn't bigger than I can handle */
55   if ((long)cinfo->image_height > (long)JPEG_MAX_DIMENSION ||
56       (long)cinfo->image_width > (long)JPEG_MAX_DIMENSION)
57     ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int)JPEG_MAX_DIMENSION);
58
59   /* For now, precision must match compiled-in value... */
60 #ifdef D_LOSSLESS_SUPPORTED
61   if (cinfo->data_precision != 8 && cinfo->data_precision != 12 &&
62       cinfo->data_precision != 16)
63 #else
64   if (cinfo->data_precision != 8 && cinfo->data_precision != 12)
65 #endif
66     ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
67
68   /* Check that number of components won't exceed internal array sizes */
69   if (cinfo->num_components > MAX_COMPONENTS)
70     ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
71              MAX_COMPONENTS);
72
73   /* Compute maximum sampling factors; check factor validity */
74   cinfo->max_h_samp_factor = 1;
75   cinfo->max_v_samp_factor = 1;
76   for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
77        ci++, compptr++) {
78     if (compptr->h_samp_factor <= 0 ||
79         compptr->h_samp_factor > MAX_SAMP_FACTOR ||
80         compptr->v_samp_factor <= 0 ||
81         compptr->v_samp_factor > MAX_SAMP_FACTOR)
82       ERREXIT(cinfo, JERR_BAD_SAMPLING);
83     cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
84                                    compptr->h_samp_factor);
85     cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
86                                    compptr->v_samp_factor);
87   }
88
89 #if JPEG_LIB_VERSION >= 80
90   cinfo->block_size = data_unit;
91   cinfo->natural_order = jpeg_natural_order;
92   cinfo->lim_Se = DCTSIZE2 - 1;
93 #endif
94
95   /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE in lossy
96    * mode.  In the full decompressor, this will be overridden by jdmaster.c;
97    * but in the transcoder, jdmaster.c is not used, so we must do it here.
98    */
99 #if JPEG_LIB_VERSION >= 70
100   cinfo->min_DCT_h_scaled_size = cinfo->min_DCT_v_scaled_size = data_unit;
101 #else
102   cinfo->min_DCT_scaled_size = data_unit;
103 #endif
104
105   /* Compute dimensions of components */
106   for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
107        ci++, compptr++) {
108 #if JPEG_LIB_VERSION >= 70
109     compptr->DCT_h_scaled_size = compptr->DCT_v_scaled_size = data_unit;
110 #else
111     compptr->DCT_scaled_size = data_unit;
112 #endif
113     /* Size in data units */
114     compptr->width_in_blocks = (JDIMENSION)
115       jdiv_round_up((long)cinfo->image_width * (long)compptr->h_samp_factor,
116                     (long)(cinfo->max_h_samp_factor * data_unit));
117     compptr->height_in_blocks = (JDIMENSION)
118       jdiv_round_up((long)cinfo->image_height * (long)compptr->v_samp_factor,
119                     (long)(cinfo->max_v_samp_factor * data_unit));
120     /* Set the first and last MCU columns to decompress from multi-scan images.
121      * By default, decompress all of the MCU columns.
122      */
123     cinfo->master->first_MCU_col[ci] = 0;
124     cinfo->master->last_MCU_col[ci] = compptr->width_in_blocks - 1;
125     /* downsampled_width and downsampled_height will also be overridden by
126      * jdmaster.c if we are doing full decompression.  The transcoder library
127      * doesn't use these values, but the calling application might.
128      */
129     /* Size in samples */
130     compptr->downsampled_width = (JDIMENSION)
131       jdiv_round_up((long)cinfo->image_width * (long)compptr->h_samp_factor,
132                     (long)cinfo->max_h_samp_factor);
133     compptr->downsampled_height = (JDIMENSION)
134       jdiv_round_up((long)cinfo->image_height * (long)compptr->v_samp_factor,
135                     (long)cinfo->max_v_samp_factor);
136     /* Mark component needed, until color conversion says otherwise */
137     compptr->component_needed = TRUE;
138     /* Mark no quantization table yet saved for component */
139     compptr->quant_table = NULL;
140   }
141
142   /* Compute number of fully interleaved MCU rows. */
143   cinfo->total_iMCU_rows = (JDIMENSION)
144     jdiv_round_up((long)cinfo->image_height,
145                   (long)(cinfo->max_v_samp_factor * data_unit));
146
147   /* Decide whether file contains multiple scans */
148   if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
149     cinfo->inputctl->has_multiple_scans = TRUE;
150   else
151     cinfo->inputctl->has_multiple_scans = FALSE;
152 }
153
154
155 LOCAL(void)
156 per_scan_setup(j_decompress_ptr cinfo)
157 /* Do computations that are needed before processing a JPEG scan */
158 /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
159 {
160   int ci, mcublks, tmp;
161   jpeg_component_info *compptr;
162   int data_unit = cinfo->master->lossless ? 1 : DCTSIZE;
163
164   if (cinfo->comps_in_scan == 1) {
165
166     /* Noninterleaved (single-component) scan */
167     compptr = cinfo->cur_comp_info[0];
168
169     /* Overall image size in MCUs */
170     cinfo->MCUs_per_row = compptr->width_in_blocks;
171     cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
172
173     /* For noninterleaved scan, always one data unit per MCU */
174     compptr->MCU_width = 1;
175     compptr->MCU_height = 1;
176     compptr->MCU_blocks = 1;
177     compptr->MCU_sample_width = compptr->_DCT_scaled_size;
178     compptr->last_col_width = 1;
179     /* For noninterleaved scans, it is convenient to define last_row_height
180      * as the number of data unit rows present in the last iMCU row.
181      */
182     tmp = (int)(compptr->height_in_blocks % compptr->v_samp_factor);
183     if (tmp == 0) tmp = compptr->v_samp_factor;
184     compptr->last_row_height = tmp;
185
186     /* Prepare array describing MCU composition */
187     cinfo->blocks_in_MCU = 1;
188     cinfo->MCU_membership[0] = 0;
189
190   } else {
191
192     /* Interleaved (multi-component) scan */
193     if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
194       ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
195                MAX_COMPS_IN_SCAN);
196
197     /* Overall image size in MCUs */
198     cinfo->MCUs_per_row = (JDIMENSION)
199       jdiv_round_up((long)cinfo->image_width,
200                     (long)(cinfo->max_h_samp_factor * data_unit));
201     cinfo->MCU_rows_in_scan = (JDIMENSION)
202       jdiv_round_up((long)cinfo->image_height,
203                     (long)(cinfo->max_v_samp_factor * data_unit));
204
205     cinfo->blocks_in_MCU = 0;
206
207     for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
208       compptr = cinfo->cur_comp_info[ci];
209       /* Sampling factors give # of data units of component in each MCU */
210       compptr->MCU_width = compptr->h_samp_factor;
211       compptr->MCU_height = compptr->v_samp_factor;
212       compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
213       compptr->MCU_sample_width = compptr->MCU_width *
214                                   compptr->_DCT_scaled_size;
215       /* Figure number of non-dummy data units in last MCU column & row */
216       tmp = (int)(compptr->width_in_blocks % compptr->MCU_width);
217       if (tmp == 0) tmp = compptr->MCU_width;
218       compptr->last_col_width = tmp;
219       tmp = (int)(compptr->height_in_blocks % compptr->MCU_height);
220       if (tmp == 0) tmp = compptr->MCU_height;
221       compptr->last_row_height = tmp;
222       /* Prepare array describing MCU composition */
223       mcublks = compptr->MCU_blocks;
224       if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
225         ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
226       while (mcublks-- > 0) {
227         cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
228       }
229     }
230
231   }
232 }
233
234
235 /*
236  * Save away a copy of the Q-table referenced by each component present
237  * in the current scan, unless already saved during a prior scan.
238  *
239  * In a multiple-scan JPEG file, the encoder could assign different components
240  * the same Q-table slot number, but change table definitions between scans
241  * so that each component uses a different Q-table.  (The IJG encoder is not
242  * currently capable of doing this, but other encoders might.)  Since we want
243  * to be able to dequantize all the components at the end of the file, this
244  * means that we have to save away the table actually used for each component.
245  * We do this by copying the table at the start of the first scan containing
246  * the component.
247  * Rec. ITU-T T.81 | ISO/IEC 10918-1 prohibits the encoder from changing the
248  * contents of a Q-table slot between scans of a component using that slot.  If
249  * the encoder does so anyway, this decoder will simply use the Q-table values
250  * that were current at the start of the first scan for the component.
251  *
252  * The decompressor output side looks only at the saved quant tables,
253  * not at the current Q-table slots.
254  */
255
256 LOCAL(void)
257 latch_quant_tables(j_decompress_ptr cinfo)
258 {
259   int ci, qtblno;
260   jpeg_component_info *compptr;
261   JQUANT_TBL *qtbl;
262
263   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
264     compptr = cinfo->cur_comp_info[ci];
265     /* No work if we already saved Q-table for this component */
266     if (compptr->quant_table != NULL)
267       continue;
268     /* Make sure specified quantization table is present */
269     qtblno = compptr->quant_tbl_no;
270     if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
271         cinfo->quant_tbl_ptrs[qtblno] == NULL)
272       ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
273     /* OK, save away the quantization table */
274     qtbl = (JQUANT_TBL *)
275       (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
276                                   sizeof(JQUANT_TBL));
277     memcpy(qtbl, cinfo->quant_tbl_ptrs[qtblno], sizeof(JQUANT_TBL));
278     compptr->quant_table = qtbl;
279   }
280 }
281
282
283 /*
284  * Initialize the input modules to read a scan of compressed data.
285  * The first call to this is done by jdmaster.c after initializing
286  * the entire decompressor (during jpeg_start_decompress).
287  * Subsequent calls come from consume_markers, below.
288  */
289
290 METHODDEF(void)
291 start_input_pass(j_decompress_ptr cinfo)
292 {
293   per_scan_setup(cinfo);
294   if (!cinfo->master->lossless)
295     latch_quant_tables(cinfo);
296   (*cinfo->entropy->start_pass) (cinfo);
297   (*cinfo->coef->start_input_pass) (cinfo);
298   cinfo->inputctl->consume_input = cinfo->coef->consume_data;
299 }
300
301
302 /*
303  * Finish up after inputting a compressed-data scan.
304  * This is called by the coefficient or difference controller after it's read
305  * all the expected data of the scan.
306  */
307
308 METHODDEF(void)
309 finish_input_pass(j_decompress_ptr cinfo)
310 {
311   cinfo->inputctl->consume_input = consume_markers;
312 }
313
314
315 /*
316  * Read JPEG markers before, between, or after compressed-data scans.
317  * Change state as necessary when a new scan is reached.
318  * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
319  *
320  * The consume_input method pointer points either here or to the
321  * coefficient or difference controller's consume_data routine, depending on
322  * whether we are reading a compressed data segment or inter-segment markers.
323  */
324
325 METHODDEF(int)
326 consume_markers(j_decompress_ptr cinfo)
327 {
328   my_inputctl_ptr inputctl = (my_inputctl_ptr)cinfo->inputctl;
329   int val;
330
331   if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
332     return JPEG_REACHED_EOI;
333
334   val = (*cinfo->marker->read_markers) (cinfo);
335
336   switch (val) {
337   case JPEG_REACHED_SOS:        /* Found SOS */
338     if (inputctl->inheaders) {  /* 1st SOS */
339       initial_setup(cinfo);
340       inputctl->inheaders = FALSE;
341       /* Note: start_input_pass must be called by jdmaster.c
342        * before any more input can be consumed.  jdapimin.c is
343        * responsible for enforcing this sequencing.
344        */
345     } else {                    /* 2nd or later SOS marker */
346       if (!inputctl->pub.has_multiple_scans)
347         ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
348       start_input_pass(cinfo);
349     }
350     break;
351   case JPEG_REACHED_EOI:        /* Found EOI */
352     inputctl->pub.eoi_reached = TRUE;
353     if (inputctl->inheaders) {  /* Tables-only datastream, apparently */
354       if (cinfo->marker->saw_SOF)
355         ERREXIT(cinfo, JERR_SOF_NO_SOS);
356     } else {
357       /* Prevent infinite loop in coef ctlr's decompress_data routine
358        * if user set output_scan_number larger than number of scans.
359        */
360       if (cinfo->output_scan_number > cinfo->input_scan_number)
361         cinfo->output_scan_number = cinfo->input_scan_number;
362     }
363     break;
364   case JPEG_SUSPENDED:
365     break;
366   }
367
368   return val;
369 }
370
371
372 /*
373  * Reset state to begin a fresh datastream.
374  */
375
376 METHODDEF(void)
377 reset_input_controller(j_decompress_ptr cinfo)
378 {
379   my_inputctl_ptr inputctl = (my_inputctl_ptr)cinfo->inputctl;
380
381   inputctl->pub.consume_input = consume_markers;
382   inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
383   inputctl->pub.eoi_reached = FALSE;
384   inputctl->inheaders = TRUE;
385   /* Reset other modules */
386   (*cinfo->err->reset_error_mgr) ((j_common_ptr)cinfo);
387   (*cinfo->marker->reset_marker_reader) (cinfo);
388   /* Reset progression state -- would be cleaner if entropy decoder did this */
389   cinfo->coef_bits = NULL;
390 }
391
392
393 /*
394  * Initialize the input controller module.
395  * This is called only once, when the decompression object is created.
396  */
397
398 GLOBAL(void)
399 jinit_input_controller(j_decompress_ptr cinfo)
400 {
401   my_inputctl_ptr inputctl;
402
403   /* Create subobject in permanent pool */
404   inputctl = (my_inputctl_ptr)
405     (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_PERMANENT,
406                                 sizeof(my_input_controller));
407   cinfo->inputctl = (struct jpeg_input_controller *)inputctl;
408   /* Initialize method pointers */
409   inputctl->pub.consume_input = consume_markers;
410   inputctl->pub.reset_input_controller = reset_input_controller;
411   inputctl->pub.start_input_pass = start_input_pass;
412   inputctl->pub.finish_input_pass = finish_input_pass;
413   /* Initialize state: can't use reset_input_controller since we don't
414    * want to try to reset other modules yet.
415    */
416   inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
417   inputctl->pub.eoi_reached = FALSE;
418   inputctl->inheaders = TRUE;
419 }