1 // jpgd.h - C++ class for JPEG decompression. 2 // Public domain, Rich Geldreich <richgel99@gmail.com> 3 #ifndef JPEG_DECODER_H 4 #define JPEG_DECODER_H 5 6 #include <stdlib.h> 7 #include <stdio.h> 8 #include <setjmp.h> 9 10 #ifdef _MSC_VER 11 #define JPGD_NORETURN __declspec(noreturn) 12 #elif defined(__GNUC__) 13 #define JPGD_NORETURN __attribute__ ((noreturn)) 14 #else 15 #define JPGD_NORETURN 16 #endif 17 18 namespace jpgd 19 { 20 typedef unsigned char uint8; 21 typedef signed short int16; 22 typedef unsigned short uint16; 23 typedef unsigned int uint; 24 typedef signed int int32; 25 26 // Loads a JPEG image from a memory buffer or a file. 27 // req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA). 28 // 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). 29 // 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. 30 // 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. 31 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); 32 unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps); 33 34 // Success/failure error codes. 35 enum jpgd_status 36 { 37 JPGD_SUCCESS = 0, JPGD_FAILED = -1, JPGD_DONE = 1, 38 JPGD_BAD_DHT_COUNTS = -256, JPGD_BAD_DHT_INDEX, JPGD_BAD_DHT_MARKER, JPGD_BAD_DQT_MARKER, JPGD_BAD_DQT_TABLE, 39 JPGD_BAD_PRECISION, JPGD_BAD_HEIGHT, JPGD_BAD_WIDTH, JPGD_TOO_MANY_COMPONENTS, 40 JPGD_BAD_SOF_LENGTH, JPGD_BAD_VARIABLE_MARKER, JPGD_BAD_DRI_LENGTH, JPGD_BAD_SOS_LENGTH, 41 JPGD_BAD_SOS_COMP_ID, JPGD_W_EXTRA_BYTES_BEFORE_MARKER, JPGD_NO_ARITHMITIC_SUPPORT, JPGD_UNEXPECTED_MARKER, 42 JPGD_NOT_JPEG, JPGD_UNSUPPORTED_MARKER, JPGD_BAD_DQT_LENGTH, JPGD_TOO_MANY_BLOCKS, 43 JPGD_UNDEFINED_QUANT_TABLE, JPGD_UNDEFINED_HUFF_TABLE, JPGD_NOT_SINGLE_SCAN, JPGD_UNSUPPORTED_COLORSPACE, 44 JPGD_UNSUPPORTED_SAMP_FACTORS, JPGD_DECODE_ERROR, JPGD_BAD_RESTART_MARKER, JPGD_ASSERTION_ERROR, 45 JPGD_BAD_SOS_SPECTRAL, JPGD_BAD_SOS_SUCCESSIVE, JPGD_STREAM_READ, JPGD_NOTENOUGHMEM 46 }; 47 48 // Input stream interface. 49 // 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. 50 // 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. 51 // 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. 52 // Call the get_total_bytes_read() method to determine the actual size of the JPEG stream after successful decoding. 53 class jpeg_decoder_stream 54 { 55 public: jpeg_decoder_stream()56 jpeg_decoder_stream() { } ~jpeg_decoder_stream()57 virtual ~jpeg_decoder_stream() { } 58 59 // The read() method is called when the internal input buffer is empty. 60 // Parameters: 61 // pBuf - input buffer 62 // max_bytes_to_read - maximum bytes that can be written to pBuf 63 // pEOF_flag - set this to true if at end of stream (no more bytes remaining) 64 // Returns -1 on error, otherwise return the number of bytes actually written to the buffer (which may be 0). 65 // Notes: This method will be called in a loop until you set *pEOF_flag to true or the internal buffer is full. 66 virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) = 0; 67 }; 68 69 // stdio FILE stream class. 70 class jpeg_decoder_file_stream : public jpeg_decoder_stream 71 { 72 jpeg_decoder_file_stream(const jpeg_decoder_file_stream &); 73 jpeg_decoder_file_stream &operator =(const jpeg_decoder_file_stream &); 74 75 FILE *m_pFile; 76 bool m_eof_flag, m_error_flag; 77 78 public: 79 jpeg_decoder_file_stream(); 80 virtual ~jpeg_decoder_file_stream(); 81 82 bool open(const char *Pfilename); 83 void close(); 84 85 virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag); 86 }; 87 88 // Memory stream class. 89 class jpeg_decoder_mem_stream : public jpeg_decoder_stream 90 { 91 const uint8 *m_pSrc_data; 92 uint m_ofs, m_size; 93 94 public: jpeg_decoder_mem_stream()95 jpeg_decoder_mem_stream() : m_pSrc_data(NULL), m_ofs(0), m_size(0) { } jpeg_decoder_mem_stream(const uint8 * pSrc_data,uint size)96 jpeg_decoder_mem_stream(const uint8 *pSrc_data, uint size) : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size) { } 97 ~jpeg_decoder_mem_stream()98 virtual ~jpeg_decoder_mem_stream() { } 99 100 bool open(const uint8 *pSrc_data, uint size); close()101 void close() { m_pSrc_data = NULL; m_ofs = 0; m_size = 0; } 102 103 virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag); 104 }; 105 106 // Loads JPEG file from a jpeg_decoder_stream. 107 unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps); 108 109 enum 110 { 111 JPGD_IN_BUF_SIZE = 8192, JPGD_MAX_BLOCKS_PER_MCU = 10, JPGD_MAX_HUFF_TABLES = 8, JPGD_MAX_QUANT_TABLES = 4, 112 JPGD_MAX_COMPONENTS = 4, JPGD_MAX_COMPS_IN_SCAN = 4, JPGD_MAX_BLOCKS_PER_ROW = 8192, JPGD_MAX_HEIGHT = 16384, JPGD_MAX_WIDTH = 16384 113 }; 114 115 typedef int16 jpgd_quant_t; 116 typedef int16 jpgd_block_t; 117 118 class jpeg_decoder 119 { 120 public: 121 // Call get_error_code() after constructing to determine if the stream is valid or not. You may call the get_width(), get_height(), etc. 122 // 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. 123 jpeg_decoder(jpeg_decoder_stream *pStream); 124 125 ~jpeg_decoder(); 126 127 // Call this method after constructing the object to begin decompression. 128 // If JPGD_SUCCESS is returned you may then call decode() on each scanline. 129 int begin_decoding(); 130 131 // Returns the next scan line. 132 // For grayscale images, pScan_line will point to a buffer containing 8-bit pixels (get_bytes_per_pixel() will return 1). 133 // 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). 134 // Returns JPGD_SUCCESS if a scan line has been returned. 135 // Returns JPGD_DONE if all scan lines have been returned. 136 // Returns JPGD_FAILED if an error occurred. Call get_error_code() for a more info. 137 int decode(const void** pScan_line, uint* pScan_line_len); 138 get_error_code()139 inline jpgd_status get_error_code() const { return m_error_code; } 140 get_width()141 inline int get_width() const { return m_image_x_size; } get_height()142 inline int get_height() const { return m_image_y_size; } 143 get_num_components()144 inline int get_num_components() const { return m_comps_in_frame; } 145 get_bytes_per_pixel()146 inline int get_bytes_per_pixel() const { return m_dest_bytes_per_pixel; } get_bytes_per_scan_line()147 inline int get_bytes_per_scan_line() const { return m_image_x_size * get_bytes_per_pixel(); } 148 149 // Returns the total number of bytes actually consumed by the decoder (which should equal the actual size of the JPEG file). get_total_bytes_read()150 inline int get_total_bytes_read() const { return m_total_bytes_read; } 151 152 private: 153 jpeg_decoder(const jpeg_decoder &); 154 jpeg_decoder &operator =(const jpeg_decoder &); 155 156 typedef void (*pDecode_block_func)(jpeg_decoder *, int, int, int); 157 158 struct huff_tables 159 { 160 bool ac_table; 161 uint look_up[256]; 162 uint look_up2[256]; 163 uint8 code_size[256]; 164 uint tree[512]; 165 }; 166 167 struct coeff_buf 168 { 169 uint8 *pData; 170 int block_num_x, block_num_y; 171 int block_len_x, block_len_y; 172 int block_size; 173 }; 174 175 struct mem_block 176 { 177 mem_block *m_pNext; 178 size_t m_used_count; 179 size_t m_size; 180 char m_data[1]; 181 }; 182 183 jmp_buf m_jmp_state; 184 mem_block *m_pMem_blocks; 185 int m_image_x_size; 186 int m_image_y_size; 187 jpeg_decoder_stream *m_pStream; 188 int m_progressive_flag; 189 uint8 m_huff_ac[JPGD_MAX_HUFF_TABLES]; 190 uint8* m_huff_num[JPGD_MAX_HUFF_TABLES]; // pointer to number of Huffman codes per bit size 191 uint8* m_huff_val[JPGD_MAX_HUFF_TABLES]; // pointer to Huffman codes per bit size 192 jpgd_quant_t* m_quant[JPGD_MAX_QUANT_TABLES]; // pointer to quantization tables 193 int m_scan_type; // Gray, Yh1v1, Yh1v2, Yh2v1, Yh2v2 (CMYK111, CMYK4114 no longer supported) 194 int m_comps_in_frame; // # of components in frame 195 int m_comp_h_samp[JPGD_MAX_COMPONENTS]; // component's horizontal sampling factor 196 int m_comp_v_samp[JPGD_MAX_COMPONENTS]; // component's vertical sampling factor 197 int m_comp_quant[JPGD_MAX_COMPONENTS]; // component's quantization table selector 198 int m_comp_ident[JPGD_MAX_COMPONENTS]; // component's ID 199 int m_comp_h_blocks[JPGD_MAX_COMPONENTS]; 200 int m_comp_v_blocks[JPGD_MAX_COMPONENTS]; 201 int m_comps_in_scan; // # of components in scan 202 int m_comp_list[JPGD_MAX_COMPS_IN_SCAN]; // components in this scan 203 int m_comp_dc_tab[JPGD_MAX_COMPONENTS]; // component's DC Huffman coding table selector 204 int m_comp_ac_tab[JPGD_MAX_COMPONENTS]; // component's AC Huffman coding table selector 205 int m_spectral_start; // spectral selection start 206 int m_spectral_end; // spectral selection end 207 int m_successive_low; // successive approximation low 208 int m_successive_high; // successive approximation high 209 int m_max_mcu_x_size; // MCU's max. X size in pixels 210 int m_max_mcu_y_size; // MCU's max. Y size in pixels 211 int m_blocks_per_mcu; 212 int m_max_blocks_per_row; 213 int m_mcus_per_row, m_mcus_per_col; 214 int m_mcu_org[JPGD_MAX_BLOCKS_PER_MCU]; 215 int m_total_lines_left; // total # lines left in image 216 int m_mcu_lines_left; // total # lines left in this MCU 217 int m_real_dest_bytes_per_scan_line; 218 int m_dest_bytes_per_scan_line; // rounded up 219 int m_dest_bytes_per_pixel; // 4 (RGB) or 1 (Y) 220 huff_tables* m_pHuff_tabs[JPGD_MAX_HUFF_TABLES]; 221 coeff_buf* m_dc_coeffs[JPGD_MAX_COMPONENTS]; 222 coeff_buf* m_ac_coeffs[JPGD_MAX_COMPONENTS]; 223 int m_eob_run; 224 int m_block_y_mcu[JPGD_MAX_COMPONENTS]; 225 uint8* m_pIn_buf_ofs; 226 int m_in_buf_left; 227 int m_tem_flag; 228 bool m_eof_flag; 229 uint8 m_in_buf_pad_start[128]; 230 uint8 m_in_buf[JPGD_IN_BUF_SIZE + 128]; 231 uint8 m_in_buf_pad_end[128]; 232 int m_bits_left; 233 uint m_bit_buf; 234 int m_restart_interval; 235 int m_restarts_left; 236 int m_next_restart_num; 237 int m_max_mcus_per_row; 238 int m_max_blocks_per_mcu; 239 int m_expanded_blocks_per_mcu; 240 int m_expanded_blocks_per_row; 241 int m_expanded_blocks_per_component; 242 bool m_freq_domain_chroma_upsample; 243 int m_max_mcus_per_col; 244 uint m_last_dc_val[JPGD_MAX_COMPONENTS]; 245 jpgd_block_t* m_pMCU_coefficients; 246 int m_mcu_block_max_zag[JPGD_MAX_BLOCKS_PER_MCU]; 247 uint8* m_pSample_buf; 248 int m_crr[256]; 249 int m_cbb[256]; 250 int m_crg[256]; 251 int m_cbg[256]; 252 uint8* m_pScan_line_0; 253 uint8* m_pScan_line_1; 254 jpgd_status m_error_code; 255 bool m_ready_flag; 256 int m_total_bytes_read; 257 258 void free_all_blocks(); 259 JPGD_NORETURN void stop_decoding(jpgd_status status); 260 void *alloc(size_t n, bool zero = false); 261 void word_clear(void *p, uint16 c, uint n); 262 void prep_in_buffer(); 263 void read_dht_marker(); 264 void read_dqt_marker(); 265 void read_sof_marker(); 266 void skip_variable_marker(); 267 void read_dri_marker(); 268 void read_sos_marker(); 269 int next_marker(); 270 int process_markers(); 271 void locate_soi_marker(); 272 void locate_sof_marker(); 273 int locate_sos_marker(); 274 void init(jpeg_decoder_stream * pStream); 275 void create_look_ups(); 276 void fix_in_buffer(); 277 void transform_mcu(int mcu_row); 278 void transform_mcu_expand(int mcu_row); 279 coeff_buf* coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y); 280 inline jpgd_block_t *coeff_buf_getp(coeff_buf *cb, int block_x, int block_y); 281 void load_next_row(); 282 void decode_next_row(); 283 void make_huff_table(int index, huff_tables *pH); 284 void check_quant_tables(); 285 void check_huff_tables(); 286 void calc_mcu_block_order(); 287 int init_scan(); 288 void init_frame(); 289 void process_restart(); 290 void decode_scan(pDecode_block_func decode_block_func); 291 void init_progressive(); 292 void init_sequential(); 293 void decode_start(); 294 void decode_init(jpeg_decoder_stream * pStream); 295 void H2V2Convert(); 296 void H2V1Convert(); 297 void H1V2Convert(); 298 void H1V1Convert(); 299 void gray_convert(); 300 void expanded_convert(); 301 void find_eoi(); 302 inline uint get_char(); 303 inline uint get_char(bool *pPadding_flag); 304 inline void stuff_char(uint8 q); 305 inline uint8 get_octet(); 306 inline uint get_bits(int num_bits); 307 inline uint get_bits_no_markers(int numbits); 308 inline int huff_decode(huff_tables *pH); 309 inline int huff_decode(huff_tables *pH, int& extrabits); 310 static inline uint8 clamp(int i); 311 static void decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y); 312 static void decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y); 313 static void decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y); 314 static void decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y); 315 }; 316 317 } // namespace jpgd 318 319 #endif // JPEG_DECODER_H 320