]> git.cworth.org Git - vogl/blob - src/voglcore/vogl_jpgd.h
Initial vogl checkin
[vogl] / src / voglcore / vogl_jpgd.h
1 /**************************************************************************
2  *
3  * Copyright 2013-2014 RAD Game Tools and Valve Software
4  * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  *
25  **************************************************************************/
26
27 // jpgd.h - C++ class for JPEG decompression.
28 // Public domain, Rich Geldreich <richgel99@gmail.com>
29 #ifndef JPEG_DECODER_H
30 #define JPEG_DECODER_H
31
32 #include "vogl_core.h"
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <setjmp.h>
36
37 #ifdef _MSC_VER
38 #define JPGD_NORETURN __declspec(noreturn)
39 #elif defined(__GNUC__)
40 #define JPGD_NORETURN __attribute__((noreturn))
41 #else
42 #define JPGD_NORETURN
43 #endif
44
45 namespace jpgd
46 {
47     typedef unsigned char uint8;
48     typedef signed short int16;
49     typedef unsigned short uint16;
50     typedef unsigned int uint;
51     typedef signed int int32;
52
53     // Loads a JPEG image from a memory buffer or a file.
54     // req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA).
55     // On return, width/height will be set to the image's dimensions, and actual_comps will be set to the either 1 (grayscale) or 3 (RGB).
56     // Notes: For more control over where and how the source data is read, see the decompress_jpeg_image_from_stream() function below, or call the jpeg_decoder class directly.
57     // Requesting a 8 or 32bpp image is currently a little faster than 24bpp because the jpeg_decoder class itself currently always unpacks to either 8 or 32bpp.
58     unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps);
59     unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps);
60
61     // Success/failure error codes.
62     enum jpgd_status
63     {
64         JPGD_SUCCESS = 0,
65         JPGD_FAILED = -1,
66         JPGD_DONE = 1,
67         JPGD_BAD_DHT_COUNTS = -256,
68         JPGD_BAD_DHT_INDEX,
69         JPGD_BAD_DHT_MARKER,
70         JPGD_BAD_DQT_MARKER,
71         JPGD_BAD_DQT_TABLE,
72         JPGD_BAD_PRECISION,
73         JPGD_BAD_HEIGHT,
74         JPGD_BAD_WIDTH,
75         JPGD_TOO_MANY_COMPONENTS,
76         JPGD_BAD_SOF_LENGTH,
77         JPGD_BAD_VARIABLE_MARKER,
78         JPGD_BAD_DRI_LENGTH,
79         JPGD_BAD_SOS_LENGTH,
80         JPGD_BAD_SOS_COMP_ID,
81         JPGD_W_EXTRA_BYTES_BEFORE_MARKER,
82         JPGD_NO_ARITHMITIC_SUPPORT,
83         JPGD_UNEXPECTED_MARKER,
84         JPGD_NOT_JPEG,
85         JPGD_UNSUPPORTED_MARKER,
86         JPGD_BAD_DQT_LENGTH,
87         JPGD_TOO_MANY_BLOCKS,
88         JPGD_UNDEFINED_QUANT_TABLE,
89         JPGD_UNDEFINED_HUFF_TABLE,
90         JPGD_NOT_SINGLE_SCAN,
91         JPGD_UNSUPPORTED_COLORSPACE,
92         JPGD_UNSUPPORTED_SAMP_FACTORS,
93         JPGD_DECODE_ERROR,
94         JPGD_BAD_RESTART_MARKER,
95         JPGD_ASSERTION_ERROR,
96         JPGD_BAD_SOS_SPECTRAL,
97         JPGD_BAD_SOS_SUCCESSIVE,
98         JPGD_STREAM_READ,
99         JPGD_NOTENOUGHMEM
100     };
101
102     // Input stream interface.
103     // Derive from this class to read input data from sources other than files or memory. Set m_eof_flag to true when no more data is available.
104     // The decoder is rather greedy: it will keep on calling this method until its internal input buffer is full, or until the EOF flag is set.
105     // It the input stream contains data after the JPEG stream's EOI (end of image) marker it will probably be pulled into the internal buffer.
106     // Call the get_total_bytes_read() method to determine the actual size of the JPEG stream after successful decoding.
107     class jpeg_decoder_stream
108     {
109     public:
110         jpeg_decoder_stream()
111         {
112         }
113         virtual ~jpeg_decoder_stream()
114         {
115         }
116
117         // The read() method is called when the internal input buffer is empty.
118         // Parameters:
119         // pBuf - input buffer
120         // max_bytes_to_read - maximum bytes that can be written to pBuf
121         // pEOF_flag - set this to true if at end of stream (no more bytes remaining)
122         // Returns -1 on error, otherwise return the number of bytes actually written to the buffer (which may be 0).
123         // Notes: This method will be called in a loop until you set *pEOF_flag to true or the internal buffer is full.
124         virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) = 0;
125     };
126
127     // stdio FILE stream class.
128     class jpeg_decoder_file_stream : public jpeg_decoder_stream
129     {
130         jpeg_decoder_file_stream(const jpeg_decoder_file_stream &);
131         jpeg_decoder_file_stream &operator=(const jpeg_decoder_file_stream &);
132
133         FILE *m_pFile;
134         bool m_eof_flag, m_error_flag;
135
136     public:
137         jpeg_decoder_file_stream();
138         virtual ~jpeg_decoder_file_stream();
139
140         bool open(const char *Pfilename);
141         void close();
142
143         virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag);
144     };
145
146     // Memory stream class.
147     class jpeg_decoder_mem_stream : public jpeg_decoder_stream
148     {
149         const uint8 *m_pSrc_data;
150         uint m_ofs, m_size;
151
152     public:
153         jpeg_decoder_mem_stream()
154             : m_pSrc_data(NULL), m_ofs(0), m_size(0)
155         {
156         }
157         jpeg_decoder_mem_stream(const uint8 *pSrc_data, uint size)
158             : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size)
159         {
160         }
161
162         virtual ~jpeg_decoder_mem_stream()
163         {
164         }
165
166         bool open(const uint8 *pSrc_data, uint size);
167         void close()
168         {
169             m_pSrc_data = NULL;
170             m_ofs = 0;
171             m_size = 0;
172         }
173
174         virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag);
175     };
176
177     // Loads JPEG file from a jpeg_decoder_stream.
178     unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps);
179
180     enum
181     {
182         JPGD_IN_BUF_SIZE = 8192,
183         JPGD_MAX_BLOCKS_PER_MCU = 10,
184         JPGD_MAX_HUFF_TABLES = 8,
185         JPGD_MAX_QUANT_TABLES = 4,
186         JPGD_MAX_COMPONENTS = 4,
187         JPGD_MAX_COMPS_IN_SCAN = 4,
188         JPGD_MAX_BLOCKS_PER_ROW = 8192,
189         JPGD_MAX_HEIGHT = 16384,
190         JPGD_MAX_WIDTH = 16384
191     };
192
193     typedef int16 jpgd_quant_t;
194     typedef int16 jpgd_block_t;
195
196     class jpeg_decoder
197     {
198     public:
199         // Call get_error_code() after constructing to determine if the stream is valid or not. You may call the get_width(), get_height(), etc.
200         // methods after the constructor is called. You may then either destruct the object, or begin decoding the image by calling begin_decoding(), then decode() on each scanline.
201         jpeg_decoder(jpeg_decoder_stream *pStream);
202
203         ~jpeg_decoder();
204
205         // Call this method after constructing the object to begin decompression.
206         // If JPGD_SUCCESS is returned you may then call decode() on each scanline.
207         int begin_decoding();
208
209         // Returns the next scan line.
210         // For grayscale images, pScan_line will point to a buffer containing 8-bit pixels (get_bytes_per_pixel() will return 1).
211         // Otherwise, it will always point to a buffer containing 32-bit RGBA pixels (A will always be 255, and get_bytes_per_pixel() will return 4).
212         // Returns JPGD_SUCCESS if a scan line has been returned.
213         // Returns JPGD_DONE if all scan lines have been returned.
214         // Returns JPGD_FAILED if an error occurred. Call get_error_code() for a more info.
215         int decode(const void **pScan_line, uint *pScan_line_len);
216
217         inline jpgd_status get_error_code() const
218         {
219             return m_error_code;
220         }
221
222         inline int get_width() const
223         {
224             return m_image_x_size;
225         }
226         inline int get_height() const
227         {
228             return m_image_y_size;
229         }
230
231         inline int get_num_components() const
232         {
233             return m_comps_in_frame;
234         }
235
236         inline int get_bytes_per_pixel() const
237         {
238             return m_dest_bytes_per_pixel;
239         }
240         inline int get_bytes_per_scan_line() const
241         {
242             return m_image_x_size * get_bytes_per_pixel();
243         }
244
245         // Returns the total number of bytes actually consumed by the decoder (which should equal the actual size of the JPEG file).
246         inline int get_total_bytes_read() const
247         {
248             return m_total_bytes_read;
249         }
250
251     private:
252         jpeg_decoder(const jpeg_decoder &);
253         jpeg_decoder &operator=(const jpeg_decoder &);
254
255         typedef void (*pDecode_block_func)(jpeg_decoder *, int, int, int);
256
257         struct huff_tables
258         {
259             bool ac_table;
260             uint look_up[256];
261             uint look_up2[256];
262             uint8 code_size[256];
263             uint tree[512];
264         };
265
266         struct coeff_buf
267         {
268             uint8 *pData;
269             int block_num_x, block_num_y;
270             int block_len_x, block_len_y;
271             int block_size;
272         };
273
274         struct mem_block
275         {
276             mem_block *m_pNext;
277             size_t m_used_count;
278             size_t m_size;
279             char m_data[1];
280         };
281
282         jmp_buf m_jmp_state;
283         mem_block *m_pMem_blocks;
284         int m_image_x_size;
285         int m_image_y_size;
286         jpeg_decoder_stream *m_pStream;
287         int m_progressive_flag;
288         uint8 m_huff_ac[JPGD_MAX_HUFF_TABLES];
289         uint8 *m_huff_num[JPGD_MAX_HUFF_TABLES];      // pointer to number of Huffman codes per bit size
290         uint8 *m_huff_val[JPGD_MAX_HUFF_TABLES];      // pointer to Huffman codes per bit size
291         jpgd_quant_t *m_quant[JPGD_MAX_QUANT_TABLES]; // pointer to quantization tables
292         int m_scan_type;                              // Gray, Yh1v1, Yh1v2, Yh2v1, Yh2v2 (CMYK111, CMYK4114 no longer supported)
293         int m_comps_in_frame;                         // # of components in frame
294         int m_comp_h_samp[JPGD_MAX_COMPONENTS];       // component's horizontal sampling factor
295         int m_comp_v_samp[JPGD_MAX_COMPONENTS];       // component's vertical sampling factor
296         int m_comp_quant[JPGD_MAX_COMPONENTS];        // component's quantization table selector
297         int m_comp_ident[JPGD_MAX_COMPONENTS];        // component's ID
298         int m_comp_h_blocks[JPGD_MAX_COMPONENTS];
299         int m_comp_v_blocks[JPGD_MAX_COMPONENTS];
300         int m_comps_in_scan;                     // # of components in scan
301         int m_comp_list[JPGD_MAX_COMPS_IN_SCAN]; // components in this scan
302         int m_comp_dc_tab[JPGD_MAX_COMPONENTS];  // component's DC Huffman coding table selector
303         int m_comp_ac_tab[JPGD_MAX_COMPONENTS];  // component's AC Huffman coding table selector
304         int m_spectral_start;                    // spectral selection start
305         int m_spectral_end;                      // spectral selection end
306         int m_successive_low;                    // successive approximation low
307         int m_successive_high;                   // successive approximation high
308         int m_max_mcu_x_size;                    // MCU's max. X size in pixels
309         int m_max_mcu_y_size;                    // MCU's max. Y size in pixels
310         int m_blocks_per_mcu;
311         int m_max_blocks_per_row;
312         int m_mcus_per_row, m_mcus_per_col;
313         int m_mcu_org[JPGD_MAX_BLOCKS_PER_MCU];
314         int m_total_lines_left; // total # lines left in image
315         int m_mcu_lines_left;   // total # lines left in this MCU
316         int m_real_dest_bytes_per_scan_line;
317         int m_dest_bytes_per_scan_line; // rounded up
318         int m_dest_bytes_per_pixel;     // 4 (RGB) or 1 (Y)
319         huff_tables *m_pHuff_tabs[JPGD_MAX_HUFF_TABLES];
320         coeff_buf *m_dc_coeffs[JPGD_MAX_COMPONENTS];
321         coeff_buf *m_ac_coeffs[JPGD_MAX_COMPONENTS];
322         int m_eob_run;
323         int m_block_y_mcu[JPGD_MAX_COMPONENTS];
324         uint8 *m_pIn_buf_ofs;
325         int m_in_buf_left;
326         int m_tem_flag;
327         bool m_eof_flag;
328         uint8 m_in_buf_pad_start[128];
329         uint8 m_in_buf[JPGD_IN_BUF_SIZE + 128];
330         uint8 m_in_buf_pad_end[128];
331         int m_bits_left;
332         uint m_bit_buf;
333         int m_restart_interval;
334         int m_restarts_left;
335         int m_next_restart_num;
336         int m_max_mcus_per_row;
337         int m_max_blocks_per_mcu;
338         int m_expanded_blocks_per_mcu;
339         int m_expanded_blocks_per_row;
340         int m_expanded_blocks_per_component;
341         bool m_freq_domain_chroma_upsample;
342         int m_max_mcus_per_col;
343         uint m_last_dc_val[JPGD_MAX_COMPONENTS];
344         jpgd_block_t *m_pMCU_coefficients;
345         int m_mcu_block_max_zag[JPGD_MAX_BLOCKS_PER_MCU];
346         uint8 *m_pSample_buf;
347         int m_crr[256];
348         int m_cbb[256];
349         int m_crg[256];
350         int m_cbg[256];
351         uint8 *m_pScan_line_0;
352         uint8 *m_pScan_line_1;
353         jpgd_status m_error_code;
354         bool m_ready_flag;
355         int m_total_bytes_read;
356
357         void free_all_blocks();
358         JPGD_NORETURN void stop_decoding(jpgd_status status);
359         void *alloc(size_t n, bool zero = false);
360         void word_clear(void *p, uint16 c, uint n);
361         void prep_in_buffer();
362         void read_dht_marker();
363         void read_dqt_marker();
364         void read_sof_marker();
365         void skip_variable_marker();
366         void read_dri_marker();
367         void read_sos_marker();
368         int next_marker();
369         int process_markers();
370         void locate_soi_marker();
371         void locate_sof_marker();
372         int locate_sos_marker();
373         void init(jpeg_decoder_stream *pStream);
374         void create_look_ups();
375         void fix_in_buffer();
376         void transform_mcu(int mcu_row);
377         void transform_mcu_expand(int mcu_row);
378         coeff_buf *coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y);
379         inline jpgd_block_t *coeff_buf_getp(coeff_buf *cb, int block_x, int block_y);
380         void load_next_row();
381         void decode_next_row();
382         void make_huff_table(int index, huff_tables *pH);
383         void check_quant_tables();
384         void check_huff_tables();
385         void calc_mcu_block_order();
386         int init_scan();
387         void init_frame();
388         void process_restart();
389         void decode_scan(pDecode_block_func decode_block_func);
390         void init_progressive();
391         void init_sequential();
392         void decode_start();
393         void decode_init(jpeg_decoder_stream *pStream);
394         void H2V2Convert();
395         void H2V1Convert();
396         void H1V2Convert();
397         void H1V1Convert();
398         void gray_convert();
399         void expanded_convert();
400         void find_eoi();
401         inline uint get_char();
402         inline uint get_char(bool *pPadding_flag);
403         inline void stuff_char(uint8 q);
404         inline uint8 get_octet();
405         inline uint get_bits(int num_bits);
406         inline uint get_bits_no_markers(int numbits);
407         inline int huff_decode(huff_tables *pH);
408         inline int huff_decode(huff_tables *pH, int &extrabits);
409         static inline uint8 clamp(int i);
410         static void decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y);
411         static void decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y);
412         static void decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y);
413         static void decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y);
414     };
415
416 } // namespace jpgd
417
418 #endif // JPEG_DECODER_H