1 //------------------------------------------------------------------------------
2 // jpegdecoder.h
3 // Small JPEG Decoder Library v0.93b
4 // Last updated: Dec. 28, 2001
5 // Copyright (C) 1994-2000 Rich Geldreich
6 // richgel@voicenet.com
7 //
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
12 //
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // Lesser General Public License for more details.
17 //
18 // You should have received a copy of the GNU Lesser General Public
19 // License along with this library; if not, write to the Free Software
20 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 //------------------------------------------------------------------------------
22 #ifndef JPEG_DECODER_H
23 #define JPEG_DECODER_H
24 //------------------------------------------------------------------------------
25 #include "main.h"
26 //------------------------------------------------------------------------------
27 // Define SUPPORT_X86ASM to include the inline x86 assembler code.
28 //#define SUPPORT_X86ASM
29 //------------------------------------------------------------------------------
30 // Define SUPPORT_MMX to include MMX support.
31 //#define SUPPORT_MMX
32 //------------------------------------------------------------------------------
33 #define JPGD_INBUFSIZE       4096
34 //------------------------------------------------------------------------------
35 // May need to be adjusted if support for other colorspaces/sampling factors is added
36 #define JPGD_MAXBLOCKSPERMCU 10
37 //------------------------------------------------------------------------------
38 #define JPGD_MAXHUFFTABLES   8
39 #define JPGD_MAXQUANTTABLES  4
40 #define JPGD_MAXCOMPONENTS   4
41 #define JPGD_MAXCOMPSINSCAN  4
42 //------------------------------------------------------------------------------
43 // Increase this if you increase the max width!
44 #define JPGD_MAXBLOCKSPERROW 6144
45 //------------------------------------------------------------------------------
46 // Max. allocated blocks
47 #define JPGD_MAXBLOCKS    100
48 //------------------------------------------------------------------------------
49 #define JPGD_MAX_HEIGHT 8192
50 #define JPGD_MAX_WIDTH  8192
51 //------------------------------------------------------------------------------
52 /* JPEG specific errors */
53 #define JPGD_BAD_DHT_COUNTS              -200
54 #define JPGD_BAD_DHT_INDEX               -201
55 #define JPGD_BAD_DHT_MARKER              -202
56 #define JPGD_BAD_DQT_MARKER              -203
57 #define JPGD_BAD_DQT_TABLE               -204
58 #define JPGD_BAD_PRECISION               -205
59 #define JPGD_BAD_HEIGHT                  -206
60 #define JPGD_BAD_WIDTH                   -207
61 #define JPGD_TOO_MANY_COMPONENTS         -208
62 #define JPGD_BAD_SOF_LENGTH              -209
63 #define JPGD_BAD_VARIABLE_MARKER         -210
64 #define JPGD_BAD_DRI_LENGTH              -211
65 #define JPGD_BAD_SOS_LENGTH              -212
66 #define JPGD_BAD_SOS_COMP_ID             -213
67 #define JPGD_W_EXTRA_BYTES_BEFORE_MARKER -214
68 #define JPGD_NO_ARITHMITIC_SUPPORT       -215
69 #define JPGD_UNEXPECTED_MARKER           -216
70 #define JPGD_NOT_JPEG                    -217
71 #define JPGD_UNSUPPORTED_MARKER          -218
72 #define JPGD_BAD_DQT_LENGTH              -219
73 #define JPGD_TOO_MANY_BLOCKS             -221
74 #define JPGD_UNDEFINED_QUANT_TABLE       -222
75 #define JPGD_UNDEFINED_HUFF_TABLE        -223
76 #define JPGD_NOT_SINGLE_SCAN             -224
77 #define JPGD_UNSUPPORTED_COLORSPACE      -225
78 #define JPGD_UNSUPPORTED_SAMP_FACTORS    -226
79 #define JPGD_DECODE_ERROR                -227
80 #define JPGD_BAD_RESTART_MARKER          -228
81 #define JPGD_ASSERTION_ERROR             -229
82 #define JPGD_BAD_SOS_SPECTRAL            -230
83 #define JPGD_BAD_SOS_SUCCESSIVE          -231
84 #define JPGD_STREAM_READ                 -232
85 #define JPGD_NOTENOUGHMEM                -233
86 //------------------------------------------------------------------------------
87 #define JPGD_GRAYSCALE 0
88 #define JPGD_YH1V1     1
89 #define JPGD_YH2V1     2
90 #define JPGD_YH1V2     3
91 #define JPGD_YH2V2     4
92 //------------------------------------------------------------------------------
93 const int JPGD_FAILED = -1;
94 const int JPGD_DONE = 1;
95 const int JPGD_OKAY = 0;
96 //------------------------------------------------------------------------------
97 typedef enum
98 {
99   M_SOF0  = 0xC0,
100   M_SOF1  = 0xC1,
101   M_SOF2  = 0xC2,
102   M_SOF3  = 0xC3,
103 
104   M_SOF5  = 0xC5,
105   M_SOF6  = 0xC6,
106   M_SOF7  = 0xC7,
107 
108   M_JPG   = 0xC8,
109   M_SOF9  = 0xC9,
110   M_SOF10 = 0xCA,
111   M_SOF11 = 0xCB,
112 
113   M_SOF13 = 0xCD,
114   M_SOF14 = 0xCE,
115   M_SOF15 = 0xCF,
116 
117   M_DHT   = 0xC4,
118 
119   M_DAC   = 0xCC,
120 
121   M_RST0  = 0xD0,
122   M_RST1  = 0xD1,
123   M_RST2  = 0xD2,
124   M_RST3  = 0xD3,
125   M_RST4  = 0xD4,
126   M_RST5  = 0xD5,
127   M_RST6  = 0xD6,
128   M_RST7  = 0xD7,
129 
130   M_SOI   = 0xD8,
131   M_EOI   = 0xD9,
132   M_SOS   = 0xDA,
133   M_DQT   = 0xDB,
134   M_DNL   = 0xDC,
135   M_DRI   = 0xDD,
136   M_DHP   = 0xDE,
137   M_EXP   = 0xDF,
138 
139   M_APP0  = 0xE0,
140   M_APP15 = 0xEF,
141 
142   M_JPG0  = 0xF0,
143   M_JPG13 = 0xFD,
144   M_COM   = 0xFE,
145 
146   M_TEM   = 0x01,
147 
148   M_ERROR = 0x100
149 } JPEG_MARKER;
150 //------------------------------------------------------------------------------
151 #define RST0 0xD0
152 //------------------------------------------------------------------------------
153 typedef struct huff_tables_tag
154 {
155   uint  look_up[256];
156   uchar code_size[256];
157   // FIXME: Is 512 tree entries really enough to handle _all_ possible
158   // code sets? I think so but not 100% positive.
159   uint  tree[512];
160 } huff_tables_t, *Phuff_tables_t;
161 //------------------------------------------------------------------------------
162 typedef struct coeff_buf_tag
163 {
164   uchar *Pdata;
165 
166   int block_num_x, block_num_y;
167   int block_len_x, block_len_y;
168 
169   int block_size;
170 
171 } coeff_buf_t, *Pcoeff_buf_t;
172 //------------------------------------------------------------------------------
173 class jpeg_decoder;
174 typedef void (*Pdecode_block_func)(jpeg_decoder *, int, int, int);
175 //------------------------------------------------------------------------------
176 class progressive_block_decoder
177 {
178 public:
179   static void decode_block_dc_first(
180     jpeg_decoder *Pd,
181     int component_id, int block_x, int block_y);
182   static void decode_block_dc_refine(
183     jpeg_decoder *Pd,
184     int component_id, int block_x, int block_y);
185   static void decode_block_ac_first(
186     jpeg_decoder *Pd,
187     int component_id, int block_x, int block_y);
188   static void decode_block_ac_refine(
189     jpeg_decoder *Pd,
190     int component_id, int block_x, int block_y);
191 };
192 //------------------------------------------------------------------------------
193 // Input stream interface.
194 // Derive from this class to fetch input data from sources other than
195 // files. An important requirement is that you *must* set eof_flag to true
196 // when no more data is available to fetch!
197 // The decoder is rather "greedy": it will keep on calling this method until
198 // its internal input buffer is full, or until the EOF flag is set.
199 // It the input stream contains data after the JPEG stream's EOI (end of
200 // image) marker it will probably be pulled into the internal buffer.
201 // Call the get_total_bytes_read() method to determine the true
202 // size of the JPEG stream.
203 class jpeg_decoder_stream
204 {
205 public:
206 
jpeg_decoder_stream()207   jpeg_decoder_stream()
208   {
209   }
210 
~jpeg_decoder_stream()211   virtual ~jpeg_decoder_stream()
212   {
213   }
214 
215   // The read() method is called when the internal input buffer is empty.
216   // Pbuf - input buffer
217   // max_bytes_to_read - maximum bytes that can be written to Pbuf
218   // Peof_flag - set this to true if at end of stream (no more bytes remaining)
219   // Return -1 on error, otherwise return the number of bytes actually
220   // written to the buffer (which may be 0).
221   // Notes: This method will be called in a loop until you set *Peof_flag to
222   // true or the internal buffer is full.
223   // The MMX state will be automatically saved/restored before this method is
224   // called, unlike previous versions.
225   virtual int read(uchar *Pbuf, int max_bytes_to_read, bool *Peof_flag) = 0;
226 
attach(void)227   virtual void attach(void)
228   {
229   }
230 
detach(void)231   virtual void detach(void)
232   {
233   }
234 };
235 //------------------------------------------------------------------------------
236 typedef jpeg_decoder_stream *Pjpeg_decoder_stream;
237 //------------------------------------------------------------------------------
238 // Here's an example FILE stream class.
239 class jpeg_decoder_file_stream : public jpeg_decoder_stream
240 {
241   FILE *Pfile;
242   bool   eof_flag, error_flag;
243 
244 public:
245 
jpeg_decoder_file_stream()246   jpeg_decoder_file_stream()
247   {
248     Pfile = NULL;
249     eof_flag = false;
250     error_flag = false;
251   }
252 
close(void)253   void close(void)
254   {
255     if (Pfile)
256     {
257       fclose(Pfile);
258       Pfile = NULL;
259     }
260 
261     eof_flag = false;
262     error_flag = false;
263   }
264 
~jpeg_decoder_file_stream()265   virtual ~jpeg_decoder_file_stream()
266   {
267     close();
268   }
269 
open(const char * Pfilename)270   bool open(const char *Pfilename)
271   {
272     close();
273 
274     eof_flag = false;
275     error_flag = false;
276 
277 
278     Pfile=fopen(Pfilename,"rb");
279 
280     if (Pfile==NULL) {
281       return (true);
282 	}
283 
284     return (false);
285   }
286 
read(uchar * Pbuf,int max_bytes_to_read,bool * Peof_flag)287   virtual int read(uchar *Pbuf, int max_bytes_to_read, bool *Peof_flag)
288   {
289 
290     if (!Pfile)
291       return (-1);
292 
293     if (eof_flag)
294     {
295       *Peof_flag = true;
296       return (0);
297     }
298 
299     if (error_flag)
300       return (-1);
301 
302 	unsigned long bytes_read=0;
303 	bytes_read = (unsigned long)fread(Pbuf, 1, max_bytes_to_read, Pfile);
304 
305     if ((int)bytes_read < max_bytes_to_read)
306     {
307       eof_flag = true;
308       *Peof_flag = true;
309     }
310 
311     return ((int)bytes_read);
312   }
313 
get_error_status(void)314   bool get_error_status(void)
315   {
316     return (error_flag);
317   }
318 
319 };
320 //------------------------------------------------------------------------------
321 typedef jpeg_decoder_file_stream *Pjpeg_decoder_file_stream;
322 //------------------------------------------------------------------------------
323 #define QUANT_TYPE int16
324 #define BLOCK_TYPE int16
325 //------------------------------------------------------------------------------
326 // Disable no return value warning, for rol() method
327 #pragma warning(push)
328 #pragma warning( disable : 4035 4799 )
329 //------------------------------------------------------------------------------
330 class jpeg_decoder
331 {
332   friend class progressive_block_decoder;
333 
334 private:
335 
336   void free_all_blocks(void);
337 
338   void terminate(int status);
339 
340   void *alloc(int n);
341 
342   void word_clear(void *p, ushort c, uint n);
343 
344   void prep_in_buffer(void);
345 
346   void read_dht_marker(void);
347 
348   void read_dqt_marker(void);
349 
350   void read_sof_marker(void);
351 
352   void skip_variable_marker(void);
353 
354   void read_dri_marker(void);
355 
356   void read_sos_marker(void);
357 
358   int next_marker(void);
359 
360   int process_markers(void);
361 
362   void locate_soi_marker(void);
363 
364   void locate_sof_marker(void);
365 
366   int locate_sos_marker(void);
367 
368   void init(Pjpeg_decoder_stream Pstream, bool use_mmx);
369 
370   void create_look_ups(void);
371 
372   void fix_in_buffer(void);
373 
374   void transform_row(void);
375 
376   Pcoeff_buf_t coeff_buf_open(
377     int block_num_x, int block_num_y,
378     int block_len_x, int block_len_y);
379 
380   void coeff_buf_read(
381     Pcoeff_buf_t cb,
382     int block_x, int block_y,
383     BLOCK_TYPE *buffer);
384 
385   void coeff_buf_write(
386     Pcoeff_buf_t cb,
387     int block_x, int block_y,
388     BLOCK_TYPE *buffer);
389 
390   BLOCK_TYPE *coeff_buf_getp(
391     Pcoeff_buf_t cb,
392     int block_x, int block_y);
393 
394   void load_next_row(void);
395 
396   void decode_next_row(void);
397 #ifdef SUPPORT_MMX
398   void decode_next_row_mmx(void);
399 #endif
400 
401   void make_huff_table(
402     int index,
403     Phuff_tables_t hs);
404 
405   void check_quant_tables(void);
406 
407   void check_huff_tables(void);
408 
409   void calc_mcu_block_order(void);
410 
411   int init_scan(void);
412 
413   void init_frame(void);
414 
415   void process_restart(void);
416 
417   void decode_scan(
418     Pdecode_block_func decode_block_func);
419 
420   void init_progressive(void);
421 
422   void init_sequential(void);
423 
424   void decode_start(void);
425 
426   void decode_init(Pjpeg_decoder_stream Pstream, bool use_mmx);
427 
428   void H2V2Convert(void);
429   void H2V1Convert(void);
430   void H1V2Convert(void);
431   void H1V1Convert(void);
432   void GrayConvert(void);
433 
434   void find_eoi(void);
435 //------------------
436   inline uint rol(uint i, uchar j);
437   inline uint get_char(void);
438   inline uint get_char(bool *Ppadding_flag);
439   inline void stuff_char(uchar q);
440   inline uchar get_octet(void);
441   inline uint get_bits_1(int num_bits);
442   inline uint get_bits_2(int numbits);
443   inline int huff_decode(Phuff_tables_t Ph);
444 #ifdef SUPPORT_X86ASM
445   inline uint huff_extend(uint i, int c);
446 #endif
447   inline uchar clamp(int i);
448 
449 #ifdef SUPPORT_MMX
450   inline uint get_high_byte_mmx(void);
451   inline uint get_high_word_mmx(void);
452   inline void get_bits_2_mmx_init(void);
453   inline void get_bits_2_mmx_deinit(void);
454   inline uint get_bits_2_mmx(int numbits);
455   inline int  huff_decode_mmx(Phuff_tables_t Ph);
456 #endif
457 //------------------
458   int   image_x_size;
459   int   image_y_size;
460 
461   Pjpeg_decoder_stream Pstream;
462 
463   int   progressive_flag;
464 
465   uchar *huff_num[JPGD_MAXHUFFTABLES];  /* pointer to number of Huffman codes per bit size */
466   uchar *huff_val[JPGD_MAXHUFFTABLES];  /* pointer to Huffman codes per bit size */
467 
468   QUANT_TYPE *quant[JPGD_MAXQUANTTABLES];    /* pointer to quantization tables */
469 
470   int   scan_type;                      /* Grey, Yh1v1, Yh1v2, Yh2v1, Yh2v2,
471                                            CMYK111, CMYK4114 */
472 
473   int   comps_in_frame;                 /* # of components in frame */
474   int   comp_h_samp[JPGD_MAXCOMPONENTS];     /* component's horizontal sampling factor */
475   int   comp_v_samp[JPGD_MAXCOMPONENTS];     /* component's vertical sampling factor */
476   int   comp_quant[JPGD_MAXCOMPONENTS];      /* component's quantization table selector */
477   int   comp_ident[JPGD_MAXCOMPONENTS];      /* component's ID */
478 
479   int   comp_h_blocks[JPGD_MAXCOMPONENTS];
480   int   comp_v_blocks[JPGD_MAXCOMPONENTS];
481 
482   int   comps_in_scan;                  /* # of components in scan */
483   int   comp_list[JPGD_MAXCOMPSINSCAN];      /* components in this scan */
484   int   comp_dc_tab[JPGD_MAXCOMPONENTS];     /* component's DC Huffman coding table selector */
485   int   comp_ac_tab[JPGD_MAXCOMPONENTS];     /* component's AC Huffman coding table selector */
486 
487   int   spectral_start;                 /* spectral selection start */
488   int   spectral_end;                   /* spectral selection end   */
489   int   successive_low;                 /* successive approximation low */
490   int   successive_high;                /* successive approximation high */
491 
492   int   max_mcu_x_size;                 /* MCU's max. X size in pixels */
493   int   max_mcu_y_size;                 /* MCU's max. Y size in pixels */
494 
495   int   blocks_per_mcu;
496   int   max_blocks_per_row;
497   int   mcus_per_row, mcus_per_col;
498 
499   int   mcu_org[JPGD_MAXBLOCKSPERMCU];
500 
501   int   total_lines_left;               /* total # lines left in image */
502   int   mcu_lines_left;                 /* total # lines left in this MCU */
503 
504   int   real_dest_bytes_per_scan_line;
505   int   dest_bytes_per_scan_line;        /* rounded up */
506   int   dest_bytes_per_pixel;            /* currently, 4 (RGB) or 1 (Y) */
507 
508   void  *blocks[JPGD_MAXBLOCKS];         /* list of all dynamically allocated blocks */
509 
510   Phuff_tables_t h[JPGD_MAXHUFFTABLES];
511 
512   Pcoeff_buf_t dc_coeffs[JPGD_MAXCOMPONENTS];
513   Pcoeff_buf_t ac_coeffs[JPGD_MAXCOMPONENTS];
514 
515   int eob_run;
516 
517   int block_y_mcu[JPGD_MAXCOMPONENTS];
518 
519   uchar *Pin_buf_ofs;
520   int in_buf_left;
521   int tem_flag;
522   bool eof_flag;
523 
524   uchar padd_1[128];
525   uchar in_buf[JPGD_INBUFSIZE + 128];
526   uchar padd_2[128];
527 
528   int   bits_left;
529   union
530   {
531     uint bit_buf;
532     uint bit_buf_64[2];
533   };
534 
535   uint  saved_mm1[2];
536 
537   bool  use_mmx_getbits;
538 
539   int   restart_interval;
540   int   restarts_left;
541   int   next_restart_num;
542 
543   int   max_mcus_per_row;
544   int   max_blocks_per_mcu;
545 
546   int   max_mcus_per_col;
547 
548   uint *component[JPGD_MAXBLOCKSPERMCU];   /* points into the lastdcvals table */
549   uint  last_dc_val[JPGD_MAXCOMPONENTS];
550 
551   Phuff_tables_t dc_huff_seg[JPGD_MAXBLOCKSPERMCU];
552   Phuff_tables_t ac_huff_seg[JPGD_MAXBLOCKSPERMCU];
553 
554   BLOCK_TYPE *block_seg[JPGD_MAXBLOCKSPERROW];
555   int   block_max_zag_set[JPGD_MAXBLOCKSPERROW];
556 
557   uchar *Psample_buf;
558   //int   block_num[JPGD_MAXBLOCKSPERROW];
559 
560   int   crr[256];
561   int   cbb[256];
562   int   padd;
563   long  crg[256];
564   long  cbg[256];
565 
566   uchar *scan_line_0;
567   uchar *scan_line_1;
568 
569   BLOCK_TYPE temp_block[64];
570 
571   bool use_mmx;
572   bool use_mmx_idct;
573   bool mmx_active;
574 
575   int error_code;
576   bool ready_flag;
577 
578   jmp_buf jmp_state;
579 
580   int total_bytes_read;
581 
582 public:
583 
584   // If SUPPORT_MMX is not defined, the use_mmx flag is ignored.
585   jpeg_decoder(Pjpeg_decoder_stream Pstream,
586                bool use_mmx);
587 
588   int begin(void);
589 
590   int decode(void * *Pscan_line_ofs, uint *Pscan_line_len);
591 
592   ~jpeg_decoder();
593 
get_error_code(void)594   int get_error_code(void)
595   {
596     return (error_code);
597   }
598 
get_width(void)599   int get_width(void)
600   {
601     return (image_x_size);
602   }
603 
get_height(void)604   int get_height(void)
605   {
606     return (image_y_size);
607   }
608 
get_num_components(void)609   int get_num_components(void)
610   {
611     return (comps_in_frame);
612   }
613 
get_bytes_per_pixel(void)614   int get_bytes_per_pixel(void)
615   {
616     return (dest_bytes_per_pixel);
617   }
618 
get_bytes_per_scan_line(void)619   int get_bytes_per_scan_line(void)
620   {
621     return (image_x_size * get_bytes_per_pixel());
622   }
623 
get_total_bytes_read(void)624   int get_total_bytes_read(void)
625   {
626     return (total_bytes_read);
627   }
628 };
629 //------------------------------------------------------------------------------
630 #include "jpegdecoder.inl"
631 //------------------------------------------------------------------------------
632 #pragma warning(pop)
633 //------------------------------------------------------------------------------
634 typedef jpeg_decoder *Pjpeg_decoder;
635 //------------------------------------------------------------------------------
636 // idct.cpp
637 void idct(BLOCK_TYPE *data, uchar *Pdst_ptr);
638 //------------------------------------------------------------------------------
639 // fidctfst.cpp
640 void jpeg_idct_ifast (
641   BLOCK_TYPE* inptr,
642   short *quantptr,
643   uchar * *outptr,
644   int output_col);
645 
646 void jpeg_idct_ifast_deinit(void);
647 
648 bool jpeg_idct_ifast_avail(void);
649 //------------------------------------------------------------------------------
650 #endif
651 //------------------------------------------------------------------------------
652 
653 typedef struct{
654   char FileName[512];     /* JPG file Name               */
655   int width;              /* Image width (pixels)        */
656   int height;             /* Image height (pixels)       */
657   char *data;		      /* Image data  24Bit BGR       */
658 } JPEG_IMAGE;
659 
660 extern char JpegErrorMessage[];
661 int LoadJpegImage(JPEG_IMAGE *d);
662