Skip to content
Myr

stb_image.c

This file

Path

deprecated/stb_image.c

4,678 lines · 145.5 KiB · C

Last changed by

Not known.

History of this file

Take it

1/* stb_image - v1.35 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c2   when you control the images you're loading3                                     no warranty implied; use at your own risk45   QUICK NOTES:6      Primarily of interest to game developers and other people who can7          avoid problematic images and only need the trivial interface89      JPEG baseline (no JPEG progressive)10      PNG 8-bit-per-channel only1112      TGA (not sure what subset, if a subset)13      BMP non-1bpp, non-RLE14      PSD (composited view only, no extra channels)1516      GIF (*comp always reports as 4-channel)17      HDR (radiance rgbE format)18      PIC (Softimage PIC)1920      - decode from memory or through FILE (define STBI_NO_STDIO to remove code)21      - decode from arbitrary I/O callbacks22      - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)2324   Latest revisions:25      1.35 (2014-05-27) warnings, bugfixes, TGA optimization, etc26      1.34 (unknown   ) warning fix27      1.33 (2011-07-14) minor fixes suggested by Dave Moore28      1.32 (2011-07-13) info support for all filetypes (SpartanJ)29      1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ)30      1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger)31      1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 32      1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)3334   See end of file for full revision history.3536   TODO:37      stbi_info support for BMP,PSD,HDR,PIC383940 ============================    Contributors    =========================41              42 Image formats                                Bug fixes & warning fixes43    Sean Barrett (jpeg, png, bmp)                Marc LeBlanc44    Nicolas Schulz (hdr, psd)                    Christpher Lloyd45    Jonathan Dummer (tga)                        Dave Moore46    Jean-Marc Lienher (gif)                      Won Chun47    Tom Seddon (pic)                             the Horde3D community48    Thatcher Ulrich (psd)                        Janez Zemva49                                                 Jonathan Blow50                                                 Laurent Gomila51 Extensions, features                            Aruelien Pocheville52    Jetro Lauha (stbi_info)                      Ryamond Barbiero53    James "moose2000" Brown (iPhone PNG)         David Woo54    Ben "Disch" Wenger (io callbacks)            Roy Eltham55    Martin "SpartanJ" Golini                     Luke Graham56                                                 Thomas Ruf57                                                 John Bartholomew58 Optimizations & bugfixes                        Ken Hamada59    Fabian "ryg" Giesen                          Cort Stratton60    Arseny Kapoulkine                            Blazej Dariusz Roszkowski61                                                 Thibault Reuille62 If your name should be here but                 Paul Du Bois63 isn't let Sean know.                            Guillaume George6465*/6667#ifndef STBI_INCLUDE_STB_IMAGE_H68#define STBI_INCLUDE_STB_IMAGE_H6970// To get a header file for this, either cut and paste the header,71// or create stb_image.h, #define STBI_HEADER_FILE_ONLY, and72// then include stb_image.c from it.7374////   begin header file  ////////////////////////////////////////////////////75//76// Limitations:77//    - no jpeg progressive support78//    - non-HDR formats support 8-bit samples only (jpeg, png)79//    - no delayed line count (jpeg) -- IJG doesn't support either80//    - no 1-bit BMP81//    - GIF always returns *comp=482//83// Basic usage (see HDR discussion below):84//    int x,y,n;85//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);86//    // ... process data if not NULL ... 87//    // ... x = width, y = height, n = # 8-bit components per pixel ...88//    // ... replace '0' with '1'..'4' to force that many components per pixel89//    // ... but 'n' will always be the number that it would have been if you said 090//    stbi_image_free(data)91//92// Standard parameters:93//    int *x       -- outputs image width in pixels94//    int *y       -- outputs image height in pixels95//    int *comp    -- outputs # of image components in image file96//    int req_comp -- if non-zero, # of image components requested in result97//98// The return value from an image loader is an 'unsigned char *' which points99// to the pixel data. The pixel data consists of *y scanlines of *x pixels,100// with each pixel consisting of N interleaved 8-bit components; the first101// pixel pointed to is top-left-most in the image. There is no padding between102// image scanlines or between pixels, regardless of format. The number of103// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.104// If req_comp is non-zero, *comp has the number of components that _would_105// have been output otherwise. E.g. if you set req_comp to 4, you will always106// get RGBA output, but you can check *comp to easily see if it's opaque.107//108// An output image with N components has the following components interleaved109// in this order in each pixel:110//111//     N=#comp     components112//       1           grey113//       2           grey, alpha114//       3           red, green, blue115//       4           red, green, blue, alpha116//117// If image loading fails for any reason, the return value will be NULL,118// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()119// can be queried for an extremely brief, end-user unfriendly explanation120// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid121// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly122// more user-friendly ones.123//124// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.125//126// ===========================================================================127//128// iPhone PNG support:129//130// By default we convert iphone-formatted PNGs back to RGB; nominally they131// would silently load as BGR, except the existing code should have just132// failed on such iPhone PNGs. But you can disable this conversion by133// by calling stbi_convert_iphone_png_to_rgb(0), in which case134// you will always just get the native iphone "format" through.135//136// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per137// pixel to remove any premultiplied alpha *only* if the image file explicitly138// says there's premultiplied data (currently only happens in iPhone images,139// and only if iPhone convert-to-rgb processing is on).140//141// ===========================================================================142//143// HDR image support   (disable by defining STBI_NO_HDR)144//145// stb_image now supports loading HDR images in general, and currently146// the Radiance .HDR file format, although the support is provided147// generically. You can still load any file through the existing interface;148// if you attempt to load an HDR file, it will be automatically remapped to149// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;150// both of these constants can be reconfigured through this interface:151//152//     stbi_hdr_to_ldr_gamma(2.2f);153//     stbi_hdr_to_ldr_scale(1.0f);154//155// (note, do not use _inverse_ constants; stbi_image will invert them156// appropriately).157//158// Additionally, there is a new, parallel interface for loading files as159// (linear) floats to preserve the full dynamic range:160//161//    float *data = stbi_loadf(filename, &x, &y, &n, 0);162// 163// If you load LDR images through this interface, those images will164// be promoted to floating point values, run through the inverse of165// constants corresponding to the above:166//167//     stbi_ldr_to_hdr_scale(1.0f);168//     stbi_ldr_to_hdr_gamma(2.2f);169//170// Finally, given a filename (or an open file or memory block--see header171// file for details) containing image data, you can query for the "most172// appropriate" interface to use (that is, whether the image is HDR or173// not), using:174//175//     stbi_is_hdr(char *filename);176//177// ===========================================================================178//179// I/O callbacks180//181// I/O callbacks allow you to read from arbitrary sources, like packaged182// files or some other source. Data read from callbacks are processed183// through a small internal buffer (currently 128 bytes) to try to reduce184// overhead. 185//186// The three functions you must define are "read" (reads some bytes of data),187// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).188189190#ifndef STBI_NO_STDIO191192#if defined(_MSC_VER) && _MSC_VER >= 1400193#define _CRT_SECURE_NO_WARNINGS // suppress warnings about fopen()194#pragma warning(push)195#pragma warning(disable:4996)   // suppress even more warnings about fopen()196#endif197#include <stdio.h>198#endif // STBI_NO_STDIO199200#define STBI_VERSION 1201202enum203{204   STBI_default = 0, // only used for req_comp205206   STBI_grey       = 1,207   STBI_grey_alpha = 2,208   STBI_rgb        = 3,209   STBI_rgb_alpha  = 4210};211212typedef unsigned char stbi_uc;213214#ifdef __cplusplus215extern "C" {216#endif217218//////////////////////////////////////////////////////////////////////////////219//220// PRIMARY API - works on images of any type221//222223//224// load image by filename, open file, or memory buffer225//226227extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);228229#ifndef STBI_NO_STDIO230extern stbi_uc *stbi_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);231extern stbi_uc *stbi_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);232// for stbi_load_from_file, file pointer is left pointing immediately after image233#endif234235typedef struct236{237   int      (*read)  (void *user,char *data,int size);   // fill 'data' with 'size' bytes.  return number of bytes actually read 238   void     (*skip)  (void *user,int n);                 // skip the next 'n' bytes, or 'unget' the last -n bytes if negative239   int      (*eof)   (void *user);                       // returns nonzero if we are at end of file/data240} stbi_io_callbacks;241242extern stbi_uc *stbi_load_from_callbacks  (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);243244#ifndef STBI_NO_HDR245   extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);246247   #ifndef STBI_NO_STDIO248   extern float *stbi_loadf            (char const *filename,   int *x, int *y, int *comp, int req_comp);249   extern float *stbi_loadf_from_file  (FILE *f,                int *x, int *y, int *comp, int req_comp);250   #endif251   252   extern float *stbi_loadf_from_callbacks  (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);253254   extern void   stbi_hdr_to_ldr_gamma(float gamma);255   extern void   stbi_hdr_to_ldr_scale(float scale);256257   extern void   stbi_ldr_to_hdr_gamma(float gamma);258   extern void   stbi_ldr_to_hdr_scale(float scale);259#endif // STBI_NO_HDR260261// stbi_is_hdr is always defined262extern int    stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);263extern int    stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);264#ifndef STBI_NO_STDIO265extern int      stbi_is_hdr          (char const *filename);266extern int      stbi_is_hdr_from_file(FILE *f);267#endif // STBI_NO_STDIO268269270// get a VERY brief reason for failure271// NOT THREADSAFE272extern const char *stbi_failure_reason  (void); 273274// free the loaded image -- this is just free()275extern void     stbi_image_free      (void *retval_from_stbi_load);276277// get image dimensions & components without fully decoding278extern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);279extern int      stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);280281#ifndef STBI_NO_STDIO282extern int      stbi_info            (char const *filename,     int *x, int *y, int *comp);283extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);284285#endif286287288289// for image formats that explicitly notate that they have premultiplied alpha,290// we just return the colors as stored in the file. set this flag to force291// unpremultiplication. results are undefined if the unpremultiply overflow.292extern void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);293294// indicate whether we should process iphone images back to canonical format,295// or just pass them through "as-is"296extern void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);297298299// ZLIB client - used by PNG, available for other purposes300301extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);302extern char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);303extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);304extern int   stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);305306extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);307extern int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);308309310// define faster low-level operations (typically SIMD support)311#ifdef STBI_SIMD312typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);313// compute an integer IDCT on "input"314//     input[x] = data[x] * dequantize[x]315//     write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'316//                             CLAMP results to 0..255317typedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const  *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step);318// compute a conversion from YCbCr to RGB319//     'count' pixels320//     write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B321//     y: Y input channel322//     cb: Cb input channel; scale/biased to be 0..255323//     cr: Cr input channel; scale/biased to be 0..255324325extern void stbi_install_idct(stbi_idct_8x8 func);326extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);327#endif // STBI_SIMD328329330#ifdef __cplusplus331}332#endif333334//335//336////   end header file   /////////////////////////////////////////////////////337#endif // STBI_INCLUDE_STB_IMAGE_H338339#ifndef STBI_HEADER_FILE_ONLY340341#ifndef STBI_NO_HDR342#include <math.h>  // ldexp343#include <string.h> // strcmp, strtok344#endif345346#ifndef STBI_NO_STDIO347#include <stdio.h>348#endif349#include <stdlib.h>350#include <memory.h>351#include <assert.h>352#include <stdarg.h>353#include <stddef.h> // ptrdiff_t on osx354355#ifndef _MSC_VER356   #ifdef __cplusplus357   #define stbi_inline inline358   #else359   #define stbi_inline360   #endif361#else362   #define stbi_inline __forceinline363#endif364365366#ifdef _MSC_VER367typedef unsigned char  stbi__uint8;368typedef unsigned short stbi__uint16;369typedef   signed short stbi__int16;370typedef unsigned int   stbi__uint32;371typedef   signed int   stbi__int32;372#else373#include <stdint.h>374typedef uint8_t  stbi__uint8;375typedef uint16_t stbi__uint16;376typedef int16_t  stbi__int16;377typedef uint32_t stbi__uint32;378typedef int32_t  stbi__int32;379#endif380381// should produce compiler error if size is wrong382typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];383384#ifdef _MSC_VER385#define STBI_NOTUSED(v)  (void)(v)386#else387#define STBI_NOTUSED(v)  (void)sizeof(v)388#endif389390#ifdef _MSC_VER391#define STBI_HAS_LROTL392#endif393394#ifdef STBI_HAS_LROTL395   #define stbi_lrot(x,y)  _lrotl(x,y)396#else397   #define stbi_lrot(x,y)  (((x) << (y)) | ((x) >> (32 - (y))))398#endif399400///////////////////////////////////////////////401//402//  stbi struct and start_xxx functions403404// stbi structure is our basic context used by all images, so it405// contains all the IO context, plus some basic image information406typedef struct407{408   stbi__uint32 img_x, img_y;409   int img_n, img_out_n;410   411   stbi_io_callbacks io;412   void *io_user_data;413414   int read_from_callbacks;415   int buflen;416   stbi__uint8 buffer_start[128];417418   stbi__uint8 *img_buffer, *img_buffer_end;419   stbi__uint8 *img_buffer_original;420} stbi;421422423static void refill_buffer(stbi *s);424425// initialize a memory-decode context426static void start_mem(stbi *s, stbi__uint8 const *buffer, int len)427{428   s->io.read = NULL;429   s->read_from_callbacks = 0;430   s->img_buffer = s->img_buffer_original = (stbi__uint8 *) buffer;431   s->img_buffer_end = (stbi__uint8 *) buffer+len;432}433434// initialize a callback-based context435static void start_callbacks(stbi *s, stbi_io_callbacks *c, void *user)436{437   s->io = *c;438   s->io_user_data = user;439   s->buflen = sizeof(s->buffer_start);440   s->read_from_callbacks = 1;441   s->img_buffer_original = s->buffer_start;442   refill_buffer(s);443}444445#ifndef STBI_NO_STDIO446447static int stdio_read(void *user, char *data, int size)448{449   return (int) fread(data,1,size,(FILE*) user);450}451452static void stdio_skip(void *user, int n)453{454   fseek((FILE*) user, n, SEEK_CUR);455}456457static int stdio_eof(void *user)458{459   return feof((FILE*) user);460}461462static stbi_io_callbacks stbi_stdio_callbacks =463{464   stdio_read,465   stdio_skip,466   stdio_eof,467};468469static void start_file(stbi *s, FILE *f)470{471   start_callbacks(s, &stbi_stdio_callbacks, (void *) f);472}473474//static void stop_file(stbi *s) { }475476#endif // !STBI_NO_STDIO477478static void stbi_rewind(stbi *s)479{480   // conceptually rewind SHOULD rewind to the beginning of the stream,481   // but we just rewind to the beginning of the initial buffer, because482   // we only use it after doing 'test', which only ever looks at at most 92 bytes483   s->img_buffer = s->img_buffer_original;484}485486static int      stbi_jpeg_test(stbi *s);487static stbi_uc *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp);488static int      stbi_jpeg_info(stbi *s, int *x, int *y, int *comp);489static int      stbi_png_test(stbi *s);490static stbi_uc *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp);491static int      stbi_png_info(stbi *s, int *x, int *y, int *comp);492static int      stbi_bmp_test(stbi *s);493static stbi_uc *stbi_bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp);494static int      stbi_tga_test(stbi *s);495static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp);496static int      stbi_tga_info(stbi *s, int *x, int *y, int *comp);497static int      stbi_psd_test(stbi *s);498static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp);499#ifndef STBI_NO_HDR500static int      stbi_hdr_test(stbi *s);501static float   *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);502#endif503static int      stbi_pic_test(stbi *s);504static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp);505static int      stbi_gif_test(stbi *s);506static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp);507static int      stbi_gif_info(stbi *s, int *x, int *y, int *comp);508509510// this is not threadsafe511static const char *failure_reason;512513const char *stbi_failure_reason(void)514{515   return failure_reason;516}517518static int e(const char *str)519{520   failure_reason = str;521   return 0;522}523524// e - error525// epf - error returning pointer to float526// epuc - error returning pointer to unsigned char527528#ifdef STBI_NO_FAILURE_STRINGS529   #define e(x,y)  0530#elif defined(STBI_FAILURE_USERMSG)531   #define e(x,y)  e(y)532#else533   #define e(x,y)  e(x)534#endif535536#define epf(x,y)   ((float *) (e(x,y)?NULL:NULL))537#define epuc(x,y)  ((unsigned char *) (e(x,y)?NULL:NULL))538539void stbi_image_free(void *retval_from_stbi_load)540{541   free(retval_from_stbi_load);542}543544#ifndef STBI_NO_HDR545static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);546static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp);547#endif548549static unsigned char *stbi_load_main(stbi *s, int *x, int *y, int *comp, int req_comp)550{551   if (stbi_jpeg_test(s)) return stbi_jpeg_load(s,x,y,comp,req_comp);552   if (stbi_png_test(s))  return stbi_png_load(s,x,y,comp,req_comp);553   if (stbi_bmp_test(s))  return stbi_bmp_load(s,x,y,comp,req_comp);554   if (stbi_gif_test(s))  return stbi_gif_load(s,x,y,comp,req_comp);555   if (stbi_psd_test(s))  return stbi_psd_load(s,x,y,comp,req_comp);556   if (stbi_pic_test(s))  return stbi_pic_load(s,x,y,comp,req_comp);557558   #ifndef STBI_NO_HDR559   if (stbi_hdr_test(s)) {560      float *hdr = stbi_hdr_load(s, x,y,comp,req_comp);561      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);562   }563   #endif564565   // test tga last because it's a crappy test!566   if (stbi_tga_test(s))567      return stbi_tga_load(s,x,y,comp,req_comp);568   return epuc("unknown image type", "Image not of any known type, or corrupt");569}570571#ifndef STBI_NO_STDIO572unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)573{574   FILE *f = fopen(filename, "rb");575   unsigned char *result;576   if (!f) return epuc("can't fopen", "Unable to open file");577   result = stbi_load_from_file(f,x,y,comp,req_comp);578   fclose(f);579   return result;580}581582unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)583{584   unsigned char *result;585   stbi s;586   start_file(&s,f);587   result = stbi_load_main(&s,x,y,comp,req_comp);588   if (result) {589      // need to 'unget' all the characters in the IO buffer590      fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);591   }592   return result;593}594#endif //!STBI_NO_STDIO595596unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)597{598   stbi s;599   start_mem(&s,buffer,len);600   return stbi_load_main(&s,x,y,comp,req_comp);601}602603unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)604{605   stbi s;606   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);607   return stbi_load_main(&s,x,y,comp,req_comp);608}609610#ifndef STBI_NO_HDR611612float *stbi_loadf_main(stbi *s, int *x, int *y, int *comp, int req_comp)613{614   unsigned char *data;615   #ifndef STBI_NO_HDR616   if (stbi_hdr_test(s))617      return stbi_hdr_load(s,x,y,comp,req_comp);618   #endif619   data = stbi_load_main(s, x, y, comp, req_comp);620   if (data)621      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);622   return epf("unknown image type", "Image not of any known type, or corrupt");623}624625float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)626{627   stbi s;628   start_mem(&s,buffer,len);629   return stbi_loadf_main(&s,x,y,comp,req_comp);630}631632float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)633{634   stbi s;635   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);636   return stbi_loadf_main(&s,x,y,comp,req_comp);637}638639#ifndef STBI_NO_STDIO640float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)641{642   FILE *f = fopen(filename, "rb");643   float *result;644   if (!f) return epf("can't fopen", "Unable to open file");645   result = stbi_loadf_from_file(f,x,y,comp,req_comp);646   fclose(f);647   return result;648}649650float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)651{652   stbi s;653   start_file(&s,f);654   return stbi_loadf_main(&s,x,y,comp,req_comp);655}656#endif // !STBI_NO_STDIO657658#endif // !STBI_NO_HDR659660// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is661// defined, for API simplicity; if STBI_NO_HDR is defined, it always662// reports false!663664int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)665{666   #ifndef STBI_NO_HDR667   stbi s;668   start_mem(&s,buffer,len);669   return stbi_hdr_test(&s);670   #else671   STBI_NOTUSED(buffer);672   STBI_NOTUSED(len);673   return 0;674   #endif675}676677#ifndef STBI_NO_STDIO678extern int      stbi_is_hdr          (char const *filename)679{680   FILE *f = fopen(filename, "rb");681   int result=0;682   if (f) {683      result = stbi_is_hdr_from_file(f);684      fclose(f);685   }686   return result;687}688689extern int      stbi_is_hdr_from_file(FILE *f)690{691   #ifndef STBI_NO_HDR692   stbi s;693   start_file(&s,f);694   return stbi_hdr_test(&s);695   #else696   return 0;697   #endif698}699#endif // !STBI_NO_STDIO700701extern int      stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)702{703   #ifndef STBI_NO_HDR704   stbi s;705   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);706   return stbi_hdr_test(&s);707   #else708   return 0;709   #endif710}711712#ifndef STBI_NO_HDR713static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;714static float l2h_gamma=2.2f, l2h_scale=1.0f;715716void   stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }717void   stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }718719void   stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }720void   stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }721#endif722723724//////////////////////////////////////////////////////////////////////////////725//726// Common code used by all image loaders727//728729enum730{731   SCAN_load=0,732   SCAN_type,733   SCAN_header734};735736static void refill_buffer(stbi *s)737{738   int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);739   if (n == 0) {740      // at end of file, treat same as if from memory, but need to handle case741      // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file742      s->read_from_callbacks = 0;743      s->img_buffer = s->buffer_start;744      s->img_buffer_end = s->buffer_start+1;745      *s->img_buffer = 0;746   } else {747      s->img_buffer = s->buffer_start;748      s->img_buffer_end = s->buffer_start + n;749   }750}751752stbi_inline static int get8(stbi *s)753{754   if (s->img_buffer < s->img_buffer_end)755      return *s->img_buffer++;756   if (s->read_from_callbacks) {757      refill_buffer(s);758      return *s->img_buffer++;759   }760   return 0;761}762763stbi_inline static int at_eof(stbi *s)764{765   if (s->io.read) {766      if (!(s->io.eof)(s->io_user_data)) return 0;767      // if feof() is true, check if buffer = end768      // special case: we've only got the special 0 character at the end769      if (s->read_from_callbacks == 0) return 1;770   }771772   return s->img_buffer >= s->img_buffer_end;   773}774775stbi_inline static stbi__uint8 get8u(stbi *s)776{777   return (stbi__uint8) get8(s);778}779780static void skip(stbi *s, int n)781{782   if (s->io.read) {783      int blen = (int) (s->img_buffer_end - s->img_buffer);784      if (blen < n) {785         s->img_buffer = s->img_buffer_end;786         (s->io.skip)(s->io_user_data, n - blen);787         return;788      }789   }790   s->img_buffer += n;791}792793static int getn(stbi *s, stbi_uc *buffer, int n)794{795   if (s->io.read) {796      int blen = (int) (s->img_buffer_end - s->img_buffer);797      if (blen < n) {798         int res, count;799800         memcpy(buffer, s->img_buffer, blen);801         802         count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);803         res = (count == (n-blen));804         s->img_buffer = s->img_buffer_end;805         return res;806      }807   }808809   if (s->img_buffer+n <= s->img_buffer_end) {810      memcpy(buffer, s->img_buffer, n);811      s->img_buffer += n;812      return 1;813   } else814      return 0;815}816817static int get16(stbi *s)818{819   int z = get8(s);820   return (z << 8) + get8(s);821}822823static stbi__uint32 get32(stbi *s)824{825   stbi__uint32 z = get16(s);826   return (z << 16) + get16(s);827}828829static int get16le(stbi *s)830{831   int z = get8(s);832   return z + (get8(s) << 8);833}834835static stbi__uint32 get32le(stbi *s)836{837   stbi__uint32 z = get16le(s);838   return z + (get16le(s) << 16);839}840841//////////////////////////////////////////////////////////////////////////////842//843//  generic converter from built-in img_n to req_comp844//    individual types do this automatically as much as possible (e.g. jpeg845//    does all cases internally since it needs to colorspace convert anyway,846//    and it never has alpha, so very few cases ). png can automatically847//    interleave an alpha=255 channel, but falls back to this for other cases848//849//  assume data buffer is malloced, so malloc a new one and free that one850//  only failure mode is malloc failing851852static stbi__uint8 compute_y(int r, int g, int b)853{854   return (stbi__uint8) (((r*77) + (g*150) +  (29*b)) >> 8);855}856857static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)858{859   int i,j;860   unsigned char *good;861862   if (req_comp == img_n) return data;863   assert(req_comp >= 1 && req_comp <= 4);864865   good = (unsigned char *) malloc(req_comp * x * y);866   if (good == NULL) {867      free(data);868      return epuc("outofmem", "Out of memory");869   }870871   for (j=0; j < (int) y; ++j) {872      unsigned char *src  = data + j * x * img_n   ;873      unsigned char *dest = good + j * x * req_comp;874875      #define COMBO(a,b)  ((a)*8+(b))876      #define CASE(a,b)   case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)877      // convert source image with img_n components to one with req_comp components;878      // avoid switch per pixel, so use switch per scanline and massive macros879      switch (COMBO(img_n, req_comp)) {880         CASE(1,2) dest[0]=src[0], dest[1]=255; break;881         CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;882         CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;883         CASE(2,1) dest[0]=src[0]; break;884         CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;885         CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;886         CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;887         CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;888         CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;889         CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;890         CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;891         CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;892         default: assert(0);893      }894      #undef CASE895   }896897   free(data);898   return good;899}900901#ifndef STBI_NO_HDR902static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)903{904   int i,k,n;905   float *output = (float *) malloc(x * y * comp * sizeof(float));906   if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }907   // compute number of non-alpha components908   if (comp & 1) n = comp; else n = comp-1;909   for (i=0; i < x*y; ++i) {910      for (k=0; k < n; ++k) {911         output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;912      }913      if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;914   }915   free(data);916   return output;917}918919#define float2int(x)   ((int) (x))920static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp)921{922   int i,k,n;923   stbi_uc *output = (stbi_uc *) malloc(x * y * comp);924   if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }925   // compute number of non-alpha components926   if (comp & 1) n = comp; else n = comp-1;927   for (i=0; i < x*y; ++i) {928      for (k=0; k < n; ++k) {929         float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;930         if (z < 0) z = 0;931         if (z > 255) z = 255;932         output[i*comp + k] = (stbi__uint8) float2int(z);933      }934      if (k < comp) {935         float z = data[i*comp+k] * 255 + 0.5f;936         if (z < 0) z = 0;937         if (z > 255) z = 255;938         output[i*comp + k] = (stbi__uint8) float2int(z);939      }940   }941   free(data);942   return output;943}944#endif945946//////////////////////////////////////////////////////////////////////////////947//948//  "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)949//950//    simple implementation951//      - channel subsampling of at most 2 in each dimension952//      - doesn't support delayed output of y-dimension953//      - simple interface (only one output format: 8-bit interleaved RGB)954//      - doesn't try to recover corrupt jpegs955//      - doesn't allow partial loading, loading multiple at once956//      - still fast on x86 (copying globals into locals doesn't help x86)957//      - allocates lots of intermediate memory (full size of all components)958//        - non-interleaved case requires this anyway959//        - allows good upsampling (see next)960//    high-quality961//      - upsampled channels are bilinearly interpolated, even across blocks962//      - quality integer IDCT derived from IJG's 'slow'963//    performance964//      - fast huffman; reasonable integer IDCT965//      - uses a lot of intermediate memory, could cache poorly966//      - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4967//          stb_jpeg:   1.34 seconds (MSVC6, default release build)968//          stb_jpeg:   1.06 seconds (MSVC6, processor = Pentium Pro)969//          IJL11.dll:  1.08 seconds (compiled by intel)970//          IJG 1998:   0.98 seconds (MSVC6, makefile provided by IJG)971//          IJG 1998:   0.95 seconds (MSVC6, makefile + proc=PPro)972973// huffman decoding acceleration974#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache975976typedef struct977{978   stbi__uint8  fast[1 << FAST_BITS];979   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win980   stbi__uint16 code[256];981   stbi__uint8  values[256];982   stbi__uint8  size[257];983   unsigned int maxcode[18];984   int    delta[17];   // old 'firstsymbol' - old 'firstcode'985} huffman;986987typedef struct988{989   #ifdef STBI_SIMD990   unsigned short dequant2[4][64];991   #endif992   stbi *s;993   huffman huff_dc[4];994   huffman huff_ac[4];995   stbi__uint8 dequant[4][64];996997// sizes for components, interleaved MCUs998   int img_h_max, img_v_max;999   int img_mcu_x, img_mcu_y;1000   int img_mcu_w, img_mcu_h;10011002// definition of jpeg image component1003   struct1004   {1005      int id;1006      int h,v;1007      int tq;1008      int hd,ha;1009      int dc_pred;10101011      int x,y,w2,h2;1012      stbi__uint8 *data;1013      void *raw_data;1014      stbi__uint8 *linebuf;1015   } img_comp[4];10161017   stbi__uint32         code_buffer; // jpeg entropy-coded buffer1018   int            code_bits;   // number of valid bits1019   unsigned char  marker;      // marker seen while filling entropy buffer1020   int            nomore;      // flag if we saw a marker so must stop10211022   int scan_n, order[4];1023   int restart_interval, todo;1024} jpeg;10251026static int build_huffman(huffman *h, int *count)1027{1028   int i,j,k=0,code;1029   // build size list for each symbol (from JPEG spec)1030   for (i=0; i < 16; ++i)1031      for (j=0; j < count[i]; ++j)1032         h->size[k++] = (stbi__uint8) (i+1);1033   h->size[k] = 0;10341035   // compute actual symbols (from jpeg spec)1036   code = 0;1037   k = 0;1038   for(j=1; j <= 16; ++j) {1039      // compute delta to add to code to compute symbol id1040      h->delta[j] = k - code;1041      if (h->size[k] == j) {1042         while (h->size[k] == j)1043            h->code[k++] = (stbi__uint16) (code++);1044         if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");1045      }1046      // compute largest code + 1 for this size, preshifted as needed later1047      h->maxcode[j] = code << (16-j);1048      code <<= 1;1049   }1050   h->maxcode[j] = 0xffffffff;10511052   // build non-spec acceleration table; 255 is flag for not-accelerated1053   memset(h->fast, 255, 1 << FAST_BITS);1054   for (i=0; i < k; ++i) {1055      int s = h->size[i];1056      if (s <= FAST_BITS) {1057         int c = h->code[i] << (FAST_BITS-s);1058         int m = 1 << (FAST_BITS-s);1059         for (j=0; j < m; ++j) {1060            h->fast[c+j] = (stbi__uint8) i;1061         }1062      }1063   }1064   return 1;1065}10661067static void grow_buffer_unsafe(jpeg *j)1068{1069   do {1070      int b = j->nomore ? 0 : get8(j->s);1071      if (b == 0xff) {1072         int c = get8(j->s);1073         if (c != 0) {1074            j->marker = (unsigned char) c;1075            j->nomore = 1;1076            return;1077         }1078      }1079      j->code_buffer |= b << (24 - j->code_bits);1080      j->code_bits += 8;1081   } while (j->code_bits <= 24);1082}10831084// (1 << n) - 11085static stbi__uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};10861087// decode a jpeg huffman value from the bitstream1088stbi_inline static int decode(jpeg *j, huffman *h)1089{1090   unsigned int temp;1091   int c,k;10921093   if (j->code_bits < 16) grow_buffer_unsafe(j);10941095   // look at the top FAST_BITS and determine what symbol ID it is,1096   // if the code is <= FAST_BITS1097   c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);1098   k = h->fast[c];1099   if (k < 255) {1100      int s = h->size[k];1101      if (s > j->code_bits)1102         return -1;1103      j->code_buffer <<= s;1104      j->code_bits -= s;1105      return h->values[k];1106   }11071108   // naive test is to shift the code_buffer down so k bits are1109   // valid, then test against maxcode. To speed this up, we've1110   // preshifted maxcode left so that it has (16-k) 0s at the1111   // end; in other words, regardless of the number of bits, it1112   // wants to be compared against something shifted to have 16;1113   // that way we don't need to shift inside the loop.1114   temp = j->code_buffer >> 16;1115   for (k=FAST_BITS+1 ; ; ++k)1116      if (temp < h->maxcode[k])1117         break;1118   if (k == 17) {1119      // error! code not found1120      j->code_bits -= 16;1121      return -1;1122   }11231124   if (k > j->code_bits)1125      return -1;11261127   // convert the huffman code to the symbol id1128   c = ((j->code_buffer >> (32 - k)) & bmask[k]) + h->delta[k];1129   assert((((j->code_buffer) >> (32 - h->size[c])) & bmask[h->size[c]]) == h->code[c]);11301131   // convert the id to a symbol1132   j->code_bits -= k;1133   j->code_buffer <<= k;1134   return h->values[c];1135}11361137// combined JPEG 'receive' and JPEG 'extend', since baseline1138// always extends everything it receives.1139stbi_inline static int extend_receive(jpeg *j, int n)1140{1141   unsigned int m = 1 << (n-1);1142   unsigned int k;1143   if (j->code_bits < n) grow_buffer_unsafe(j);11441145   #if 11146   k = stbi_lrot(j->code_buffer, n);1147   j->code_buffer = k & ~bmask[n];1148   k &= bmask[n];1149   j->code_bits -= n;1150   #else1151   k = (j->code_buffer >> (32 - n)) & bmask[n];1152   j->code_bits -= n;1153   j->code_buffer <<= n;1154   #endif1155   // the following test is probably a random branch that won't1156   // predict well. I tried to table accelerate it but failed.1157   // maybe it's compiling as a conditional move?1158   if (k < m)1159      return (-1 << n) + k + 1;1160   else1161      return k;1162}11631164// given a value that's at position X in the zigzag stream,1165// where does it appear in the 8x8 matrix coded as row-major?1166static stbi__uint8 dezigzag[64+15] =1167{1168    0,  1,  8, 16,  9,  2,  3, 10,1169   17, 24, 32, 25, 18, 11,  4,  5,1170   12, 19, 26, 33, 40, 48, 41, 34,1171   27, 20, 13,  6,  7, 14, 21, 28,1172   35, 42, 49, 56, 57, 50, 43, 36,1173   29, 22, 15, 23, 30, 37, 44, 51,1174   58, 59, 52, 45, 38, 31, 39, 46,1175   53, 60, 61, 54, 47, 55, 62, 63,1176   // let corrupt input sample past end1177   63, 63, 63, 63, 63, 63, 63, 63,1178   63, 63, 63, 63, 63, 63, 631179};11801181// decode one 64-entry block--1182static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)1183{1184   int diff,dc,k;1185   int t = decode(j, hdc);1186   if (t < 0) return e("bad huffman code","Corrupt JPEG");11871188   // 0 all the ac values now so we can do it 32-bits at a time1189   memset(data,0,64*sizeof(data[0]));11901191   diff = t ? extend_receive(j, t) : 0;1192   dc = j->img_comp[b].dc_pred + diff;1193   j->img_comp[b].dc_pred = dc;1194   data[0] = (short) dc;11951196   // decode AC components, see JPEG spec1197   k = 1;1198   do {1199      int r,s;1200      int rs = decode(j, hac);1201      if (rs < 0) return e("bad huffman code","Corrupt JPEG");1202      s = rs & 15;1203      r = rs >> 4;1204      if (s == 0) {1205         if (rs != 0xf0) break; // end block1206         k += 16;1207      } else {1208         k += r;1209         // decode into unzigzag'd location1210         data[dezigzag[k++]] = (short) extend_receive(j,s);1211      }1212   } while (k < 64);1213   return 1;1214}12151216// take a -128..127 value and clamp it and convert to 0..2551217stbi_inline static stbi__uint8 clamp(int x)1218{1219   // trick to use a single test to catch both cases1220   if ((unsigned int) x > 255) {1221      if (x < 0) return 0;1222      if (x > 255) return 255;1223   }1224   return (stbi__uint8) x;1225}12261227#define f2f(x)  (int) (((x) * 4096 + 0.5))1228#define fsh(x)  ((x) << 12)12291230// derived from jidctint -- DCT_ISLOW1231#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7)       \1232   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \1233   p2 = s2;                                    \1234   p3 = s6;                                    \1235   p1 = (p2+p3) * f2f(0.5411961f);             \1236   t2 = p1 + p3*f2f(-1.847759065f);            \1237   t3 = p1 + p2*f2f( 0.765366865f);            \1238   p2 = s0;                                    \1239   p3 = s4;                                    \1240   t0 = fsh(p2+p3);                            \1241   t1 = fsh(p2-p3);                            \1242   x0 = t0+t3;                                 \1243   x3 = t0-t3;                                 \1244   x1 = t1+t2;                                 \1245   x2 = t1-t2;                                 \1246   t0 = s7;                                    \1247   t1 = s5;                                    \1248   t2 = s3;                                    \1249   t3 = s1;                                    \1250   p3 = t0+t2;                                 \1251   p4 = t1+t3;                                 \1252   p1 = t0+t3;                                 \1253   p2 = t1+t2;                                 \1254   p5 = (p3+p4)*f2f( 1.175875602f);            \1255   t0 = t0*f2f( 0.298631336f);                 \1256   t1 = t1*f2f( 2.053119869f);                 \1257   t2 = t2*f2f( 3.072711026f);                 \1258   t3 = t3*f2f( 1.501321110f);                 \1259   p1 = p5 + p1*f2f(-0.899976223f);            \1260   p2 = p5 + p2*f2f(-2.562915447f);            \1261   p3 = p3*f2f(-1.961570560f);                 \1262   p4 = p4*f2f(-0.390180644f);                 \1263   t3 += p1+p4;                                \1264   t2 += p2+p3;                                \1265   t1 += p2+p4;                                \1266   t0 += p1+p3;12671268#ifdef STBI_SIMD1269typedef unsigned short stbi_dequantize_t;1270#else1271typedef stbi__uint8 stbi_dequantize_t;1272#endif12731274// .344 seconds on 3*anemones.jpg1275static void idct_block(stbi__uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)1276{1277   int i,val[64],*v=val;1278   stbi_dequantize_t *dq = dequantize;1279   stbi__uint8 *o;1280   short *d = data;12811282   // columns1283   for (i=0; i < 8; ++i,++d,++dq, ++v) {1284      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing1285      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==01286           && d[40]==0 && d[48]==0 && d[56]==0) {1287         //    no shortcut                 0     seconds1288         //    (1|2|3|4|5|6|7)==0          0     seconds1289         //    all separate               -0.047 seconds1290         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds1291         int dcterm = d[0] * dq[0] << 2;1292         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;1293      } else {1294         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],1295                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])1296         // constants scaled things up by 1<<12; let's bring them back1297         // down, but keep 2 extra bits of precision1298         x0 += 512; x1 += 512; x2 += 512; x3 += 512;1299         v[ 0] = (x0+t3) >> 10;1300         v[56] = (x0-t3) >> 10;1301         v[ 8] = (x1+t2) >> 10;1302         v[48] = (x1-t2) >> 10;1303         v[16] = (x2+t1) >> 10;1304         v[40] = (x2-t1) >> 10;1305         v[24] = (x3+t0) >> 10;1306         v[32] = (x3-t0) >> 10;1307      }1308   }13091310   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {1311      // no fast case since the first 1D IDCT spread components out1312      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])1313      // constants scaled things up by 1<<12, plus we had 1<<2 from first1314      // loop, plus horizontal and vertical each scale by sqrt(8) so together1315      // we've got an extra 1<<3, so 1<<17 total we need to remove.1316      // so we want to round that, which means adding 0.5 * 1<<17,1317      // aka 65536. Also, we'll end up with -128 to 127 that we want1318      // to encode as 0..255 by adding 128, so we'll add that before the shift1319      x0 += 65536 + (128<<17);1320      x1 += 65536 + (128<<17);1321      x2 += 65536 + (128<<17);1322      x3 += 65536 + (128<<17);1323      // tried computing the shifts into temps, or'ing the temps to see1324      // if any were out of range, but that was slower1325      o[0] = clamp((x0+t3) >> 17);1326      o[7] = clamp((x0-t3) >> 17);1327      o[1] = clamp((x1+t2) >> 17);1328      o[6] = clamp((x1-t2) >> 17);1329      o[2] = clamp((x2+t1) >> 17);1330      o[5] = clamp((x2-t1) >> 17);1331      o[3] = clamp((x3+t0) >> 17);1332      o[4] = clamp((x3-t0) >> 17);1333   }1334}13351336#ifdef STBI_SIMD1337static stbi_idct_8x8 stbi_idct_installed = idct_block;13381339void stbi_install_idct(stbi_idct_8x8 func)1340{1341   stbi_idct_installed = func;1342}1343#endif13441345#define MARKER_none  0xff1346// if there's a pending marker from the entropy stream, return that1347// otherwise, fetch from the stream and get a marker. if there's no1348// marker, return 0xff, which is never a valid marker value1349static stbi__uint8 get_marker(jpeg *j)1350{1351   stbi__uint8 x;1352   if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }1353   x = get8u(j->s);1354   if (x != 0xff) return MARKER_none;1355   while (x == 0xff)1356      x = get8u(j->s);1357   return x;1358}13591360// in each scan, we'll have scan_n components, and the order1361// of the components is specified by order[]1362#define RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)13631364// after a restart interval, reset the entropy decoder and1365// the dc prediction1366static void reset(jpeg *j)1367{1368   j->code_bits = 0;1369   j->code_buffer = 0;1370   j->nomore = 0;1371   j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;1372   j->marker = MARKER_none;1373   j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;1374   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,1375   // since we don't even allow 1<<30 pixels1376}13771378static int parse_entropy_coded_data(jpeg *z)1379{1380   reset(z);1381   if (z->scan_n == 1) {1382      int i,j;1383      #ifdef STBI_SIMD1384      __declspec(align(16))1385      #endif1386      short data[64];1387      int n = z->order[0];1388      // non-interleaved data, we just need to process one block at a time,1389      // in trivial scanline order1390      // number of blocks to do just depends on how many actual "pixels" this1391      // component has, independent of interleaved MCU blocking and such1392      int w = (z->img_comp[n].x+7) >> 3;1393      int h = (z->img_comp[n].y+7) >> 3;1394      for (j=0; j < h; ++j) {1395         for (i=0; i < w; ++i) {1396            if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;1397            #ifdef STBI_SIMD1398            stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);1399            #else1400            idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);1401            #endif1402            // every data block is an MCU, so countdown the restart interval1403            if (--z->todo <= 0) {1404               if (z->code_bits < 24) grow_buffer_unsafe(z);1405               // if it's NOT a restart, then just bail, so we get corrupt data1406               // rather than no data1407               if (!RESTART(z->marker)) return 1;1408               reset(z);1409            }1410         }1411      }1412   } else { // interleaved!1413      int i,j,k,x,y;1414      short data[64];1415      for (j=0; j < z->img_mcu_y; ++j) {1416         for (i=0; i < z->img_mcu_x; ++i) {1417            // scan an interleaved mcu... process scan_n components in order1418            for (k=0; k < z->scan_n; ++k) {1419               int n = z->order[k];1420               // scan out an mcu's worth of this component; that's just determined1421               // by the basic H and V specified for the component1422               for (y=0; y < z->img_comp[n].v; ++y) {1423                  for (x=0; x < z->img_comp[n].h; ++x) {1424                     int x2 = (i*z->img_comp[n].h + x)*8;1425                     int y2 = (j*z->img_comp[n].v + y)*8;1426                     if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;1427                     #ifdef STBI_SIMD1428                     stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);1429                     #else1430                     idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);1431                     #endif1432                  }1433               }1434            }1435            // after all interleaved components, that's an interleaved MCU,1436            // so now count down the restart interval1437            if (--z->todo <= 0) {1438               if (z->code_bits < 24) grow_buffer_unsafe(z);1439               // if it's NOT a restart, then just bail, so we get corrupt data1440               // rather than no data1441               if (!RESTART(z->marker)) return 1;1442               reset(z);1443            }1444         }1445      }1446   }1447   return 1;1448}14491450static int process_marker(jpeg *z, int m)1451{1452   int L;1453   switch (m) {1454      case MARKER_none: // no marker found1455         return e("expected marker","Corrupt JPEG");14561457      case 0xC2: // SOF - progressive1458         return e("progressive jpeg","JPEG format not supported (progressive)");14591460      case 0xDD: // DRI - specify restart interval1461         if (get16(z->s) != 4) return e("bad DRI len","Corrupt JPEG");1462         z->restart_interval = get16(z->s);1463         return 1;14641465      case 0xDB: // DQT - define quantization table1466         L = get16(z->s)-2;1467         while (L > 0) {1468            int q = get8(z->s);1469            int p = q >> 4;1470            int t = q & 15,i;1471            if (p != 0) return e("bad DQT type","Corrupt JPEG");1472            if (t > 3) return e("bad DQT table","Corrupt JPEG");1473            for (i=0; i < 64; ++i)1474               z->dequant[t][dezigzag[i]] = get8u(z->s);1475            #ifdef STBI_SIMD1476            for (i=0; i < 64; ++i)1477               z->dequant2[t][i] = z->dequant[t][i];1478            #endif1479            L -= 65;1480         }1481         return L==0;14821483      case 0xC4: // DHT - define huffman table1484         L = get16(z->s)-2;1485         while (L > 0) {1486            stbi__uint8 *v;1487            int sizes[16],i,n=0;1488            int q = get8(z->s);1489            int tc = q >> 4;1490            int th = q & 15;1491            if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");1492            for (i=0; i < 16; ++i) {1493               sizes[i] = get8(z->s);1494               n += sizes[i];1495            }1496            L -= 17;1497            if (tc == 0) {1498               if (!build_huffman(z->huff_dc+th, sizes)) return 0;1499               v = z->huff_dc[th].values;1500            } else {1501               if (!build_huffman(z->huff_ac+th, sizes)) return 0;1502               v = z->huff_ac[th].values;1503            }1504            for (i=0; i < n; ++i)1505               v[i] = get8u(z->s);1506            L -= n;1507         }1508         return L==0;1509   }1510   // check for comment block or APP blocks1511   if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {1512      skip(z->s, get16(z->s)-2);1513      return 1;1514   }1515   return 0;1516}15171518// after we see SOS1519static int process_scan_header(jpeg *z)1520{1521   int i;1522   int Ls = get16(z->s);1523   z->scan_n = get8(z->s);1524   if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return e("bad SOS component count","Corrupt JPEG");1525   if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG");1526   for (i=0; i < z->scan_n; ++i) {1527      int id = get8(z->s), which;1528      int q = get8(z->s);1529      for (which = 0; which < z->s->img_n; ++which)1530         if (z->img_comp[which].id == id)1531            break;1532      if (which == z->s->img_n) return 0;1533      z->img_comp[which].hd = q >> 4;   if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");1534      z->img_comp[which].ha = q & 15;   if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");1535      z->order[i] = which;1536   }1537   if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG");1538   get8(z->s); // should be 63, but might be 01539   if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG");15401541   return 1;1542}15431544static int process_frame_header(jpeg *z, int scan)1545{1546   stbi *s = z->s;1547   int Lf,p,i,q, h_max=1,v_max=1,c;1548   Lf = get16(s);         if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG1549   p  = get8(s);          if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline1550   s->img_y = get16(s);   if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG1551   s->img_x = get16(s);   if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires1552   c = get8(s);1553   if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG");    // JFIF requires1554   s->img_n = c;1555   for (i=0; i < c; ++i) {1556      z->img_comp[i].data = NULL;1557      z->img_comp[i].linebuf = NULL;1558   }15591560   if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG");15611562   for (i=0; i < s->img_n; ++i) {1563      z->img_comp[i].id = get8(s);1564      if (z->img_comp[i].id != i+1)   // JFIF requires1565         if (z->img_comp[i].id != i)  // some version of jpegtran outputs non-JFIF-compliant files!1566            return e("bad component ID","Corrupt JPEG");1567      q = get8(s);1568      z->img_comp[i].h = (q >> 4);  if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG");1569      z->img_comp[i].v = q & 15;    if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG");1570      z->img_comp[i].tq = get8(s);  if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");1571   }15721573   if (scan != SCAN_load) return 1;15741575   if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");15761577   for (i=0; i < s->img_n; ++i) {1578      if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;1579      if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;1580   }15811582   // compute interleaved mcu info1583   z->img_h_max = h_max;1584   z->img_v_max = v_max;1585   z->img_mcu_w = h_max * 8;1586   z->img_mcu_h = v_max * 8;1587   z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;1588   z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;15891590   for (i=0; i < s->img_n; ++i) {1591      // number of effective pixels (e.g. for non-interleaved MCU)1592      z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;1593      z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;1594      // to simplify generation, we'll allocate enough memory to decode1595      // the bogus oversized data from using interleaved MCUs and their1596      // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't1597      // discard the extra data until colorspace conversion1598      z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;1599      z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;1600      z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);1601      if (z->img_comp[i].raw_data == NULL) {1602         for(--i; i >= 0; --i) {1603            free(z->img_comp[i].raw_data);1604            z->img_comp[i].data = NULL;1605         }1606         return e("outofmem", "Out of memory");1607      }1608      // align blocks for installable-idct using mmx/sse1609      z->img_comp[i].data = (stbi__uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);1610      z->img_comp[i].linebuf = NULL;1611   }16121613   return 1;1614}16151616// use comparisons since in some cases we handle more than one case (e.g. SOF)1617#define DNL(x)         ((x) == 0xdc)1618#define SOI(x)         ((x) == 0xd8)1619#define EOI(x)         ((x) == 0xd9)1620#define SOF(x)         ((x) == 0xc0 || (x) == 0xc1)1621#define SOS(x)         ((x) == 0xda)16221623static int decode_jpeg_header(jpeg *z, int scan)1624{1625   int m;1626   z->marker = MARKER_none; // initialize cached marker to empty1627   m = get_marker(z);1628   if (!SOI(m)) return e("no SOI","Corrupt JPEG");1629   if (scan == SCAN_type) return 1;1630   m = get_marker(z);1631   while (!SOF(m)) {1632      if (!process_marker(z,m)) return 0;1633      m = get_marker(z);1634      while (m == MARKER_none) {1635         // some files have extra padding after their blocks, so ok, we'll scan1636         if (at_eof(z->s)) return e("no SOF", "Corrupt JPEG");1637         m = get_marker(z);1638      }1639   }1640   if (!process_frame_header(z, scan)) return 0;1641   return 1;1642}16431644static int decode_jpeg_image(jpeg *j)1645{1646   int m;1647   j->restart_interval = 0;1648   if (!decode_jpeg_header(j, SCAN_load)) return 0;1649   m = get_marker(j);1650   while (!EOI(m)) {1651      if (SOS(m)) {1652         if (!process_scan_header(j)) return 0;1653         if (!parse_entropy_coded_data(j)) return 0;1654         if (j->marker == MARKER_none ) {1655            // handle 0s at the end of image data from IP Kamera 90601656            while (!at_eof(j->s)) {1657               int x = get8(j->s);1658               if (x == 255) {1659                  j->marker = get8u(j->s);1660                  break;1661               } else if (x != 0) {1662                  return 0;1663               }1664            }1665            // if we reach eof without hitting a marker, get_marker() below will fail and we'll eventually return 01666         }1667      } else {1668         if (!process_marker(j, m)) return 0;1669      }1670      m = get_marker(j);1671   }1672   return 1;1673}16741675// static jfif-centered resampling (across block boundaries)16761677typedef stbi__uint8 *(*resample_row_func)(stbi__uint8 *out, stbi__uint8 *in0, stbi__uint8 *in1,1678                                    int w, int hs);16791680#define div4(x) ((stbi__uint8) ((x) >> 2))16811682static stbi__uint8 *resample_row_1(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)1683{1684   STBI_NOTUSED(out);1685   STBI_NOTUSED(in_far);1686   STBI_NOTUSED(w);1687   STBI_NOTUSED(hs);1688   return in_near;1689}16901691static stbi__uint8* resample_row_v_2(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)1692{1693   // need to generate two samples vertically for every one in input1694   int i;1695   STBI_NOTUSED(hs);1696   for (i=0; i < w; ++i)1697      out[i] = div4(3*in_near[i] + in_far[i] + 2);1698   return out;1699}17001701static stbi__uint8*  resample_row_h_2(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)1702{1703   // need to generate two samples horizontally for every one in input1704   int i;1705   stbi__uint8 *input = in_near;17061707   if (w == 1) {1708      // if only one sample, can't do any interpolation1709      out[0] = out[1] = input[0];1710      return out;1711   }17121713   out[0] = input[0];1714   out[1] = div4(input[0]*3 + input[1] + 2);1715   for (i=1; i < w-1; ++i) {1716      int n = 3*input[i]+2;1717      out[i*2+0] = div4(n+input[i-1]);1718      out[i*2+1] = div4(n+input[i+1]);1719   }1720   out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2);1721   out[i*2+1] = input[w-1];17221723   STBI_NOTUSED(in_far);1724   STBI_NOTUSED(hs);17251726   return out;1727}17281729#define div16(x) ((stbi__uint8) ((x) >> 4))17301731static stbi__uint8 *resample_row_hv_2(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)1732{1733   // need to generate 2x2 samples for every one in input1734   int i,t0,t1;1735   if (w == 1) {1736      out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2);1737      return out;1738   }17391740   t1 = 3*in_near[0] + in_far[0];1741   out[0] = div4(t1+2);1742   for (i=1; i < w; ++i) {1743      t0 = t1;1744      t1 = 3*in_near[i]+in_far[i];1745      out[i*2-1] = div16(3*t0 + t1 + 8);1746      out[i*2  ] = div16(3*t1 + t0 + 8);1747   }1748   out[w*2-1] = div4(t1+2);17491750   STBI_NOTUSED(hs);17511752   return out;1753}17541755static stbi__uint8 *resample_row_generic(stbi__uint8 *out, stbi__uint8 *in_near, stbi__uint8 *in_far, int w, int hs)1756{1757   // resample with nearest-neighbor1758   int i,j;1759   STBI_NOTUSED(in_far);1760   for (i=0; i < w; ++i)1761      for (j=0; j < hs; ++j)1762         out[i*hs+j] = in_near[i];1763   return out;1764}17651766#define float2fixed(x)  ((int) ((x) * 65536 + 0.5))17671768// 0.38 seconds on 3*anemones.jpg   (0.25 with processor = Pro)1769// VC6 without processor=Pro is generating multiple LEAs per multiply!1770static void YCbCr_to_RGB_row(stbi__uint8 *out, const stbi__uint8 *y, const stbi__uint8 *pcb, const stbi__uint8 *pcr, int count, int step)1771{1772   int i;1773   for (i=0; i < count; ++i) {1774      int y_fixed = (y[i] << 16) + 32768; // rounding1775      int r,g,b;1776      int cr = pcr[i] - 128;1777      int cb = pcb[i] - 128;1778      r = y_fixed + cr*float2fixed(1.40200f);1779      g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);1780      b = y_fixed                            + cb*float2fixed(1.77200f);1781      r >>= 16;1782      g >>= 16;1783      b >>= 16;1784      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }1785      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }1786      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }1787      out[0] = (stbi__uint8)r;1788      out[1] = (stbi__uint8)g;1789      out[2] = (stbi__uint8)b;1790      out[3] = 255;1791      out += step;1792   }1793}17941795#ifdef STBI_SIMD1796static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;17971798void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)1799{1800   stbi_YCbCr_installed = func;1801}1802#endif180318041805// clean up the temporary component buffers1806static void cleanup_jpeg(jpeg *j)1807{1808   int i;1809   for (i=0; i < j->s->img_n; ++i) {1810      if (j->img_comp[i].data) {1811         free(j->img_comp[i].raw_data);1812         j->img_comp[i].data = NULL;1813      }1814      if (j->img_comp[i].linebuf) {1815         free(j->img_comp[i].linebuf);1816         j->img_comp[i].linebuf = NULL;1817      }1818   }1819}18201821typedef struct1822{1823   resample_row_func resample;1824   stbi__uint8 *line0,*line1;1825   int hs,vs;   // expansion factor in each axis1826   int w_lores; // horizontal pixels pre-expansion 1827   int ystep;   // how far through vertical expansion we are1828   int ypos;    // which pre-expansion row we're on1829} stbi_resample;18301831static stbi__uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)1832{1833   int n, decode_n;1834   // validate req_comp1835   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");1836   z->s->img_n = 0;18371838   // load a jpeg image from whichever source1839   if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }18401841   // determine actual number of components to generate1842   n = req_comp ? req_comp : z->s->img_n;18431844   if (z->s->img_n == 3 && n < 3)1845      decode_n = 1;1846   else1847      decode_n = z->s->img_n;18481849   // resample and color-convert1850   {1851      int k;1852      unsigned int i,j;1853      stbi__uint8 *output;1854      stbi__uint8 *coutput[4];18551856      stbi_resample res_comp[4];18571858      for (k=0; k < decode_n; ++k) {1859         stbi_resample *r = &res_comp[k];18601861         // allocate line buffer big enough for upsampling off the edges1862         // with upsample factor of 41863         z->img_comp[k].linebuf = (stbi__uint8 *) malloc(z->s->img_x + 3);1864         if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }18651866         r->hs      = z->img_h_max / z->img_comp[k].h;1867         r->vs      = z->img_v_max / z->img_comp[k].v;1868         r->ystep   = r->vs >> 1;1869         r->w_lores = (z->s->img_x + r->hs-1) / r->hs;1870         r->ypos    = 0;1871         r->line0   = r->line1 = z->img_comp[k].data;18721873         if      (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;1874         else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;1875         else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;1876         else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;1877         else                               r->resample = resample_row_generic;1878      }18791880      // can't error after this so, this is safe1881      output = (stbi__uint8 *) malloc(n * z->s->img_x * z->s->img_y + 1);1882      if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }18831884      // now go ahead and resample1885      for (j=0; j < z->s->img_y; ++j) {1886         stbi__uint8 *out = output + n * z->s->img_x * j;1887         for (k=0; k < decode_n; ++k) {1888            stbi_resample *r = &res_comp[k];1889            int y_bot = r->ystep >= (r->vs >> 1);1890            coutput[k] = r->resample(z->img_comp[k].linebuf,1891                                     y_bot ? r->line1 : r->line0,1892                                     y_bot ? r->line0 : r->line1,1893                                     r->w_lores, r->hs);1894            if (++r->ystep >= r->vs) {1895               r->ystep = 0;1896               r->line0 = r->line1;1897               if (++r->ypos < z->img_comp[k].y)1898                  r->line1 += z->img_comp[k].w2;1899            }1900         }1901         if (n >= 3) {1902            stbi__uint8 *y = coutput[0];1903            if (z->s->img_n == 3) {1904               #ifdef STBI_SIMD1905               stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s->img_x, n);1906               #else1907               YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);1908               #endif1909            } else1910               for (i=0; i < z->s->img_x; ++i) {1911                  out[0] = out[1] = out[2] = y[i];1912                  out[3] = 255; // not used if n==31913                  out += n;1914               }1915         } else {1916            stbi__uint8 *y = coutput[0];1917            if (n == 1)1918               for (i=0; i < z->s->img_x; ++i) out[i] = y[i];1919            else1920               for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;1921         }1922      }1923      cleanup_jpeg(z);1924      *out_x = z->s->img_x;1925      *out_y = z->s->img_y;1926      if (comp) *comp  = z->s->img_n; // report original components, not output1927      return output;1928   }1929}19301931static unsigned char *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp)1932{1933   jpeg j;1934   j.s = s;1935   return load_jpeg_image(&j, x,y,comp,req_comp);1936}19371938static int stbi_jpeg_test(stbi *s)1939{1940   int r;1941   jpeg j;1942   j.s = s;1943   r = decode_jpeg_header(&j, SCAN_type);1944   stbi_rewind(s);1945   return r;1946}19471948static int stbi_jpeg_info_raw(jpeg *j, int *x, int *y, int *comp)1949{1950   if (!decode_jpeg_header(j, SCAN_header)) {1951      stbi_rewind( j->s );1952      return 0;1953   }1954   if (x) *x = j->s->img_x;1955   if (y) *y = j->s->img_y;1956   if (comp) *comp = j->s->img_n;1957   return 1;1958}19591960static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp)1961{1962   jpeg j;1963   j.s = s;1964   return stbi_jpeg_info_raw(&j, x, y, comp);1965}19661967// public domain zlib decode    v0.2  Sean Barrett 2006-11-181968//    simple implementation1969//      - all input must be provided in an upfront buffer1970//      - all output is written to a single output buffer (can malloc/realloc)1971//    performance1972//      - fast huffman19731974// fast-way is faster to check than jpeg huffman, but slow way is slower1975#define ZFAST_BITS  9 // accelerate all cases in default tables1976#define ZFAST_MASK  ((1 << ZFAST_BITS) - 1)19771978// zlib-style huffman encoding1979// (jpegs packs from left, zlib from right, so can't share code)1980typedef struct1981{1982   stbi__uint16 fast[1 << ZFAST_BITS];1983   stbi__uint16 firstcode[16];1984   int maxcode[17];1985   stbi__uint16 firstsymbol[16];1986   stbi__uint8  size[288];1987   stbi__uint16 value[288]; 1988} zhuffman;19891990stbi_inline static int bitreverse16(int n)1991{1992  n = ((n & 0xAAAA) >>  1) | ((n & 0x5555) << 1);1993  n = ((n & 0xCCCC) >>  2) | ((n & 0x3333) << 2);1994  n = ((n & 0xF0F0) >>  4) | ((n & 0x0F0F) << 4);1995  n = ((n & 0xFF00) >>  8) | ((n & 0x00FF) << 8);1996  return n;1997}19981999stbi_inline static int bit_reverse(int v, int bits)2000{

The first 2,000 of 4,678 lines.