CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/ext/jpge/jpgd.h
Views: 1401
// jpgd.h - C++ class for JPEG decompression.1// Richard Geldreich <[email protected]>2// See jpgd.cpp for license (Public Domain or Apache 2.0).3#ifndef JPEG_DECODER_H4#define JPEG_DECODER_H56#include <stdlib.h>7#include <stdio.h>8#include <setjmp.h>9#include <assert.h>10#include <stdint.h>1112#ifdef _MSC_VER13#define JPGD_NORETURN __declspec(noreturn)14#elif defined(__GNUC__)15#define JPGD_NORETURN __attribute__ ((noreturn))16#else17#define JPGD_NORETURN18#endif1920#define JPGD_HUFF_TREE_MAX_LENGTH 51221#define JPGD_HUFF_CODE_SIZE_MAX_LENGTH 2562223namespace jpgd24{25typedef unsigned char uint8;26typedef signed short int16;27typedef unsigned short uint16;28typedef unsigned int uint;29typedef signed int int32;3031// Loads a JPEG image from a memory buffer or a file.32// req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA).33// 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).34// 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.35// 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.36unsigned 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);37unsigned char* decompress_jpeg_image_from_file(const char* pSrc_filename, int* width, int* height, int* actual_comps, int req_comps, uint32_t flags = 0);3839// Success/failure error codes.40enum jpgd_status41{42JPGD_SUCCESS = 0, JPGD_FAILED = -1, JPGD_DONE = 1,43JPGD_BAD_DHT_COUNTS = -256, JPGD_BAD_DHT_INDEX, JPGD_BAD_DHT_MARKER, JPGD_BAD_DQT_MARKER, JPGD_BAD_DQT_TABLE,44JPGD_BAD_PRECISION, JPGD_BAD_HEIGHT, JPGD_BAD_WIDTH, JPGD_TOO_MANY_COMPONENTS,45JPGD_BAD_SOF_LENGTH, JPGD_BAD_VARIABLE_MARKER, JPGD_BAD_DRI_LENGTH, JPGD_BAD_SOS_LENGTH,46JPGD_BAD_SOS_COMP_ID, JPGD_W_EXTRA_BYTES_BEFORE_MARKER, JPGD_NO_ARITHMITIC_SUPPORT, JPGD_UNEXPECTED_MARKER,47JPGD_NOT_JPEG, JPGD_UNSUPPORTED_MARKER, JPGD_BAD_DQT_LENGTH, JPGD_TOO_MANY_BLOCKS,48JPGD_UNDEFINED_QUANT_TABLE, JPGD_UNDEFINED_HUFF_TABLE, JPGD_NOT_SINGLE_SCAN, JPGD_UNSUPPORTED_COLORSPACE,49JPGD_UNSUPPORTED_SAMP_FACTORS, JPGD_DECODE_ERROR, JPGD_BAD_RESTART_MARKER,50JPGD_BAD_SOS_SPECTRAL, JPGD_BAD_SOS_SUCCESSIVE, JPGD_STREAM_READ, JPGD_NOTENOUGHMEM, JPGD_TOO_MANY_SCANS51};5253// Input stream interface.54// 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.55// 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.56// 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.57// Call the get_total_bytes_read() method to determine the actual size of the JPEG stream after successful decoding.58class jpeg_decoder_stream59{60public:61jpeg_decoder_stream() { }62virtual ~jpeg_decoder_stream() { }6364// The read() method is called when the internal input buffer is empty.65// Parameters:66// pBuf - input buffer67// max_bytes_to_read - maximum bytes that can be written to pBuf68// pEOF_flag - set this to true if at end of stream (no more bytes remaining)69// Returns -1 on error, otherwise return the number of bytes actually written to the buffer (which may be 0).70// Notes: This method will be called in a loop until you set *pEOF_flag to true or the internal buffer is full.71virtual int read(uint8* pBuf, int max_bytes_to_read, bool* pEOF_flag) = 0;72};7374// stdio FILE stream class.75class jpeg_decoder_file_stream : public jpeg_decoder_stream76{77jpeg_decoder_file_stream(const jpeg_decoder_file_stream&);78jpeg_decoder_file_stream& operator =(const jpeg_decoder_file_stream&);7980FILE* m_pFile;81bool m_eof_flag, m_error_flag;8283public:84jpeg_decoder_file_stream();85virtual ~jpeg_decoder_file_stream();8687bool open(const char* Pfilename);88void close();8990virtual int read(uint8* pBuf, int max_bytes_to_read, bool* pEOF_flag);91};9293// Memory stream class.94class jpeg_decoder_mem_stream : public jpeg_decoder_stream95{96const uint8* m_pSrc_data;97uint m_ofs, m_size;9899public:100jpeg_decoder_mem_stream() : m_pSrc_data(NULL), m_ofs(0), m_size(0) { }101jpeg_decoder_mem_stream(const uint8* pSrc_data, uint size) : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size) { }102103virtual ~jpeg_decoder_mem_stream() { }104105bool open(const uint8* pSrc_data, uint size);106void close() { m_pSrc_data = NULL; m_ofs = 0; m_size = 0; }107108virtual int read(uint8* pBuf, int max_bytes_to_read, bool* pEOF_flag);109};110111// Loads JPEG file from a jpeg_decoder_stream.112unsigned char* decompress_jpeg_image_from_stream(jpeg_decoder_stream* pStream, int* width, int* height, int* actual_comps, int req_comps, uint32_t flags = 0);113114enum115{116JPGD_IN_BUF_SIZE = 8192, JPGD_MAX_BLOCKS_PER_MCU = 10, JPGD_MAX_HUFF_TABLES = 8, JPGD_MAX_QUANT_TABLES = 4,117JPGD_MAX_COMPONENTS = 4, JPGD_MAX_COMPS_IN_SCAN = 4, JPGD_MAX_BLOCKS_PER_ROW = 16384, JPGD_MAX_HEIGHT = 32768, JPGD_MAX_WIDTH = 32768118};119120typedef int16 jpgd_quant_t;121typedef int16 jpgd_block_coeff_t;122123class jpeg_decoder124{125public:126enum127{128cFlagBoxChromaFiltering = 1,129cFlagDisableSIMD = 2130};131132// Call get_error_code() after constructing to determine if the stream is valid or not. You may call the get_width(), get_height(), etc.133// 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.134jpeg_decoder(jpeg_decoder_stream* pStream, uint32_t flags = 0);135136~jpeg_decoder();137138// Call this method after constructing the object to begin decompression.139// If JPGD_SUCCESS is returned you may then call decode() on each scanline.140141int begin_decoding();142143// Returns the next scan line.144// For grayscale images, pScan_line will point to a buffer containing 8-bit pixels (get_bytes_per_pixel() will return 1).145// 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).146// Returns JPGD_SUCCESS if a scan line has been returned.147// Returns JPGD_DONE if all scan lines have been returned.148// Returns JPGD_FAILED if an error occurred. Call get_error_code() for a more info.149int decode(const void** pScan_line, uint* pScan_line_len);150151inline jpgd_status get_error_code() const { return m_error_code; }152153inline int get_width() const { return m_image_x_size; }154inline int get_height() const { return m_image_y_size; }155156inline int get_num_components() const { return m_comps_in_frame; }157158inline int get_bytes_per_pixel() const { return m_dest_bytes_per_pixel; }159inline int get_bytes_per_scan_line() const { return m_image_x_size * get_bytes_per_pixel(); }160161// Returns the total number of bytes actually consumed by the decoder (which should equal the actual size of the JPEG file).162inline int get_total_bytes_read() const { return m_total_bytes_read; }163164private:165jpeg_decoder(const jpeg_decoder&);166jpeg_decoder& operator =(const jpeg_decoder&);167168typedef void (*pDecode_block_func)(jpeg_decoder*, int, int, int);169170struct huff_tables171{172bool ac_table;173uint look_up[256];174uint look_up2[256];175uint8 code_size[JPGD_HUFF_CODE_SIZE_MAX_LENGTH];176uint tree[JPGD_HUFF_TREE_MAX_LENGTH];177};178179struct coeff_buf180{181uint8* pData;182int block_num_x, block_num_y;183int block_len_x, block_len_y;184int block_size;185};186187struct mem_block188{189mem_block* m_pNext;190size_t m_used_count;191size_t m_size;192char m_data[1];193};194195jmp_buf m_jmp_state;196uint32_t m_flags;197mem_block* m_pMem_blocks;198int m_image_x_size;199int m_image_y_size;200jpeg_decoder_stream* m_pStream;201202int m_progressive_flag;203204uint8 m_huff_ac[JPGD_MAX_HUFF_TABLES];205uint8* m_huff_num[JPGD_MAX_HUFF_TABLES]; // pointer to number of Huffman codes per bit size206uint8* m_huff_val[JPGD_MAX_HUFF_TABLES]; // pointer to Huffman codes per bit size207jpgd_quant_t* m_quant[JPGD_MAX_QUANT_TABLES]; // pointer to quantization tables208int m_scan_type; // Gray, Yh1v1, Yh1v2, Yh2v1, Yh2v2 (CMYK111, CMYK4114 no longer supported)209int m_comps_in_frame; // # of components in frame210int m_comp_h_samp[JPGD_MAX_COMPONENTS]; // component's horizontal sampling factor211int m_comp_v_samp[JPGD_MAX_COMPONENTS]; // component's vertical sampling factor212int m_comp_quant[JPGD_MAX_COMPONENTS]; // component's quantization table selector213int m_comp_ident[JPGD_MAX_COMPONENTS]; // component's ID214int m_comp_h_blocks[JPGD_MAX_COMPONENTS];215int m_comp_v_blocks[JPGD_MAX_COMPONENTS];216int m_comps_in_scan; // # of components in scan217int m_comp_list[JPGD_MAX_COMPS_IN_SCAN]; // components in this scan218int m_comp_dc_tab[JPGD_MAX_COMPONENTS]; // component's DC Huffman coding table selector219int m_comp_ac_tab[JPGD_MAX_COMPONENTS]; // component's AC Huffman coding table selector220int m_spectral_start; // spectral selection start221int m_spectral_end; // spectral selection end222int m_successive_low; // successive approximation low223int m_successive_high; // successive approximation high224int m_max_mcu_x_size; // MCU's max. X size in pixels225int m_max_mcu_y_size; // MCU's max. Y size in pixels226int m_blocks_per_mcu;227int m_max_blocks_per_row;228int m_mcus_per_row, m_mcus_per_col;229int m_mcu_org[JPGD_MAX_BLOCKS_PER_MCU];230int m_total_lines_left; // total # lines left in image231int m_mcu_lines_left; // total # lines left in this MCU232int m_num_buffered_scanlines;233int m_real_dest_bytes_per_scan_line;234int m_dest_bytes_per_scan_line; // rounded up235int m_dest_bytes_per_pixel; // 4 (RGB) or 1 (Y)236huff_tables* m_pHuff_tabs[JPGD_MAX_HUFF_TABLES];237coeff_buf* m_dc_coeffs[JPGD_MAX_COMPONENTS];238coeff_buf* m_ac_coeffs[JPGD_MAX_COMPONENTS];239int m_eob_run;240int m_block_y_mcu[JPGD_MAX_COMPONENTS];241uint8* m_pIn_buf_ofs;242int m_in_buf_left;243int m_tem_flag;244245uint8 m_in_buf_pad_start[64];246uint8 m_in_buf[JPGD_IN_BUF_SIZE + 128];247uint8 m_in_buf_pad_end[64];248249int m_bits_left;250uint m_bit_buf;251int m_restart_interval;252int m_restarts_left;253int m_next_restart_num;254int m_max_mcus_per_row;255int m_max_blocks_per_mcu;256257int m_max_mcus_per_col;258uint m_last_dc_val[JPGD_MAX_COMPONENTS];259jpgd_block_coeff_t* m_pMCU_coefficients;260int m_mcu_block_max_zag[JPGD_MAX_BLOCKS_PER_MCU];261uint8* m_pSample_buf;262uint8* m_pSample_buf_prev;263int m_crr[256];264int m_cbb[256];265int m_crg[256];266int m_cbg[256];267uint8* m_pScan_line_0;268uint8* m_pScan_line_1;269jpgd_status m_error_code;270int m_total_bytes_read;271272bool m_ready_flag;273bool m_eof_flag;274bool m_sample_buf_prev_valid;275bool m_has_sse2;276277inline int check_sample_buf_ofs(int ofs) const { assert(ofs >= 0); assert(ofs < m_max_blocks_per_row * 64); return ofs; }278void free_all_blocks();279JPGD_NORETURN void stop_decoding(jpgd_status status);280void* alloc(size_t n, bool zero = false);281void* alloc_aligned(size_t nSize, uint32_t align = 16, bool zero = false);282void word_clear(void* p, uint16 c, uint n);283void prep_in_buffer();284void read_dht_marker();285void read_dqt_marker();286void read_sof_marker();287void skip_variable_marker();288void read_dri_marker();289void read_sos_marker();290int next_marker();291int process_markers();292void locate_soi_marker();293void locate_sof_marker();294int locate_sos_marker();295void init(jpeg_decoder_stream* pStream, uint32_t flags);296void create_look_ups();297void fix_in_buffer();298void transform_mcu(int mcu_row);299coeff_buf* coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y);300inline jpgd_block_coeff_t* coeff_buf_getp(coeff_buf* cb, int block_x, int block_y);301void load_next_row();302void decode_next_row();303void make_huff_table(int index, huff_tables* pH);304void check_quant_tables();305void check_huff_tables();306bool calc_mcu_block_order();307int init_scan();308void init_frame();309void process_restart();310void decode_scan(pDecode_block_func decode_block_func);311void init_progressive();312void init_sequential();313void decode_start();314void decode_init(jpeg_decoder_stream* pStream, uint32_t flags);315void H2V2Convert();316uint32_t H2V2ConvertFiltered();317void H2V1Convert();318void H2V1ConvertFiltered();319void H1V2Convert();320void H1V2ConvertFiltered();321void H1V1Convert();322void gray_convert();323void find_eoi();324inline uint get_char();325inline uint get_char(bool* pPadding_flag);326inline void stuff_char(uint8 q);327inline uint8 get_octet();328inline uint get_bits(int num_bits);329inline uint get_bits_no_markers(int numbits);330inline int huff_decode(huff_tables* pH);331inline int huff_decode(huff_tables* pH, int& extrabits);332333// Clamps a value between 0-255.334static inline uint8 clamp(int i)335{336if (static_cast<uint>(i) > 255)337i = (((~i) >> 31) & 0xFF);338return static_cast<uint8>(i);339}340int decode_next_mcu_row();341342static void decode_block_dc_first(jpeg_decoder* pD, int component_id, int block_x, int block_y);343static void decode_block_dc_refine(jpeg_decoder* pD, int component_id, int block_x, int block_y);344static void decode_block_ac_first(jpeg_decoder* pD, int component_id, int block_x, int block_y);345static void decode_block_ac_refine(jpeg_decoder* pD, int component_id, int block_x, int block_y);346};347348} // namespace jpgd349350#endif // JPEG_DECODER_H351352353