1 /* libhpojip -- HP OfficeJet image-processing library. */
2 
3 /* Copyright (C) 1995-2002 HP Company
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
12  * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
13  * NON-INFRINGEMENT.  See the GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
18  * MA 02111-1307, USA.
19  *
20  * In addition, as a special exception, HP Company
21  * gives permission to link the code of this program with any
22  * version of the OpenSSL library which is distributed under a
23  * license identical to that listed in the included LICENSE.OpenSSL
24  * file, and distribute linked combinations including the two.
25  * You must obey the GNU General Public License in all respects
26  * for all of the code used other than OpenSSL.  If you modify
27  * this file, you may extend this exception to your version of the
28  * file, but you are not obligated to do so.  If you do not wish to
29  * do so, delete this exception statement from your version.
30  */
31 
32 /* Original author: Mark Overton and others.
33  *
34  * Ported to Linux by David Paschal.
35  */
36 
37 /*****************************************************************************\
38  *
39  * xjpg_dec.c - Decodes a JPEG file into a raw gray image
40  *
41  *****************************************************************************
42  *
43  * Name of Global Jump-Table:
44  *
45  *    jpgDecodeTbl
46  *
47  * Items in aXformInfo array passed into setXformSpec:
48  *
49  *    aXformInfo[IP_JPG_DECODE_OUTPUT_SUBSAMPLED]:
50  *            Output only subsampled raw data? 0=no, 1=yes.
51  *    aXformInfo[IP_JPG_DECODE_FROM_DENALI]:
52  *            Data came from a Denali? 0=no, 1=yes.
53  *
54  *    The aXformInfo items above may all be set to 0 for typical JPEG files.
55  *
56  *    For Denali, we assume the following:
57  *        - Every 8x8 block ends with an EOB
58  *        - A slight change in the Huffman tables (no 15-bit code)
59  *        - Denali sends us a proprietary short header (APP1 marker)
60  *
61  * Capabilities and Limitations:
62  *
63  *    Decodes a standard JPEG file.  Also handles JFIF 1.0 (APP0 marker).
64  *    Also handles the non-standard short header output by OfficeJet firmware
65  *    (APP1 marker).  Also handles APP1 markers defined by color fax standard.
66  *    Will *not* decode a non-interleaved file; it must be interleaved.
67  *    Handles 1-4 components per pixel, and 4 Huffman tables, so SOF1 with
68  *    8 bits/component is okay.
69  *
70  * Default Input Traits, and Output Traits:
71  *
72  *    For decoder:
73  *
74  *          trait             default input             output
75  *    -------------------  -------------------  ------------------------
76  *    iPixelsPerRow           ignored              based on header
77  *    iBitsPerPixel           ignored              based on header
78  *    iComponentsPerPixel     ignored              based on header
79  *    lHorizDPI               ignored              based on header
80  *    lVertDPI                ignored              based on header
81  *    lNumRows                ignored              based on header
82  *    iNumPages               passed into output   same as default input
83  *    iPageNum                passed into output   same as default input
84  *
85  * Kludges:
86  *
87  *    Chromafax and other software inserts fill 0's instead of fill 1's
88  *    before a marker, such as the all-important EOI marker.  So when
89  *    we get a syntax error when parsing those 0's, we do not report
90  *    an error if there's a following marker, but simply proceed to
91  *    process the marker as usual.
92  *
93  *    Chromafax uses an SOF1 instead of the correct SOF0, so we allow
94  *    that, and also handle four Huffman tables that SOF1 requires.
95  *
96  * Jan 1998 Mark Overton -- Ported to new software Image Processor
97  * Apr 1996 Mark Overton -- Finished software-only JPEG decoder
98  * Feb 1996 Mark Overton -- initial code
99  *
100 \*****************************************************************************/
101 
102 #include <string.h>
103 #include <assert.h>
104 
105 #include "hpip.h"
106 #include "ipdefs.h"
107 #include "setjmp.h"
108 #include "xjpg_dct.h"
109 #include "xjpg_mrk.h"
110 
111 
112 #define DUMP_JPEG 0
113 
114 #if DUMP_JPEG
115     #include "stdio.h"
116     #include <tchar.h>
117 
118     #define DUMP(msg,arg1,arg2,arg3) \
119         _ftprintf(stdout, msg, (int)(arg1), (int)(arg2), (int)(arg3))
120 #else
121     #define DUMP(msg,arg1,arg2,arg3)
122 #endif
123 
124 
125 #if 0
126     #include "stdio.h"
127     #include <tchar.h>
128     #define PRINT(msg,arg1,arg2) \
129         _ftprintf(stdout, _T("(jpeg) ") msg, (int)arg1, (int)arg2)
130 #else
131     #define PRINT(msg,arg1,arg2)
132 #endif
133 
134 
135 /*____________________________________________________________________________
136  |                                                                            |
137  | Constants                                                                  |
138  |____________________________________________________________________________|
139 */
140 
141 #define MAX_HUFF_TBLS     4
142 
143 #define UNEXPECTED_MARKER       1
144 #define BAD_MARKER_ID           2
145 #define BAD_MARKER_DATA         3
146 #define NO_RESTART_MARKER       4
147 #define BAD_HUFF_CODE           5
148 #define UNEXPECTED_END_OF_DATA  6
149 #define NOT_IMPLEMENTED         7
150 
151 #define MAX_MARKER_LEN    15000   /* large in case marker holds a thumbnail */
152 #define MAX_HEADER_SIZE   (MAX_MARKER_LEN+2000)
153 #define MAX_BLOCKS_IN_MCU 6
154 #define MAX_MCU_SIZE      (MAX_BLOCKS_IN_MCU*304)
155                                   /* max encoded MCU size, plus stuff-bytes */
156 #define INBUF_NUM_MCUS    2       /* workbuf will be this multiple of max MCU */
157 
158 #define DC_TBL_INDEX_LEN  9
159 #define AC_TBL_INDEX_LEN  12
160 
161 #define CHECK_VALUE  0x1ce5ca7e
162 
163 
164 
165 /*____________________________________________________________________________
166  |                                                                            |
167  | Instance Variables                                                         |
168  |____________________________________________________________________________|
169 */
170 
171 typedef struct {
172     BYTE  size;     /* number of bits in the Huff code (code is the index) */
173     BYTE  value;    /* value that was coded */
174 } main_huff_elem_t;
175 
176 typedef struct {
177     WORD   code;    /* Huff code to use for the 'value' below */
178     BYTE   size;    /* number of bits in above Huff 'code' */
179     BYTE   value;   /* value that was coded */
180 } aux_huff_elem_t;
181 
182 typedef struct {
183     BYTE             *index_p;
184     main_huff_elem_t *main_p;
185     aux_huff_elem_t  *aux_p;
186 } huff_tbl_t;
187 
188 
189 /* Decoding is centered around out_rows_ap.  It is indexed by
190  * [color_component_number][row_number].
191  * color_component_number 0 is Y (intensity); mono only has this component.
192  *
193  * Each component in out_rows_ap has a height (# rows) equal to the number of
194  * samples in the MCU, and a width equal to the number of samples in all the
195  * MCUs in a row. That is, pixels are stored in out_rows_ap with NO REPLICATION.
196  * So if a component has sample factors of H and V, it will have 8*V rows and
197  * pixels_in_row*H/max_horiz_samp_fac columns in out_rows_ap.
198  */
199 
200 typedef struct {
201     BYTE   *out_rows_ap[4][32];  /* row-buffers [component][row] */
202 
203     /***** Items from SOF, Start Of Frame *****/
204 
205     IP_IMAGE_TRAITS traits;      /* traits of the image */
206     BYTE    num_comps;           /* # of components (1 => mono) */
207     BYTE    horiz_samp_facs[4];  /* horizontal sampling factors */
208     BYTE    vert_samp_facs [4];  /* vertical sampling factors */
209     BYTE    max_horiz_samp_fac;  /* max sample factors */
210     BYTE    max_vert_samp_fac;
211     BYTE    which_quant_tbl[4];  /* selects q tbl for component */
212     UINT    rows_per_mcu;        /* # rows & cols in each MCU */
213     UINT    cols_per_mcu;
214     UINT    mcus_per_row;        /* # of MCUs in each row */
215     UINT    rowCountOffset;
216 
217     /***** Items from other markers *****/
218 
219     WORD    restart_interval;    /* restart interval (0 -> none) */
220     long    quant_tbls[4][64];   /* quantization tables */
221     BYTE    which_dc_tbl[4];     /* selects DC tbl for component */
222     BYTE    which_ac_tbl[4];     /* selects AC tbl for component */
223     BOOL    fColorFax;           /* is this from a fax? */
224 
225     /***** Huffman tables *****/
226 
227     huff_tbl_t dc_tbls[MAX_HUFF_TBLS];
228     huff_tbl_t ac_tbls[MAX_HUFF_TBLS];
229 
230     /***** Configuration variables *****/
231 
232     BOOL     output_subsampled;   /* output subsampled data? */
233     BOOL     fDenali;             /* data is from a Denali? */
234 
235     /***** Variables used while decoding *****/
236 
237     DWORD    dwInNextPos;         /* next read pos in input file */
238     DWORD    dwOutNextPos;        /* next write pos in output file */
239     long     rows_done;           /* # rows decoded and output */
240     UINT     mcus_done;           /* # MCUs decoded so far in row */
241     BOOL     sending_rows;        /* returning the decoded rows? */
242     BOOL     got_short_header;    /* got an OfficeJet short header? */
243     BOOL     got_EOI;             /* hit the end-of-image marker? */
244     BYTE     restart_cur_marker;  /* index of next expected marker */
245     WORD     restart_cur_mcu;     /* current MCU-count in interval */
246     int      prior_dc[4];         /* DC values of prior block */
247     jmp_buf  syntax_error;        /* jump-target for syntax errors */
248     jmp_buf  old_syntax_error;
249     DWORD    dwValidChk;          /* struct validity check value */
250 
251     /***** Reading bits variables *****/
252 
253     DWORD rd_bit_buf;
254         /* Bits to be read from inbuf (read left-to-right). */
255 
256     int rd_bits_avail;
257         /* Number of bits not yet read in rd_bit_buf (= 32 - number read). */
258 
259     BYTE *rd_inbuf_beg;
260         /* The beginning of the input buffer. */
261 
262     BYTE *rd_inbuf_next;
263         /* Next byte in inbuf to be read. */
264 
265     /***** Decoding 8x8 blocks *****/
266 
267     int  block[64];           /* scratch-pad 8x8 block */
268     int *block_zz[64+16];     /* zig-zag ptrs into above block */
269 
270 } JDEC_INST, *PJDEC_INST;
271 
272 
273 
274 /*____________________________________________________________________________
275  |                                                                            |
276  | Forward Routines                                                           |
277  |____________________________________________________________________________|
278 */
279 
280 static void huff_define_table (
281     PJDEC_INST   g,
282     BOOL         ac,         /* defining an AC table? (else DC) */
283     UINT         id,         /* which table is being defined (0-3) */
284     const BYTE   counts[16], /* number of Huffman codes of each length 1-16 */
285     const BYTE   values[]);  /* values associated with codes of above lengths */
286 
287 void wino_scale_table (long *tbl_p);
288 
289 
290 
291 
292 /******************************************************************************
293  ******************************************************************************
294 
295                                 R E A D I N G
296 
297 
298  Interface into this section:
299 
300      read_init          - inits this section
301      read_buf_open      - we are being given a (new) input buffer
302      read_buf_close     - done with current input buffer; return # bytes used
303      read_byte          - returns next input byte (syncs to byte-boundary)
304      read_uint          - returns next 2-byte integer (syncs)
305      read_skip_forward  - discards the given number of input bytes
306      read_skip_backward - backs up the given number of bytes
307      READ_BITS_LOAD     - loads N bits of input into lsb's of a var (no advance)
308      READ_BITS_ADVANCE  - advance input N bits; you must call this to eat input
309 
310  ******************************************************************************
311  ******************************************************************************/
312 
313 
314 
315 /*____________________________________________________________________________
316  |           |                                                                |
317  | read_init | Inits this section                                             |
318  |___________|________________________________________________________________|
319 */
read_init(PJDEC_INST g)320 static void read_init (PJDEC_INST g)
321 {
322     g->rd_bits_avail = 0;
323     g->rd_bit_buf    = 0;
324 }
325 
326 
327 
328 /*____________________________________________________________________________
329  |               |                                                            |
330  | read_buf_open | We are being given a (new) buffer to read input            |
331  |_______________|____________________________________________________________|
332  |                                                                            |
333  | This routine records the location of the new input buffer.                 |
334  |____________________________________________________________________________|
335 */
read_buf_open(PJDEC_INST g,BYTE * buf_p)336 static void read_buf_open (PJDEC_INST g, BYTE *buf_p)
337 {
338     g->rd_inbuf_beg  = buf_p;
339     g->rd_inbuf_next = buf_p;
340 }
341 
342 
343 
344 /*____________________________________________________________________________
345  |                |                                                           |
346  | read_buf_close | We are done with the current input buffer                 |
347  |________________|___________________________________________________________|
348  |                                                                            |
349  | This function returns # bytes read from the input buffer.                  |
350  |____________________________________________________________________________|
351 */
read_buf_close(PJDEC_INST g)352 static int read_buf_close (PJDEC_INST g)
353 {
354     return g->rd_inbuf_next - g->rd_inbuf_beg;
355 }
356 
357 
358 
359 /*____________________________________________________________________________
360  |         |                                                                  |
361  | rd_sync | Empties the bit-cache, and syncs to a byte-boundary              |
362  |_________|__________________________________________________________________|
363 */
rd_sync(PJDEC_INST g)364 static void rd_sync (PJDEC_INST g)
365 {
366     g->rd_bits_avail = 0;
367 }
368 
369 
370 
371 /*____________________________________________________________________________
372  |           |                                                                |
373  | read_byte | returns next input byte (syncs to byte-boundary)               |
374  |___________|________________________________________________________________|
375 */
read_byte(PJDEC_INST g)376 static BYTE  read_byte (PJDEC_INST g)
377 {
378     rd_sync (g);
379     return *(g->rd_inbuf_next)++;
380 }
381 
382 
383 
384 /*____________________________________________________________________________
385  |           |                                                                |
386  | read_uint | returns next 2-byte integer (syncs)                            |
387  |___________|________________________________________________________________|
388 */
read_uint(PJDEC_INST g)389 static unsigned read_uint (PJDEC_INST g)
390 {
391     UINT uval;
392 
393     rd_sync (g);
394     uval = (unsigned)*(g->rd_inbuf_next)++ << 8;
395     return uval | *(g->rd_inbuf_next)++;
396 }
397 
398 
399 
400 /*____________________________________________________________________________
401  |                   |                                                        |
402  | read_skip_forward | discards the given number of input bytes               |
403  |___________________|________________________________________________________|
404 */
read_skip_forward(PJDEC_INST g,UINT n)405 static void read_skip_forward (PJDEC_INST g, UINT n)
406 {
407     if (n > MAX_MARKER_LEN)
408         longjmp (g->syntax_error, BAD_MARKER_DATA);
409     rd_sync (g);
410     g->rd_inbuf_next += n;
411 }
412 
413 
414 
415 /*____________________________________________________________________________
416  |                    |                                                       |
417  | read_skip_backward | backs up N bytes in the input buffer                  |
418  |____________________|_______________________________________________________|
419 */
read_skip_backward(PJDEC_INST g,UINT n)420 static void read_skip_backward (PJDEC_INST g, UINT n)
421 {
422     rd_sync (g);
423     g->rd_inbuf_next -= n;
424 }
425 
426 
427 
428 /*____________________________________________________________________________
429  |                |                                                           |
430  | READ_BITS_LOAD | loads next par_n_bits of input into par_value (no advance)|
431  |________________|___________________________________________________________|
432  |                                                                            |
433  | If a marker is encountered:                                                |
434  |     - this macro will goto hit_marker                                      |
435  |     - the marker will be the next two bytes in the buffer                  |
436  |     - the cache will be empty (ie, any fill 1's were discarded)            |
437  |                                                                            |
438  | If the JPEG file erroneously has fill 0's (instead of 1's) before a        |
439  | marker, we'll parse them as Huffman codes.  If such a bogus Huffman code   |
440  | has more bits than were in our bit-buffer, the extra non-existent bits     |
441  | will be returned as zeroes.                                                |
442  |____________________________________________________________________________|
443 */
444 
445 #define CANT_LOAD_NEAR_MARKER(g)                                            \
446     (g->rd_bits_avail<=0 ||                                                 \
447      (g->rd_bits_avail<=7 && (((1u<<g->rd_bits_avail)-1) & ~g->rd_bit_buf) == 0))
448         /* we just parsed past erroneous fill 0's  OR */
449         /* cached bits are just fill 1's; toss them */
450 
451 
452 #define READ_BITS_LOAD(g, fixed_len, par_n_bits, par_value, hit_marker)     \
453 {                                                                           \
454     if ((int)(par_n_bits) > g->rd_bits_avail) {                             \
455         BYTE  a_byte;                                                       \
456                                                                             \
457         do {                                                                \
458             a_byte = *(g->rd_inbuf_next)++;                                 \
459             DUMP (_T("<%02x>"), a_byte, 0, 0);                                  \
460                                                                             \
461             if (a_byte == (BYTE )0xffu) {                                   \
462                 if (*(g->rd_inbuf_next)++ != 0) {   /* we hit a marker */   \
463                     g->rd_inbuf_next -= 2;                                  \
464                     if (CANT_LOAD_NEAR_MARKER(g))                           \
465                         goto hit_marker;                                    \
466                     break;   /* exit 'while' loop */                        \
467                 }                                                           \
468             }                                                               \
469                                                                             \
470             g->rd_bit_buf = (g->rd_bit_buf<<8) | a_byte;                    \
471             g->rd_bits_avail += 8;                                          \
472         } while (g->rd_bits_avail <= 24);                                   \
473     }                                                                       \
474                                                                             \
475     par_value = (g->rd_bit_buf << (32-g->rd_bits_avail)) >> (32-(par_n_bits)); \
476 }
477 
478 
479 
480 /*____________________________________________________________________________
481  |                   |                                                        |
482  | READ_BITS_ADVANCE | discards next par_n_bits of input                      |
483  |___________________|________________________________________________________|
484 */
485 #define READ_BITS_ADVANCE(g, par_n_bits)   \
486 {                                          \
487     g->rd_bits_avail -= par_n_bits;        \
488 }
489 
490 
491 
492 /******************************************************************************
493  ******************************************************************************
494 
495                                M A R K E R S
496 
497 
498  Interface into this section:
499 
500      mar_get   - parses and returns next marker-id
501      mar_parse - parses the data associated with the marker
502 
503  ******************************************************************************
504  ******************************************************************************/
505 
506 
507 
508 /*____________________________________________________________________________
509  |               |                                                            |
510  | parse_factors | parses sample-factors as nibbles into array                |
511  |_______________|____________________________________________________________|
512  |                                                                            |
513  | This is only called by parse_app_short_header below.                       |
514  | Function return value = maximum sample factor.                             |
515  |____________________________________________________________________________|
516 */
parse_factors(UINT factors,BYTE fac_array[4])517 static UINT parse_factors (
518     UINT factors,       /* in:  sample factors, one nibble each, l-to-r */
519     BYTE fac_array[4])  /* out: array of sample factors */
520 {
521     int  i;
522     UINT fac;
523     UINT max_fac;
524 
525     max_fac = 0;
526 
527     for (i=3; i>=0; i--) {
528         fac = factors & 0x000fu;
529         factors >>= 4;
530         if (fac > max_fac) max_fac = fac;
531         fac_array[i] = fac;
532     }
533 
534     return max_fac;
535 }
536 
537 
538 
539 /*____________________________________________________________________________
540  |                  |                                                         |
541  | calc_quant_table | calculates a quantization table                         |
542  |__________________|_________________________________________________________|
543  |                                                                            |
544  | This is only called by parse_app_short_header below.                       |
545  | Warning: The calculation below should match the firmware.                  |
546  |____________________________________________________________________________|
547 */
calc_quant_table(PJDEC_INST g,UINT dc_q_fac,UINT ac_q_fac,const BYTE * orig_tbl_p,UINT which_q_tbl)548 static void calc_quant_table (
549     PJDEC_INST  g,
550     UINT        dc_q_fac,      /* orig DC  is  scaled by (dc_q_fac/50) */
551     UINT        ac_q_fac,      /* orig ACs are scaled by (ac_q_fac/50) */
552     const BYTE *orig_tbl_p,    /* original table */
553     UINT        which_q_tbl)   /* which table is being defined (0-3) */
554 {
555     int   i;
556     UINT  quant;
557     long *tbl_p;
558 
559     tbl_p = g->quant_tbls[which_q_tbl];
560 
561     for (i=0; i<64; i++) {
562         quant = ((*orig_tbl_p++)*(i==0 ? dc_q_fac : ac_q_fac) + 25u) / 50u;
563         if (quant ==  0) quant = 1;
564         if (quant > 255) quant = 255;
565         tbl_p[i] = quant;
566     }
567 
568     wino_scale_table (tbl_p);
569 }
570 
571 
572 
573 /*____________________________________________________________________________
574  |         |                                                                  |
575  | mar_get | parses and returns next marker-id                                |
576  |_________|__________________________________________________________________|
577 */
mar_get(PJDEC_INST g)578 static UINT mar_get (PJDEC_INST g)
579 {
580     UINT   marker = 0;   /* init to eliminate a compiler warning */
581     BOOL   got_ff;
582 
583     got_ff = FALSE;
584 
585     while (TRUE) {
586         marker = read_byte (g);
587         if (marker == 0xff) got_ff = TRUE;
588         else                break;
589     }
590 
591     if (!got_ff || marker==0)
592         longjmp (g->syntax_error, BAD_MARKER_ID);
593 
594     return marker;
595 }
596 
597 
598 
599 /*____________________________________________________________________________
600  |           |                                                                |
601  | mar_flush | discards data associated with current marker                   |
602  |___________|________________________________________________________________|
603 */
mar_flush(PJDEC_INST g,UINT marker)604 static void mar_flush (PJDEC_INST g, UINT marker)
605 {
606     if (marker==MARKER_SOI || marker==MARKER_EOI ||
607         (marker>=MARKER_RST0 && marker<=MARKER_RST7))
608         return;   /* marker has no associated segment */
609 
610     read_skip_forward (g, read_uint(g) - 2);
611 }
612 
613 
614 
615 /*____________________________________________________________________________
616  |                |                                                           |
617  | parse_app_jfif | parses a JFIF APP0 marker                                 |
618  |________________|___________________________________________________________|
619  |                                                                            |
620  | Sets these fields in 'traits': lHorizDPI, lVertDPI                         |
621  |____________________________________________________________________________|
622 */
parse_app_jfif(PJDEC_INST g)623 static void parse_app_jfif (PJDEC_INST g)
624 {
625     UINT  len;
626     BYTE  byt;
627     UINT  h_dpi, v_dpi;
628 
629     len = read_uint (g);
630     byt = read_byte (g);
631     if (! (len==16 && (byt==(BYTE )'J' || byt==(BYTE )'j'))) {
632         /* This is not a JFIF APP-marker, so silently discard it */
633         read_skip_forward (g, len-3);
634         return;
635     }
636 
637     read_skip_forward (g,6);  /* discard "FIF\0" + 0x01 + 0x00 */
638     byt = read_byte (g);
639     h_dpi = read_uint (g);
640     v_dpi = read_uint (g);
641     read_skip_forward (g,2);  /* discard thumbnail X and Y */
642 
643     if (byt == 1) {   /* 1 means that units are dots/inch */
644         g->traits.lHorizDPI = (DWORD)h_dpi << 16;
645         g->traits.lVertDPI  = (DWORD)v_dpi << 16;
646     }
647 }
648 
649 
650 
651 /*____________________________________________________________________________
652  |                 |                                                          |
653  | parse_app_g3fax | parses a color fax APP1 marker                           |
654  |_________________|__________________________________________________________|
655  |                                                                            |
656  | Can set these fields in 'traits': lHorizDPI, lVertDPI                      |
657  |____________________________________________________________________________|
658  */
parse_app_g3fax(PJDEC_INST g)659 static void parse_app_g3fax (PJDEC_INST g)
660 {
661     int  i;
662     UINT len, dpi;
663     BYTE id_ver[8];
664     const BYTE valid_id_ver[8] = {
665         0x47, 0x33, 0x46, 0x41, 0x58, 0x00,  /* "G3FAX" plus a 0 byte */
666         0x07, 0xca };                        /* version is year of std, 1994 */
667 
668     len = read_uint (g);
669     if (len != 12) {
670         /* wrong version, or a gamut or illuminant spec which we ignore */
671         read_skip_forward (g, len-2);
672         return;
673     }
674 
675     for (i=0; i<8; i++)   /* fax id is 6 bytes; version is 2 bytes */
676         id_ver[i] = read_byte (g);
677 
678     dpi = read_uint (g);
679 
680     if (memcmp(id_ver,valid_id_ver,8) == 0
681         && (dpi==200 || dpi==300 || dpi==400)) {
682         /* everything is valid (whew!), so save dpi */
683        g->traits.lHorizDPI = g->traits.lVertDPI = (long)dpi << 16;
684        g->fColorFax = TRUE;
685     }
686 }
687 
688 
689 
690 /*____________________________________________________________________________
691  |                        |                                                   |
692  | parse_app_short_header | An APP1 marker output by OfficeJet firmware       |
693  |________________________|___________________________________________________|
694 */
parse_app_short_header(PJDEC_INST g)695 static void parse_app_short_header (PJDEC_INST g)
696 {
697     /* Since the firmware does not supply tables in its header,
698      * the tables used in the firmware are supplied below.  */
699 
700     static const BYTE orig_lum_quant[64] = {
701          16,  11,  12,  14,  12,  10,  16,  14,
702          13,  14,  18,  17,  16,  19,  24,  40,
703          26,  24,  22,  22,  24,  49,  35,  37,
704          29,  40,  58,  51,  61,  60,  57,  51,
705          56,  55,  64,  72,  92,  78,  64,  68,
706          87,  69,  55,  56,  80, 109,  81,  87,
707          95,  98, 103, 104, 103,  62,  77, 113,
708         121, 112, 100, 120,  92, 101, 103,  99
709     };
710 
711 
712     static const BYTE orig_chrom_quant[64] = {
713         17,  18,  18,  24,  21,  24,  47,  26,
714         26,  47,  99,  66,  56,  66,  99,  99,
715         99,  99,  99,  99,  99,  99,  99,  99,
716         99,  99,  99,  99,  99,  99,  99,  99,
717         99,  99,  99,  99,  99,  99,  99,  99,
718         99,  99,  99,  99,  99,  99,  99,  99,
719         99,  99,  99,  99,  99,  99,  99,  99,
720         99,  99,  99,  99,  99,  99,  99,  99
721     };
722 
723     static const BYTE lum_DC_counts[16] = {
724         0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
725         0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
726     };
727 
728     static const BYTE lum_DC_values[12] = {
729         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b
730     };
731 
732     static const BYTE chrom_DC_counts[16] = {
733         0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
734         0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00
735     };
736 
737     static const BYTE chrom_DC_values[12] = {
738         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b
739     };
740 
741     static const BYTE lum_AC_counts[16] = {
742         0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
743         0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d
744     };
745 
746     static const BYTE lum_AC_counts_Denali[16] = {
747         0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03,
748         0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x00, 0x7e
749         /* Above, the [01,7d] in the normal table was changed to [00,7e].
750          * This alteration eliminates the sole 15-bit code, and yields
751          * Huffman codes as follows:
752          *    - common codes are 12 bits wide or less,
753          *    - uncommon codes are exactly 16 bits wide, and all those codes
754          *      start with nine '1' bits, leaving seven bits of useful info.
755          * Denali uses a 4K-entry table for the common codes, and a
756          * quick lookup for the 7-bit leftover codes.  So parsing of all
757          * codes is simple and fast.
758          */
759     };
760 
761     static const BYTE lum_AC_values[162] = {
762         0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
763         0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
764         0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
765         0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
766         0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
767         0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
768         0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
769         0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
770         0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
771         0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
772         0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
773         0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
774         0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
775         0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
776         0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
777         0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
778         0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
779         0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
780         0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
781         0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
782         0xf9, 0xfa
783     };
784 
785     static const BYTE chrom_AC_counts[16] = {
786         0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04,
787         0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77
788     };
789 
790     static const BYTE chrom_AC_values[162] = {
791         0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
792         0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
793         0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
794         0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
795         0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
796         0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
797         0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
798         0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
799         0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
800         0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
801         0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
802         0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
803         0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
804         0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
805         0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
806         0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
807         0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
808         0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
809         0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
810         0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
811         0xf9, 0xfa
812     };
813 
814     UINT len;
815     UINT dc_q_fac, ac_q_fac;
816     UINT reserved;
817 
818     /***** default items not in the short header *****/
819 
820     g->restart_interval = 0;
821 
822     g->which_quant_tbl[0] = 0;
823     g->which_quant_tbl[1] = 1;
824     g->which_quant_tbl[2] = 1;
825 
826     g->which_dc_tbl[0] = 0;
827     g->which_ac_tbl[0] = 0;
828     g->which_dc_tbl[1] = 1;
829     g->which_ac_tbl[1] = 1;
830     g->which_dc_tbl[2] = 1;
831     g->which_ac_tbl[2] = 1;
832 
833     huff_define_table (g, FALSE, 0, lum_DC_counts  , lum_DC_values);
834     huff_define_table (g, TRUE , 0, g->fDenali     ? lum_AC_counts_Denali
835                                                    : lum_AC_counts, lum_AC_values);
836     huff_define_table (g, FALSE, 1, chrom_DC_counts, chrom_DC_values);
837     huff_define_table (g, TRUE , 1, chrom_AC_counts, chrom_AC_values);
838 
839     /***** parse the short header *****/
840 
841     len = read_uint (g);
842     if (len != 18)
843         longjmp (g->syntax_error, BAD_MARKER_DATA);
844 
845     g->traits.lNumRows      = read_uint (g);
846     g->traits.iPixelsPerRow = read_uint (g);
847     g->traits.lHorizDPI     = (long)read_uint(g) << 16;
848     g->traits.lVertDPI      = (long)read_uint(g) << 16;
849     ac_q_fac                = read_byte (g);
850     g->num_comps            = read_byte (g);
851     g->max_horiz_samp_fac   = parse_factors (read_uint(g), g->horiz_samp_facs);
852     g->max_vert_samp_fac    = parse_factors (read_uint(g), g->vert_samp_facs);
853     dc_q_fac                = read_byte (g);
854     reserved                = read_byte (g);   /* should be 0 */
855 
856     g->traits.iComponentsPerPixel = g->num_comps;
857     g->traits.iBitsPerPixel       = g->num_comps * 8;
858     if (g->traits.lNumRows == 0)
859         g->traits.lNumRows = -1;   /* -1 means 'unknown' */
860     if (dc_q_fac == 0)
861         dc_q_fac = ac_q_fac;
862 
863     calc_quant_table (g, dc_q_fac, ac_q_fac, orig_lum_quant, 0);
864     calc_quant_table (g, dc_q_fac, ac_q_fac, orig_chrom_quant, 1);
865 
866     g->got_short_header = TRUE;
867 }
868 
869 
870 
871 /*____________________________________________________________________________
872  |               |                                                            |
873  | mar_parse_app | application-specific marker                                |
874  |_______________|____________________________________________________________|
875  |                                                                            |
876  | Can set these fields in 'traits': lHorizDPI, lVertDPI                      |
877  |____________________________________________________________________________|
878  */
mar_parse_app(PJDEC_INST g,UINT marker)879 static void mar_parse_app (PJDEC_INST g, UINT marker)
880 {
881     UINT len;
882     BYTE id1, id2, id3;
883 
884     len = read_uint (g);
885     if (len <= 5) {
886         /* unknown marker; discard it */
887         read_skip_forward (g, len-2);
888         return;
889     }
890 
891     id1 = read_byte (g);
892     id2 = read_byte (g);
893     id3 = read_byte (g);
894     read_skip_backward (g, 5);
895 
896     if (marker==MARKER_APP+1 && id1==0x47 && id2==0x33 && id3==0x46) {
897         /* G3 color fax APP1 marker */
898         parse_app_g3fax (g);
899     } else if (marker==MARKER_APP+0 && (id1=='J' || id1=='j')
900                && (id2=='F' || id2=='f') && (id3=='I' || id3=='i')) {
901         /* JFIF APP0 marker for generic JPEG files */
902         parse_app_jfif (g);
903     } else if (marker==MARKER_APP+1 && len==18) {
904         /* assume that APP1 marker is a short header */
905         parse_app_short_header (g);
906     } else {
907         /* unrecognized APP marker; discard it */
908         read_skip_forward (g, len);
909     }
910 }
911 
912 
913 
914 /*____________________________________________________________________________
915  |               |                                                            |
916  | mar_parse_sof | start of frame                                             |
917  |_______________|____________________________________________________________|
918  |                                                                            |
919  | Sets these fields in 'traits':  lNumRows, iPixelsPerRow, iBitsPerPixel,    |
920  |                                 iComponentsPerPixel.                       |
921  |                                                                            |
922  | Sets these variables:  num_comps (equal to iComponentsPerPixel),           |
923  |    horiz_samp_facs, vert_samp_facs, which_quant_tbl,                       |
924  |    max_horiz_samp_fac, max_vert_samp_fac                                   |
925  |____________________________________________________________________________|
926 */
mar_parse_sof(PJDEC_INST g,UINT marker)927 static void mar_parse_sof (PJDEC_INST g, UINT marker)
928 {
929     UINT len;
930     UINT uBitsPerComp;
931     UINT comp;
932     BYTE comp_id;
933     BYTE hv_samp;
934     BYTE q_table;
935     BYTE h, v;
936 
937     len                                          = read_uint (g);
938     uBitsPerComp                                 = read_byte (g);
939     g->rowCountOffset=g->rd_inbuf_next-g->rd_inbuf_beg;
940     g->traits.lNumRows                           = read_uint (g);
941     g->traits.iPixelsPerRow                      = read_uint (g);
942     g->traits.iComponentsPerPixel = g->num_comps = read_byte (g);
943     g->traits.iBitsPerPixel       = g->num_comps * uBitsPerComp;
944 
945     if (g->traits.lNumRows == 0)
946         g->traits.lNumRows = -1;   /* -1 means 'unknown' */
947 
948     if (len != (8u + 3u*g->num_comps) || g->num_comps==0)
949         longjmp (g->syntax_error, BAD_MARKER_DATA);
950 
951     /* Below, we also check for SOF1 because Chromafax erroneously outputs it */
952     if ((marker!=MARKER_SOF0 && marker!=MARKER_SOF0+1)
953         || uBitsPerComp!=8 || g->num_comps>4)
954         longjmp (g->syntax_error, NOT_IMPLEMENTED);
955 
956     g->max_horiz_samp_fac = 1;
957     g->max_vert_samp_fac  = 1;
958 
959     #if DUMP_JPEG
960         _ftprintf (stderr, _T("\nSOF marker:\n"));
961         _ftprintf (stderr, _T("   bits per sample = %d\n"), uBitsPerComp);
962         _ftprintf (stderr, _T("   number of rows  = %d\n"), g->traits.lNumRows);
963         _ftprintf (stderr, _T("   pixels per row  = %d\n"), g->traits.iPixelsPerRow);
964         _ftprintf (stderr, _T("   # components    = %d\n"), g->num_comps);
965     #endif
966 
967     for (comp=0; comp<g->num_comps; comp++) {
968         comp_id = read_byte (g);
969         hv_samp = read_byte (g);
970         q_table = read_byte (g);
971 
972         #if DUMP_JPEG
973             _ftprintf (stderr,
974                      _T("    %d: comp id = %d, hv samp fac = %02x, which q = %d\n"),
975                      comp, comp_id, hv_samp, q_table);
976         #endif
977 
978         g->horiz_samp_facs[comp] = h = hv_samp >> 4;
979         g->vert_samp_facs [comp] = v = hv_samp & 0x0fu;
980         g->which_quant_tbl[comp] = q_table;
981 
982         if (h > g->max_horiz_samp_fac) g->max_horiz_samp_fac = h;
983         if (v > g->max_vert_samp_fac ) g->max_vert_samp_fac  = v;
984     }
985 }
986 
987 
988 
989 /*____________________________________________________________________________
990  |               |                                                            |
991  | mar_parse_dqt | discrete quantization table                                |
992  |_______________|____________________________________________________________|
993  |                                                                            |
994  | Sets the following variables:  quant_tbls.                                 |
995  |____________________________________________________________________________|
996 */
mar_parse_dqt(PJDEC_INST g)997 static void mar_parse_dqt (PJDEC_INST g)
998 {
999     int   len, i;
1000     BYTE  pt;
1001     long *tbl_p;
1002 
1003     len = read_uint(g) - 2;
1004 
1005     while (len >= 65) {
1006         len -= 65;
1007         pt = read_byte (g);
1008         if ((pt & 0xfcu) != 0)
1009             longjmp (g->syntax_error, NOT_IMPLEMENTED);
1010         tbl_p = g->quant_tbls[pt & 3];
1011         DUMP (_T("\nDQT marker:  table=%d"), pt & 3, 0, 0);
1012         for (i=0; i<64; i++) {
1013             if ((i & 15) == 0) DUMP(_T("\n    "), 0,0,0);
1014             tbl_p[i] = read_byte (g);
1015             DUMP (_T("%2d "), tbl_p[i], 0, 0);
1016         }
1017         DUMP (_T("\n"), 0,0,0);
1018         wino_scale_table (tbl_p);
1019     }
1020 
1021     if (len != 0)
1022         longjmp (g->syntax_error, BAD_MARKER_DATA);
1023 }
1024 
1025 
1026 
1027 /*____________________________________________________________________________
1028  |               |                                                            |
1029  | mar_parse_dht | define Huffman tables                                      |
1030  |_______________|____________________________________________________________|
1031  |                                                                            |
1032  | Sets the following variables:  dc_tbls, ac_tbls.                           |
1033  |____________________________________________________________________________|
1034 */
mar_parse_dht(PJDEC_INST g)1035 static void mar_parse_dht (PJDEC_INST g)
1036 {
1037     BYTE num_codes[16];
1038     BYTE values[256];
1039 
1040     int  len, i, tot_codes;
1041     BYTE class_id;
1042 
1043     len = read_uint(g) - 2;
1044 
1045     while (len > 17) {
1046         class_id = read_byte (g);
1047 
1048         for (tot_codes=0, i=0; i<=15; i++) {
1049             num_codes[i] = read_byte (g);
1050             tot_codes += num_codes[i];
1051         }
1052 
1053         len -= 17;
1054         if (len < tot_codes)
1055             longjmp (g->syntax_error, BAD_MARKER_DATA);
1056 
1057         for (i=0; i<tot_codes; i++)
1058             values[i] = read_byte (g);
1059         len -= tot_codes;
1060 
1061         #if DUMP_JPEG
1062             _ftprintf (stderr, _T("\nDHT marker:  class=%d, id=%d\n   counts = "),
1063                      (BOOL  )(class_id>>4), class_id & 0x0f);
1064             for (i=0; i<16; i++)
1065                 _ftprintf (stderr, _T("%2d "), num_codes[i]);
1066             _ftprintf (stderr, _T("\n   values = "));
1067             for (i=0; i<tot_codes; i++)
1068                 _ftprintf (stderr, _T("%02x "), values[i]);
1069             _ftprintf (stderr, _T("\n"));
1070         #endif
1071 
1072         huff_define_table (g, (BOOL)(class_id>>4), class_id & 0x0f,
1073                            num_codes, values);
1074     }
1075 
1076     if (len != 0)
1077         longjmp (g->syntax_error, BAD_MARKER_DATA);
1078 }
1079 
1080 
1081 
1082 /*____________________________________________________________________________
1083  |               |                                                            |
1084  | mar_parse_dri | define restart interval                                    |
1085  |_______________|____________________________________________________________|
1086  |                                                                            |
1087  | Sets the following variable:  restart_interval.                            |
1088  |____________________________________________________________________________|
1089 */
mar_parse_dri(PJDEC_INST g)1090 static void mar_parse_dri (PJDEC_INST g)
1091 {
1092     UINT len;
1093 
1094     len = read_uint (g);
1095     if (len != 4)
1096         longjmp (g->syntax_error, BAD_MARKER_DATA);
1097 
1098     g->restart_interval = read_uint (g);
1099     DUMP (_T("\nDRI marker:  restart interval = %d\n"), g->restart_interval, 0,0);
1100 }
1101 
1102 
1103 
1104 /*____________________________________________________________________________
1105  |               |                                                            |
1106  | mar_parse_sos | start of scan                                              |
1107  |_______________|____________________________________________________________|
1108 */
mar_parse_sos(PJDEC_INST g)1109 static void mar_parse_sos (PJDEC_INST g)
1110 {
1111     UINT len;
1112     UINT comp;
1113     UINT cs;
1114     UINT dc_ac;
1115 
1116     len = read_uint (g);
1117     if (len != 6u+2u*g->num_comps)
1118         longjmp (g->syntax_error, BAD_MARKER_DATA);
1119 
1120     read_byte (g);   /* skip Ns value (number of components in scan) */
1121 
1122     DUMP (_T("\nSOS marker:\n"), 0,0,0);
1123 
1124     for (comp=0; comp<g->num_comps; comp++) {
1125         cs = read_byte (g);    /* skip Cs value (component selector) */
1126         dc_ac = read_byte (g);
1127         DUMP (_T("   %d: cs = %d, which dc_ac tbl = %02x\n"), comp, cs, dc_ac);
1128         g->which_dc_tbl[comp] = dc_ac >> 4;
1129         g->which_ac_tbl[comp] = dc_ac & 0x0fu;
1130     }
1131 
1132     read_byte (g);   /* skip Ss value (start selection) */
1133     read_byte (g);   /* skip Se value (end selection) */
1134     read_byte (g);   /* skip AhAl value (approximation bit positions) */
1135 }
1136 
1137 
1138 
1139 /*____________________________________________________________________________
1140  |               |                                                            |
1141  | mar_parse_dnl | Define Number of Lines                                     |
1142  |_______________|____________________________________________________________|
1143  |                                                                            |
1144  | Sets the following variable:  traits.lNumRows                              |
1145  |____________________________________________________________________________|
1146 */
mar_parse_dnl(PJDEC_INST g)1147 static void mar_parse_dnl (PJDEC_INST g)
1148 {
1149     UINT len, nRows;
1150 
1151     len   = read_uint (g);
1152     nRows = read_uint (g);
1153 
1154     if (len!=4u || nRows==0)
1155         longjmp (g->syntax_error, BAD_MARKER_DATA);
1156 
1157     DUMP (_T("\nDNL marker: %d\n"), nRows,0,0);
1158     g->traits.lNumRows = nRows;
1159 }
1160 
1161 
1162 
1163 /*____________________________________________________________________________
1164  |           |                                                                |
1165  | mar_parse | parses the marker, storing results in global variables         |
1166  |___________|________________________________________________________________|
1167 */
mar_parse(PJDEC_INST g,UINT marker)1168 static void mar_parse (PJDEC_INST g, UINT marker)
1169 {
1170     PRINT (_T("mar_parse: marker = %02xh\n"), marker, 0);
1171 
1172     switch (marker)
1173     {
1174         case MARKER_APP+0:
1175         case MARKER_APP+1:
1176         case MARKER_APP+2:
1177         case MARKER_APP+3:
1178         case MARKER_APP+4:
1179         case MARKER_APP+5:
1180         case MARKER_APP+6:
1181         case MARKER_APP+7:
1182         case MARKER_APP+8:
1183         case MARKER_APP+9:
1184         case MARKER_APP+10:
1185         case MARKER_APP+11:
1186         case MARKER_APP+12:
1187         case MARKER_APP+13:
1188         case MARKER_APP+14:
1189         case MARKER_APP+15:
1190             mar_parse_app (g, marker);
1191             break;
1192 
1193         case MARKER_COM:  /* comment marker */
1194         case MARKER_JPG+0:
1195         case MARKER_JPG+1:
1196         case MARKER_JPG+2:
1197         case MARKER_JPG+3:
1198         case MARKER_JPG+4:
1199         case MARKER_JPG+5:
1200         case MARKER_JPG+6:
1201         case MARKER_JPG+7:
1202         case MARKER_JPG+8:
1203         case MARKER_JPG+9:
1204         case MARKER_JPG+10:
1205         case MARKER_JPG+11:
1206         case MARKER_JPG+12:
1207         case MARKER_JPG+13:
1208             mar_flush (g, marker);
1209             break;
1210 
1211         case MARKER_SOF0:
1212         case MARKER_SOF1:
1213         case MARKER_SOF2:
1214         case MARKER_SOF3:
1215         case MARKER_SOF5:
1216         case MARKER_SOF6:
1217         case MARKER_SOF7:
1218         case MARKER_SOF8:
1219         case MARKER_SOF9:
1220         case MARKER_SOFA:
1221         case MARKER_SOFB:
1222         case MARKER_SOFD:
1223         case MARKER_SOFE:
1224         case MARKER_SOFF:
1225             mar_parse_sof (g, marker);
1226             break;
1227 
1228         case MARKER_RST0:
1229         case MARKER_RST1:
1230         case MARKER_RST2:
1231         case MARKER_RST3:
1232         case MARKER_RST4:
1233         case MARKER_RST5:
1234         case MARKER_RST6:
1235         case MARKER_RST7:
1236             DUMP (_T("\nRST marker.\n"), 0,0,0);
1237             break;
1238 
1239         case MARKER_DHT:  mar_parse_dht (g);   break;
1240         case MARKER_DQT:  mar_parse_dqt (g);   break;
1241         case MARKER_DRI:  mar_parse_dri (g);   break;
1242         case MARKER_SOS:  mar_parse_sos (g);   break;
1243         case MARKER_DNL:  mar_parse_dnl (g);   break;
1244 
1245         case MARKER_DAC:
1246         case MARKER_DHP:
1247         case MARKER_EXP:
1248             longjmp (g->syntax_error, NOT_IMPLEMENTED);
1249             break;
1250 
1251         /* The following markers have no data following them */
1252 
1253         case MARKER_SOI:
1254             DUMP (_T("\nSOI marker.\n"), 0,0,0);
1255             break;
1256 
1257         case MARKER_EOI:
1258             DUMP (_T("\nEOI marker.\n"), 0,0,0);
1259             break;
1260 
1261         default:
1262             longjmp (g->syntax_error, BAD_MARKER_DATA);
1263     }
1264 }
1265 
1266 
1267 
1268 /******************************************************************************
1269  ******************************************************************************
1270 
1271                                H U F F M A N
1272 
1273 
1274  Interface into this section:
1275 
1276      huff_init         - inits this section
1277      huff_free_tbl     - deallocates memory for one table
1278      huff_free_all     - deallocates memory for all tables
1279      huff_define_table - defines a new Huffman table
1280      DECODE_HUFF       - decodes and returns next Huffman code
1281 
1282  ******************************************************************************
1283  ******************************************************************************/
1284 
1285 
1286 
1287 /*____________________________________________________________________________
1288  |             |                                                              |
1289  | DECODE_HUFF | Decodes a Huffman code, returning corresponding value        |
1290  |_____________|______________________________________________________________|
1291 */
1292 #define DECODE_HUFF(                                                    \
1293     g,                                                                  \
1294     huff_tbl_p,                                                         \
1295     main_ix_len,                                                        \
1296     par_result,                                                         \
1297     hit_marker)                                                         \
1298 {                                                                       \
1299     UINT tbl_index, code, size;                                         \
1300     main_huff_elem_t *elem;                                             \
1301                                                                         \
1302     READ_BITS_LOAD (g, FALSE, main_ix_len, code, hit_marker)            \
1303     tbl_index = huff_tbl_p->index_p[code];                              \
1304     elem = &(huff_tbl_p->main_p[tbl_index]);                            \
1305     par_result = elem->value;                                           \
1306     size = elem->size;                                                  \
1307                                                                         \
1308     if (size == 0) {                                                    \
1309         par_result = parse_aux_code (g, huff_tbl_p->aux_p);             \
1310     } else {                                                            \
1311         DUMP (_T("    %2d-%04x-%3d(main)  "), size, code, par_result);      \
1312         READ_BITS_ADVANCE (g, size)                                     \
1313     }                                                                   \
1314 }
1315 
1316 
1317 
1318 /*____________________________________________________________________________
1319  |                |                                                           |
1320  | parse_aux_code | Code is not in short-width table; look in aux table       |
1321  |________________|___________________________________________________________|
1322  |                                                                            |
1323  | Returns the value associated with the code.                                |
1324  |____________________________________________________________________________|
1325 */
parse_aux_code(PJDEC_INST g,aux_huff_elem_t * aux_tbl_par_p)1326 static UINT parse_aux_code (
1327     PJDEC_INST       g,
1328     aux_huff_elem_t *aux_tbl_par_p)
1329 {
1330     UINT code, size, val;
1331     UINT diff;
1332     UINT excess;
1333     aux_huff_elem_t *lo_p, *hi_p, *mid_p;
1334 
1335     READ_BITS_LOAD (g, FALSE, 16, code, syntax_err)
1336 
1337 #if 0   /* we are no longer using ROM tables */
1338     if ((BYTE *)aux_tbl_par_p == dec_AC_aux_tbl)
1339     {
1340         /* We are using our default ROM table */
1341         val = dec_AC_aux_tbl [code & 0x7f];
1342         DUMP (_T("    %2d-%4x-%3d(aux-rom)  "), 16, code, val);
1343         if (val==0 || (code & 0xff80)!=0xff80) goto syntax_err;
1344         READ_BITS_ADVANCE (g,16)
1345     }
1346 #endif
1347 
1348     lo_p = aux_tbl_par_p;
1349     hi_p = lo_p + lo_p->size - 1;
1350     lo_p += 1;  /* 1st table-entry is a dummy containing above table-size */
1351 
1352     while ((diff=(hi_p-lo_p)) > 1) {
1353         mid_p = lo_p + (diff>>1);
1354         if (mid_p->code > code) hi_p = mid_p;
1355         else                    lo_p = mid_p;
1356     }
1357 
1358     size = lo_p->size;
1359     excess = 16u - size;
1360     if ((code>>excess) != (UINT)(lo_p->code>>excess)) {
1361         lo_p = hi_p;
1362         size = lo_p->size;
1363         excess = 16u - size;
1364         if ((code>>excess) != (UINT)(lo_p->code>>excess)) {
1365             PRINT (_T("aux code of %x not found\n"), code, 0);
1366             goto syntax_err;
1367         }
1368     }
1369 
1370     val = lo_p->value;
1371     READ_BITS_ADVANCE (g,size)
1372     DUMP (_T("    %2d-%4x-%3d(aux)  "), size, code, val);
1373 
1374     return val;
1375 
1376     syntax_err:
1377         PRINT (_T("parse_aux_code: syntax error\n"), 0, 0);
1378         longjmp (g->syntax_error, BAD_HUFF_CODE);
1379 }
1380 
1381 
1382 
1383 /*____________________________________________________________________________
1384  |           |                                                                |
1385  | huff_init | Inits this section                                             |
1386  |___________|________________________________________________________________|
1387 */
huff_init(PJDEC_INST g)1388 static void huff_init (PJDEC_INST g)
1389 {
1390     memset (g->dc_tbls, 0, sizeof(g->dc_tbls));
1391     memset (g->ac_tbls, 0, sizeof(g->ac_tbls));
1392 }
1393 
1394 
1395 
1396 /*____________________________________________________________________________
1397  |               |                                                            |
1398  | huff_free_tbl | Frees memory allocated for the given table                 |
1399  |_______________|____________________________________________________________|
1400 */
huff_free_tbl(PJDEC_INST g,huff_tbl_t * tbl_p)1401 static void huff_free_tbl (PJDEC_INST g, huff_tbl_t *tbl_p)
1402 {
1403     if (tbl_p->index_p != NULL)
1404         IP_MEM_FREE (tbl_p->index_p);
1405     if (tbl_p->main_p != NULL)
1406         IP_MEM_FREE (tbl_p->main_p);
1407     if (tbl_p->aux_p != NULL)
1408         IP_MEM_FREE (tbl_p->aux_p);
1409 
1410     tbl_p->index_p = NULL;
1411     tbl_p->main_p  = NULL;
1412     tbl_p->aux_p   = NULL;
1413 }
1414 
1415 
1416 
1417 /*____________________________________________________________________________
1418  |               |                                                            |
1419  | huff_free_all | Frees all memory allocated for Huffman tables              |
1420  |_______________|____________________________________________________________|
1421 */
huff_free_all(PJDEC_INST g)1422 static void huff_free_all (PJDEC_INST g)
1423 {
1424     int i;
1425 
1426     for (i=0; i<MAX_HUFF_TBLS; i++) {
1427         huff_free_tbl (g, &(g->dc_tbls[i]));
1428         huff_free_tbl (g, &(g->ac_tbls[i]));
1429     }
1430 }
1431 
1432 
1433 
1434 /*____________________________________________________________________________
1435  |            |                                                               |
1436  | calc_table | Defines a Huffman table                                       |
1437  |____________|_______________________________________________________________|
1438 */
calc_table(const BYTE counts[16],const BYTE huffval[],UINT main_ix_len,huff_tbl_t * huff_tbl_p)1439 static void calc_table (
1440     const BYTE   counts[16],    /* in:  # Huffman codes of each length 1-16 */
1441     const BYTE   huffval[],     /* in:  values for codes of above lengths */
1442     UINT         main_ix_len,   /* in:  # bits in main tbl index (0=use max) */
1443     huff_tbl_t  *huff_tbl_p)    /* out: the three tables */
1444 {
1445     BYTE              huffsize[257];
1446     WORD              huffcode[257];
1447     int               tot_codes;
1448     int               i;
1449     BYTE             *index_p;
1450     main_huff_elem_t *main_p;
1451     aux_huff_elem_t  *aux_p;
1452 
1453        /***************************************************/
1454       /* Compute a complete Huffman table.               */
1455      /* output:  huffval, huffsize, huffcode, tot_codes */
1456     /***************************************************/
1457 
1458     {
1459         int i, j, k, code, siz;
1460 
1461         /* Generate size array -- see JPEG document
1462          *
1463          * Note that list BITS in JPEG doc. has index from 1-16, but this list
1464          * is called 'counts', indexed 0-15.  This thus BITS[i] is replaced
1465          * by counts[i-1]
1466          */
1467         tot_codes = 0;
1468         for (i=1; i<=16; i++)
1469             for (j=1; j<=counts[i-1]; j++)
1470                 huffsize[tot_codes++] = i;
1471 
1472         huffsize[tot_codes] = 0;
1473 
1474         #if 0   /* we now only use RAM tables */
1475         if (memcmp(counts, rom_counts, 16) == 0  &&
1476             memcmp(huffval, rom_val, tot_codes) == 0) {
1477            PRINT (_T("calc_table: using ROM Huffman tables\n"), 0, 0);
1478            return FALSE;   /* tell caller to use ROM-tables instead */
1479         }
1480         #endif
1481 
1482         /* Generate code array -- see JPEG document
1483          *
1484          * The resulting table is sorted by increasing 'code', and also by
1485          * increasing 'size'.
1486          */
1487         k = 0;
1488         code = 0;
1489         siz = huffsize[0];
1490         while (TRUE) {
1491             do {
1492                 huffcode[k++] = code++;
1493             } while (huffsize[k]==siz && k<257);   /* Overflow Detection */
1494             if (huffsize[k] == 0)
1495                 break;   /* all done */
1496             do {              /* Shift next code to expand prefix */
1497                 code <<= 1;
1498                 siz += 1;
1499             } while (huffsize[k] != siz);
1500         }
1501     }
1502 
1503       /****************************************/
1504      /* Make the main table (output: main_p) */
1505     /****************************************/
1506 
1507     {   /* This "main" table is indexed by the output of the "table table",
1508          * which is indexed by 'main_ix_len' bits of input.
1509          * If the table-entry has a 'size' of 0, the aux table is examined.
1510          */
1511         int  i, nbytes;
1512         int  extra_bits;
1513         UINT first, final, code_plus_junk;
1514 
1515         if (main_ix_len == 0)
1516             main_ix_len = huffsize[tot_codes-1];
1517 
1518         nbytes = (tot_codes+1) * sizeof(main_huff_elem_t);
1519         IP_MEM_ALLOC (nbytes, main_p);
1520         memset (main_p, 0, nbytes);
1521 
1522         nbytes = 1lu << main_ix_len;
1523         IP_MEM_ALLOC (nbytes, index_p);
1524         memset (index_p, 0, nbytes);
1525 
1526         for (i=0; i<tot_codes && huffsize[i]<=main_ix_len; i++) {
1527             main_p[i+1].value = huffval [i];
1528             main_p[i+1].size  = huffsize[i] ;
1529 
1530             extra_bits = main_ix_len - huffsize[i];
1531             first = huffcode[i] << extra_bits;
1532             final = first + (1lu << extra_bits) - 1;
1533             for (code_plus_junk = first;
1534                  code_plus_junk <= final;
1535                  code_plus_junk++)
1536                 index_p[code_plus_junk] = i+1;
1537         }
1538     }
1539 
1540       /********************************************/
1541      /* Make the auxiliary table (output: aux_p) */
1542     /********************************************/
1543 
1544     {   /* This is used when an entry in the main table was 0, meaning that
1545          * the code is longer than 'main_ix_len'.  The aux table consists of
1546          * all [code, size, value] triples for sizes > main_ix_len.  A binary
1547          * search is used to locate the code.
1548          * The first table-entry is a dummy whose 'size' field is the number
1549          * of table-entries (including the dummy).
1550          */
1551         int first, n_entries;
1552         aux_huff_elem_t *p;
1553 
1554         /* locate first huffsize > main_ix_len */
1555         for (first=0; first<tot_codes && huffsize[first]<=main_ix_len; first++);
1556 
1557         if (first == tot_codes) {
1558             /* the main table captured everything; no aux table is needed */
1559             IP_MEM_ALLOC (1, aux_p);
1560         } else {
1561             n_entries = tot_codes - first + 1;  /* +1 because of dummy entry */
1562             IP_MEM_ALLOC (n_entries * sizeof(aux_huff_elem_t), aux_p);
1563 
1564             /* fill-in the dummy entry (contains # entries in table) */
1565             p = aux_p;
1566             p->size = (UINT) n_entries;
1567             p->code = p->value = 0;
1568             p += 1;
1569 
1570             for (i=first; i<tot_codes; i++) {
1571                 p->size  = huffsize[i];
1572                 p->code  = huffcode[i] << (16u - p->size);
1573                 p->value = huffval [i];
1574                 p += 1;
1575             }
1576         }
1577     }
1578 
1579     #if DUMP_JPEG
1580     {
1581         int i, n;
1582 
1583         _ftprintf (stderr, _T("\nOriginal size-code-val tuples:\n"));
1584         for (i=0; i<tot_codes; i++) {
1585             if ((i&7) == 0) _ftprintf(stderr, _T("   "));
1586             _ftprintf (stderr, _T("%2d-%04x-%02x "),
1587                 huffsize[i], huffcode[i], huffval[i]);
1588             if ((i&7)==7 || i==tot_codes-1) _ftprintf(stderr, _T("\n"));
1589         }
1590 
1591         _ftprintf(stderr, _T("\nIndex table: (%d entries)\n"), 1lu<<main_ix_len);
1592         for (i=0; i<(1lu<<main_ix_len); i++) {
1593             if ((i&7) == 0) _ftprintf(stderr, _T("   %3d: "), i);
1594             _ftprintf (stderr, _T("%3d, "), index_p[i]);
1595             if ((i&7) == 7) _ftprintf(stderr, _T("\n"));
1596         }
1597 
1598         _ftprintf(stderr, _T("\nMain table: (%d entries)\n"), tot_codes+1);
1599         for (i=0; i<tot_codes; i++) {
1600             if ((i&7) == 0) _ftprintf(stderr, _T("   %3d: "), i);
1601             _ftprintf (stderr, _T("%04x(%2d) "), main_p[i].value, main_p[i].size);
1602             if ((i&7)==7 || i==tot_codes-1) _ftprintf(stderr, _T("\n"));
1603         }
1604 
1605         if (huffsize[tot_codes-1] > main_ix_len) {
1606             n = aux_p[0].size;
1607             _ftprintf(stderr, _T("\nAux table: (%d entries of size-code-value)\n"),n);
1608             for (i=0; i<n; i++) {
1609                 if ((i&3) == 0) _ftprintf(stderr, _T("   %3d: "), i);
1610                 _ftprintf (stderr, _T("%2d-%4x-%3d  "),
1611                         aux_p[i].size, aux_p[i].code, aux_p[i].value);
1612                 if ((i&3)==3 || i==n-1) _ftprintf(stderr, _T("\n"));
1613             }
1614         }
1615     }
1616     #endif
1617 
1618     huff_tbl_p->index_p = index_p;
1619     huff_tbl_p->main_p  = main_p;
1620     huff_tbl_p->aux_p   = aux_p;
1621     return;
1622 
1623     fatal_error:
1624         assert (0);   /* todo: eliminate this assert */
1625 }
1626 
1627 
1628 
1629 /*____________________________________________________________________________
1630  |                   |                                                        |
1631  | huff_define_table | Defines the given Huffman table                        |
1632  |___________________|________________________________________________________|
1633  |                                                                            |
1634  | Sets the following variables:  dc_tbls, ac_tbls.                           |
1635  |____________________________________________________________________________|
1636 */
huff_define_table(PJDEC_INST g,BOOL ac,UINT id,const BYTE counts[16],const BYTE values[])1637 static void huff_define_table (
1638     PJDEC_INST g,
1639     BOOL       ac,         /* defining an AC table? (else DC) */
1640     UINT       id,         /* which table is being defined (0-3) */
1641     const BYTE counts[16], /* number of Huffman codes of each length 1-16 */
1642     const BYTE values[])   /* values associated with codes of above lengths */
1643 {
1644     huff_tbl_t *tbl_p;
1645 
1646     tbl_p = ac ? &(g->ac_tbls[id]) : &(g->dc_tbls[id]);
1647     huff_free_tbl (g,tbl_p);
1648 
1649     DUMP (_T("\nhuff_define_table: ac=%d, id=%d\n"), ac, id, 0);
1650     calc_table (counts, values,
1651                 ac ? AC_TBL_INDEX_LEN : DC_TBL_INDEX_LEN,
1652                 tbl_p);
1653 }
1654 
1655 
1656 
1657 /******************************************************************************
1658  ******************************************************************************
1659 
1660                               W I N O G R A D
1661 
1662 
1663  Interface into this section:
1664 
1665      QNORM_TO_INPUT   - adjusts precision of scaled DCT value for wino-input
1666      INPUT_PRECISION  - scales result of wino_inverse_dct back to pixels
1667      wino_scale_table - scale a quantization table into a Winograd table
1668      wino_inverse_dct - computes inverse DCT using Winograd's algorithm
1669 
1670  ******************************************************************************
1671  ******************************************************************************/
1672 
1673 
1674 
1675 #define SHIFT_TRUNC(mvalue,mshift)  ((mvalue) >> (mshift))
1676 
1677 #define QNORM_TO_INPUT(mval)  SHIFT_TRUNC(mval, QNORM_PRECISION-INPUT_PRECISION)
1678 
1679 #define QNORM_PRECISION 16  /* prec of q-table scaled by Wino norm constants */
1680 #define INPUT_PRECISION  5  /* prec of input to inverse-DCT */
1681 #define CONST_PRECISION  9  /* prec of b1-b5 below */
1682 
1683 #define b1 724L
1684 #define b2 1338L
1685 #define b3 724L
1686 #define b4 554L
1687 #define b5 392L
1688 
1689 #if 0
1690 #define CONST_PRECISION 15
1691 
1692 #define b1 46341L
1693 #define b2 85627L
1694 #define b3 46341L
1695 #define b4 35468L
1696 #define b5 25080L
1697 #endif
1698 
1699 
1700 
1701 /*____________________________________________________________________________
1702  |                  |                                                         |
1703  | wino_scale_table | Scales a quantization table into a Winograd table       |
1704  |__________________|_________________________________________________________|
1705  |                                                                            |
1706  | Multiplies all the components of the Quantization matrix by the fractional |
1707  | normalization constants as required by the Winograd Transform.  The        |
1708  | results are fixed-point with QNORM_PRECISION bits of fraction.             |
1709  |____________________________________________________________________________|
1710 */
1711 
1712 static const float inv_dct_norm[] = {
1713     0.125000f, 0.173380f, 0.173380f, 0.163320f,
1714     0.240485f, 0.163320f, 0.146984f, 0.226532f,
1715     0.226532f, 0.146984f, 0.125000f, 0.203873f,
1716     0.213388f, 0.203873f, 0.125000f, 0.098212f,
1717     0.173380f, 0.192044f, 0.192044f, 0.173380f,
1718     0.098212f, 0.067650f, 0.136224f, 0.163320f,
1719     0.172835f, 0.163320f, 0.136224f, 0.067650f,
1720     0.034566f, 0.093833f, 0.128320f, 0.146984f,
1721     0.146984f, 0.128320f, 0.093833f, 0.034566f,
1722     0.047944f, 0.088388f, 0.115485f, 0.125000f,
1723     0.115485f, 0.088388f, 0.047944f, 0.045162f,
1724     0.079547f, 0.098212f, 0.098212f, 0.079547f,
1725     0.045162f, 0.040645f, 0.067650f, 0.077165f,
1726     0.067650f, 0.040645f, 0.034566f, 0.053152f,
1727     0.053152f, 0.034566f, 0.027158f, 0.036612f,
1728     0.027158f, 0.018707f, 0.018707f, 0.009558f
1729 };
1730 
wino_scale_table(long * tbl_p)1731 void wino_scale_table (
1732     long   *tbl_p)
1733 {
1734     const float *fptr;
1735     int i;
1736 
1737     fptr = inv_dct_norm;
1738     for (i=0; i<64; i++) {
1739         *tbl_p = (long  ) ((*tbl_p) * (*fptr++) * (1l<<QNORM_PRECISION) + 0.5);
1740         tbl_p += 1;
1741     }
1742 }
1743 
1744 
1745 
1746 /******************************************************************************
1747  ******************************************************************************
1748 
1749                                D E C O D I N G
1750 
1751 
1752  Interface into this section:
1753 
1754      zero_prior_DC - sets the predicted DC values to zero
1755      decode_MCU    - decodes a single Minimum Coded Unit
1756 
1757  ******************************************************************************
1758  ******************************************************************************/
1759 
1760 
1761 
1762 static BYTE const zigzag_index_tbl[] = {
1763      0,  1,  8, 16,  9,  2,  3, 10,
1764     17, 24, 32, 25, 18, 11,  4,  5,
1765     12, 19, 26, 33, 40, 48, 41, 34,
1766     27, 20, 13,  6,  7, 14, 21, 28,
1767     35, 42, 49, 56, 57, 50, 43, 36,
1768     29, 22, 15, 23, 30, 37, 44, 51,
1769     58, 59, 52, 45, 38, 31, 39, 46,
1770     53, 60, 61, 54, 47, 55, 62, 63,
1771      0,  0,  0,  0,  0,  0,  0,  0,    /* extra 16 elements in case */
1772      0,  0,  0,  0,  0,  0,  0,  0     /* parse_block overruns */
1773 };
1774 
1775 
1776 
1777 /*____________________________________________________________________________
1778  |             |                                                              |
1779  | decode_init | inits this section                                           |
1780  |_____________|______________________________________________________________|
1781 */
decode_init(PJDEC_INST g)1782 static void decode_init (PJDEC_INST g)
1783 {
1784     BYTE const *zig_p;
1785     int       **block_pp;
1786 
1787     zig_p = zigzag_index_tbl;
1788     for (block_pp=g->block_zz; block_pp<g->block_zz+(64+16); block_pp++)
1789         *block_pp = &(g->block[*zig_p++]);
1790 }
1791 
1792 
1793 
1794 /*____________________________________________________________________________
1795  |               |                                                            |
1796  | zero_prior_DC | zeroes the predicted DC values                             |
1797  |_______________|____________________________________________________________|
1798 */
zero_prior_DC(PJDEC_INST g)1799 static void zero_prior_DC (PJDEC_INST g)
1800 {
1801     g->prior_dc[0] = g->prior_dc[1] = g->prior_dc[2] = g->prior_dc[3] = 0;
1802 }
1803 
1804 
1805 
1806 /*____________________________________________________________________________
1807  |             |                                                              |
1808  | parse_block | parses an 8x8 block; return data is ready for inverse DCT    |
1809  |_____________|______________________________________________________________|
1810  |                                                                            |
1811  | Return value:  TRUE  = we parsed a block,                                  |
1812  |                FALSE = hit a marker.                                       |
1813  | Output data is put in 'block' array.                                       |
1814  |____________________________________________________________________________|
1815 */
parse_block(PJDEC_INST g,int comp)1816 static BOOL parse_block (
1817     PJDEC_INST g,
1818     int        comp)    /* in: image component number */
1819 {
1820     /* FIX_TERM - changes a term (fetched from JPEG file) into an integer.
1821      * The term is in ones-complement, with the sign-bit (and higher bits)
1822      * zeroed.  So the leftmost bit within the given size is the opposite of
1823      * the desired sign bit.  If that bit is 1, the number is positive, and
1824      * needs no change.  If it's 0, we set the higher bits to 1s, and add 1
1825      * to convert from ones-complement to twos-complement.
1826      * Select the macro below which is fastest on your computer.
1827      */
1828 
1829    #if 1
1830     #define FIX_TERM(msize,mterm) {                     \
1831         if ((mterm & (1u<<((msize)-1))) == 0)           \
1832             mterm = (mterm | (-1 << (msize))) + 1;      \
1833     }
1834    #endif
1835 
1836    #if 0
1837     #define FIX_TERM(msize,mterm) {                     \
1838         int mask = -1 << msize;                         \
1839         if (((mterm<<1) & mask) == 0)                   \
1840             mterm += mask + 1;                          \
1841     }
1842    #endif
1843 
1844    #if 0
1845     #define FIX_TERM(msize,mterm)                    \
1846         mterm += ((mterm>>(msize-1)) - 1) & ~((1<<msize) - 2);
1847    #endif
1848 
1849     huff_tbl_t  *huff_p;
1850     int        **block_p;
1851     long        *dequant_p;
1852     UINT         siz, run, rl_byte;
1853     int          dc, ac;
1854 
1855     /* memset (block, 0, 64*sizeof(int)); */
1856     {
1857         int *block_p, *after_p;
1858 
1859         for (block_p=g->block, after_p=g->block+64; block_p<after_p; ) {
1860             *block_p++ = 0;
1861             *block_p++ = 0;
1862             *block_p++ = 0;
1863             *block_p++ = 0;
1864             *block_p++ = 0;
1865             *block_p++ = 0;
1866             *block_p++ = 0;
1867             *block_p++ = 0;
1868         }
1869     }
1870 
1871     dequant_p = g->quant_tbls[g->which_quant_tbl[comp]];
1872     block_p = g->block_zz;
1873 
1874       /**************************************/
1875      /* Decode and dequantize the DC value */
1876     /**************************************/
1877 
1878     DUMP (_T("\nStart of block for component %d:\n"), comp, 0, 0);
1879 
1880     huff_p = &(g->dc_tbls[g->which_dc_tbl[comp]]);
1881     DECODE_HUFF (g, huff_p, DC_TBL_INDEX_LEN, siz, hit_marker)
1882 
1883     if (siz == 0) {
1884         DUMP (_T("dc=0, size of dc=0\n"), 0,0,0);
1885         dc = 0;
1886     } else {
1887         READ_BITS_LOAD (g, TRUE, siz, dc, syntax_err)
1888         READ_BITS_ADVANCE (g, siz)
1889         DUMP (_T("dc=%x, size of dc=%d\n"), dc, siz, 0);
1890         FIX_TERM (siz, dc)
1891     }
1892 
1893     dc += g->prior_dc[comp];
1894     g->prior_dc[comp] = dc;
1895     *(*block_p++) = QNORM_TO_INPUT ((long  )*dequant_p++ * dc);
1896 
1897       /*************************************************/
1898      /* Decode, dezigzag and dequantize the AC values */
1899     /*************************************************/
1900 
1901     huff_p = &(g->ac_tbls[g->which_ac_tbl[comp]]);
1902 
1903     /* The two 'hit_marker's below should be 'syntax_error' instead. But
1904      * Chromafax and other software erroneously uses fill 0's instead
1905      * of fill 1's, so we parse a few of those 0's before hitting the
1906      * marker.
1907      */
1908 
1909     while (TRUE) {
1910         DECODE_HUFF (g, huff_p, AC_TBL_INDEX_LEN, rl_byte, hit_marker);
1911         run = rl_byte >> 4;
1912         siz = rl_byte & 0x0f;
1913         DUMP (_T("rlc: run=%d, size of ac=%d"), run, siz, 0);
1914 
1915         if (siz == 0) {
1916             if (run == 15) {
1917                 DUMP (_T(", run of 16\n"), 0,0,0);
1918                 block_p   += 16;
1919                 dequant_p += 16;
1920             } else if (run == 0) {
1921                 DUMP (_T(", EOB\n"), 0,0,0);
1922                 break;   /* hit EOB */
1923             } else
1924                 goto syntax_err;
1925         } else {
1926             block_p   += run;
1927             dequant_p += run;
1928             READ_BITS_LOAD (g, TRUE, siz, ac, hit_marker);
1929             READ_BITS_ADVANCE (g, siz);
1930             DUMP (_T(", ac=%x\n"), ac, siz, 0);
1931             FIX_TERM (siz, ac);
1932             *(*block_p++) = QNORM_TO_INPUT ((long  )*dequant_p++ * ac);
1933         }
1934 
1935         if (block_p >= g->block_zz+64) {
1936             if (block_p > g->block_zz+64) {
1937                 PRINT(_T("parse_block: over 63 AC terms\n"), 0,0);
1938                 goto syntax_err;
1939             }
1940             if (! g->fDenali)
1941                 break;   /* 63rd AC term was non-zero */
1942         }
1943     }
1944 
1945     return TRUE;
1946 
1947     syntax_err:
1948         PRINT(_T("parse_block: syntax error\n"), 0,0);
1949         longjmp (g->syntax_error, BAD_HUFF_CODE);
1950 
1951     hit_marker:
1952         return FALSE;
1953 
1954     #undef FIX_TERM
1955 }
1956 
1957 
1958 
1959 /*____________________________________________________________________________
1960  |                      |                                                     |
1961  | handleMarkerInStream | handles a marker in the data-stream                 |
1962  |______________________|_____________________________________________________|
1963  |                                                                            |
1964  | Parses EOI, DNL and RST; other markers cause an error (longjmp).           |
1965  | For an EOI, g->got_EOI is set to true.                                     |
1966  |____________________________________________________________________________|
1967 */
handleMarkerInStream(PJDEC_INST g)1968 static void handleMarkerInStream (PJDEC_INST g)
1969 {
1970     BYTE marker;
1971 
1972     marker = mar_get(g);
1973 
1974     if (marker == MARKER_EOI) {
1975         PRINT (_T("handleMarkerInStream: parsed EOI\n"), 0, 0);
1976         g->got_EOI = TRUE;
1977     } else if (marker == MARKER_DNL) {
1978         PRINT (_T("handleMarkerInStream: parsing DNL\n"), 0, 0);
1979         mar_parse_dnl (g);
1980     } else if (g->restart_interval > 0
1981         && g->restart_cur_mcu == g->restart_interval
1982         && (marker-MARKER_RST0) == g->restart_cur_marker)
1983     {
1984         /* it's a restart, and we expected it at this point in the data */
1985         PRINT (_T("handleMarkerInStream: parsed expected RST\n"), 0, 0);
1986         g->restart_cur_marker = (g->restart_cur_marker+1) & 7;
1987         g->restart_cur_mcu = 0;
1988         zero_prior_DC (g);
1989     } else {
1990         PRINT (_T("handleMarkerInStream: illegal marker=0x%2.2X\n"), marker, 0);
1991         longjmp (g->syntax_error, BAD_MARKER_DATA);
1992     }
1993 }
1994 
1995 
1996 
1997 /*____________________________________________________________________________
1998  |                    |                                                       |
1999  | LevelShiftAndRound | Level-shifts, rounds, and outputs pixels in 0..255    |
2000  |____________________|_______________________________________________________|
2001 */
LevelShiftAndRound(int * inBlock_p,BYTE * outBlock_p)2002 static void LevelShiftAndRound (int *inBlock_p, BYTE *outBlock_p)
2003 {
2004     BYTE *outAfter;
2005     int   pixel;
2006 
2007     for (outAfter = outBlock_p + 64;
2008          outBlock_p < outAfter;
2009          outBlock_p++, inBlock_p++)
2010     {
2011         pixel = (*inBlock_p +
2012                  ((1<<(INPUT_PRECISION-1)) + (128<<INPUT_PRECISION)))
2013                 >> INPUT_PRECISION;
2014         if (pixel>>8 != 0)
2015             pixel = pixel>0 ? 255 : 0;  /* clamp to 0 or 255 */
2016         *outBlock_p = (BYTE) pixel;
2017     }
2018 }
2019 
2020 
2021 
2022 /*____________________________________________________________________________
2023  |            |                                                               |
2024  | decode_MCU | Parses a Minimum Coded Unit, and loads pixels into out_rows_ap|
2025  |____________|_______________________________________________________________|
2026  |                                                                            |
2027  | The pixels are loaded starting at mcus_done (not incremented).             |
2028  | This routine handles the restart interval logic, and markers.              |
2029  |                                                                            |
2030  | Returns TRUE if an MCU was parsed, else FALSE.                             |
2031  |____________________________________________________________________________|
2032 */
decode_MCU(PJDEC_INST g)2033 static BOOL decode_MCU (PJDEC_INST g)
2034 {
2035     BYTE   baPixels[256];
2036     BYTE  *pPixel;
2037     int    comp;
2038     int    h_block, v_block;
2039     int    ul_row, ul_col;
2040     int    row;
2041     BYTE **row_pp;
2042     BYTE  *row_p;
2043 
2044     for (comp=0; comp<g->num_comps; comp++) {
2045         for (v_block=0; v_block<g->vert_samp_facs[comp]; v_block++) {
2046             for (h_block=0; h_block<g->horiz_samp_facs[comp]; h_block++) {
2047 
2048                 /***** parse and inverse-dct an 8x8 block *****/
2049 
2050                 while (! parse_block(g,comp)) {
2051                     /* we hit a marker */
2052                     #if 0
2053                         /* The error-check below is commented-out to make us
2054                          * more forgiving of unexpected in-data markers, which
2055                          * we saw the Genoa color-fax test suite output at the
2056                          * end of the file.
2057                          */
2058                         if (comp>0 || v_block>0 || h_block>0)
2059                             longjmp (g->syntax_error, UNEXPECTED_MARKER);
2060                     #endif
2061                     handleMarkerInStream(g);
2062                     if (g->got_EOI)
2063                         return FALSE;  /* we're out of data; cannot proceed */
2064                 }
2065 
2066                 dct_inverse (g->block);
2067 
2068                 /***** compute output pixels *****/
2069 
2070                 LevelShiftAndRound (g->block, baPixels);
2071 
2072                 /***** copy block into out_rows_ap *****/
2073 
2074                 ul_row = v_block*8;
2075                 ul_col = (g->mcus_done*g->horiz_samp_facs[comp] + h_block) * 8;
2076                 row_pp = &(g->out_rows_ap[comp][ul_row]);
2077                 pPixel = baPixels;
2078 
2079                 for (row=0; row<8; row++) {
2080                     row_p = *row_pp++ + ul_col;
2081                     /* copy the 8 pixel row quickly, using two dword transfers */
2082                     *(DWORD*) row_p    = *(DWORD*) pPixel;
2083                     *(DWORD*)(row_p+4) = *(DWORD*)(pPixel+4);
2084                     pPixel += 8;
2085                 }
2086             }
2087         }
2088     }
2089 
2090     if (g->restart_interval>0 && g->restart_cur_mcu==g->restart_interval)
2091         longjmp (g->syntax_error, NO_RESTART_MARKER);
2092     g->restart_cur_mcu += 1;
2093 
2094     return TRUE;
2095 }
2096 
2097 
2098 
2099 /*____________________________________________________________________________
2100  |               |                                                            |
2101  | copy_out_rows | copies a row (or rows) from out_rows_ap to output buffer   |
2102  |_______________|____________________________________________________________|
2103  |                                                                            |
2104  | If output_subsampled is true, we output row data in the same odd order     |
2105  | which the ASIC outputs it.                                                 |
2106  |                                                                            |
2107  | View a period as being a group of max_horiz_samp_fac by max_vert_samp_fac  |
2108  | samples.  (BTW, an MCU contains exactly 8x8 periods.)  Divide the entire   |
2109  | image into a grid of such periods.  The ASIC outputs the periods left to   |
2110  | right, top to bottom.  It outputs all the data in each period, before      |
2111  | moving to the next period.  Within a period, it outputs the components in  |
2112  | succession; within a component, it outputs the samples left to right, top  |
2113  | to bottom.                                                                 |
2114  |                                                                            |
2115  | For example:                                                               |
2116  |     Three components = Y U V                                               |
2117  |     Horiz sample factors = 2 1 1                                           |
2118  |     Vert  sample factors = 2 1 1                                           |
2119  |     A period is 2x2 samples (i.e., a 2x2 square).                          |
2120  |     Each period contains these samples:  YYYYUV.                           |
2121  |     Bytes output:  YYYYUV YYYYUV YYYYUV ....                               |
2122  |                                                                            |
2123  | In this routine,                                                           |
2124  |                                                                            |
2125  |     vert_period  = index of which period we're outputting vertically within|
2126  |                    an MCU (0-7).                                           |
2127  |                                                                            |
2128  |     horiz_period = index of which period we're outputting horizontally;    |
2129  |                    since an MCU has 8 periods, this is 0 .. 8*mcus_per_row.|
2130  |____________________________________________________________________________|
2131 */
copy_out_rows(PJDEC_INST g,UINT row_index,BYTE * outbuf_p,UINT * n_rows_p,UINT * n_bytes_p)2132 static void copy_out_rows (
2133     PJDEC_INST  g,
2134     UINT        row_index,    /* in:  index of next row to send within MCU */
2135     BYTE       *outbuf_p,     /* out: copied-out row data */
2136     UINT       *n_rows_p,     /* out: # of rows copied out */
2137     UINT       *n_bytes_p)    /* out: # of bytes output */
2138 {
2139     BYTE *out_p;
2140     UINT  comp;
2141     UINT  vert_period, vert_mod;
2142     UINT  row, col;
2143     BYTE *row_p;
2144 
2145     vert_period = row_index / g->max_vert_samp_fac;
2146     vert_mod    = row_index % g->max_vert_samp_fac;
2147 
2148     if (! g->output_subsampled) {
2149 
2150           /*******************************************/
2151          /* Perform duplication to undo subsampling */
2152         /*******************************************/
2153 
2154         UINT samp_fac;
2155         UINT horiz_mod;
2156 
2157         for (comp=0; comp<g->num_comps; comp++) {
2158             samp_fac = g->vert_samp_facs[comp];
2159             out_p = outbuf_p + comp;
2160             row = vert_period*samp_fac +
2161                     (vert_mod<samp_fac ? vert_mod : samp_fac-1);
2162             row_p = g->out_rows_ap[comp][row];
2163 
2164             horiz_mod = 0;
2165             samp_fac = g->horiz_samp_facs[comp];
2166 
2167             if (samp_fac == g->max_horiz_samp_fac) {
2168 
2169                 /***** fast case: copying all pixels, with no duplication *****/
2170 
2171                 if (g->num_comps == 1) {
2172                     memcpy (out_p, row_p, g->traits.iPixelsPerRow);
2173                 } else {
2174                     for (col=0; col<(UINT)g->traits.iPixelsPerRow; col++) {
2175                         *out_p = *row_p++;
2176                         out_p += g->num_comps;
2177                     }
2178                 }
2179 
2180             } else if (samp_fac==1 && g->max_horiz_samp_fac==2) {
2181 
2182                 /***** fast case: duplicating every other pixel *****/
2183 
2184                 BYTE  prev_pix;
2185                 for (col=0; col<(UINT)g->traits.iPixelsPerRow; col+=2) {
2186                     *out_p = prev_pix = *row_p++;
2187                     out_p += g->num_comps;
2188                     *out_p = prev_pix;
2189                     out_p += g->num_comps;
2190                 }
2191 
2192             } else {
2193 
2194                 /***** slow general case *****/
2195 
2196                 for (col=0; col<(UINT)g->traits.iPixelsPerRow; col++) {
2197                     *out_p = horiz_mod<samp_fac ? *row_p++ : row_p[-1];
2198                     out_p += g->num_comps;
2199                     horiz_mod += 1;
2200                     if (horiz_mod == g->max_horiz_samp_fac) horiz_mod = 0;
2201                 }
2202             }
2203         }
2204 
2205         *n_rows_p = 1;
2206         *n_bytes_p = g->num_comps * g->traits.iPixelsPerRow;
2207 
2208     } else {
2209 
2210           /**********************************************/
2211          /* Output subsampled data in ASIC's odd order */
2212         /**********************************************/
2213 
2214         UINT horiz_period, periods_per_row;
2215         UINT ul_row, ul_col;
2216         BYTE *row_y1_p, *row_y2_p, *row_cb_p, *row_cr_p;
2217 
2218         out_p = outbuf_p;
2219         periods_per_row = g->mcus_per_row * 8;
2220 
2221         if (g->num_comps==1 && g->max_horiz_samp_fac==1 && g->max_vert_samp_fac==1) {
2222 
2223             /***** fast case: one component; just copy the row *****/
2224 
2225             memcpy (out_p, g->out_rows_ap[0][row_index], g->traits.iPixelsPerRow);
2226             out_p += g->traits.iPixelsPerRow;
2227 
2228         } else if (g->num_comps==3 &&
2229                    (g->horiz_samp_facs[0]==1 &&
2230                     g->horiz_samp_facs[1]==1 &&
2231                     g->horiz_samp_facs[2]==1) &&
2232                    (g->vert_samp_facs[0]==1 &&
2233                     g->vert_samp_facs[1]==1 &&
2234                     g->vert_samp_facs[2]==1)) {
2235 
2236             /***** fast case: color with no subsampling *****/
2237 
2238             row_y1_p = g->out_rows_ap[0][vert_period];
2239             row_cb_p = g->out_rows_ap[1][vert_period];
2240             row_cr_p = g->out_rows_ap[2][vert_period];
2241             for (col=0; col<(UINT)g->traits.iPixelsPerRow; col++) {
2242                 *out_p++ = *row_y1_p++;
2243                 *out_p++ = *row_cb_p++;
2244                 *out_p++ = *row_cr_p++;
2245             }
2246 
2247         } else if (g->num_comps==3 &&
2248                    (g->horiz_samp_facs[0]==2 &&
2249                     g->horiz_samp_facs[1]==1 &&
2250                     g->horiz_samp_facs[2]==1) &&
2251                    (g->vert_samp_facs[0]==2 &&
2252                     g->vert_samp_facs[1]==1 &&
2253                     g->vert_samp_facs[2]==1)) {
2254 
2255             /***** fast case: 4-1-1 color subsampling *****/
2256 
2257             row_y1_p = g->out_rows_ap[0][2*vert_period];
2258             row_y2_p = g->out_rows_ap[0][2*vert_period+1];
2259             row_cb_p = g->out_rows_ap[1][vert_period];
2260             row_cr_p = g->out_rows_ap[2][vert_period];
2261             for (horiz_period=0; horiz_period<periods_per_row; horiz_period++) {
2262                 *out_p++ = *row_y1_p++;
2263                 *out_p++ = *row_y1_p++;
2264                 *out_p++ = *row_y2_p++;
2265                 *out_p++ = *row_y2_p++;
2266                 *out_p++ = *row_cb_p++;
2267                 *out_p++ = *row_cr_p++;
2268             }
2269 
2270         } else {
2271 
2272             /***** slow general case *****/
2273 
2274             for (horiz_period=0; horiz_period<periods_per_row; horiz_period++) {
2275                 for (comp=0; comp<g->num_comps; comp++) {
2276                     ul_row =  vert_period *  g->vert_samp_facs[comp];
2277                     ul_col = horiz_period * g->horiz_samp_facs[comp];
2278 
2279                     for (row=ul_row; row<ul_row+ g->vert_samp_facs[comp]; row++)
2280                     for (col=ul_col; col<ul_col+g->horiz_samp_facs[comp]; col++) {
2281                         *out_p++ = g->out_rows_ap[comp][row][col];
2282                     }
2283                 }
2284             }
2285         }
2286 
2287         *n_rows_p = g->max_vert_samp_fac;
2288         *n_bytes_p = out_p - outbuf_p;
2289     }
2290 }
2291 
2292 
2293 
2294 
2295 /******************************************************************************
2296  ******************************************************************************
2297 
2298                       E X P O R T E D   R O U T I N E S
2299 
2300  ******************************************************************************
2301  ******************************************************************************/
2302 
2303 
2304 
2305 /*****************************************************************************\
2306  *
2307  * jpgDecode_openXform - Creates a new instance of the transformer
2308  *
2309  *****************************************************************************
2310  *
2311  * This returns a handle for the new instance to be passed into
2312  * all subsequent calls.
2313  *
2314  * Return value: IP_DONE=success; IP_FATAL_ERROR=misc error.
2315  *
2316 \*****************************************************************************/
2317 
jpgDecode_openXform(IP_XFORM_HANDLE * pXform)2318 static WORD jpgDecode_openXform (
2319     IP_XFORM_HANDLE *pXform)   /* out: returned handle */
2320 {
2321     PJDEC_INST g;
2322 
2323     INSURE (pXform != NULL);
2324     IP_MEM_ALLOC (sizeof(JDEC_INST), g);
2325     *pXform = g;
2326     memset (g, 0, sizeof(JDEC_INST));
2327     g->dwValidChk = CHECK_VALUE;
2328     decode_init (g);
2329     return IP_DONE;
2330 
2331     fatal_error:
2332     return IP_FATAL_ERROR;
2333 }
2334 
2335 
2336 
2337 /*****************************************************************************\
2338  *
2339  * jpgDecode_setDefaultInputTraits - Specifies default input image traits
2340  *
2341  *****************************************************************************
2342  *
2343  * The header of the file-type handled by the transform probably does
2344  * not include *all* the image traits we'd like to know.  Those not
2345  * specified in the file-header are filled in from info provided by
2346  * this routine.
2347  *
2348  * Return value: IP_DONE=success; IP_FATAL_ERROR=misc error.
2349  *
2350 \*****************************************************************************/
2351 
jpgDecode_setDefaultInputTraits(IP_XFORM_HANDLE hXform,PIP_IMAGE_TRAITS pTraits)2352 static WORD jpgDecode_setDefaultInputTraits (
2353     IP_XFORM_HANDLE  hXform,     /* in: handle for xform */
2354     PIP_IMAGE_TRAITS pTraits)    /* in: default image traits */
2355 {
2356     PJDEC_INST g;
2357 
2358     HANDLE_TO_PTR (hXform, g);
2359     g->traits = *pTraits;   /* a structure copy */
2360     return IP_DONE;
2361 
2362     fatal_error:
2363     return IP_FATAL_ERROR;
2364 }
2365 
2366 
2367 
2368 /*****************************************************************************\
2369  *
2370  * jpgDecode_setXformSpec - Provides xform-specific information
2371  *
2372 \*****************************************************************************/
2373 
jpgDecode_setXformSpec(IP_XFORM_HANDLE hXform,DWORD_OR_PVOID aXformInfo[])2374 static WORD jpgDecode_setXformSpec (
2375     IP_XFORM_HANDLE  hXform,         /* in: handle for xform */
2376     DWORD_OR_PVOID   aXformInfo[])   /* in: xform information */
2377 {
2378     PJDEC_INST g;
2379 
2380     HANDLE_TO_PTR (hXform, g);
2381     g->output_subsampled = aXformInfo[IP_JPG_DECODE_OUTPUT_SUBSAMPLED].dword;
2382     g->fDenali           = aXformInfo[IP_JPG_DECODE_FROM_DENALI].dword;
2383     return IP_DONE;
2384 
2385     fatal_error:
2386     return IP_FATAL_ERROR;
2387 }
2388 
2389 
2390 
2391 /*****************************************************************************\
2392  *
2393  * jpgDecode_getHeaderBufSize- Returns size of input buf needed to hold header
2394  *
2395 \*****************************************************************************/
2396 
jpgDecode_getHeaderBufSize(IP_XFORM_HANDLE hXform,DWORD * pdwInBufLen)2397 static WORD jpgDecode_getHeaderBufSize (
2398     IP_XFORM_HANDLE  hXform,         /* in:  handle for xform */
2399     DWORD           *pdwInBufLen)    /* out: buf size for parsing header */
2400 {
2401     PJDEC_INST g;
2402 
2403     HANDLE_TO_PTR (hXform, g);
2404     *pdwInBufLen = MAX_HEADER_SIZE;
2405     return IP_DONE;
2406 
2407     fatal_error:
2408     return IP_FATAL_ERROR;
2409 }
2410 
2411 
2412 
2413 /*****************************************************************************\
2414  *
2415  * jpgDecode_getActualTraits - Parses header, and returns input & output traits
2416  *
2417 \*****************************************************************************/
2418 
jpgDecode_getActualTraits(IP_XFORM_HANDLE hXform,DWORD dwInputAvail,PBYTE pbInputBuf,PDWORD pdwInputUsed,PDWORD pdwInputNextPos,PIP_IMAGE_TRAITS pInTraits,PIP_IMAGE_TRAITS pOutTraits)2419 static WORD jpgDecode_getActualTraits (
2420     IP_XFORM_HANDLE  hXform,         /* in:  handle for xform */
2421     DWORD            dwInputAvail,   /* in:  # avail bytes in input buf */
2422     PBYTE            pbInputBuf,     /* in:  ptr to input buffer */
2423     PDWORD           pdwInputUsed,   /* out: # bytes used from input buf */
2424     PDWORD           pdwInputNextPos,/* out: file-pos to read from next */
2425     PIP_IMAGE_TRAITS pInTraits,      /* out: input image traits */
2426     PIP_IMAGE_TRAITS pOutTraits)     /* out: output image traits */
2427 {
2428     PJDEC_INST g;
2429     UINT  comp;
2430     UINT  marker;
2431     UINT  row_len, n_rows;
2432     UINT  row;
2433     UINT  err;
2434     BYTE *p;
2435 
2436       /**************/
2437      /* Misc. Init */
2438     /**************/
2439 
2440     HANDLE_TO_PTR (hXform, g);
2441 
2442     g->rows_done = 0;
2443     g->mcus_done = 0;
2444     g->sending_rows = FALSE;
2445     g->got_EOI = FALSE;
2446     g->got_short_header = FALSE;
2447     read_init (g);
2448     huff_init (g);
2449     zero_prior_DC (g);
2450     g->restart_cur_mcu    = 0;
2451     g->restart_cur_marker = 0;
2452     g->dwOutNextPos = 0;
2453 
2454       /********************/
2455      /* Parse the header */
2456     /********************/
2457 
2458     if ((err=setjmp(g->syntax_error)) != 0) {
2459         PRINT (_T("jpeg_decode_parse_header: syntax error = %d\n"), err, 0);
2460         return IP_FATAL_ERROR | IP_INPUT_ERROR;
2461     }
2462 
2463     read_buf_open (g, pbInputBuf);
2464 
2465     if (mar_get(g) != MARKER_SOI)
2466         return IP_FATAL_ERROR | IP_INPUT_ERROR;
2467 
2468     do {
2469         marker = mar_get (g);
2470         mar_parse (g, marker);
2471         if (marker == MARKER_EOI)
2472             return IP_FATAL_ERROR | IP_INPUT_ERROR;
2473     } while (!(marker==MARKER_SOS || g->got_short_header));
2474 
2475     *pdwInputNextPos = g->dwInNextPos = *pdwInputUsed = read_buf_close (g);
2476 
2477     /* todo: check that all markers arrived */
2478 
2479     PRINT (_T("jpeg_decode_parse_header: pixels/row=%d, num_rows=%d\n"),
2480            g->traits.iPixelsPerRow, g->traits.lNumRows);
2481 
2482     g->cols_per_mcu = g->max_horiz_samp_fac * 8;
2483     g->rows_per_mcu =  g->max_vert_samp_fac * 8;
2484     g->mcus_per_row = (g->traits.iPixelsPerRow + g->cols_per_mcu - 1) / g->cols_per_mcu;
2485 
2486       /*******************************************/
2487      /* Allocate the row-buffers in out_rows_ap */
2488     /*******************************************/
2489 
2490     memset (g->out_rows_ap, 0, sizeof(g->out_rows_ap));
2491 
2492     for (comp=0; comp<g->num_comps; comp++) {
2493         row_len =  g->horiz_samp_facs[comp] * g->mcus_per_row * 8;
2494         n_rows = g->vert_samp_facs[comp] * 8;
2495 
2496         for (row=0; row<n_rows; row++) {
2497             IP_MEM_ALLOC (row_len, p);
2498             g->out_rows_ap[comp][row] = p;
2499         }
2500     }
2501 
2502       /***************/
2503      /* Return info */
2504     /***************/
2505 
2506     *pInTraits  = g->traits;
2507     *pOutTraits = g->traits;
2508 
2509     return IP_DONE | IP_READY_FOR_DATA;
2510 
2511     fatal_error:
2512         return IP_FATAL_ERROR;
2513 }
2514 
2515 
2516 
2517 /****************************************************************************\
2518  *
2519  * jpgDecode_getActualBufSizes - Returns buf sizes needed for remainder of job
2520  *
2521 \****************************************************************************/
2522 
jpgDecode_getActualBufSizes(IP_XFORM_HANDLE hXform,PDWORD pdwMinInBufLen,PDWORD pdwMinOutBufLen)2523 static WORD jpgDecode_getActualBufSizes (
2524     IP_XFORM_HANDLE hXform,           /* in:  handle for xform */
2525     PDWORD          pdwMinInBufLen,   /* out: min input buf size */
2526     PDWORD          pdwMinOutBufLen)  /* out: min output buf size */
2527 {
2528     PJDEC_INST g;
2529 
2530     HANDLE_TO_PTR (hXform, g);
2531     *pdwMinInBufLen  = INBUF_NUM_MCUS * MAX_MCU_SIZE;
2532     *pdwMinOutBufLen = g->num_comps * g->traits.iPixelsPerRow;
2533 
2534     return IP_DONE;
2535 
2536     fatal_error:
2537     return IP_FATAL_ERROR;
2538 }
2539 
2540 
2541 
2542 /*****************************************************************************\
2543  *
2544  * jpgDecode_convert - the work-horse routine
2545  *
2546 \*****************************************************************************/
2547 
jpgDecode_convert(IP_XFORM_HANDLE hXform,DWORD dwInputAvail,PBYTE pbInputBuf,PDWORD pdwInputUsed,PDWORD pdwInputNextPos,DWORD dwOutputAvail,PBYTE pbOutputBuf,PDWORD pdwOutputUsed,PDWORD pdwOutputThisPos)2548 static WORD jpgDecode_convert (
2549     IP_XFORM_HANDLE hXform,
2550     DWORD           dwInputAvail,     /* in:  # avail bytes in in-buf */
2551     PBYTE           pbInputBuf,       /* in:  ptr to in-buffer */
2552     PDWORD          pdwInputUsed,     /* out: # bytes used from in-buf */
2553     PDWORD          pdwInputNextPos,  /* out: file-pos to read from next */
2554     DWORD           dwOutputAvail,    /* in:  # avail bytes in out-buf */
2555     PBYTE           pbOutputBuf,      /* in:  ptr to out-buffer */
2556     PDWORD          pdwOutputUsed,    /* out: # bytes written in out-buf */
2557     PDWORD          pdwOutputThisPos) /* out: file-pos to write the data */
2558 {
2559     PJDEC_INST g;
2560     /* The "static" keyword for ret_val and bDecoded is to prevent the
2561      * "variable `' might be clobbered by `longjmp' or `vfork'" warning. */
2562     static unsigned   ret_val;
2563     UINT       comp, row, row_len, n_rows, n_bytes, trash;
2564     int        iErrorCode;
2565     static BOOL       bDecoded;
2566     const BYTE ycc_white[4] = { 255, 128, 128, 255 };
2567 
2568     HANDLE_TO_PTR (hXform, g);
2569 
2570     *pdwInputUsed     = 0;
2571     *pdwOutputThisPos = g->dwOutNextPos;
2572     *pdwOutputUsed    = 0;
2573     ret_val           = IP_READY_FOR_DATA;
2574 
2575     if (setjmp(g->syntax_error) != 0) {
2576         PRINT (_T("got a syntax error\n"), 0, 0);
2577         *pdwInputNextPos = g->dwInNextPos;
2578         return IP_FATAL_ERROR | IP_INPUT_ERROR;
2579     }
2580 
2581       /**********************/
2582      /* Parsing input data */
2583     /**********************/
2584 
2585     if (! g->sending_rows) {
2586         if (pbInputBuf == NULL) {
2587 
2588             /* We are being told to flush, so we should have consumed the EOI,
2589              * and have discarded any bytes following it.  */
2590             if (! g->got_EOI) {
2591                 /* Unexpected end of data: we did not get an EOI */
2592                 ret_val |= IP_INPUT_ERROR;
2593             }
2594             ret_val |= IP_DONE;
2595 
2596         } else if (g->got_EOI) {
2597 
2598             /* Discard bytes after the EOI. We should report an error here, but
2599              * the ASIC+firmware of Denali/Kodiak can send stuff after the EOI. */
2600             *pdwInputUsed = dwInputAvail;
2601 
2602         } else {
2603 
2604             if (g->mcus_done == 0) {
2605                 /* init all row-buffers to white */
2606                 PRINT (_T("initing all row-buffers to white\n"), 0, 0);
2607                 for (comp=0; comp<g->num_comps; comp++) {
2608                     row_len = g->horiz_samp_facs[comp] * g->mcus_per_row * 8;
2609                     n_rows = g->vert_samp_facs[comp] * 8;
2610 
2611                     for (row=0; row<n_rows; row++)
2612                         memset (g->out_rows_ap[comp][row], ycc_white[comp], row_len);
2613                 }
2614             }
2615 
2616             do {
2617                 bDecoded = FALSE;
2618                 read_buf_open (g, pbInputBuf + *pdwInputUsed);
2619                     memcpy(&(g->old_syntax_error),  &(g->syntax_error), sizeof(jmp_buf));
2620                     iErrorCode = setjmp(g->syntax_error);
2621                     if (iErrorCode == 0) {
2622                         bDecoded = decode_MCU(g);
2623 
2624                         /* Check for (and handle) a marker (DNL, RST, EOI).
2625                          * We need to handle DNL here so the sending_rows state below
2626                          * won't output the pad rows on the bottom of the image
2627                          */
2628                         if (! g->got_EOI) {
2629                             READ_BITS_LOAD (g, FALSE, 8, trash, at_a_marker);
2630                             goto no_marker;
2631                             at_a_marker:
2632                                 handleMarkerInStream(g);
2633                             no_marker:;
2634                         }
2635                     }
2636                     memcpy(&(g->syntax_error),  &(g->old_syntax_error), sizeof(jmp_buf));
2637                 n_bytes = read_buf_close (g);
2638 
2639                 *pdwInputUsed  += n_bytes;
2640                 g->dwInNextPos += n_bytes;
2641 
2642                 if (*pdwInputUsed > dwInputAvail) {
2643                     /* Parser read past end of input buffer */
2644                     *pdwInputUsed = dwInputAvail;
2645                     g->dwInNextPos += dwInputAvail - n_bytes;
2646                     /* We will not make this a fatal error because that would
2647                      * immediately shut down the remaining xforms in the pipeline.
2648                      * Instead, we assume that the input data was truncated, and
2649                      * let the pipeline finish up normally so that it'll give a
2650                      * valid output file.
2651                      */
2652                     ret_val |= IP_INPUT_ERROR;
2653                 } else if (iErrorCode != 0) {
2654                     /* An error within the data: Make it fatal */
2655                     longjmp (g->syntax_error, iErrorCode);
2656                 } else if (g->got_EOI) {
2657                     ret_val |= IP_NEW_OUTPUT_PAGE;
2658                     /* Note: we should have just done the final MCU in a row, but
2659                      * we don't check for this because the firmware of Denali/Kodiak
2660                      * can't guarantee it. */
2661                 }
2662 
2663                 if (bDecoded) {
2664                     g->mcus_done += 1;
2665 
2666                     if (g->mcus_done >= g->mcus_per_row) {
2667                         PRINT (_T("done with row of MCUs; starting row-sends\n"), 0, 0);
2668                         g->sending_rows = TRUE;
2669                         g->mcus_done = 0;
2670                     }
2671                 }
2672             } while (!g->got_EOI && !g->sending_rows &&
2673                      (dwInputAvail-*pdwInputUsed) >= MAX_MCU_SIZE);
2674         }
2675     }
2676 
2677       /***************************/
2678      /* Sending the output rows */
2679     /***************************/
2680 
2681     if (g->sending_rows) {
2682         if (g->rows_done>=g->traits.lNumRows && g->traits.lNumRows>=0) {
2683             /* we've already output all rows, so discard these */
2684             g->sending_rows = FALSE;
2685         } else {
2686             copy_out_rows (
2687                 g,
2688                 g->rows_done % g->rows_per_mcu,  /* in:  index of next row to send */
2689                 pbOutputBuf,               /* out: copied-out row data */
2690                 &n_rows,                   /* out: # of rows copied out */
2691                 &n_bytes);                 /* out: # of bytes output */
2692             PRINT (_T("copied out %d rows\n"), n_rows, 0);
2693             *pdwOutputUsed   = n_bytes;
2694             g->dwOutNextPos += n_bytes;
2695             g->rows_done    += n_rows;
2696 
2697             if ((g->rows_done>=g->traits.lNumRows && g->traits.lNumRows>=0)
2698                 || (g->rows_done % g->rows_per_mcu)==0) {
2699                 g->sending_rows = FALSE;
2700             }
2701             /* n_rows is 1, unless the never-used output_subsampled feature is used */
2702             if (n_rows > 0)
2703                 ret_val |= IP_CONSUMED_ROW | IP_PRODUCED_ROW;
2704         }
2705     }
2706 
2707     *pdwInputNextPos = g->dwInNextPos;
2708 
2709     PRINT (_T("jpeg_decode_convert_row: Returning %04x, in_used=%d\n"),
2710            ret_val, *pdwInputUsed);
2711     return ret_val;
2712 
2713     fatal_error:
2714     return IP_FATAL_ERROR;
2715 }
2716 
2717 
2718 
2719 /*****************************************************************************\
2720  *
2721  * jpgDecode_insertedData - client inserted into our output stream
2722  *
2723 \*****************************************************************************/
2724 
jpgDecode_insertedData(IP_XFORM_HANDLE hXform,DWORD dwNumBytes)2725 static WORD jpgDecode_insertedData (
2726     IP_XFORM_HANDLE hXform,
2727     DWORD           dwNumBytes)
2728 {
2729     fatalBreakPoint ();
2730     return IP_FATAL_ERROR;   /* must never be called (can't insert data) */
2731 }
2732 
2733 
2734 
2735 /*****************************************************************************\
2736  *
2737  * jpgDecode_newPage - Tells us to flush this page, and start a new page
2738  *
2739 \*****************************************************************************/
2740 
jpgDecode_newPage(IP_XFORM_HANDLE hXform)2741 static WORD jpgDecode_newPage (
2742     IP_XFORM_HANDLE hXform)
2743 {
2744     return IP_DONE;   /* can't insert page-breaks, so ignore this call */
2745 }
2746 
2747 
2748 
2749 /*****************************************************************************\
2750  *
2751  * jpgDecode_closeXform - Destroys this instance
2752  *
2753 \*****************************************************************************/
2754 
jpgDecode_closeXform(IP_XFORM_HANDLE hXform)2755 static WORD jpgDecode_closeXform (IP_XFORM_HANDLE hXform)
2756 {
2757     PJDEC_INST g;
2758     BYTE       **row_pp, **after_pp, *p;
2759 
2760     HANDLE_TO_PTR (hXform, g);
2761     PRINT (_T("jpeg_decode_close\n"), 0, 0);
2762 
2763     row_pp = &(g->out_rows_ap[0][0]);
2764     after_pp = row_pp + (sizeof(g->out_rows_ap)/sizeof(BYTE *));
2765 
2766     for ( ; row_pp<after_pp; row_pp++) {
2767         p = *row_pp;
2768         if (p != NULL) {
2769             IP_MEM_FREE (p);
2770             *row_pp = NULL;
2771         }
2772     }
2773 
2774     huff_free_all (g);
2775     g->dwValidChk = 0;
2776     IP_MEM_FREE (g);       /* free memory for the instance */
2777     return IP_DONE;
2778 
2779     fatal_error:
2780     return IP_FATAL_ERROR;
2781 }
2782 
2783 
2784 
2785 /*****************************************************************************\
2786  *
2787  * jpgDecode_getRowCountInfo - Returns information for determining row count
2788  *
2789 \*****************************************************************************/
2790 
jpgDecode_getRowCountInfo(IP_XFORM_HANDLE hXform,int * pRcCountup,int * pRcTraits,int * pSofOffset)2791 WORD jpgDecode_getRowCountInfo(IP_XFORM_HANDLE hXform,
2792     int *pRcCountup,int *pRcTraits,int *pSofOffset)
2793 {
2794     PJDEC_INST g;
2795 
2796     HANDLE_TO_PTR (hXform, g);
2797     *pRcCountup=g->rows_done;
2798     *pRcTraits=g->traits.lNumRows;
2799     *pSofOffset=g->rowCountOffset;
2800 
2801     return IP_DONE;
2802 
2803     fatal_error:
2804     return IP_FATAL_ERROR;
2805 }
2806 
2807 
2808 
2809 /*****************************************************************************\
2810  *
2811  * jpgDecodeTbl - Jump-table for decoder
2812  *
2813 \*****************************************************************************/
2814 
2815 IP_XFORM_TBL jpgDecodeTbl = {
2816     jpgDecode_openXform,
2817     jpgDecode_setDefaultInputTraits,
2818     jpgDecode_setXformSpec,
2819     jpgDecode_getHeaderBufSize,
2820     jpgDecode_getActualTraits,
2821     jpgDecode_getActualBufSizes,
2822     jpgDecode_convert,
2823     jpgDecode_newPage,
2824     jpgDecode_insertedData,
2825     jpgDecode_closeXform
2826 };
2827 
2828 /* End of File */
2829 
2830 
2831 
2832 
2833 
2834 
2835 
2836 
2837 
2838 
2839