1 /* libhpojip -- HP OfficeJet image-processing library. */
3 /* Copyright (C) 1995-2002 Hewlett-Packard Company
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.
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.
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,
20 * In addition, as a special exception, Hewlett-Packard 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.
32 /* Original author: Mark Overton and others.
34 * Ported to Linux by David Paschal.
37 /*****************************************************************************\
39 * xjpg_dec.c - Decodes a JPEG file into a raw gray image
41 *****************************************************************************
43 * Name of Global Jump-Table:
47 * Items in aXformInfo array passed into setXformSpec:
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.
54 * The aXformInfo items above may all be set to 0 for typical JPEG files.
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)
61 * Capabilities and Limitations:
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.
70 * Default Input Traits, and Output Traits:
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
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.
93 * Chromafax uses an SOF1 instead of the correct SOF0, so we allow
94 * that, and also handle four Huffman tables that SOF1 requires.
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
100 \*****************************************************************************/
108 #include "xjpg_dct.h"
109 #include "xjpg_mrk.h"
118 #define DUMP(msg,arg1,arg2,arg3) \
119 _ftprintf(stdout, msg, (int)(arg1), (int)(arg2), (int)(arg3))
121 #define DUMP(msg,arg1,arg2,arg3)
128 #define PRINT(msg,arg1,arg2) \
129 _ftprintf(stdout, _T("(jpeg) ") msg, (int)arg1, (int)arg2)
131 #define PRINT(msg,arg1,arg2)
135 /*____________________________________________________________________________
138 |____________________________________________________________________________|
141 #define MAX_HUFF_TBLS 4
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
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 */
158 #define DC_TBL_INDEX_LEN 9
159 #define AC_TBL_INDEX_LEN 12
161 #define CHECK_VALUE 0x1ce5ca7e
165 /*____________________________________________________________________________
167 | Instance Variables |
168 |____________________________________________________________________________|
172 BYTE size; /* number of bits in the Huff code (code is the index) */
173 BYTE value; /* value that was coded */
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 */
184 main_huff_elem_t *main_p;
185 aux_huff_elem_t *aux_p;
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.
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.
201 BYTE *out_rows_ap[4][32]; /* row-buffers [component][row] */
203 /***** Items from SOF, Start Of Frame *****/
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 */
214 UINT mcus_per_row; /* # of MCUs in each row */
217 /***** Items from other markers *****/
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? */
225 /***** Huffman tables *****/
227 huff_tbl_t dc_tbls[MAX_HUFF_TBLS];
228 huff_tbl_t ac_tbls[MAX_HUFF_TBLS];
230 /***** Configuration variables *****/
232 BOOL output_subsampled; /* output subsampled data? */
233 BOOL fDenali; /* data is from a Denali? */
235 /***** Variables used while decoding *****/
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 */
251 /***** Reading bits variables *****/
254 /* Bits to be read from inbuf (read left-to-right). */
257 /* Number of bits not yet read in rd_bit_buf (= 32 - number read). */
260 /* The beginning of the input buffer. */
263 /* Next byte in inbuf to be read. */
265 /***** Decoding 8x8 blocks *****/
267 int block[64]; /* scratch-pad 8x8 block */
268 int *block_zz[64+16]; /* zig-zag ptrs into above block */
270 } JDEC_INST, *PJDEC_INST;
274 /*____________________________________________________________________________
277 |____________________________________________________________________________|
280 static void huff_define_table (
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 */
287 void wino_scale_table (long *tbl_p);
292 /******************************************************************************
293 ******************************************************************************
298 Interface into this section:
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
310 ******************************************************************************
311 ******************************************************************************/
315 /*____________________________________________________________________________
317 | read_init | Inits this section |
318 |___________|________________________________________________________________|
320 static void read_init (PJDEC_INST g)
322 g->rd_bits_avail = 0;
328 /*____________________________________________________________________________
330 | read_buf_open | We are being given a (new) buffer to read input |
331 |_______________|____________________________________________________________|
333 | This routine records the location of the new input buffer. |
334 |____________________________________________________________________________|
336 static void read_buf_open (PJDEC_INST g, BYTE *buf_p)
338 g->rd_inbuf_beg = buf_p;
339 g->rd_inbuf_next = buf_p;
344 /*____________________________________________________________________________
346 | read_buf_close | We are done with the current input buffer |
347 |________________|___________________________________________________________|
349 | This function returns # bytes read from the input buffer. |
350 |____________________________________________________________________________|
352 static int read_buf_close (PJDEC_INST g)
354 return g->rd_inbuf_next - g->rd_inbuf_beg;
359 /*____________________________________________________________________________
361 | rd_sync | Empties the bit-cache, and syncs to a byte-boundary |
362 |_________|__________________________________________________________________|
364 static void rd_sync (PJDEC_INST g)
366 g->rd_bits_avail = 0;
371 /*____________________________________________________________________________
373 | read_byte | returns next input byte (syncs to byte-boundary) |
374 |___________|________________________________________________________________|
376 static BYTE read_byte (PJDEC_INST g)
379 return *(g->rd_inbuf_next)++;
384 /*____________________________________________________________________________
386 | read_uint | returns next 2-byte integer (syncs) |
387 |___________|________________________________________________________________|
389 static unsigned read_uint (PJDEC_INST g)
394 uval = (unsigned)*(g->rd_inbuf_next)++ << 8;
395 return uval | *(g->rd_inbuf_next)++;
400 /*____________________________________________________________________________
402 | read_skip_forward | discards the given number of input bytes |
403 |___________________|________________________________________________________|
405 static void read_skip_forward (PJDEC_INST g, UINT n)
407 if (n > MAX_MARKER_LEN)
408 longjmp (g->syntax_error, BAD_MARKER_DATA);
410 g->rd_inbuf_next += n;
415 /*____________________________________________________________________________
417 | read_skip_backward | backs up N bytes in the input buffer |
418 |____________________|_______________________________________________________|
420 static void read_skip_backward (PJDEC_INST g, UINT n)
423 g->rd_inbuf_next -= n;
428 /*____________________________________________________________________________
430 | READ_BITS_LOAD | loads next par_n_bits of input into par_value (no advance)|
431 |________________|___________________________________________________________|
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) |
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 |____________________________________________________________________________|
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 */
452 #define READ_BITS_LOAD(g, fixed_len, par_n_bits, par_value, hit_marker) \
454 if ((int)(par_n_bits) > g->rd_bits_avail) { \
458 a_byte = *(g->rd_inbuf_next)++; \
459 DUMP (_T("<%02x>"), a_byte, 0, 0); \
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)) \
466 break; /* exit 'while' loop */ \
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); \
475 par_value = (g->rd_bit_buf << (32-g->rd_bits_avail)) >> (32-(par_n_bits)); \
480 /*____________________________________________________________________________
482 | READ_BITS_ADVANCE | discards next par_n_bits of input |
483 |___________________|________________________________________________________|
485 #define READ_BITS_ADVANCE(g, par_n_bits) \
487 g->rd_bits_avail -= par_n_bits; \
492 /******************************************************************************
493 ******************************************************************************
498 Interface into this section:
500 mar_get - parses and returns next marker-id
501 mar_parse - parses the data associated with the marker
503 ******************************************************************************
504 ******************************************************************************/
508 /*____________________________________________________________________________
510 | parse_factors | parses sample-factors as nibbles into array |
511 |_______________|____________________________________________________________|
513 | This is only called by parse_app_short_header below. |
514 | Function return value = maximum sample factor. |
515 |____________________________________________________________________________|
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 */
527 for (i=3; i>=0; i--) {
528 fac = factors & 0x000fu;
530 if (fac > max_fac) max_fac = fac;
539 /*____________________________________________________________________________
541 | calc_quant_table | calculates a quantization table |
542 |__________________|_________________________________________________________|
544 | This is only called by parse_app_short_header below. |
545 | Warning: The calculation below should match the firmware. |
546 |____________________________________________________________________________|
548 static void calc_quant_table (
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) */
559 tbl_p = g->quant_tbls[which_q_tbl];
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;
568 wino_scale_table (tbl_p);
573 /*____________________________________________________________________________
575 | mar_get | parses and returns next marker-id |
576 |_________|__________________________________________________________________|
578 static UINT mar_get (PJDEC_INST g)
580 UINT marker = 0; /* init to eliminate a compiler warning */
586 marker = read_byte (g);
587 if (marker == 0xff) got_ff = TRUE;
591 if (!got_ff || marker==0)
592 longjmp (g->syntax_error, BAD_MARKER_ID);
599 /*____________________________________________________________________________
601 | mar_flush | discards data associated with current marker |
602 |___________|________________________________________________________________|
604 static void mar_flush (PJDEC_INST g, UINT marker)
606 if (marker==MARKER_SOI || marker==MARKER_EOI ||
607 (marker>=MARKER_RST0 && marker<=MARKER_RST7))
608 return; /* marker has no associated segment */
610 read_skip_forward (g, read_uint(g) - 2);
615 /*____________________________________________________________________________
617 | parse_app_jfif | parses a JFIF APP0 marker |
618 |________________|___________________________________________________________|
620 | Sets these fields in 'traits': lHorizDPI, lVertDPI |
621 |____________________________________________________________________________|
623 static void parse_app_jfif (PJDEC_INST 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);
637 read_skip_forward (g,6); /* discard "FIF\0" + 0x01 + 0x00 */
639 h_dpi = read_uint (g);
640 v_dpi = read_uint (g);
641 read_skip_forward (g,2); /* discard thumbnail X and Y */
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;
651 /*____________________________________________________________________________
653 | parse_app_g3fax | parses a color fax APP1 marker |
654 |_________________|__________________________________________________________|
656 | Can set these fields in 'traits': lHorizDPI, lVertDPI |
657 |____________________________________________________________________________|
659 static void parse_app_g3fax (PJDEC_INST g)
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 */
670 /* wrong version, or a gamut or illuminant spec which we ignore */
671 read_skip_forward (g, len-2);
675 for (i=0; i<8; i++) /* fax id is 6 bytes; version is 2 bytes */
676 id_ver[i] = read_byte (g);
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;
690 /*____________________________________________________________________________
692 | parse_app_short_header | An APP1 marker output by OfficeJet firmware |
693 |________________________|___________________________________________________|
695 static void parse_app_short_header (PJDEC_INST g)
697 /* Since the firmware does not supply tables in its header,
698 * the tables used in the firmware are supplied below. */
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
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
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
728 static const BYTE lum_DC_values[12] = {
729 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b
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
737 static const BYTE chrom_DC_values[12] = {
738 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b
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
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.
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,
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
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,
815 UINT dc_q_fac, ac_q_fac;
818 /***** default items not in the short header *****/
820 g->restart_interval = 0;
822 g->which_quant_tbl[0] = 0;
823 g->which_quant_tbl[1] = 1;
824 g->which_quant_tbl[2] = 1;
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;
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);
839 /***** parse the short header *****/
843 longjmp (g->syntax_error, BAD_MARKER_DATA);
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 */
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' */
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);
866 g->got_short_header = TRUE;
871 /*____________________________________________________________________________
873 | mar_parse_app | application-specific marker |
874 |_______________|____________________________________________________________|
876 | Can set these fields in 'traits': lHorizDPI, lVertDPI |
877 |____________________________________________________________________________|
879 static void mar_parse_app (PJDEC_INST g, UINT marker)
886 /* unknown marker; discard it */
887 read_skip_forward (g, len-2);
894 read_skip_backward (g, 5);
896 if (marker==MARKER_APP+1 && id1==0x47 && id2==0x33 && id3==0x46) {
897 /* G3 color fax APP1 marker */
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 */
903 } else if (marker==MARKER_APP+1 && len==18) {
904 /* assume that APP1 marker is a short header */
905 parse_app_short_header (g);
907 /* unrecognized APP marker; discard it */
908 read_skip_forward (g, len);
914 /*____________________________________________________________________________
916 | mar_parse_sof | start of frame |
917 |_______________|____________________________________________________________|
919 | Sets these fields in 'traits': lNumRows, iPixelsPerRow, iBitsPerPixel, |
920 | iComponentsPerPixel. |
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 |____________________________________________________________________________|
927 static void mar_parse_sof (PJDEC_INST g, UINT marker)
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;
945 if (g->traits.lNumRows == 0)
946 g->traits.lNumRows = -1; /* -1 means 'unknown' */
948 if (len != (8u + 3u*g->num_comps) || g->num_comps==0)
949 longjmp (g->syntax_error, BAD_MARKER_DATA);
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);
956 g->max_horiz_samp_fac = 1;
957 g->max_vert_samp_fac = 1;
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);
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);
974 _T(" %d: comp id = %d, hv samp fac = %02x, which q = %d\n"),
975 comp, comp_id, hv_samp, q_table);
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;
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;
989 /*____________________________________________________________________________
991 | mar_parse_dqt | discrete quantization table |
992 |_______________|____________________________________________________________|
994 | Sets the following variables: quant_tbls. |
995 |____________________________________________________________________________|
997 static void mar_parse_dqt (PJDEC_INST g)
1003 len = read_uint(g) - 2;
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);
1017 DUMP (_T("\n"), 0,0,0);
1018 wino_scale_table (tbl_p);
1022 longjmp (g->syntax_error, BAD_MARKER_DATA);
1027 /*____________________________________________________________________________
1029 | mar_parse_dht | define Huffman tables |
1030 |_______________|____________________________________________________________|
1032 | Sets the following variables: dc_tbls, ac_tbls. |
1033 |____________________________________________________________________________|
1035 static void mar_parse_dht (PJDEC_INST g)
1040 int len, i, tot_codes;
1043 len = read_uint(g) - 2;
1046 class_id = read_byte (g);
1048 for (tot_codes=0, i=0; i<=15; i++) {
1049 num_codes[i] = read_byte (g);
1050 tot_codes += num_codes[i];
1054 if (len < tot_codes)
1055 longjmp (g->syntax_error, BAD_MARKER_DATA);
1057 for (i=0; i<tot_codes; i++)
1058 values[i] = read_byte (g);
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"));
1072 huff_define_table (g, (BOOL)(class_id>>4), class_id & 0x0f,
1077 longjmp (g->syntax_error, BAD_MARKER_DATA);
1082 /*____________________________________________________________________________
1084 | mar_parse_dri | define restart interval |
1085 |_______________|____________________________________________________________|
1087 | Sets the following variable: restart_interval. |
1088 |____________________________________________________________________________|
1090 static void mar_parse_dri (PJDEC_INST g)
1094 len = read_uint (g);
1096 longjmp (g->syntax_error, BAD_MARKER_DATA);
1098 g->restart_interval = read_uint (g);
1099 DUMP (_T("\nDRI marker: restart interval = %d\n"), g->restart_interval, 0,0);
1104 /*____________________________________________________________________________
1106 | mar_parse_sos | start of scan |
1107 |_______________|____________________________________________________________|
1109 static void mar_parse_sos (PJDEC_INST g)
1116 len = read_uint (g);
1117 if (len != 6u+2u*g->num_comps)
1118 longjmp (g->syntax_error, BAD_MARKER_DATA);
1120 read_byte (g); /* skip Ns value (number of components in scan) */
1122 DUMP (_T("\nSOS marker:\n"), 0,0,0);
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;
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) */
1139 /*____________________________________________________________________________
1141 | mar_parse_dnl | Define Number of Lines |
1142 |_______________|____________________________________________________________|
1144 | Sets the following variable: traits.lNumRows |
1145 |____________________________________________________________________________|
1147 static void mar_parse_dnl (PJDEC_INST g)
1151 len = read_uint (g);
1152 nRows = read_uint (g);
1154 if (len!=4u || nRows==0)
1155 longjmp (g->syntax_error, BAD_MARKER_DATA);
1157 DUMP (_T("\nDNL marker: %d\n"), nRows,0,0);
1158 g->traits.lNumRows = nRows;
1163 /*____________________________________________________________________________
1165 | mar_parse | parses the marker, storing results in global variables |
1166 |___________|________________________________________________________________|
1168 static void mar_parse (PJDEC_INST g, UINT marker)
1170 PRINT (_T("mar_parse: marker = %02xh\n"), marker, 0);
1190 mar_parse_app (g, marker);
1193 case MARKER_COM: /* comment marker */
1208 mar_flush (g, marker);
1225 mar_parse_sof (g, marker);
1236 DUMP (_T("\nRST marker.\n"), 0,0,0);
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;
1248 longjmp (g->syntax_error, NOT_IMPLEMENTED);
1251 /* The following markers have no data following them */
1254 DUMP (_T("\nSOI marker.\n"), 0,0,0);
1258 DUMP (_T("\nEOI marker.\n"), 0,0,0);
1262 longjmp (g->syntax_error, BAD_MARKER_DATA);
1268 /******************************************************************************
1269 ******************************************************************************
1274 Interface into this section:
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
1282 ******************************************************************************
1283 ******************************************************************************/
1287 /*____________________________________________________________________________
1289 | DECODE_HUFF | Decodes a Huffman code, returning corresponding value |
1290 |_____________|______________________________________________________________|
1292 #define DECODE_HUFF( \
1299 UINT tbl_index, code, size; \
1300 main_huff_elem_t *elem; \
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; \
1309 par_result = parse_aux_code (g, huff_tbl_p->aux_p); \
1311 DUMP (_T(" %2d-%04x-%3d(main) "), size, code, par_result); \
1312 READ_BITS_ADVANCE (g, size) \
1318 /*____________________________________________________________________________
1320 | parse_aux_code | Code is not in short-width table; look in aux table |
1321 |________________|___________________________________________________________|
1323 | Returns the value associated with the code. |
1324 |____________________________________________________________________________|
1326 static UINT parse_aux_code (
1328 aux_huff_elem_t *aux_tbl_par_p)
1330 UINT code, size, val;
1333 aux_huff_elem_t *lo_p, *hi_p, *mid_p;
1335 READ_BITS_LOAD (g, FALSE, 16, code, syntax_err)
1337 #if 0 /* we are no longer using ROM tables */
1338 if ((BYTE *)aux_tbl_par_p == dec_AC_aux_tbl)
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)
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 */
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;
1359 excess = 16u - size;
1360 if ((code>>excess) != (UINT)(lo_p->code>>excess)) {
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);
1371 READ_BITS_ADVANCE (g,size)
1372 DUMP (_T(" %2d-%4x-%3d(aux) "), size, code, val);
1377 PRINT (_T("parse_aux_code: syntax error\n"), 0, 0);
1378 longjmp (g->syntax_error, BAD_HUFF_CODE);
1383 /*____________________________________________________________________________
1385 | huff_init | Inits this section |
1386 |___________|________________________________________________________________|
1388 static void huff_init (PJDEC_INST g)
1390 memset (g->dc_tbls, 0, sizeof(g->dc_tbls));
1391 memset (g->ac_tbls, 0, sizeof(g->ac_tbls));
1396 /*____________________________________________________________________________
1398 | huff_free_tbl | Frees memory allocated for the given table |
1399 |_______________|____________________________________________________________|
1401 static void huff_free_tbl (PJDEC_INST g, huff_tbl_t *tbl_p)
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);
1410 tbl_p->index_p = NULL;
1411 tbl_p->main_p = NULL;
1412 tbl_p->aux_p = NULL;
1417 /*____________________________________________________________________________
1419 | huff_free_all | Frees all memory allocated for Huffman tables |
1420 |_______________|____________________________________________________________|
1422 static void huff_free_all (PJDEC_INST g)
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]));
1434 /*____________________________________________________________________________
1436 | calc_table | Defines a Huffman table |
1437 |____________|_______________________________________________________________|
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 */
1450 main_huff_elem_t *main_p;
1451 aux_huff_elem_t *aux_p;
1453 /***************************************************/
1454 /* Compute a complete Huffman table. */
1455 /* output: huffval, huffsize, huffcode, tot_codes */
1456 /***************************************************/
1459 int i, j, k, code, siz;
1461 /* Generate size array -- see JPEG document
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
1468 for (i=1; i<=16; i++)
1469 for (j=1; j<=counts[i-1]; j++)
1470 huffsize[tot_codes++] = i;
1472 huffsize[tot_codes] = 0;
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 */
1482 /* Generate code array -- see JPEG document
1484 * The resulting table is sorted by increasing 'code', and also by
1485 * increasing 'size'.
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 */
1499 } while (huffsize[k] != siz);
1503 /****************************************/
1504 /* Make the main table (output: main_p) */
1505 /****************************************/
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.
1513 UINT first, final, code_plus_junk;
1515 if (main_ix_len == 0)
1516 main_ix_len = huffsize[tot_codes-1];
1518 nbytes = (tot_codes+1) * sizeof(main_huff_elem_t);
1519 IP_MEM_ALLOC (nbytes, main_p);
1520 memset (main_p, 0, nbytes);
1522 nbytes = 1lu << main_ix_len;
1523 IP_MEM_ALLOC (nbytes, index_p);
1524 memset (index_p, 0, nbytes);
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] ;
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;
1536 index_p[code_plus_junk] = i+1;
1540 /********************************************/
1541 /* Make the auxiliary table (output: aux_p) */
1542 /********************************************/
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).
1551 int first, n_entries;
1554 /* locate first huffsize > main_ix_len */
1555 for (first=0; first<tot_codes && huffsize[first]<=main_ix_len; first++);
1557 if (first == tot_codes) {
1558 /* the main table captured everything; no aux table is needed */
1559 IP_MEM_ALLOC (1, aux_p);
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);
1564 /* fill-in the dummy entry (contains # entries in table) */
1566 p->size = (UINT) n_entries;
1567 p->code = p->value = 0;
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];
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"));
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"));
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"));
1605 if (huffsize[tot_codes-1] > main_ix_len) {
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"));
1618 huff_tbl_p->index_p = index_p;
1619 huff_tbl_p->main_p = main_p;
1620 huff_tbl_p->aux_p = aux_p;
1624 assert (0); /* todo: eliminate this assert */
1629 /*____________________________________________________________________________
1631 | huff_define_table | Defines the given Huffman table |
1632 |___________________|________________________________________________________|
1634 | Sets the following variables: dc_tbls, ac_tbls. |
1635 |____________________________________________________________________________|
1637 static void huff_define_table (
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 */
1646 tbl_p = ac ? &(g->ac_tbls[id]) : &(g->dc_tbls[id]);
1647 huff_free_tbl (g,tbl_p);
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,
1657 /******************************************************************************
1658 ******************************************************************************
1663 Interface into this section:
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
1670 ******************************************************************************
1671 ******************************************************************************/
1675 #define SHIFT_TRUNC(mvalue,mshift) ((mvalue) >> (mshift))
1677 #define QNORM_TO_INPUT(mval) SHIFT_TRUNC(mval, QNORM_PRECISION-INPUT_PRECISION)
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 */
1690 #define CONST_PRECISION 15
1701 /*____________________________________________________________________________
1703 | wino_scale_table | Scales a quantization table into a Winograd table |
1704 |__________________|_________________________________________________________|
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 |____________________________________________________________________________|
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
1731 void wino_scale_table (
1737 fptr = inv_dct_norm;
1738 for (i=0; i<64; i++) {
1739 *tbl_p = (long ) ((*tbl_p) * (*fptr++) * (1l<<QNORM_PRECISION) + 0.5);
1746 /******************************************************************************
1747 ******************************************************************************
1752 Interface into this section:
1754 zero_prior_DC - sets the predicted DC values to zero
1755 decode_MCU - decodes a single Minimum Coded Unit
1757 ******************************************************************************
1758 ******************************************************************************/
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 */
1777 /*____________________________________________________________________________
1779 | decode_init | inits this section |
1780 |_____________|______________________________________________________________|
1782 static void decode_init (PJDEC_INST g)
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++]);
1794 /*____________________________________________________________________________
1796 | zero_prior_DC | zeroes the predicted DC values |
1797 |_______________|____________________________________________________________|
1799 static void zero_prior_DC (PJDEC_INST g)
1801 g->prior_dc[0] = g->prior_dc[1] = g->prior_dc[2] = g->prior_dc[3] = 0;
1806 /*____________________________________________________________________________
1808 | parse_block | parses an 8x8 block; return data is ready for inverse DCT |
1809 |_____________|______________________________________________________________|
1811 | Return value: TRUE = we parsed a block, |
1812 | FALSE = hit a marker. |
1813 | Output data is put in 'block' array. |
1814 |____________________________________________________________________________|
1816 static BOOL parse_block (
1818 int comp) /* in: image component number */
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.
1830 #define FIX_TERM(msize,mterm) { \
1831 if ((mterm & (1u<<((msize)-1))) == 0) \
1832 mterm = (mterm | (-1 << (msize))) + 1; \
1837 #define FIX_TERM(msize,mterm) { \
1838 int mask = -1 << msize; \
1839 if (((mterm<<1) & mask) == 0) \
1840 mterm += mask + 1; \
1845 #define FIX_TERM(msize,mterm) \
1846 mterm += ((mterm>>(msize-1)) - 1) & ~((1<<msize) - 2);
1852 UINT siz, run, rl_byte;
1855 /* memset (block, 0, 64*sizeof(int)); */
1857 int *block_p, *after_p;
1859 for (block_p=g->block, after_p=g->block+64; block_p<after_p; ) {
1871 dequant_p = g->quant_tbls[g->which_quant_tbl[comp]];
1872 block_p = g->block_zz;
1874 /**************************************/
1875 /* Decode and dequantize the DC value */
1876 /**************************************/
1878 DUMP (_T("\nStart of block for component %d:\n"), comp, 0, 0);
1880 huff_p = &(g->dc_tbls[g->which_dc_tbl[comp]]);
1881 DECODE_HUFF (g, huff_p, DC_TBL_INDEX_LEN, siz, hit_marker)
1884 DUMP (_T("dc=0, size of dc=0\n"), 0,0,0);
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);
1893 dc += g->prior_dc[comp];
1894 g->prior_dc[comp] = dc;
1895 *(*block_p++) = QNORM_TO_INPUT ((long )*dequant_p++ * dc);
1897 /*************************************************/
1898 /* Decode, dezigzag and dequantize the AC values */
1899 /*************************************************/
1901 huff_p = &(g->ac_tbls[g->which_ac_tbl[comp]]);
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
1910 DECODE_HUFF (g, huff_p, AC_TBL_INDEX_LEN, rl_byte, hit_marker);
1912 siz = rl_byte & 0x0f;
1913 DUMP (_T("rlc: run=%d, size of ac=%d"), run, siz, 0);
1917 DUMP (_T(", run of 16\n"), 0,0,0);
1920 } else if (run == 0) {
1921 DUMP (_T(", EOB\n"), 0,0,0);
1922 break; /* hit EOB */
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);
1932 *(*block_p++) = QNORM_TO_INPUT ((long )*dequant_p++ * ac);
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);
1941 break; /* 63rd AC term was non-zero */
1948 PRINT(_T("parse_block: syntax error\n"), 0,0);
1949 longjmp (g->syntax_error, BAD_HUFF_CODE);
1959 /*____________________________________________________________________________
1961 | handleMarkerInStream | handles a marker in the data-stream |
1962 |______________________|_____________________________________________________|
1964 | Parses EOI, DNL and RST; other markers cause an error (longjmp). |
1965 | For an EOI, g->got_EOI is set to true. |
1966 |____________________________________________________________________________|
1968 static void handleMarkerInStream (PJDEC_INST g)
1972 marker = mar_get(g);
1974 if (marker == MARKER_EOI) {
1975 PRINT (_T("handleMarkerInStream: parsed EOI\n"), 0, 0);
1977 } else if (marker == MARKER_DNL) {
1978 PRINT (_T("handleMarkerInStream: parsing DNL\n"), 0, 0);
1980 } else if (g->restart_interval > 0
1981 && g->restart_cur_mcu == g->restart_interval
1982 && (marker-MARKER_RST0) == g->restart_cur_marker)
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;
1990 PRINT (_T("handleMarkerInStream: illegal marker=0x%2.2X\n"), marker, 0);
1991 longjmp (g->syntax_error, BAD_MARKER_DATA);
1997 /*____________________________________________________________________________
1999 | LevelShiftAndRound | Level-shifts, rounds, and outputs pixels in 0..255 |
2000 |____________________|_______________________________________________________|
2002 static void LevelShiftAndRound (int *inBlock_p, BYTE *outBlock_p)
2007 for (outAfter = outBlock_p + 64;
2008 outBlock_p < outAfter;
2009 outBlock_p++, inBlock_p++)
2011 pixel = (*inBlock_p +
2012 ((1<<(INPUT_PRECISION-1)) + (128<<INPUT_PRECISION)))
2015 pixel = pixel>0 ? 255 : 0; /* clamp to 0 or 255 */
2016 *outBlock_p = (BYTE) pixel;
2022 /*____________________________________________________________________________
2024 | decode_MCU | Parses a Minimum Coded Unit, and loads pixels into out_rows_ap|
2025 |____________|_______________________________________________________________|
2027 | The pixels are loaded starting at mcus_done (not incremented). |
2028 | This routine handles the restart interval logic, and markers. |
2030 | Returns TRUE if an MCU was parsed, else FALSE. |
2031 |____________________________________________________________________________|
2033 static BOOL decode_MCU (PJDEC_INST g)
2038 int h_block, v_block;
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++) {
2048 /***** parse and inverse-dct an 8x8 block *****/
2050 while (! parse_block(g,comp)) {
2051 /* we hit a marker */
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
2058 if (comp>0 || v_block>0 || h_block>0)
2059 longjmp (g->syntax_error, UNEXPECTED_MARKER);
2061 handleMarkerInStream(g);
2063 return FALSE; /* we're out of data; cannot proceed */
2066 dct_inverse (g->block);
2068 /***** compute output pixels *****/
2070 LevelShiftAndRound (g->block, baPixels);
2072 /***** copy block into out_rows_ap *****/
2075 ul_col = (g->mcus_done*g->horiz_samp_facs[comp] + h_block) * 8;
2076 row_pp = &(g->out_rows_ap[comp][ul_row]);
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);
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;
2099 /*____________________________________________________________________________
2101 | copy_out_rows | copies a row (or rows) from out_rows_ap to output buffer |
2102 |_______________|____________________________________________________________|
2104 | If output_subsampled is true, we output row data in the same odd order |
2105 | which the ASIC outputs it. |
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 |
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 .... |
2123 | In this routine, |
2125 | vert_period = index of which period we're outputting vertically within|
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 |____________________________________________________________________________|
2132 static void copy_out_rows (
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 */
2141 UINT vert_period, vert_mod;
2145 vert_period = row_index / g->max_vert_samp_fac;
2146 vert_mod = row_index % g->max_vert_samp_fac;
2148 if (! g->output_subsampled) {
2150 /*******************************************/
2151 /* Perform duplication to undo subsampling */
2152 /*******************************************/
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];
2165 samp_fac = g->horiz_samp_facs[comp];
2167 if (samp_fac == g->max_horiz_samp_fac) {
2169 /***** fast case: copying all pixels, with no duplication *****/
2171 if (g->num_comps == 1) {
2172 memcpy (out_p, row_p, g->traits.iPixelsPerRow);
2174 for (col=0; col<(UINT)g->traits.iPixelsPerRow; col++) {
2176 out_p += g->num_comps;
2180 } else if (samp_fac==1 && g->max_horiz_samp_fac==2) {
2182 /***** fast case: duplicating every other pixel *****/
2185 for (col=0; col<(UINT)g->traits.iPixelsPerRow; col+=2) {
2186 *out_p = prev_pix = *row_p++;
2187 out_p += g->num_comps;
2189 out_p += g->num_comps;
2194 /***** slow general case *****/
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;
2200 if (horiz_mod == g->max_horiz_samp_fac) horiz_mod = 0;
2206 *n_bytes_p = g->num_comps * g->traits.iPixelsPerRow;
2210 /**********************************************/
2211 /* Output subsampled data in ASIC's odd order */
2212 /**********************************************/
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;
2219 periods_per_row = g->mcus_per_row * 8;
2221 if (g->num_comps==1 && g->max_horiz_samp_fac==1 && g->max_vert_samp_fac==1) {
2223 /***** fast case: one component; just copy the row *****/
2225 memcpy (out_p, g->out_rows_ap[0][row_index], g->traits.iPixelsPerRow);
2226 out_p += g->traits.iPixelsPerRow;
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)) {
2236 /***** fast case: color with no subsampling *****/
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++;
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)) {
2255 /***** fast case: 4-1-1 color subsampling *****/
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++;
2272 /***** slow general case *****/
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];
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];
2287 *n_rows_p = g->max_vert_samp_fac;
2288 *n_bytes_p = out_p - outbuf_p;
2295 /******************************************************************************
2296 ******************************************************************************
2298 E X P O R T E D R O U T I N E S
2300 ******************************************************************************
2301 ******************************************************************************/
2305 /*****************************************************************************\
2307 * jpgDecode_openXform - Creates a new instance of the transformer
2309 *****************************************************************************
2311 * This returns a handle for the new instance to be passed into
2312 * all subsequent calls.
2314 * Return value: IP_DONE=success; IP_FATAL_ERROR=misc error.
2316 \*****************************************************************************/
2318 static WORD jpgDecode_openXform (
2319 IP_XFORM_HANDLE *pXform) /* out: returned handle */
2323 INSURE (pXform != NULL);
2324 IP_MEM_ALLOC (sizeof(JDEC_INST), g);
2326 memset (g, 0, sizeof(JDEC_INST));
2327 g->dwValidChk = CHECK_VALUE;
2332 return IP_FATAL_ERROR;
2337 /*****************************************************************************\
2339 * jpgDecode_setDefaultInputTraits - Specifies default input image traits
2341 *****************************************************************************
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
2348 * Return value: IP_DONE=success; IP_FATAL_ERROR=misc error.
2350 \*****************************************************************************/
2352 static WORD jpgDecode_setDefaultInputTraits (
2353 IP_XFORM_HANDLE hXform, /* in: handle for xform */
2354 PIP_IMAGE_TRAITS pTraits) /* in: default image traits */
2358 HANDLE_TO_PTR (hXform, g);
2359 g->traits = *pTraits; /* a structure copy */
2363 return IP_FATAL_ERROR;
2368 /*****************************************************************************\
2370 * jpgDecode_setXformSpec - Provides xform-specific information
2372 \*****************************************************************************/
2374 static WORD jpgDecode_setXformSpec (
2375 IP_XFORM_HANDLE hXform, /* in: handle for xform */
2376 DWORD_OR_PVOID aXformInfo[]) /* in: xform information */
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;
2386 return IP_FATAL_ERROR;
2391 /*****************************************************************************\
2393 * jpgDecode_getHeaderBufSize- Returns size of input buf needed to hold header
2395 \*****************************************************************************/
2397 static WORD jpgDecode_getHeaderBufSize (
2398 IP_XFORM_HANDLE hXform, /* in: handle for xform */
2399 DWORD *pdwInBufLen) /* out: buf size for parsing header */
2403 HANDLE_TO_PTR (hXform, g);
2404 *pdwInBufLen = MAX_HEADER_SIZE;
2408 return IP_FATAL_ERROR;
2413 /*****************************************************************************\
2415 * jpgDecode_getActualTraits - Parses header, and returns input & output traits
2417 \*****************************************************************************/
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 */
2431 UINT row_len, n_rows;
2440 HANDLE_TO_PTR (hXform, g);
2444 g->sending_rows = FALSE;
2446 g->got_short_header = FALSE;
2450 g->restart_cur_mcu = 0;
2451 g->restart_cur_marker = 0;
2452 g->dwOutNextPos = 0;
2454 /********************/
2455 /* Parse the header */
2456 /********************/
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;
2463 read_buf_open (g, pbInputBuf);
2465 if (mar_get(g) != MARKER_SOI)
2466 return IP_FATAL_ERROR | IP_INPUT_ERROR;
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));
2475 *pdwInputNextPos = g->dwInNextPos = *pdwInputUsed = read_buf_close (g);
2477 /* todo: check that all markers arrived */
2479 PRINT (_T("jpeg_decode_parse_header: pixels/row=%d, num_rows=%d\n"),
2480 g->traits.iPixelsPerRow, g->traits.lNumRows);
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;
2486 /*******************************************/
2487 /* Allocate the row-buffers in out_rows_ap */
2488 /*******************************************/
2490 memset (g->out_rows_ap, 0, sizeof(g->out_rows_ap));
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;
2496 for (row=0; row<n_rows; row++) {
2497 IP_MEM_ALLOC (row_len, p);
2498 g->out_rows_ap[comp][row] = p;
2506 *pInTraits = g->traits;
2507 *pOutTraits = g->traits;
2509 return IP_DONE | IP_READY_FOR_DATA;
2512 return IP_FATAL_ERROR;
2517 /****************************************************************************\
2519 * jpgDecode_getActualBufSizes - Returns buf sizes needed for remainder of job
2521 \****************************************************************************/
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 */
2530 HANDLE_TO_PTR (hXform, g);
2531 *pdwMinInBufLen = INBUF_NUM_MCUS * MAX_MCU_SIZE;
2532 *pdwMinOutBufLen = g->num_comps * g->traits.iPixelsPerRow;
2537 return IP_FATAL_ERROR;
2542 /*****************************************************************************\
2544 * jpgDecode_convert - the work-horse routine
2546 \*****************************************************************************/
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 */
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;
2565 static BOOL bDecoded;
2566 const BYTE ycc_white[4] = { 255, 128, 128, 255 };
2568 HANDLE_TO_PTR (hXform, g);
2571 *pdwOutputThisPos = g->dwOutNextPos;
2573 ret_val = IP_READY_FOR_DATA;
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;
2581 /**********************/
2582 /* Parsing input data */
2583 /**********************/
2585 if (! g->sending_rows) {
2586 if (pbInputBuf == NULL) {
2588 /* We are being told to flush, so we should have consumed the EOI,
2589 * and have discarded any bytes following it. */
2591 /* Unexpected end of data: we did not get an EOI */
2592 ret_val |= IP_INPUT_ERROR;
2596 } else if (g->got_EOI) {
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;
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;
2611 for (row=0; row<n_rows; row++)
2612 memset (g->out_rows_ap[comp][row], ycc_white[comp], row_len);
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);
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
2629 READ_BITS_LOAD (g, FALSE, 8, trash, at_a_marker);
2632 handleMarkerInStream(g);
2636 memcpy(&(g->syntax_error), &(g->old_syntax_error), sizeof(jmp_buf));
2637 n_bytes = read_buf_close (g);
2639 *pdwInputUsed += n_bytes;
2640 g->dwInNextPos += n_bytes;
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.
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. */
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;
2672 } while (!g->got_EOI && !g->sending_rows &&
2673 (dwInputAvail-*pdwInputUsed) >= MAX_MCU_SIZE);
2677 /***************************/
2678 /* Sending the output rows */
2679 /***************************/
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;
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;
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;
2701 /* n_rows is 1, unless the never-used output_subsampled feature is used */
2703 ret_val |= IP_CONSUMED_ROW | IP_PRODUCED_ROW;
2707 *pdwInputNextPos = g->dwInNextPos;
2709 PRINT (_T("jpeg_decode_convert_row: Returning %04x, in_used=%d\n"),
2710 ret_val, *pdwInputUsed);
2714 return IP_FATAL_ERROR;
2719 /*****************************************************************************\
2721 * jpgDecode_insertedData - client inserted into our output stream
2723 \*****************************************************************************/
2725 static WORD jpgDecode_insertedData (
2726 IP_XFORM_HANDLE hXform,
2730 return IP_FATAL_ERROR; /* must never be called (can't insert data) */
2735 /*****************************************************************************\
2737 * jpgDecode_newPage - Tells us to flush this page, and start a new page
2739 \*****************************************************************************/
2741 static WORD jpgDecode_newPage (
2742 IP_XFORM_HANDLE hXform)
2744 return IP_DONE; /* can't insert page-breaks, so ignore this call */
2749 /*****************************************************************************\
2751 * jpgDecode_closeXform - Destroys this instance
2753 \*****************************************************************************/
2755 static WORD jpgDecode_closeXform (IP_XFORM_HANDLE hXform)
2758 BYTE **row_pp, **after_pp, *p;
2760 HANDLE_TO_PTR (hXform, g);
2761 PRINT (_T("jpeg_decode_close\n"), 0, 0);
2763 row_pp = &(g->out_rows_ap[0][0]);
2764 after_pp = row_pp + (sizeof(g->out_rows_ap)/sizeof(BYTE *));
2766 for ( ; row_pp<after_pp; row_pp++) {
2776 IP_MEM_FREE (g); /* free memory for the instance */
2780 return IP_FATAL_ERROR;
2785 /*****************************************************************************\
2787 * jpgDecode_getRowCountInfo - Returns information for determining row count
2789 \*****************************************************************************/
2791 WORD jpgDecode_getRowCountInfo(IP_XFORM_HANDLE hXform,
2792 int *pRcCountup,int *pRcTraits,int *pSofOffset)
2796 HANDLE_TO_PTR (hXform, g);
2797 *pRcCountup=g->rows_done;
2798 *pRcTraits=g->traits.lNumRows;
2799 *pSofOffset=g->rowCountOffset;
2804 return IP_FATAL_ERROR;
2809 /*****************************************************************************\
2811 * jpgDecodeTbl - Jump-table for decoder
2813 \*****************************************************************************/
2815 IP_XFORM_TBL jpgDecodeTbl = {
2816 jpgDecode_openXform,
2817 jpgDecode_setDefaultInputTraits,
2818 jpgDecode_setXformSpec,
2819 jpgDecode_getHeaderBufSize,
2820 jpgDecode_getActualTraits,
2821 jpgDecode_getActualBufSizes,
2824 jpgDecode_insertedData,
2825 jpgDecode_closeXform