1 /**************************************************************************
3 * Copyright 2013-2014 RAD Game Tools and Valve Software
4 * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
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:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
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
25 **************************************************************************/
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
32 #include "vogl_core.h"
38 #define JPGD_NORETURN __declspec(noreturn)
39 #elif defined(__GNUC__)
40 #define JPGD_NORETURN __attribute__((noreturn))
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;
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);
61 // Success/failure error codes.
67 JPGD_BAD_DHT_COUNTS = -256,
75 JPGD_TOO_MANY_COMPONENTS,
77 JPGD_BAD_VARIABLE_MARKER,
81 JPGD_W_EXTRA_BYTES_BEFORE_MARKER,
82 JPGD_NO_ARITHMITIC_SUPPORT,
83 JPGD_UNEXPECTED_MARKER,
85 JPGD_UNSUPPORTED_MARKER,
88 JPGD_UNDEFINED_QUANT_TABLE,
89 JPGD_UNDEFINED_HUFF_TABLE,
91 JPGD_UNSUPPORTED_COLORSPACE,
92 JPGD_UNSUPPORTED_SAMP_FACTORS,
94 JPGD_BAD_RESTART_MARKER,
96 JPGD_BAD_SOS_SPECTRAL,
97 JPGD_BAD_SOS_SUCCESSIVE,
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
110 jpeg_decoder_stream()
113 virtual ~jpeg_decoder_stream()
117 // The read() method is called when the internal input buffer is empty.
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;
127 // stdio FILE stream class.
128 class jpeg_decoder_file_stream : public jpeg_decoder_stream
130 jpeg_decoder_file_stream(const jpeg_decoder_file_stream &);
131 jpeg_decoder_file_stream &operator=(const jpeg_decoder_file_stream &);
134 bool m_eof_flag, m_error_flag;
137 jpeg_decoder_file_stream();
138 virtual ~jpeg_decoder_file_stream();
140 bool open(const char *Pfilename);
143 virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag);
146 // Memory stream class.
147 class jpeg_decoder_mem_stream : public jpeg_decoder_stream
149 const uint8 *m_pSrc_data;
153 jpeg_decoder_mem_stream()
154 : m_pSrc_data(NULL), m_ofs(0), m_size(0)
157 jpeg_decoder_mem_stream(const uint8 *pSrc_data, uint size)
158 : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size)
162 virtual ~jpeg_decoder_mem_stream()
166 bool open(const uint8 *pSrc_data, uint size);
174 virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag);
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);
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
193 typedef int16 jpgd_quant_t;
194 typedef int16 jpgd_block_t;
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);
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();
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);
217 inline jpgd_status get_error_code() const
222 inline int get_width() const
224 return m_image_x_size;
226 inline int get_height() const
228 return m_image_y_size;
231 inline int get_num_components() const
233 return m_comps_in_frame;
236 inline int get_bytes_per_pixel() const
238 return m_dest_bytes_per_pixel;
240 inline int get_bytes_per_scan_line() const
242 return m_image_x_size * get_bytes_per_pixel();
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
248 return m_total_bytes_read;
252 jpeg_decoder(const jpeg_decoder &);
253 jpeg_decoder &operator=(const jpeg_decoder &);
255 typedef void (*pDecode_block_func)(jpeg_decoder *, int, int, int);
262 uint8 code_size[256];
269 int block_num_x, block_num_y;
270 int block_len_x, block_len_y;
283 mem_block *m_pMem_blocks;
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];
323 int m_block_y_mcu[JPGD_MAX_COMPONENTS];
324 uint8 *m_pIn_buf_ofs;
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];
333 int m_restart_interval;
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;
351 uint8 *m_pScan_line_0;
352 uint8 *m_pScan_line_1;
353 jpgd_status m_error_code;
355 int m_total_bytes_read;
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();
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();
388 void process_restart();
389 void decode_scan(pDecode_block_func decode_block_func);
390 void init_progressive();
391 void init_sequential();
393 void decode_init(jpeg_decoder_stream *pStream);
399 void expanded_convert();
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);
418 #endif // JPEG_DECODER_H