Path: blob/master/thirdparty/basis_universal/encoder/jpgd.h
9903 views
// jpgd.h - C++ class for JPEG decompression.1// Public domain, Rich Geldreich <[email protected]>2#ifndef JPEG_DECODER_H3#define JPEG_DECODER_H45#include <stdlib.h>6#include <stdio.h>7#include <setjmp.h>8#include <assert.h>9#include <stdint.h>1011#ifdef _MSC_VER12#define JPGD_NORETURN __declspec(noreturn)13#elif defined(__GNUC__)14#define JPGD_NORETURN __attribute__ ((noreturn))15#else16#define JPGD_NORETURN17#endif1819#define JPGD_HUFF_TREE_MAX_LENGTH 51220#define JPGD_HUFF_CODE_SIZE_MAX_LENGTH 2562122namespace jpgd23{24typedef unsigned char uint8;25typedef signed short int16;26typedef unsigned short uint16;27typedef unsigned int uint;28typedef signed int int32;2930// Loads a JPEG image from a memory buffer or a file.31// req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA).32// 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).33// 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.34// 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.35unsigned 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, uint32_t flags = 0);36unsigned char* decompress_jpeg_image_from_file(const char* pSrc_filename, int* width, int* height, int* actual_comps, int req_comps, uint32_t flags = 0);3738// Success/failure error codes.39enum jpgd_status40{41JPGD_SUCCESS = 0, JPGD_FAILED = -1, JPGD_DONE = 1,42JPGD_BAD_DHT_COUNTS = -256, JPGD_BAD_DHT_INDEX, JPGD_BAD_DHT_MARKER, JPGD_BAD_DQT_MARKER, JPGD_BAD_DQT_TABLE,43JPGD_BAD_PRECISION, JPGD_BAD_HEIGHT, JPGD_BAD_WIDTH, JPGD_TOO_MANY_COMPONENTS,44JPGD_BAD_SOF_LENGTH, JPGD_BAD_VARIABLE_MARKER, JPGD_BAD_DRI_LENGTH, JPGD_BAD_SOS_LENGTH,45JPGD_BAD_SOS_COMP_ID, JPGD_W_EXTRA_BYTES_BEFORE_MARKER, JPGD_NO_ARITHMITIC_SUPPORT, JPGD_UNEXPECTED_MARKER,46JPGD_NOT_JPEG, JPGD_UNSUPPORTED_MARKER, JPGD_BAD_DQT_LENGTH, JPGD_TOO_MANY_BLOCKS,47JPGD_UNDEFINED_QUANT_TABLE, JPGD_UNDEFINED_HUFF_TABLE, JPGD_NOT_SINGLE_SCAN, JPGD_UNSUPPORTED_COLORSPACE,48JPGD_UNSUPPORTED_SAMP_FACTORS, JPGD_DECODE_ERROR, JPGD_BAD_RESTART_MARKER,49JPGD_BAD_SOS_SPECTRAL, JPGD_BAD_SOS_SUCCESSIVE, JPGD_STREAM_READ, JPGD_NOTENOUGHMEM, JPGD_TOO_MANY_SCANS50};5152// Input stream interface.53// 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.54// 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.55// 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.56// Call the get_total_bytes_read() method to determine the actual size of the JPEG stream after successful decoding.57class jpeg_decoder_stream58{59public:60jpeg_decoder_stream() { }61virtual ~jpeg_decoder_stream() { }6263// The read() method is called when the internal input buffer is empty.64// Parameters:65// pBuf - input buffer66// max_bytes_to_read - maximum bytes that can be written to pBuf67// pEOF_flag - set this to true if at end of stream (no more bytes remaining)68// Returns -1 on error, otherwise return the number of bytes actually written to the buffer (which may be 0).69// Notes: This method will be called in a loop until you set *pEOF_flag to true or the internal buffer is full.70virtual int read(uint8* pBuf, int max_bytes_to_read, bool* pEOF_flag) = 0;71};7273// stdio FILE stream class.74class jpeg_decoder_file_stream : public jpeg_decoder_stream75{76jpeg_decoder_file_stream(const jpeg_decoder_file_stream&);77jpeg_decoder_file_stream& operator =(const jpeg_decoder_file_stream&);7879FILE* m_pFile;80bool m_eof_flag, m_error_flag;8182public:83jpeg_decoder_file_stream();84virtual ~jpeg_decoder_file_stream();8586bool open(const char* Pfilename);87void close();8889virtual int read(uint8* pBuf, int max_bytes_to_read, bool* pEOF_flag);90};9192// Memory stream class.93class jpeg_decoder_mem_stream : public jpeg_decoder_stream94{95const uint8* m_pSrc_data;96uint m_ofs, m_size;9798public:99jpeg_decoder_mem_stream() : m_pSrc_data(NULL), m_ofs(0), m_size(0) { }100jpeg_decoder_mem_stream(const uint8* pSrc_data, uint size) : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size) { }101102virtual ~jpeg_decoder_mem_stream() { }103104bool open(const uint8* pSrc_data, uint size);105void close() { m_pSrc_data = NULL; m_ofs = 0; m_size = 0; }106107virtual int read(uint8* pBuf, int max_bytes_to_read, bool* pEOF_flag);108};109110// Loads JPEG file from a jpeg_decoder_stream.111unsigned char* decompress_jpeg_image_from_stream(jpeg_decoder_stream* pStream, int* width, int* height, int* actual_comps, int req_comps, uint32_t flags = 0);112113enum114{115JPGD_IN_BUF_SIZE = 8192, JPGD_MAX_BLOCKS_PER_MCU = 10, JPGD_MAX_HUFF_TABLES = 8, JPGD_MAX_QUANT_TABLES = 4,116JPGD_MAX_COMPONENTS = 4, JPGD_MAX_COMPS_IN_SCAN = 4, JPGD_MAX_BLOCKS_PER_ROW = 16384, JPGD_MAX_HEIGHT = 32768, JPGD_MAX_WIDTH = 32768117};118119typedef int16 jpgd_quant_t;120typedef int16 jpgd_block_t;121122class jpeg_decoder123{124public:125enum126{127cFlagLinearChromaFiltering = 1128};129130// Call get_error_code() after constructing to determine if the stream is valid or not. You may call the get_width(), get_height(), etc.131// 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.132jpeg_decoder(jpeg_decoder_stream* pStream, uint32_t flags = cFlagLinearChromaFiltering);133134~jpeg_decoder();135136// Call this method after constructing the object to begin decompression.137// If JPGD_SUCCESS is returned you may then call decode() on each scanline.138139int begin_decoding();140141// Returns the next scan line.142// For grayscale images, pScan_line will point to a buffer containing 8-bit pixels (get_bytes_per_pixel() will return 1).143// 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).144// Returns JPGD_SUCCESS if a scan line has been returned.145// Returns JPGD_DONE if all scan lines have been returned.146// Returns JPGD_FAILED if an error occurred. Call get_error_code() for a more info.147int decode(const void** pScan_line, uint* pScan_line_len);148149inline jpgd_status get_error_code() const { return m_error_code; }150151inline int get_width() const { return m_image_x_size; }152inline int get_height() const { return m_image_y_size; }153154inline int get_num_components() const { return m_comps_in_frame; }155156inline int get_bytes_per_pixel() const { return m_dest_bytes_per_pixel; }157inline int get_bytes_per_scan_line() const { return m_image_x_size * get_bytes_per_pixel(); }158159// Returns the total number of bytes actually consumed by the decoder (which should equal the actual size of the JPEG file).160inline int get_total_bytes_read() const { return m_total_bytes_read; }161162private:163jpeg_decoder(const jpeg_decoder&);164jpeg_decoder& operator =(const jpeg_decoder&);165166typedef void (*pDecode_block_func)(jpeg_decoder*, int, int, int);167168struct huff_tables169{170bool ac_table;171uint look_up[256];172uint look_up2[256];173uint8 code_size[JPGD_HUFF_CODE_SIZE_MAX_LENGTH];174uint tree[JPGD_HUFF_TREE_MAX_LENGTH];175};176177struct coeff_buf178{179uint8* pData;180int block_num_x, block_num_y;181int block_len_x, block_len_y;182int block_size;183};184185struct mem_block186{187mem_block* m_pNext;188size_t m_used_count;189size_t m_size;190char m_data[1];191};192193jmp_buf m_jmp_state;194uint32_t m_flags;195mem_block* m_pMem_blocks;196int m_image_x_size;197int m_image_y_size;198jpeg_decoder_stream* m_pStream;199200int m_progressive_flag;201202uint8 m_huff_ac[JPGD_MAX_HUFF_TABLES];203uint8* m_huff_num[JPGD_MAX_HUFF_TABLES]; // pointer to number of Huffman codes per bit size204uint8* m_huff_val[JPGD_MAX_HUFF_TABLES]; // pointer to Huffman codes per bit size205jpgd_quant_t* m_quant[JPGD_MAX_QUANT_TABLES]; // pointer to quantization tables206int m_scan_type; // Gray, Yh1v1, Yh1v2, Yh2v1, Yh2v2 (CMYK111, CMYK4114 no longer supported)207int m_comps_in_frame; // # of components in frame208int m_comp_h_samp[JPGD_MAX_COMPONENTS]; // component's horizontal sampling factor209int m_comp_v_samp[JPGD_MAX_COMPONENTS]; // component's vertical sampling factor210int m_comp_quant[JPGD_MAX_COMPONENTS]; // component's quantization table selector211int m_comp_ident[JPGD_MAX_COMPONENTS]; // component's ID212int m_comp_h_blocks[JPGD_MAX_COMPONENTS];213int m_comp_v_blocks[JPGD_MAX_COMPONENTS];214int m_comps_in_scan; // # of components in scan215int m_comp_list[JPGD_MAX_COMPS_IN_SCAN]; // components in this scan216int m_comp_dc_tab[JPGD_MAX_COMPONENTS]; // component's DC Huffman coding table selector217int m_comp_ac_tab[JPGD_MAX_COMPONENTS]; // component's AC Huffman coding table selector218int m_spectral_start; // spectral selection start219int m_spectral_end; // spectral selection end220int m_successive_low; // successive approximation low221int m_successive_high; // successive approximation high222int m_max_mcu_x_size; // MCU's max. X size in pixels223int m_max_mcu_y_size; // MCU's max. Y size in pixels224int m_blocks_per_mcu;225int m_max_blocks_per_row;226int m_mcus_per_row, m_mcus_per_col;227int m_mcu_org[JPGD_MAX_BLOCKS_PER_MCU];228int m_total_lines_left; // total # lines left in image229int m_mcu_lines_left; // total # lines left in this MCU230int m_num_buffered_scanlines;231int m_real_dest_bytes_per_scan_line;232int m_dest_bytes_per_scan_line; // rounded up233int m_dest_bytes_per_pixel; // 4 (RGB) or 1 (Y)234huff_tables* m_pHuff_tabs[JPGD_MAX_HUFF_TABLES];235coeff_buf* m_dc_coeffs[JPGD_MAX_COMPONENTS];236coeff_buf* m_ac_coeffs[JPGD_MAX_COMPONENTS];237int m_eob_run;238int m_block_y_mcu[JPGD_MAX_COMPONENTS];239uint8* m_pIn_buf_ofs;240int m_in_buf_left;241int m_tem_flag;242243uint8 m_in_buf_pad_start[64];244uint8 m_in_buf[JPGD_IN_BUF_SIZE + 128];245uint8 m_in_buf_pad_end[64];246247int m_bits_left;248uint m_bit_buf;249int m_restart_interval;250int m_restarts_left;251int m_next_restart_num;252int m_max_mcus_per_row;253int m_max_blocks_per_mcu;254255int m_max_mcus_per_col;256uint m_last_dc_val[JPGD_MAX_COMPONENTS];257jpgd_block_t* m_pMCU_coefficients;258int m_mcu_block_max_zag[JPGD_MAX_BLOCKS_PER_MCU];259uint8* m_pSample_buf;260uint8* m_pSample_buf_prev;261int m_crr[256];262int m_cbb[256];263int m_crg[256];264int m_cbg[256];265uint8* m_pScan_line_0;266uint8* m_pScan_line_1;267jpgd_status m_error_code;268int m_total_bytes_read;269270bool m_ready_flag;271bool m_eof_flag;272bool m_sample_buf_prev_valid;273274inline int check_sample_buf_ofs(int ofs) const { assert(ofs >= 0); assert(ofs < m_max_blocks_per_row * 64); return ofs; }275void free_all_blocks();276JPGD_NORETURN void stop_decoding(jpgd_status status);277void* alloc(size_t n, bool zero = false);278void word_clear(void* p, uint16 c, uint n);279void prep_in_buffer();280void read_dht_marker();281void read_dqt_marker();282void read_sof_marker();283void skip_variable_marker();284void read_dri_marker();285void read_sos_marker();286int next_marker();287int process_markers();288void locate_soi_marker();289void locate_sof_marker();290int locate_sos_marker();291void init(jpeg_decoder_stream* pStream, uint32_t flags);292void create_look_ups();293void fix_in_buffer();294void transform_mcu(int mcu_row);295coeff_buf* coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y);296inline jpgd_block_t* coeff_buf_getp(coeff_buf* cb, int block_x, int block_y);297void load_next_row();298void decode_next_row();299void make_huff_table(int index, huff_tables* pH);300void check_quant_tables();301void check_huff_tables();302bool calc_mcu_block_order();303int init_scan();304void init_frame();305void process_restart();306void decode_scan(pDecode_block_func decode_block_func);307void init_progressive();308void init_sequential();309void decode_start();310void decode_init(jpeg_decoder_stream* pStream, uint32_t flags);311void H2V2Convert();312uint32_t H2V2ConvertFiltered();313void H2V1Convert();314void H2V1ConvertFiltered();315void H1V2Convert();316void H1V2ConvertFiltered();317void H1V1Convert();318void gray_convert();319void find_eoi();320inline uint get_char();321inline uint get_char(bool* pPadding_flag);322inline void stuff_char(uint8 q);323inline uint8 get_octet();324inline uint get_bits(int num_bits);325inline uint get_bits_no_markers(int numbits);326inline int huff_decode(huff_tables* pH);327inline int huff_decode(huff_tables* pH, int& extrabits);328329// Clamps a value between 0-255.330static inline uint8 clamp(int i)331{332if (static_cast<uint>(i) > 255)333i = (((~i) >> 31) & 0xFF);334return static_cast<uint8>(i);335}336int decode_next_mcu_row();337338static void decode_block_dc_first(jpeg_decoder* pD, int component_id, int block_x, int block_y);339static void decode_block_dc_refine(jpeg_decoder* pD, int component_id, int block_x, int block_y);340static void decode_block_ac_first(jpeg_decoder* pD, int component_id, int block_x, int block_y);341static void decode_block_ac_refine(jpeg_decoder* pD, int component_id, int block_x, int block_y);342};343344} // namespace jpgd345346#endif // JPEG_DECODER_H347348349