Skip to content
Myr

Merge branch 'headerify'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Conflicts: tests/stretch_test.dsp

authored by Sean Barrett · committed by Sean Barrett · parents b0d2481, 334cec8 · Browse files · 11 files+9443 added−4785 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+9443 added−4785 removed

  • tests:+46 added−22 removed
  • other:+9397 added−4763 removed

11 files+9443 added−4785 removed

added:deprecated/stb_image.c+4678 added
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{2001 assert(bits <= 16);2002 // to bit reverse n bits, reverse 16 and shift2003 // e.g. 11 bits, bit reverse and shift away 52004 return bitreverse16(v) >> (16-bits);2005}20062007static int zbuild_huffman(zhuffman *z, stbi__uint8 *sizelist, int num)2008{2009 int i,k=0;2010 int code, next_code[16], sizes[17];20112012 // DEFLATE spec for generating codes2013 memset(sizes, 0, sizeof(sizes));2014 memset(z->fast, 255, sizeof(z->fast));2015 for (i=0; i < num; ++i) 2016 ++sizes[sizelist[i]];2017 sizes[0] = 0;2018 for (i=1; i < 16; ++i)2019 assert(sizes[i] <= (1 << i));2020 code = 0;2021 for (i=1; i < 16; ++i) {2022 next_code[i] = code;2023 z->firstcode[i] = (stbi__uint16) code;2024 z->firstsymbol[i] = (stbi__uint16) k;2025 code = (code + sizes[i]);2026 if (sizes[i])2027 if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");2028 z->maxcode[i] = code << (16-i); // preshift for inner loop2029 code <<= 1;2030 k += sizes[i];2031 }2032 z->maxcode[16] = 0x10000; // sentinel2033 for (i=0; i < num; ++i) {2034 int s = sizelist[i];2035 if (s) {2036 int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];2037 z->size[c] = (stbi__uint8)s;2038 z->value[c] = (stbi__uint16)i;2039 if (s <= ZFAST_BITS) {2040 int k = bit_reverse(next_code[s],s);2041 while (k < (1 << ZFAST_BITS)) {2042 z->fast[k] = (stbi__uint16) c;2043 k += (1 << s);2044 }2045 }2046 ++next_code[s];2047 }2048 }2049 return 1;2050}20512052// zlib-from-memory implementation for PNG reading2053// because PNG allows splitting the zlib stream arbitrarily,2054// and it's annoying structurally to have PNG call ZLIB call PNG,2055// we require PNG read all the IDATs and combine them into a single2056// memory buffer20572058typedef struct2059{2060 stbi__uint8 *zbuffer, *zbuffer_end;2061 int num_bits;2062 stbi__uint32 code_buffer;20632064 char *zout;2065 char *zout_start;2066 char *zout_end;2067 int z_expandable;20682069 zhuffman z_length, z_distance;2070} zbuf;20712072stbi_inline static int zget8(zbuf *z)2073{2074 if (z->zbuffer >= z->zbuffer_end) return 0;2075 return *z->zbuffer++;2076}20772078static void fill_bits(zbuf *z)2079{2080 do {2081 assert(z->code_buffer < (1U << z->num_bits));2082 z->code_buffer |= zget8(z) << z->num_bits;2083 z->num_bits += 8;2084 } while (z->num_bits <= 24);2085}20862087stbi_inline static unsigned int zreceive(zbuf *z, int n)2088{2089 unsigned int k;2090 if (z->num_bits < n) fill_bits(z);2091 k = z->code_buffer & ((1 << n) - 1);2092 z->code_buffer >>= n;2093 z->num_bits -= n;2094 return k; 2095}20962097stbi_inline static int zhuffman_decode(zbuf *a, zhuffman *z)2098{2099 int b,s,k;2100 if (a->num_bits < 16) fill_bits(a);2101 b = z->fast[a->code_buffer & ZFAST_MASK];2102 if (b < 0xffff) {2103 s = z->size[b];2104 a->code_buffer >>= s;2105 a->num_bits -= s;2106 return z->value[b];2107 }21082109 // not resolved by fast table, so compute it the slow way2110 // use jpeg approach, which requires MSbits at top2111 k = bit_reverse(a->code_buffer, 16);2112 for (s=ZFAST_BITS+1; ; ++s)2113 if (k < z->maxcode[s])2114 break;2115 if (s == 16) return -1; // invalid code!2116 // code size is s, so:2117 b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];2118 assert(z->size[b] == s);2119 a->code_buffer >>= s;2120 a->num_bits -= s;2121 return z->value[b];2122}21232124static int expand(zbuf *z, int n) // need to make room for n bytes2125{2126 char *q;2127 int cur, limit;2128 if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");2129 cur = (int) (z->zout - z->zout_start);2130 limit = (int) (z->zout_end - z->zout_start);2131 while (cur + n > limit)2132 limit *= 2;2133 q = (char *) realloc(z->zout_start, limit);2134 if (q == NULL) return e("outofmem", "Out of memory");2135 z->zout_start = q;2136 z->zout = q + cur;2137 z->zout_end = q + limit;2138 return 1;2139}21402141static int length_base[31] = {2142 3,4,5,6,7,8,9,10,11,13,2143 15,17,19,23,27,31,35,43,51,59,2144 67,83,99,115,131,163,195,227,258,0,0 };21452146static int length_extra[31]= 2147{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };21482149static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,2150257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};21512152static int dist_extra[32] =2153{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};21542155static int parse_huffman_block(zbuf *a)2156{2157 for(;;) {2158 int z = zhuffman_decode(a, &a->z_length);2159 if (z < 256) {2160 if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes2161 if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;2162 *a->zout++ = (char) z;2163 } else {2164 stbi__uint8 *p;2165 int len,dist;2166 if (z == 256) return 1;2167 z -= 257;2168 len = length_base[z];2169 if (length_extra[z]) len += zreceive(a, length_extra[z]);2170 z = zhuffman_decode(a, &a->z_distance);2171 if (z < 0) return e("bad huffman code","Corrupt PNG");2172 dist = dist_base[z];2173 if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);2174 if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");2175 if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;2176 p = (stbi__uint8 *) (a->zout - dist);2177 while (len--)2178 *a->zout++ = *p++;2179 }2180 }2181}21822183static int compute_huffman_codes(zbuf *a)2184{2185 static stbi__uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };2186 zhuffman z_codelength;2187 stbi__uint8 lencodes[286+32+137];//padding for maximum single op2188 stbi__uint8 codelength_sizes[19];2189 int i,n;21902191 int hlit = zreceive(a,5) + 257;2192 int hdist = zreceive(a,5) + 1;2193 int hclen = zreceive(a,4) + 4;21942195 memset(codelength_sizes, 0, sizeof(codelength_sizes));2196 for (i=0; i < hclen; ++i) {2197 int s = zreceive(a,3);2198 codelength_sizes[length_dezigzag[i]] = (stbi__uint8) s;2199 }2200 if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;22012202 n = 0;2203 while (n < hlit + hdist) {2204 int c = zhuffman_decode(a, &z_codelength);2205 assert(c >= 0 && c < 19);2206 if (c < 16)2207 lencodes[n++] = (stbi__uint8) c;2208 else if (c == 16) {2209 c = zreceive(a,2)+3;2210 memset(lencodes+n, lencodes[n-1], c);2211 n += c;2212 } else if (c == 17) {2213 c = zreceive(a,3)+3;2214 memset(lencodes+n, 0, c);2215 n += c;2216 } else {2217 assert(c == 18);2218 c = zreceive(a,7)+11;2219 memset(lencodes+n, 0, c);2220 n += c;2221 }2222 }2223 if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");2224 if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;2225 if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;2226 return 1;2227}22282229static int parse_uncompressed_block(zbuf *a)2230{2231 stbi__uint8 header[4];2232 int len,nlen,k;2233 if (a->num_bits & 7)2234 zreceive(a, a->num_bits & 7); // discard2235 // drain the bit-packed data into header2236 k = 0;2237 while (a->num_bits > 0) {2238 header[k++] = (stbi__uint8) (a->code_buffer & 255); // wtf this warns?2239 a->code_buffer >>= 8;2240 a->num_bits -= 8;2241 }2242 assert(a->num_bits == 0);2243 // now fill header the normal way2244 while (k < 4)2245 header[k++] = (stbi__uint8) zget8(a);2246 len = header[1] * 256 + header[0];2247 nlen = header[3] * 256 + header[2];2248 if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");2249 if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");2250 if (a->zout + len > a->zout_end)2251 if (!expand(a, len)) return 0;2252 memcpy(a->zout, a->zbuffer, len);2253 a->zbuffer += len;2254 a->zout += len;2255 return 1;2256}22572258static int parse_zlib_header(zbuf *a)2259{2260 int cmf = zget8(a);2261 int cm = cmf & 15;2262 /* int cinfo = cmf >> 4; */2263 int flg = zget8(a);2264 if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec2265 if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png2266 if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png2267 // window = 1 << (8 + cinfo)... but who cares, we fully buffer output2268 return 1;2269}22702271// @TODO: should statically initialize these for optimal thread safety2272static stbi__uint8 default_length[288], default_distance[32];2273static void init_defaults(void)2274{2275 int i; // use <= to match clearly with spec2276 for (i=0; i <= 143; ++i) default_length[i] = 8;2277 for ( ; i <= 255; ++i) default_length[i] = 9;2278 for ( ; i <= 279; ++i) default_length[i] = 7;2279 for ( ; i <= 287; ++i) default_length[i] = 8;22802281 for (i=0; i <= 31; ++i) default_distance[i] = 5;2282}22832284int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead2285static int parse_zlib(zbuf *a, int parse_header)2286{2287 int final, type;2288 if (parse_header)2289 if (!parse_zlib_header(a)) return 0;2290 a->num_bits = 0;2291 a->code_buffer = 0;2292 do {2293 final = zreceive(a,1);2294 type = zreceive(a,2);2295 if (type == 0) {2296 if (!parse_uncompressed_block(a)) return 0;2297 } else if (type == 3) {2298 return 0;2299 } else {2300 if (type == 1) {2301 // use fixed code lengths2302 if (!default_distance[31]) init_defaults();2303 if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0;2304 if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0;2305 } else {2306 if (!compute_huffman_codes(a)) return 0;2307 }2308 if (!parse_huffman_block(a)) return 0;2309 }2310 if (stbi_png_partial && a->zout - a->zout_start > 65536)2311 break;2312 } while (!final);2313 return 1;2314}23152316static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)2317{2318 a->zout_start = obuf;2319 a->zout = obuf;2320 a->zout_end = obuf + olen;2321 a->z_expandable = exp;23222323 return parse_zlib(a, parse_header);2324}23252326char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)2327{2328 zbuf a;2329 char *p = (char *) malloc(initial_size);2330 if (p == NULL) return NULL;2331 a.zbuffer = (stbi__uint8 *) buffer;2332 a.zbuffer_end = (stbi__uint8 *) buffer + len;2333 if (do_zlib(&a, p, initial_size, 1, 1)) {2334 if (outlen) *outlen = (int) (a.zout - a.zout_start);2335 return a.zout_start;2336 } else {2337 free(a.zout_start);2338 return NULL;2339 }2340}23412342char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)2343{2344 return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);2345}23462347char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)2348{2349 zbuf a;2350 char *p = (char *) malloc(initial_size);2351 if (p == NULL) return NULL;2352 a.zbuffer = (stbi__uint8 *) buffer;2353 a.zbuffer_end = (stbi__uint8 *) buffer + len;2354 if (do_zlib(&a, p, initial_size, 1, parse_header)) {2355 if (outlen) *outlen = (int) (a.zout - a.zout_start);2356 return a.zout_start;2357 } else {2358 free(a.zout_start);2359 return NULL;2360 }2361}23622363int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)2364{2365 zbuf a;2366 a.zbuffer = (stbi__uint8 *) ibuffer;2367 a.zbuffer_end = (stbi__uint8 *) ibuffer + ilen;2368 if (do_zlib(&a, obuffer, olen, 0, 1))2369 return (int) (a.zout - a.zout_start);2370 else2371 return -1;2372}23732374char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)2375{2376 zbuf a;2377 char *p = (char *) malloc(16384);2378 if (p == NULL) return NULL;2379 a.zbuffer = (stbi__uint8 *) buffer;2380 a.zbuffer_end = (stbi__uint8 *) buffer+len;2381 if (do_zlib(&a, p, 16384, 1, 0)) {2382 if (outlen) *outlen = (int) (a.zout - a.zout_start);2383 return a.zout_start;2384 } else {2385 free(a.zout_start);2386 return NULL;2387 }2388}23892390int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)2391{2392 zbuf a;2393 a.zbuffer = (stbi__uint8 *) ibuffer;2394 a.zbuffer_end = (stbi__uint8 *) ibuffer + ilen;2395 if (do_zlib(&a, obuffer, olen, 0, 0))2396 return (int) (a.zout - a.zout_start);2397 else2398 return -1;2399}24002401// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-182402// simple implementation2403// - only 8-bit samples2404// - no CRC checking2405// - allocates lots of intermediate memory2406// - avoids problem of streaming data between subsystems2407// - avoids explicit window management2408// performance2409// - uses stb_zlib, a PD zlib implementation with fast huffman decoding241024112412typedef struct2413{2414 stbi__uint32 length;2415 stbi__uint32 type;2416} chunk;24172418#define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))24192420static chunk get_chunk_header(stbi *s)2421{2422 chunk c;2423 c.length = get32(s);2424 c.type = get32(s);2425 return c;2426}24272428static int check_png_header(stbi *s)2429{2430 static stbi__uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };2431 int i;2432 for (i=0; i < 8; ++i)2433 if (get8u(s) != png_sig[i]) return e("bad png sig","Not a PNG");2434 return 1;2435}24362437typedef struct2438{2439 stbi *s;2440 stbi__uint8 *idata, *expanded, *out;2441} png;244224432444enum {2445 F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,2446 F_avg_first, F_paeth_first2447};24482449static stbi__uint8 first_row_filter[5] =2450{2451 F_none, F_sub, F_none, F_avg_first, F_paeth_first2452};24532454static int paeth(int a, int b, int c)2455{2456 int p = a + b - c;2457 int pa = abs(p-a);2458 int pb = abs(p-b);2459 int pc = abs(p-c);2460 if (pa <= pb && pa <= pc) return a;2461 if (pb <= pc) return b;2462 return c;2463}24642465// create the png data from post-deflated data2466static int create_png_image_raw(png *a, stbi__uint8 *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y)2467{2468 stbi *s = a->s;2469 stbi__uint32 i,j,stride = x*out_n;2470 int k;2471 int img_n = s->img_n; // copy it into a local for later2472 assert(out_n == s->img_n || out_n == s->img_n+1);2473 if (stbi_png_partial) y = 1;2474 a->out = (stbi__uint8 *) malloc(x * y * out_n);2475 if (!a->out) return e("outofmem", "Out of memory");2476 if (!stbi_png_partial) {2477 if (s->img_x == x && s->img_y == y) {2478 if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");2479 } else { // interlaced:2480 if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");2481 }2482 }2483 for (j=0; j < y; ++j) {2484 stbi__uint8 *cur = a->out + stride*j;2485 stbi__uint8 *prior = cur - stride;2486 int filter = *raw++;2487 if (filter > 4) return e("invalid filter","Corrupt PNG");2488 // if first row, use special filter that doesn't sample previous row2489 if (j == 0) filter = first_row_filter[filter];2490 // handle first pixel explicitly2491 for (k=0; k < img_n; ++k) {2492 switch (filter) {2493 case F_none : cur[k] = raw[k]; break;2494 case F_sub : cur[k] = raw[k]; break;2495 case F_up : cur[k] = raw[k] + prior[k]; break;2496 case F_avg : cur[k] = raw[k] + (prior[k]>>1); break;2497 case F_paeth : cur[k] = (stbi__uint8) (raw[k] + paeth(0,prior[k],0)); break;2498 case F_avg_first : cur[k] = raw[k]; break;2499 case F_paeth_first: cur[k] = raw[k]; break;2500 }2501 }2502 if (img_n != out_n) cur[img_n] = 255;2503 raw += img_n;2504 cur += out_n;2505 prior += out_n;2506 // this is a little gross, so that we don't switch per-pixel or per-component2507 if (img_n == out_n) {2508 #define CASE(f) \2509 case f: \2510 for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \2511 for (k=0; k < img_n; ++k)2512 switch (filter) {2513 CASE(F_none) cur[k] = raw[k]; break;2514 CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break;2515 CASE(F_up) cur[k] = raw[k] + prior[k]; break;2516 CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;2517 CASE(F_paeth) cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;2518 CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;2519 CASE(F_paeth_first) cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;2520 }2521 #undef CASE2522 } else {2523 assert(img_n+1 == out_n);2524 #define CASE(f) \2525 case f: \2526 for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \2527 for (k=0; k < img_n; ++k)2528 switch (filter) {2529 CASE(F_none) cur[k] = raw[k]; break;2530 CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break;2531 CASE(F_up) cur[k] = raw[k] + prior[k]; break;2532 CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;2533 CASE(F_paeth) cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;2534 CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;2535 CASE(F_paeth_first) cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;2536 }2537 #undef CASE2538 }2539 }2540 return 1;2541}25422543static int create_png_image(png *a, stbi__uint8 *raw, stbi__uint32 raw_len, int out_n, int interlaced)2544{2545 stbi__uint8 *final;2546 int p;2547 int save;2548 if (!interlaced)2549 return create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);2550 save = stbi_png_partial;2551 stbi_png_partial = 0;25522553 // de-interlacing2554 final = (stbi__uint8 *) malloc(a->s->img_x * a->s->img_y * out_n);2555 for (p=0; p < 7; ++p) {2556 int xorig[] = { 0,4,0,2,0,1,0 };2557 int yorig[] = { 0,0,4,0,2,0,1 };2558 int xspc[] = { 8,8,4,4,2,2,1 };2559 int yspc[] = { 8,8,8,4,4,2,2 };2560 int i,j,x,y;2561 // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 12562 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];2563 y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];2564 if (x && y) {2565 if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {2566 free(final);2567 return 0;2568 }2569 for (j=0; j < y; ++j)2570 for (i=0; i < x; ++i)2571 memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,2572 a->out + (j*x+i)*out_n, out_n);2573 free(a->out);2574 raw += (x*out_n+1)*y;2575 raw_len -= (x*out_n+1)*y;2576 }2577 }2578 a->out = final;25792580 stbi_png_partial = save;2581 return 1;2582}25832584static int compute_transparency(png *z, stbi__uint8 tc[3], int out_n)2585{2586 stbi *s = z->s;2587 stbi__uint32 i, pixel_count = s->img_x * s->img_y;2588 stbi__uint8 *p = z->out;25892590 // compute color-based transparency, assuming we've2591 // already got 255 as the alpha value in the output2592 assert(out_n == 2 || out_n == 4);25932594 if (out_n == 2) {2595 for (i=0; i < pixel_count; ++i) {2596 p[1] = (p[0] == tc[0] ? 0 : 255);2597 p += 2;2598 }2599 } else {2600 for (i=0; i < pixel_count; ++i) {2601 if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])2602 p[3] = 0;2603 p += 4;2604 }2605 }2606 return 1;2607}26082609static int expand_palette(png *a, stbi__uint8 *palette, int len, int pal_img_n)2610{2611 stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;2612 stbi__uint8 *p, *temp_out, *orig = a->out;26132614 p = (stbi__uint8 *) malloc(pixel_count * pal_img_n);2615 if (p == NULL) return e("outofmem", "Out of memory");26162617 // between here and free(out) below, exitting would leak2618 temp_out = p;26192620 if (pal_img_n == 3) {2621 for (i=0; i < pixel_count; ++i) {2622 int n = orig[i]*4;2623 p[0] = palette[n ];2624 p[1] = palette[n+1];2625 p[2] = palette[n+2];2626 p += 3;2627 }2628 } else {2629 for (i=0; i < pixel_count; ++i) {2630 int n = orig[i]*4;2631 p[0] = palette[n ];2632 p[1] = palette[n+1];2633 p[2] = palette[n+2];2634 p[3] = palette[n+3];2635 p += 4;2636 }2637 }2638 free(a->out);2639 a->out = temp_out;26402641 STBI_NOTUSED(len);26422643 return 1;2644}26452646static int stbi_unpremultiply_on_load = 0;2647static int stbi_de_iphone_flag = 0;26482649void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)2650{2651 stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply;2652}2653void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)2654{2655 stbi_de_iphone_flag = flag_true_if_should_convert;2656}26572658static void stbi_de_iphone(png *z)2659{2660 stbi *s = z->s;2661 stbi__uint32 i, pixel_count = s->img_x * s->img_y;2662 stbi__uint8 *p = z->out;26632664 if (s->img_out_n == 3) { // convert bgr to rgb2665 for (i=0; i < pixel_count; ++i) {2666 stbi__uint8 t = p[0];2667 p[0] = p[2];2668 p[2] = t;2669 p += 3;2670 }2671 } else {2672 assert(s->img_out_n == 4);2673 if (stbi_unpremultiply_on_load) {2674 // convert bgr to rgb and unpremultiply2675 for (i=0; i < pixel_count; ++i) {2676 stbi__uint8 a = p[3];2677 stbi__uint8 t = p[0];2678 if (a) {2679 p[0] = p[2] * 255 / a;2680 p[1] = p[1] * 255 / a;2681 p[2] = t * 255 / a;2682 } else {2683 p[0] = p[2];2684 p[2] = t;2685 } 2686 p += 4;2687 }2688 } else {2689 // convert bgr to rgb2690 for (i=0; i < pixel_count; ++i) {2691 stbi__uint8 t = p[0];2692 p[0] = p[2];2693 p[2] = t;2694 p += 4;2695 }2696 }2697 }2698}26992700static int parse_png_file(png *z, int scan, int req_comp)2701{2702 stbi__uint8 palette[1024], pal_img_n=0;2703 stbi__uint8 has_trans=0, tc[3];2704 stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;2705 int first=1,k,interlace=0, iphone=0;2706 stbi *s = z->s;27072708 z->expanded = NULL;2709 z->idata = NULL;2710 z->out = NULL;27112712 if (!check_png_header(s)) return 0;27132714 if (scan == SCAN_type) return 1;27152716 for (;;) {2717 chunk c = get_chunk_header(s);2718 switch (c.type) {2719 case PNG_TYPE('C','g','B','I'):2720 iphone = stbi_de_iphone_flag;2721 skip(s, c.length);2722 break;2723 case PNG_TYPE('I','H','D','R'): {2724 int depth,color,comp,filter;2725 if (!first) return e("multiple IHDR","Corrupt PNG");2726 first = 0;2727 if (c.length != 13) return e("bad IHDR len","Corrupt PNG");2728 s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");2729 s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");2730 depth = get8(s); if (depth != 8) return e("8bit only","PNG not supported: 8-bit only");2731 color = get8(s); if (color > 6) return e("bad ctype","Corrupt PNG");2732 if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");2733 comp = get8(s); if (comp) return e("bad comp method","Corrupt PNG");2734 filter= get8(s); if (filter) return e("bad filter method","Corrupt PNG");2735 interlace = get8(s); if (interlace>1) return e("bad interlace method","Corrupt PNG");2736 if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG");2737 if (!pal_img_n) {2738 s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);2739 if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");2740 if (scan == SCAN_header) return 1;2741 } else {2742 // if paletted, then pal_n is our final components, and2743 // img_n is # components to decompress/filter.2744 s->img_n = 1;2745 if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG");2746 // if SCAN_header, have to scan to see if we have a tRNS2747 }2748 break;2749 }27502751 case PNG_TYPE('P','L','T','E'): {2752 if (first) return e("first not IHDR", "Corrupt PNG");2753 if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");2754 pal_len = c.length / 3;2755 if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");2756 for (i=0; i < pal_len; ++i) {2757 palette[i*4+0] = get8u(s);2758 palette[i*4+1] = get8u(s);2759 palette[i*4+2] = get8u(s);2760 palette[i*4+3] = 255;2761 }2762 break;2763 }27642765 case PNG_TYPE('t','R','N','S'): {2766 if (first) return e("first not IHDR", "Corrupt PNG");2767 if (z->idata) return e("tRNS after IDAT","Corrupt PNG");2768 if (pal_img_n) {2769 if (scan == SCAN_header) { s->img_n = 4; return 1; }2770 if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");2771 if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");2772 pal_img_n = 4;2773 for (i=0; i < c.length; ++i)2774 palette[i*4+3] = get8u(s);2775 } else {2776 if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");2777 if (c.length != (stbi__uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");2778 has_trans = 1;2779 for (k=0; k < s->img_n; ++k)2780 tc[k] = (stbi__uint8) get16(s); // non 8-bit images will be larger2781 }2782 break;2783 }27842785 case PNG_TYPE('I','D','A','T'): {2786 if (first) return e("first not IHDR", "Corrupt PNG");2787 if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");2788 if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }2789 if (ioff + c.length > idata_limit) {2790 stbi__uint8 *p;2791 if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;2792 while (ioff + c.length > idata_limit)2793 idata_limit *= 2;2794 p = (stbi__uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");2795 z->idata = p;2796 }2797 if (!getn(s, z->idata+ioff,c.length)) return e("outofdata","Corrupt PNG");2798 ioff += c.length;2799 break;2800 }28012802 case PNG_TYPE('I','E','N','D'): {2803 stbi__uint32 raw_len;2804 if (first) return e("first not IHDR", "Corrupt PNG");2805 if (scan != SCAN_load) return 1;2806 if (z->idata == NULL) return e("no IDAT","Corrupt PNG");2807 z->expanded = (stbi__uint8 *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone);2808 if (z->expanded == NULL) return 0; // zlib should set error2809 free(z->idata); z->idata = NULL;2810 if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)2811 s->img_out_n = s->img_n+1;2812 else2813 s->img_out_n = s->img_n;2814 if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;2815 if (has_trans)2816 if (!compute_transparency(z, tc, s->img_out_n)) return 0;2817 if (iphone && s->img_out_n > 2)2818 stbi_de_iphone(z);2819 if (pal_img_n) {2820 // pal_img_n == 3 or 42821 s->img_n = pal_img_n; // record the actual colors we had2822 s->img_out_n = pal_img_n;2823 if (req_comp >= 3) s->img_out_n = req_comp;2824 if (!expand_palette(z, palette, pal_len, s->img_out_n))2825 return 0;2826 }2827 free(z->expanded); z->expanded = NULL;2828 return 1;2829 }28302831 default:2832 // if critical, fail2833 if (first) return e("first not IHDR", "Corrupt PNG");2834 if ((c.type & (1 << 29)) == 0) {2835 #ifndef STBI_NO_FAILURE_STRINGS2836 // not threadsafe2837 static char invalid_chunk[] = "XXXX chunk not known";2838 invalid_chunk[0] = (stbi__uint8) (c.type >> 24);2839 invalid_chunk[1] = (stbi__uint8) (c.type >> 16);2840 invalid_chunk[2] = (stbi__uint8) (c.type >> 8);2841 invalid_chunk[3] = (stbi__uint8) (c.type >> 0);2842 #endif2843 return e(invalid_chunk, "PNG not supported: unknown chunk type");2844 }2845 skip(s, c.length);2846 break;2847 }2848 // end of chunk, read and skip CRC2849 get32(s);2850 }2851}28522853static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)2854{2855 unsigned char *result=NULL;2856 if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");2857 if (parse_png_file(p, SCAN_load, req_comp)) {2858 result = p->out;2859 p->out = NULL;2860 if (req_comp && req_comp != p->s->img_out_n) {2861 result = convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);2862 p->s->img_out_n = req_comp;2863 if (result == NULL) return result;2864 }2865 *x = p->s->img_x;2866 *y = p->s->img_y;2867 if (n) *n = p->s->img_n;2868 }2869 free(p->out); p->out = NULL;2870 free(p->expanded); p->expanded = NULL;2871 free(p->idata); p->idata = NULL;28722873 return result;2874}28752876static unsigned char *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp)2877{2878 png p;2879 p.s = s;2880 return do_png(&p, x,y,comp,req_comp);2881}28822883static int stbi_png_test(stbi *s)2884{2885 int r;2886 r = check_png_header(s);2887 stbi_rewind(s);2888 return r;2889}28902891static int stbi_png_info_raw(png *p, int *x, int *y, int *comp)2892{2893 if (!parse_png_file(p, SCAN_header, 0)) {2894 stbi_rewind( p->s );2895 return 0;2896 }2897 if (x) *x = p->s->img_x;2898 if (y) *y = p->s->img_y;2899 if (comp) *comp = p->s->img_n;2900 return 1;2901}29022903static int stbi_png_info(stbi *s, int *x, int *y, int *comp)2904{2905 png p;2906 p.s = s;2907 return stbi_png_info_raw(&p, x, y, comp);2908}29092910// Microsoft/Windows BMP image29112912static int bmp_test(stbi *s)2913{2914 int sz;2915 if (get8(s) != 'B') return 0;2916 if (get8(s) != 'M') return 0;2917 get32le(s); // discard filesize2918 get16le(s); // discard reserved2919 get16le(s); // discard reserved2920 get32le(s); // discard data offset2921 sz = get32le(s);2922 if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;2923 return 0;2924}29252926static int stbi_bmp_test(stbi *s)2927{2928 int r = bmp_test(s);2929 stbi_rewind(s);2930 return r;2931}293229332934// returns 0..31 for the highest set bit2935static int high_bit(unsigned int z)2936{2937 int n=0;2938 if (z == 0) return -1;2939 if (z >= 0x10000) n += 16, z >>= 16;2940 if (z >= 0x00100) n += 8, z >>= 8;2941 if (z >= 0x00010) n += 4, z >>= 4;2942 if (z >= 0x00004) n += 2, z >>= 2;2943 if (z >= 0x00002) n += 1, z >>= 1;2944 return n;2945}29462947static int bitcount(unsigned int a)2948{2949 a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 22950 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 42951 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits2952 a = (a + (a >> 8)); // max 16 per 8 bits2953 a = (a + (a >> 16)); // max 32 per 8 bits2954 return a & 0xff;2955}29562957static int shiftsigned(int v, int shift, int bits)2958{2959 int result;2960 int z=0;29612962 if (shift < 0) v <<= -shift;2963 else v >>= shift;2964 result = v;29652966 z = bits;2967 while (z < 8) {2968 result += v >> z;2969 z += bits;2970 }2971 return result;2972}29732974static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)2975{2976 stbi__uint8 *out;2977 unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;2978 stbi_uc pal[256][4];2979 int psize=0,i,j,compress=0,width;2980 int bpp, flip_vertically, pad, target, offset, hsz;2981 if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");2982 get32le(s); // discard filesize2983 get16le(s); // discard reserved2984 get16le(s); // discard reserved2985 offset = get32le(s);2986 hsz = get32le(s);2987 if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");2988 if (hsz == 12) {2989 s->img_x = get16le(s);2990 s->img_y = get16le(s);2991 } else {2992 s->img_x = get32le(s);2993 s->img_y = get32le(s);2994 }2995 if (get16le(s) != 1) return epuc("bad BMP", "bad BMP");2996 bpp = get16le(s);2997 if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");2998 flip_vertically = ((int) s->img_y) > 0;2999 s->img_y = abs((int) s->img_y);3000 if (hsz == 12) {3001 if (bpp < 24)3002 psize = (offset - 14 - 24) / 3;3003 } else {3004 compress = get32le(s);3005 if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");3006 get32le(s); // discard sizeof3007 get32le(s); // discard hres3008 get32le(s); // discard vres3009 get32le(s); // discard colorsused3010 get32le(s); // discard max important3011 if (hsz == 40 || hsz == 56) {3012 if (hsz == 56) {3013 get32le(s);3014 get32le(s);3015 get32le(s);3016 get32le(s);3017 }3018 if (bpp == 16 || bpp == 32) {3019 mr = mg = mb = 0;3020 if (compress == 0) {3021 if (bpp == 32) {3022 mr = 0xffu << 16;3023 mg = 0xffu << 8;3024 mb = 0xffu << 0;3025 ma = 0xffu << 24;3026 fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 2553027 STBI_NOTUSED(fake_a);3028 } else {3029 mr = 31u << 10;3030 mg = 31u << 5;3031 mb = 31u << 0;3032 }3033 } else if (compress == 3) {3034 mr = get32le(s);3035 mg = get32le(s);3036 mb = get32le(s);3037 // not documented, but generated by photoshop and handled by mspaint3038 if (mr == mg && mg == mb) {3039 // ?!?!?3040 return epuc("bad BMP", "bad BMP");3041 }3042 } else3043 return epuc("bad BMP", "bad BMP");3044 }3045 } else {3046 assert(hsz == 108);3047 mr = get32le(s);3048 mg = get32le(s);3049 mb = get32le(s);3050 ma = get32le(s);3051 get32le(s); // discard color space3052 for (i=0; i < 12; ++i)3053 get32le(s); // discard color space parameters3054 }3055 if (bpp < 16)3056 psize = (offset - 14 - hsz) >> 2;3057 }3058 s->img_n = ma ? 4 : 3;3059 if (req_comp && req_comp >= 3) // we can directly decode 3 or 43060 target = req_comp;3061 else3062 target = s->img_n; // if they want monochrome, we'll post-convert3063 out = (stbi_uc *) malloc(target * s->img_x * s->img_y);3064 if (!out) return epuc("outofmem", "Out of memory");3065 if (bpp < 16) {3066 int z=0;3067 if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }3068 for (i=0; i < psize; ++i) {3069 pal[i][2] = get8u(s);3070 pal[i][1] = get8u(s);3071 pal[i][0] = get8u(s);3072 if (hsz != 12) get8(s);3073 pal[i][3] = 255;3074 }3075 skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));3076 if (bpp == 4) width = (s->img_x + 1) >> 1;3077 else if (bpp == 8) width = s->img_x;3078 else { free(out); return epuc("bad bpp", "Corrupt BMP"); }3079 pad = (-width)&3;3080 for (j=0; j < (int) s->img_y; ++j) {3081 for (i=0; i < (int) s->img_x; i += 2) {3082 int v=get8(s),v2=0;3083 if (bpp == 4) {3084 v2 = v & 15;3085 v >>= 4;3086 }3087 out[z++] = pal[v][0];3088 out[z++] = pal[v][1];3089 out[z++] = pal[v][2];3090 if (target == 4) out[z++] = 255;3091 if (i+1 == (int) s->img_x) break;3092 v = (bpp == 8) ? get8(s) : v2;3093 out[z++] = pal[v][0];3094 out[z++] = pal[v][1];3095 out[z++] = pal[v][2];3096 if (target == 4) out[z++] = 255;3097 }3098 skip(s, pad);3099 }3100 } else {3101 int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;3102 int z = 0;3103 int easy=0;3104 skip(s, offset - 14 - hsz);3105 if (bpp == 24) width = 3 * s->img_x;3106 else if (bpp == 16) width = 2*s->img_x;3107 else /* bpp = 32 and pad = 0 */ width=0;3108 pad = (-width) & 3;3109 if (bpp == 24) {3110 easy = 1;3111 } else if (bpp == 32) {3112 if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)3113 easy = 2;3114 }3115 if (!easy) {3116 if (!mr || !mg || !mb) { free(out); return epuc("bad masks", "Corrupt BMP"); }3117 // right shift amt to put high bit in position #73118 rshift = high_bit(mr)-7; rcount = bitcount(mr);3119 gshift = high_bit(mg)-7; gcount = bitcount(mg);3120 bshift = high_bit(mb)-7; bcount = bitcount(mb);3121 ashift = high_bit(ma)-7; acount = bitcount(ma);3122 }3123 for (j=0; j < (int) s->img_y; ++j) {3124 if (easy) {3125 for (i=0; i < (int) s->img_x; ++i) {3126 int a;3127 out[z+2] = get8u(s);3128 out[z+1] = get8u(s);3129 out[z+0] = get8u(s);3130 z += 3;3131 a = (easy == 2 ? get8(s) : 255);3132 if (target == 4) out[z++] = (stbi__uint8) a;3133 }3134 } else {3135 for (i=0; i < (int) s->img_x; ++i) {3136 stbi__uint32 v = (stbi__uint32) (bpp == 16 ? get16le(s) : get32le(s));3137 int a;3138 out[z++] = (stbi__uint8) shiftsigned(v & mr, rshift, rcount);3139 out[z++] = (stbi__uint8) shiftsigned(v & mg, gshift, gcount);3140 out[z++] = (stbi__uint8) shiftsigned(v & mb, bshift, bcount);3141 a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);3142 if (target == 4) out[z++] = (stbi__uint8) a; 3143 }3144 }3145 skip(s, pad);3146 }3147 }3148 if (flip_vertically) {3149 stbi_uc t;3150 for (j=0; j < (int) s->img_y>>1; ++j) {3151 stbi_uc *p1 = out + j *s->img_x*target;3152 stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;3153 for (i=0; i < (int) s->img_x*target; ++i) {3154 t = p1[i], p1[i] = p2[i], p2[i] = t;3155 }3156 }3157 }31583159 if (req_comp && req_comp != target) {3160 out = convert_format(out, target, req_comp, s->img_x, s->img_y);3161 if (out == NULL) return out; // convert_format frees input on failure3162 }31633164 *x = s->img_x;3165 *y = s->img_y;3166 if (comp) *comp = s->img_n;3167 return out;3168}31693170static stbi_uc *stbi_bmp_load(stbi *s,int *x, int *y, int *comp, int req_comp)3171{3172 return bmp_load(s, x,y,comp,req_comp);3173}317431753176// Targa Truevision - TGA3177// by Jonathan Dummer31783179static int tga_info(stbi *s, int *x, int *y, int *comp)3180{3181 int tga_w, tga_h, tga_comp;3182 int sz;3183 get8u(s); // discard Offset3184 sz = get8u(s); // color type3185 if( sz > 1 ) {3186 stbi_rewind(s);3187 return 0; // only RGB or indexed allowed3188 }3189 sz = get8u(s); // image type3190 // only RGB or grey allowed, +/- RLE3191 if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;3192 skip(s,9);3193 tga_w = get16le(s);3194 if( tga_w < 1 ) {3195 stbi_rewind(s);3196 return 0; // test width3197 }3198 tga_h = get16le(s);3199 if( tga_h < 1 ) {3200 stbi_rewind(s);3201 return 0; // test height3202 }3203 sz = get8(s); // bits per pixel3204 // only RGB or RGBA or grey allowed3205 if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {3206 stbi_rewind(s);3207 return 0;3208 }3209 tga_comp = sz;3210 if (x) *x = tga_w;3211 if (y) *y = tga_h;3212 if (comp) *comp = tga_comp / 8;3213 return 1; // seems to have passed everything3214}32153216int stbi_tga_info(stbi *s, int *x, int *y, int *comp)3217{3218 return tga_info(s, x, y, comp);3219}32203221static int tga_test(stbi *s)3222{3223 int sz;3224 get8u(s); // discard Offset3225 sz = get8u(s); // color type3226 if ( sz > 1 ) return 0; // only RGB or indexed allowed3227 sz = get8u(s); // image type3228 if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE3229 get16(s); // discard palette start3230 get16(s); // discard palette length3231 get8(s); // discard bits per palette color entry3232 get16(s); // discard x origin3233 get16(s); // discard y origin3234 if ( get16(s) < 1 ) return 0; // test width3235 if ( get16(s) < 1 ) return 0; // test height3236 sz = get8(s); // bits per pixel3237 if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed3238 return 1; // seems to have passed everything3239}32403241static int stbi_tga_test(stbi *s)3242{3243 int res = tga_test(s);3244 stbi_rewind(s);3245 return res;3246}32473248static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)3249{3250 // read in the TGA header stuff3251 int tga_offset = get8u(s);3252 int tga_indexed = get8u(s);3253 int tga_image_type = get8u(s);3254 int tga_is_RLE = 0;3255 int tga_palette_start = get16le(s);3256 int tga_palette_len = get16le(s);3257 int tga_palette_bits = get8u(s);3258 int tga_x_origin = get16le(s);3259 int tga_y_origin = get16le(s);3260 int tga_width = get16le(s);3261 int tga_height = get16le(s);3262 int tga_bits_per_pixel = get8u(s);3263 int tga_comp = tga_bits_per_pixel / 8;3264 int tga_inverted = get8u(s);3265 // image data3266 unsigned char *tga_data;3267 unsigned char *tga_palette = NULL;3268 int i, j;3269 unsigned char raw_data[4];3270 int RLE_count = 0;3271 int RLE_repeating = 0;3272 int read_next_pixel = 1;32733274 // do a tiny bit of precessing3275 if ( tga_image_type >= 8 )3276 {3277 tga_image_type -= 8;3278 tga_is_RLE = 1;3279 }3280 /* int tga_alpha_bits = tga_inverted & 15; */3281 tga_inverted = 1 - ((tga_inverted >> 5) & 1);32823283 // error check3284 if ( //(tga_indexed) ||3285 (tga_width < 1) || (tga_height < 1) ||3286 (tga_image_type < 1) || (tga_image_type > 3) ||3287 ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&3288 (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))3289 )3290 {3291 return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA3292 }32933294 // If I'm paletted, then I'll use the number of bits from the palette3295 if ( tga_indexed )3296 {3297 tga_comp = tga_palette_bits / 8;3298 }32993300 // tga info3301 *x = tga_width;3302 *y = tga_height;3303 if (comp) *comp = tga_comp;33043305 tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );3306 if (!tga_data) return epuc("outofmem", "Out of memory");33073308 // skip to the data's starting position (offset usually = 0)3309 skip(s, tga_offset );33103311 if ( !tga_indexed && !tga_is_RLE) {3312 for (i=0; i < tga_height; ++i) {3313 int y = tga_inverted ? tga_height -i - 1 : i;3314 stbi__uint8 *tga_row = tga_data + y*tga_width*tga_comp;3315 getn(s, tga_row, tga_width * tga_comp);3316 }3317 } else {3318 // do I need to load a palette?3319 if ( tga_indexed)3320 {3321 // any data to skip? (offset usually = 0)3322 skip(s, tga_palette_start );3323 // load the palette3324 tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );3325 if (!tga_palette) {3326 free(tga_data);3327 return epuc("outofmem", "Out of memory");3328 }3329 if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {3330 free(tga_data);3331 free(tga_palette);3332 return epuc("bad palette", "Corrupt TGA");3333 }3334 }3335 // load the data3336 for (i=0; i < tga_width * tga_height; ++i)3337 {3338 // if I'm in RLE mode, do I need to get a RLE chunk?3339 if ( tga_is_RLE )3340 {3341 if ( RLE_count == 0 )3342 {3343 // yep, get the next byte as a RLE command3344 int RLE_cmd = get8u(s);3345 RLE_count = 1 + (RLE_cmd & 127);3346 RLE_repeating = RLE_cmd >> 7;3347 read_next_pixel = 1;3348 } else if ( !RLE_repeating )3349 {3350 read_next_pixel = 1;3351 }3352 } else3353 {3354 read_next_pixel = 1;3355 }3356 // OK, if I need to read a pixel, do it now3357 if ( read_next_pixel )3358 {3359 // load however much data we did have3360 if ( tga_indexed )3361 {3362 // read in 1 byte, then perform the lookup3363 int pal_idx = get8u(s);3364 if ( pal_idx >= tga_palette_len )3365 {3366 // invalid index3367 pal_idx = 0;3368 }3369 pal_idx *= tga_bits_per_pixel / 8;3370 for (j = 0; j*8 < tga_bits_per_pixel; ++j)3371 {3372 raw_data[j] = tga_palette[pal_idx+j];3373 }3374 } else3375 {3376 // read in the data raw3377 for (j = 0; j*8 < tga_bits_per_pixel; ++j)3378 {3379 raw_data[j] = get8u(s);3380 }3381 }3382 // clear the reading flag for the next pixel3383 read_next_pixel = 0;3384 } // end of reading a pixel33853386 // copy data3387 for (j = 0; j < tga_comp; ++j)3388 tga_data[i*tga_comp+j] = raw_data[j];33893390 // in case we're in RLE mode, keep counting down3391 --RLE_count;3392 }3393 // do I need to invert the image?3394 if ( tga_inverted )3395 {3396 for (j = 0; j*2 < tga_height; ++j)3397 {3398 int index1 = j * tga_width * req_comp;3399 int index2 = (tga_height - 1 - j) * tga_width * req_comp;3400 for (i = tga_width * req_comp; i > 0; --i)3401 {3402 unsigned char temp = tga_data[index1];3403 tga_data[index1] = tga_data[index2];3404 tga_data[index2] = temp;3405 ++index1;3406 ++index2;3407 }3408 }3409 }3410 // clear my palette, if I had one3411 if ( tga_palette != NULL )3412 {3413 free( tga_palette );3414 }3415 }34163417 // swap RGB3418 if (tga_comp >= 3)3419 {3420 unsigned char* tga_pixel = tga_data;3421 for (i=0; i < tga_width * tga_height; ++i)3422 {3423 unsigned char temp = tga_pixel[0];3424 tga_pixel[0] = tga_pixel[2];3425 tga_pixel[2] = temp;3426 tga_pixel += tga_comp;3427 }3428 }34293430 // convert to target component count3431 if (req_comp && req_comp != tga_comp)3432 tga_data = convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);34333434 // the things I do to get rid of an error message, and yet keep3435 // Microsoft's C compilers happy... [8^(3436 tga_palette_start = tga_palette_len = tga_palette_bits =3437 tga_x_origin = tga_y_origin = 0;3438 // OK, done3439 return tga_data;3440}34413442static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)3443{3444 return tga_load(s,x,y,comp,req_comp);3445}344634473448// *************************************************************************************************3449// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB34503451static int psd_test(stbi *s)3452{3453 if (get32(s) != 0x38425053) return 0; // "8BPS"3454 else return 1;3455}34563457static int stbi_psd_test(stbi *s)3458{3459 int r = psd_test(s);3460 stbi_rewind(s);3461 return r;3462}34633464static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)3465{3466 int pixelCount;3467 int channelCount, compression;3468 int channel, i, count, len;3469 int w,h;3470 stbi__uint8 *out;34713472 // Check identifier3473 if (get32(s) != 0x38425053) // "8BPS"3474 return epuc("not PSD", "Corrupt PSD image");34753476 // Check file type version.3477 if (get16(s) != 1)3478 return epuc("wrong version", "Unsupported version of PSD image");34793480 // Skip 6 reserved bytes.3481 skip(s, 6 );34823483 // Read the number of channels (R, G, B, A, etc).3484 channelCount = get16(s);3485 if (channelCount < 0 || channelCount > 16)3486 return epuc("wrong channel count", "Unsupported number of channels in PSD image");34873488 // Read the rows and columns of the image.3489 h = get32(s);3490 w = get32(s);3491 3492 // Make sure the depth is 8 bits.3493 if (get16(s) != 8)3494 return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");34953496 // Make sure the color mode is RGB.3497 // Valid options are:3498 // 0: Bitmap3499 // 1: Grayscale3500 // 2: Indexed color3501 // 3: RGB color3502 // 4: CMYK color3503 // 7: Multichannel3504 // 8: Duotone3505 // 9: Lab color3506 if (get16(s) != 3)3507 return epuc("wrong color format", "PSD is not in RGB color format");35083509 // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)3510 skip(s,get32(s) );35113512 // Skip the image resources. (resolution, pen tool paths, etc)3513 skip(s, get32(s) );35143515 // Skip the reserved data.3516 skip(s, get32(s) );35173518 // Find out if the data is compressed.3519 // Known values:3520 // 0: no compression3521 // 1: RLE compressed3522 compression = get16(s);3523 if (compression > 1)3524 return epuc("bad compression", "PSD has an unknown compression format");35253526 // Create the destination image.3527 out = (stbi_uc *) malloc(4 * w*h);3528 if (!out) return epuc("outofmem", "Out of memory");3529 pixelCount = w*h;35303531 // Initialize the data to zero.3532 //memset( out, 0, pixelCount * 4 );3533 3534 // Finally, the image data.3535 if (compression) {3536 // RLE as used by .PSD and .TIFF3537 // Loop until you get the number of unpacked bytes you are expecting:3538 // Read the next source byte into n.3539 // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.3540 // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.3541 // Else if n is 128, noop.3542 // Endloop35433544 // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,3545 // which we're going to just skip.3546 skip(s, h * channelCount * 2 );35473548 // Read the RLE data by channel.3549 for (channel = 0; channel < 4; channel++) {3550 stbi__uint8 *p;3551 3552 p = out+channel;3553 if (channel >= channelCount) {3554 // Fill this channel with default data.3555 for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;3556 } else {3557 // Read the RLE data.3558 count = 0;3559 while (count < pixelCount) {3560 len = get8(s);3561 if (len == 128) {3562 // No-op.3563 } else if (len < 128) {3564 // Copy next len+1 bytes literally.3565 len++;3566 count += len;3567 while (len) {3568 *p = get8u(s);3569 p += 4;3570 len--;3571 }3572 } else if (len > 128) {3573 stbi__uint8 val;3574 // Next -len+1 bytes in the dest are replicated from next source byte.3575 // (Interpret len as a negative 8-bit int.)3576 len ^= 0x0FF;3577 len += 2;3578 val = get8u(s);3579 count += len;3580 while (len) {3581 *p = val;3582 p += 4;3583 len--;3584 }3585 }3586 }3587 }3588 }3589 3590 } else {3591 // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)3592 // where each channel consists of an 8-bit value for each pixel in the image.3593 3594 // Read the data by channel.3595 for (channel = 0; channel < 4; channel++) {3596 stbi__uint8 *p;3597 3598 p = out + channel;3599 if (channel > channelCount) {3600 // Fill this channel with default data.3601 for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;3602 } else {3603 // Read the data.3604 for (i = 0; i < pixelCount; i++)3605 *p = get8u(s), p += 4;3606 }3607 }3608 }36093610 if (req_comp && req_comp != 4) {3611 out = convert_format(out, 4, req_comp, w, h);3612 if (out == NULL) return out; // convert_format frees input on failure3613 }36143615 if (comp) *comp = channelCount;3616 *y = h;3617 *x = w;3618 3619 return out;3620}36213622static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)3623{3624 return psd_load(s,x,y,comp,req_comp);3625}36263627// *************************************************************************************************3628// Softimage PIC loader3629// by Tom Seddon3630//3631// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format3632// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/36333634static int pic_is4(stbi *s,const char *str)3635{3636 int i;3637 for (i=0; i<4; ++i)3638 if (get8(s) != (stbi_uc)str[i])3639 return 0;36403641 return 1;3642}36433644static int pic_test(stbi *s)3645{3646 int i;36473648 if (!pic_is4(s,"\x53\x80\xF6\x34"))3649 return 0;36503651 for(i=0;i<84;++i)3652 get8(s);36533654 if (!pic_is4(s,"PICT"))3655 return 0;36563657 return 1;3658}36593660typedef struct3661{3662 stbi_uc size,type,channel;3663} pic_packet_t;36643665static stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest)3666{3667 int mask=0x80, i;36683669 for (i=0; i<4; ++i, mask>>=1) {3670 if (channel & mask) {3671 if (at_eof(s)) return epuc("bad file","PIC file too short");3672 dest[i]=get8u(s);3673 }3674 }36753676 return dest;3677}36783679static void pic_copyval(int channel,stbi_uc *dest,const stbi_uc *src)3680{3681 int mask=0x80,i;36823683 for (i=0;i<4; ++i, mask>>=1)3684 if (channel&mask)3685 dest[i]=src[i];3686}36873688static stbi_uc *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result)3689{3690 int act_comp=0,num_packets=0,y,chained;3691 pic_packet_t packets[10];36923693 // this will (should...) cater for even some bizarre stuff like having data3694 // for the same channel in multiple packets.3695 do {3696 pic_packet_t *packet;36973698 if (num_packets==sizeof(packets)/sizeof(packets[0]))3699 return epuc("bad format","too many packets");37003701 packet = &packets[num_packets++];37023703 chained = get8(s);3704 packet->size = get8u(s);3705 packet->type = get8u(s);3706 packet->channel = get8u(s);37073708 act_comp |= packet->channel;37093710 if (at_eof(s)) return epuc("bad file","file too short (reading packets)");3711 if (packet->size != 8) return epuc("bad format","packet isn't 8bpp");3712 } while (chained);37133714 *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?37153716 for(y=0; y<height; ++y) {3717 int packet_idx;37183719 for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {3720 pic_packet_t *packet = &packets[packet_idx];3721 stbi_uc *dest = result+y*width*4;37223723 switch (packet->type) {3724 default:3725 return epuc("bad format","packet has bad compression type");37263727 case 0: {//uncompressed3728 int x;37293730 for(x=0;x<width;++x, dest+=4)3731 if (!pic_readval(s,packet->channel,dest))3732 return 0;3733 break;3734 }37353736 case 1://Pure RLE3737 {3738 int left=width, i;37393740 while (left>0) {3741 stbi_uc count,value[4];37423743 count=get8u(s);3744 if (at_eof(s)) return epuc("bad file","file too short (pure read count)");37453746 if (count > left)3747 count = (stbi__uint8) left;37483749 if (!pic_readval(s,packet->channel,value)) return 0;37503751 for(i=0; i<count; ++i,dest+=4)3752 pic_copyval(packet->channel,dest,value);3753 left -= count;3754 }3755 }3756 break;37573758 case 2: {//Mixed RLE3759 int left=width;3760 while (left>0) {3761 int count = get8(s), i;3762 if (at_eof(s)) return epuc("bad file","file too short (mixed read count)");37633764 if (count >= 128) { // Repeated3765 stbi_uc value[4];3766 int i;37673768 if (count==128)3769 count = get16(s);3770 else3771 count -= 127;3772 if (count > left)3773 return epuc("bad file","scanline overrun");37743775 if (!pic_readval(s,packet->channel,value))3776 return 0;37773778 for(i=0;i<count;++i, dest += 4)3779 pic_copyval(packet->channel,dest,value);3780 } else { // Raw3781 ++count;3782 if (count>left) return epuc("bad file","scanline overrun");37833784 for(i=0;i<count;++i, dest+=4)3785 if (!pic_readval(s,packet->channel,dest))3786 return 0;3787 }3788 left-=count;3789 }3790 break;3791 }3792 }3793 }3794 }37953796 return result;3797}37983799static stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp)3800{3801 stbi_uc *result;3802 int i, x,y;38033804 for (i=0; i<92; ++i)3805 get8(s);38063807 x = get16(s);3808 y = get16(s);3809 if (at_eof(s)) return epuc("bad file","file too short (pic header)");3810 if ((1 << 28) / x < y) return epuc("too large", "Image too large to decode");38113812 get32(s); //skip `ratio'3813 get16(s); //skip `fields'3814 get16(s); //skip `pad'38153816 // intermediate buffer is RGBA3817 result = (stbi_uc *) malloc(x*y*4);3818 memset(result, 0xff, x*y*4);38193820 if (!pic_load2(s,x,y,comp, result)) {3821 free(result);3822 result=0;3823 }3824 *px = x;3825 *py = y;3826 if (req_comp == 0) req_comp = *comp;3827 result=convert_format(result,4,req_comp,x,y);38283829 return result;3830}38313832static int stbi_pic_test(stbi *s)3833{3834 int r = pic_test(s);3835 stbi_rewind(s);3836 return r;3837}38383839static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp)3840{3841 return pic_load(s,x,y,comp,req_comp);3842}38433844// *************************************************************************************************3845// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb3846typedef struct stbi_gif_lzw_struct {3847 stbi__int16 prefix;3848 stbi__uint8 first;3849 stbi__uint8 suffix;3850} stbi_gif_lzw;38513852typedef struct stbi_gif_struct3853{3854 int w,h;3855 stbi_uc *out; // output buffer (always 4 components)3856 int flags, bgindex, ratio, transparent, eflags;3857 stbi__uint8 pal[256][4];3858 stbi__uint8 lpal[256][4];3859 stbi_gif_lzw codes[4096];3860 stbi__uint8 *color_table;3861 int parse, step;3862 int lflags;3863 int start_x, start_y;3864 int max_x, max_y;3865 int cur_x, cur_y;3866 int line_size;3867} stbi_gif;38683869static int gif_test(stbi *s)3870{3871 int sz;3872 if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0;3873 sz = get8(s);3874 if (sz != '9' && sz != '7') return 0;3875 if (get8(s) != 'a') return 0;3876 return 1;3877}38783879static int stbi_gif_test(stbi *s)3880{3881 int r = gif_test(s);3882 stbi_rewind(s);3883 return r;3884}38853886static void stbi_gif_parse_colortable(stbi *s, stbi__uint8 pal[256][4], int num_entries, int transp)3887{3888 int i;3889 for (i=0; i < num_entries; ++i) {3890 pal[i][2] = get8u(s);3891 pal[i][1] = get8u(s);3892 pal[i][0] = get8u(s);3893 pal[i][3] = transp ? 0 : 255;3894 } 3895}38963897static int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info)3898{3899 stbi__uint8 version;3900 if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8')3901 return e("not GIF", "Corrupt GIF");39023903 version = get8u(s);3904 if (version != '7' && version != '9') return e("not GIF", "Corrupt GIF");3905 if (get8(s) != 'a') return e("not GIF", "Corrupt GIF");3906 3907 failure_reason = "";3908 g->w = get16le(s);3909 g->h = get16le(s);3910 g->flags = get8(s);3911 g->bgindex = get8(s);3912 g->ratio = get8(s);3913 g->transparent = -1;39143915 if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments39163917 if (is_info) return 1;39183919 if (g->flags & 0x80)3920 stbi_gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);39213922 return 1;3923}39243925static int stbi_gif_info_raw(stbi *s, int *x, int *y, int *comp)3926{3927 stbi_gif g; 3928 if (!stbi_gif_header(s, &g, comp, 1)) {3929 stbi_rewind( s );3930 return 0;3931 }3932 if (x) *x = g.w;3933 if (y) *y = g.h;3934 return 1;3935}39363937static void stbi_out_gif_code(stbi_gif *g, stbi__uint16 code)3938{3939 stbi__uint8 *p, *c;39403941 // recurse to decode the prefixes, since the linked-list is backwards,3942 // and working backwards through an interleaved image would be nasty3943 if (g->codes[code].prefix >= 0)3944 stbi_out_gif_code(g, g->codes[code].prefix);39453946 if (g->cur_y >= g->max_y) return;3947 3948 p = &g->out[g->cur_x + g->cur_y];3949 c = &g->color_table[g->codes[code].suffix * 4];39503951 if (c[3] >= 128) {3952 p[0] = c[2];3953 p[1] = c[1];3954 p[2] = c[0];3955 p[3] = c[3];3956 }3957 g->cur_x += 4;39583959 if (g->cur_x >= g->max_x) {3960 g->cur_x = g->start_x;3961 g->cur_y += g->step;39623963 while (g->cur_y >= g->max_y && g->parse > 0) {3964 g->step = (1 << g->parse) * g->line_size;3965 g->cur_y = g->start_y + (g->step >> 1);3966 --g->parse;3967 }3968 }3969}39703971static stbi__uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g)3972{3973 stbi__uint8 lzw_cs;3974 stbi__int32 len, code;3975 stbi__uint32 first;3976 stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;3977 stbi_gif_lzw *p;39783979 lzw_cs = get8u(s);3980 clear = 1 << lzw_cs;3981 first = 1;3982 codesize = lzw_cs + 1;3983 codemask = (1 << codesize) - 1;3984 bits = 0;3985 valid_bits = 0;3986 for (code = 0; code < clear; code++) {3987 g->codes[code].prefix = -1;3988 g->codes[code].first = (stbi__uint8) code;3989 g->codes[code].suffix = (stbi__uint8) code;3990 }39913992 // support no starting clear code3993 avail = clear+2;3994 oldcode = -1;39953996 len = 0;3997 for(;;) {3998 if (valid_bits < codesize) {3999 if (len == 0) {4000 len = get8(s); // start new block4001 if (len == 0) 4002 return g->out;4003 }4004 --len;4005 bits |= (stbi__int32) get8(s) << valid_bits;4006 valid_bits += 8;4007 } else {4008 stbi__int32 code = bits & codemask;4009 bits >>= codesize;4010 valid_bits -= codesize;4011 // @OPTIMIZE: is there some way we can accelerate the non-clear path?4012 if (code == clear) { // clear code4013 codesize = lzw_cs + 1;4014 codemask = (1 << codesize) - 1;4015 avail = clear + 2;4016 oldcode = -1;4017 first = 0;4018 } else if (code == clear + 1) { // end of stream code4019 skip(s, len);4020 while ((len = get8(s)) > 0)4021 skip(s,len);4022 return g->out;4023 } else if (code <= avail) {4024 if (first) return epuc("no clear code", "Corrupt GIF");40254026 if (oldcode >= 0) {4027 p = &g->codes[avail++];4028 if (avail > 4096) return epuc("too many codes", "Corrupt GIF");4029 p->prefix = (stbi__int16) oldcode;4030 p->first = g->codes[oldcode].first;4031 p->suffix = (code == avail) ? p->first : g->codes[code].first;4032 } else if (code == avail)4033 return epuc("illegal code in raster", "Corrupt GIF");40344035 stbi_out_gif_code(g, (stbi__uint16) code);40364037 if ((avail & codemask) == 0 && avail <= 0x0FFF) {4038 codesize++;4039 codemask = (1 << codesize) - 1;4040 }40414042 oldcode = code;4043 } else {4044 return epuc("illegal code in raster", "Corrupt GIF");4045 }4046 } 4047 }4048}40494050static void stbi_fill_gif_background(stbi_gif *g)4051{4052 int i;4053 stbi__uint8 *c = g->pal[g->bgindex];4054 // @OPTIMIZE: write a dword at a time4055 for (i = 0; i < g->w * g->h * 4; i += 4) {4056 stbi__uint8 *p = &g->out[i];4057 p[0] = c[2];4058 p[1] = c[1];4059 p[2] = c[0];4060 p[3] = c[3];4061 }4062}40634064// this function is designed to support animated gifs, although stb_image doesn't support it4065static stbi__uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp)4066{4067 int i;4068 stbi__uint8 *old_out = 0;40694070 if (g->out == 0) {4071 if (!stbi_gif_header(s, g, comp,0)) return 0; // failure_reason set by stbi_gif_header4072 g->out = (stbi__uint8 *) malloc(4 * g->w * g->h);4073 if (g->out == 0) return epuc("outofmem", "Out of memory");4074 stbi_fill_gif_background(g);4075 } else {4076 // animated-gif-only path4077 if (((g->eflags & 0x1C) >> 2) == 3) {4078 old_out = g->out;4079 g->out = (stbi__uint8 *) malloc(4 * g->w * g->h);4080 if (g->out == 0) return epuc("outofmem", "Out of memory");4081 memcpy(g->out, old_out, g->w*g->h*4);4082 }4083 }4084 4085 for (;;) {4086 switch (get8(s)) {4087 case 0x2C: /* Image Descriptor */4088 {4089 stbi__int32 x, y, w, h;4090 stbi__uint8 *o;40914092 x = get16le(s);4093 y = get16le(s);4094 w = get16le(s);4095 h = get16le(s);4096 if (((x + w) > (g->w)) || ((y + h) > (g->h)))4097 return epuc("bad Image Descriptor", "Corrupt GIF");40984099 g->line_size = g->w * 4;4100 g->start_x = x * 4;4101 g->start_y = y * g->line_size;4102 g->max_x = g->start_x + w * 4;4103 g->max_y = g->start_y + h * g->line_size;4104 g->cur_x = g->start_x;4105 g->cur_y = g->start_y;41064107 g->lflags = get8(s);41084109 if (g->lflags & 0x40) {4110 g->step = 8 * g->line_size; // first interlaced spacing4111 g->parse = 3;4112 } else {4113 g->step = g->line_size;4114 g->parse = 0;4115 }41164117 if (g->lflags & 0x80) {4118 stbi_gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);4119 g->color_table = (stbi__uint8 *) g->lpal; 4120 } else if (g->flags & 0x80) {4121 for (i=0; i < 256; ++i) // @OPTIMIZE: reset only the previous transparent4122 g->pal[i][3] = 255; 4123 if (g->transparent >= 0 && (g->eflags & 0x01))4124 g->pal[g->transparent][3] = 0;4125 g->color_table = (stbi__uint8 *) g->pal;4126 } else4127 return epuc("missing color table", "Corrupt GIF");4128 4129 o = stbi_process_gif_raster(s, g);4130 if (o == NULL) return NULL;41314132 if (req_comp && req_comp != 4)4133 o = convert_format(o, 4, req_comp, g->w, g->h);4134 return o;4135 }41364137 case 0x21: // Comment Extension.4138 {4139 int len;4140 if (get8(s) == 0xF9) { // Graphic Control Extension.4141 len = get8(s);4142 if (len == 4) {4143 g->eflags = get8(s);4144 get16le(s); // delay4145 g->transparent = get8(s);4146 } else {4147 skip(s, len);4148 break;4149 }4150 }4151 while ((len = get8(s)) != 0)4152 skip(s, len);4153 break;4154 }41554156 case 0x3B: // gif stream termination code4157 return (stbi__uint8 *) 1;41584159 default:4160 return epuc("unknown code", "Corrupt GIF");4161 }4162 }4163}41644165static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp)4166{4167 stbi__uint8 *u = 0;4168 stbi_gif g={0};41694170 u = stbi_gif_load_next(s, &g, comp, req_comp);4171 if (u == (void *) 1) u = 0; // end of animated gif marker4172 if (u) {4173 *x = g.w;4174 *y = g.h;4175 }41764177 return u;4178}41794180static int stbi_gif_info(stbi *s, int *x, int *y, int *comp)4181{4182 return stbi_gif_info_raw(s,x,y,comp);4183}418441854186// *************************************************************************************************4187// Radiance RGBE HDR loader4188// originally by Nicolas Schulz4189#ifndef STBI_NO_HDR4190static int hdr_test(stbi *s)4191{4192 const char *signature = "#?RADIANCE\n";4193 int i;4194 for (i=0; signature[i]; ++i)4195 if (get8(s) != signature[i])4196 return 0;4197 return 1;4198}41994200static int stbi_hdr_test(stbi* s)4201{4202 int r = hdr_test(s);4203 stbi_rewind(s);4204 return r;4205}42064207#define HDR_BUFLEN 10244208static char *hdr_gettoken(stbi *z, char *buffer)4209{4210 int len=0;4211 char c = '\0';42124213 c = (char) get8(z);42144215 while (!at_eof(z) && c != '\n') {4216 buffer[len++] = c;4217 if (len == HDR_BUFLEN-1) {4218 // flush to end of line4219 while (!at_eof(z) && get8(z) != '\n')4220 ;4221 break;4222 }4223 c = (char) get8(z);4224 }42254226 buffer[len] = 0;4227 return buffer;4228}42294230static void hdr_convert(float *output, stbi_uc *input, int req_comp)4231{4232 if ( input[3] != 0 ) {4233 float f1;4234 // Exponent4235 f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));4236 if (req_comp <= 2)4237 output[0] = (input[0] + input[1] + input[2]) * f1 / 3;4238 else {4239 output[0] = input[0] * f1;4240 output[1] = input[1] * f1;4241 output[2] = input[2] * f1;4242 }4243 if (req_comp == 2) output[1] = 1;4244 if (req_comp == 4) output[3] = 1;4245 } else {4246 switch (req_comp) {4247 case 4: output[3] = 1; /* fallthrough */4248 case 3: output[0] = output[1] = output[2] = 0;4249 break;4250 case 2: output[1] = 1; /* fallthrough */4251 case 1: output[0] = 0;4252 break;4253 }4254 }4255}42564257static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)4258{4259 char buffer[HDR_BUFLEN];4260 char *token;4261 int valid = 0;4262 int width, height;4263 stbi_uc *scanline;4264 float *hdr_data;4265 int len;4266 unsigned char count, value;4267 int i, j, k, c1,c2, z;426842694270 // Check identifier4271 if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)4272 return epf("not HDR", "Corrupt HDR image");4273 4274 // Parse header4275 for(;;) {4276 token = hdr_gettoken(s,buffer);4277 if (token[0] == 0) break;4278 if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;4279 }42804281 if (!valid) return epf("unsupported format", "Unsupported HDR format");42824283 // Parse width and height4284 // can't use sscanf() if we're not using stdio!4285 token = hdr_gettoken(s,buffer);4286 if (strncmp(token, "-Y ", 3)) return epf("unsupported data layout", "Unsupported HDR format");4287 token += 3;4288 height = (int) strtol(token, &token, 10);4289 while (*token == ' ') ++token;4290 if (strncmp(token, "+X ", 3)) return epf("unsupported data layout", "Unsupported HDR format");4291 token += 3;4292 width = (int) strtol(token, NULL, 10);42934294 *x = width;4295 *y = height;42964297 *comp = 3;4298 if (req_comp == 0) req_comp = 3;42994300 // Read data4301 hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));43024303 // Load image data4304 // image data is stored as some number of sca4305 if ( width < 8 || width >= 32768) {4306 // Read flat data4307 for (j=0; j < height; ++j) {4308 for (i=0; i < width; ++i) {4309 stbi_uc rgbe[4];4310 main_decode_loop:4311 getn(s, rgbe, 4);4312 hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);4313 }4314 }4315 } else {4316 // Read RLE-encoded data4317 scanline = NULL;43184319 for (j = 0; j < height; ++j) {4320 c1 = get8(s);4321 c2 = get8(s);4322 len = get8(s);4323 if (c1 != 2 || c2 != 2 || (len & 0x80)) {4324 // not run-length encoded, so we have to actually use THIS data as a decoded4325 // pixel (note this can't be a valid pixel--one of RGB must be >= 128)4326 stbi__uint8 rgbe[4];4327 rgbe[0] = (stbi__uint8) c1;4328 rgbe[1] = (stbi__uint8) c2;4329 rgbe[2] = (stbi__uint8) len;4330 rgbe[3] = (stbi__uint8) get8u(s);4331 hdr_convert(hdr_data, rgbe, req_comp);4332 i = 1;4333 j = 0;4334 free(scanline);4335 goto main_decode_loop; // yes, this makes no sense4336 }4337 len <<= 8;4338 len |= get8(s);4339 if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }4340 if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);4341 4342 for (k = 0; k < 4; ++k) {4343 i = 0;4344 while (i < width) {4345 count = get8u(s);4346 if (count > 128) {4347 // Run4348 value = get8u(s);4349 count -= 128;4350 for (z = 0; z < count; ++z)4351 scanline[i++ * 4 + k] = value;4352 } else {4353 // Dump4354 for (z = 0; z < count; ++z)4355 scanline[i++ * 4 + k] = get8u(s);4356 }4357 }4358 }4359 for (i=0; i < width; ++i)4360 hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);4361 }4362 free(scanline);4363 }43644365 return hdr_data;4366}43674368static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)4369{4370 return hdr_load(s,x,y,comp,req_comp);4371}43724373static int stbi_hdr_info(stbi *s, int *x, int *y, int *comp)4374{4375 char buffer[HDR_BUFLEN];4376 char *token;4377 int valid = 0;43784379 if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {4380 stbi_rewind( s );4381 return 0;4382 }43834384 for(;;) {4385 token = hdr_gettoken(s,buffer);4386 if (token[0] == 0) break;4387 if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;4388 }43894390 if (!valid) {4391 stbi_rewind( s );4392 return 0;4393 }4394 token = hdr_gettoken(s,buffer);4395 if (strncmp(token, "-Y ", 3)) {4396 stbi_rewind( s );4397 return 0;4398 }4399 token += 3;4400 *y = (int) strtol(token, &token, 10);4401 while (*token == ' ') ++token;4402 if (strncmp(token, "+X ", 3)) {4403 stbi_rewind( s );4404 return 0;4405 }4406 token += 3;4407 *x = (int) strtol(token, NULL, 10);4408 *comp = 3;4409 return 1;4410}4411#endif // STBI_NO_HDR44124413static int stbi_bmp_info(stbi *s, int *x, int *y, int *comp)4414{4415 int hsz;4416 if (get8(s) != 'B' || get8(s) != 'M') {4417 stbi_rewind( s );4418 return 0;4419 }4420 skip(s,12);4421 hsz = get32le(s);4422 if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {4423 stbi_rewind( s );4424 return 0;4425 }4426 if (hsz == 12) {4427 *x = get16le(s);4428 *y = get16le(s);4429 } else {4430 *x = get32le(s);4431 *y = get32le(s);4432 }4433 if (get16le(s) != 1) {4434 stbi_rewind( s );4435 return 0;4436 }4437 *comp = get16le(s) / 8;4438 return 1;4439}44404441static int stbi_psd_info(stbi *s, int *x, int *y, int *comp)4442{4443 int channelCount;4444 if (get32(s) != 0x38425053) {4445 stbi_rewind( s );4446 return 0;4447 }4448 if (get16(s) != 1) {4449 stbi_rewind( s );4450 return 0;4451 }4452 skip(s, 6);4453 channelCount = get16(s);4454 if (channelCount < 0 || channelCount > 16) {4455 stbi_rewind( s );4456 return 0;4457 }4458 *y = get32(s);4459 *x = get32(s);4460 if (get16(s) != 8) {4461 stbi_rewind( s );4462 return 0;4463 }4464 if (get16(s) != 3) {4465 stbi_rewind( s );4466 return 0;4467 }4468 *comp = 4;4469 return 1;4470}44714472static int stbi_pic_info(stbi *s, int *x, int *y, int *comp)4473{4474 int act_comp=0,num_packets=0,chained;4475 pic_packet_t packets[10];44764477 skip(s, 92);44784479 *x = get16(s);4480 *y = get16(s);4481 if (at_eof(s)) return 0;4482 if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {4483 stbi_rewind( s );4484 return 0;4485 }44864487 skip(s, 8);44884489 do {4490 pic_packet_t *packet;44914492 if (num_packets==sizeof(packets)/sizeof(packets[0]))4493 return 0;44944495 packet = &packets[num_packets++];4496 chained = get8(s);4497 packet->size = get8u(s);4498 packet->type = get8u(s);4499 packet->channel = get8u(s);4500 act_comp |= packet->channel;45014502 if (at_eof(s)) {4503 stbi_rewind( s );4504 return 0;4505 }4506 if (packet->size != 8) {4507 stbi_rewind( s );4508 return 0;4509 }4510 } while (chained);45114512 *comp = (act_comp & 0x10 ? 4 : 3);45134514 return 1;4515}45164517static int stbi_info_main(stbi *s, int *x, int *y, int *comp)4518{4519 if (stbi_jpeg_info(s, x, y, comp))4520 return 1;4521 if (stbi_png_info(s, x, y, comp))4522 return 1;4523 if (stbi_gif_info(s, x, y, comp))4524 return 1;4525 if (stbi_bmp_info(s, x, y, comp))4526 return 1;4527 if (stbi_psd_info(s, x, y, comp))4528 return 1;4529 if (stbi_pic_info(s, x, y, comp))4530 return 1;4531 #ifndef STBI_NO_HDR4532 if (stbi_hdr_info(s, x, y, comp))4533 return 1;4534 #endif4535 // test tga last because it's a crappy test!4536 if (stbi_tga_info(s, x, y, comp))4537 return 1;4538 return e("unknown image type", "Image not of any known type, or corrupt");4539}45404541#ifndef STBI_NO_STDIO4542int stbi_info(char const *filename, int *x, int *y, int *comp)4543{4544 FILE *f = fopen(filename, "rb");4545 int result;4546 if (!f) return e("can't fopen", "Unable to open file");4547 result = stbi_info_from_file(f, x, y, comp);4548 fclose(f);4549 return result;4550}45514552int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)4553{4554 int r;4555 stbi s;4556 long pos = ftell(f);4557 start_file(&s, f);4558 r = stbi_info_main(&s,x,y,comp);4559 fseek(f,pos,SEEK_SET);4560 return r;4561}4562#endif // !STBI_NO_STDIO45634564int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)4565{4566 stbi s;4567 start_mem(&s,buffer,len);4568 return stbi_info_main(&s,x,y,comp);4569}45704571int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)4572{4573 stbi s;4574 start_callbacks(&s, (stbi_io_callbacks *) c, user);4575 return stbi_info_main(&s,x,y,comp);4576}45774578#endif // STBI_HEADER_FILE_ONLY45794580#if !defined(STBI_NO_STDIO) && defined(_MSC_VER) && _MSC_VER >= 14004581#pragma warning(pop)4582#endif458345844585/*4586 revision history:4587 1.35 (2014-05-27)4588 various warnings4589 fix broken STBI_SIMD path4590 fix bug where stbi_load_from_file no longer left file pointer in correct place4591 fix broken non-easy path for 32-bit BMP (possibly never used)4592 TGA optimization by Arseny Kapoulkine4593 1.34 (unknown)4594 use STBI_NOTUSED in resample_row_generic(), fix one more leak in tga failure case4595 1.33 (2011-07-14)4596 make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements4597 1.32 (2011-07-13)4598 support for "info" function for all supported filetypes (SpartanJ)4599 1.31 (2011-06-20)4600 a few more leak fixes, bug in PNG handling (SpartanJ)4601 1.30 (2011-06-11)4602 added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)4603 removed deprecated format-specific test/load functions4604 removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway4605 error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)4606 fix inefficiency in decoding 32-bit BMP (David Woo)4607 1.29 (2010-08-16)4608 various warning fixes from Aurelien Pocheville 4609 1.28 (2010-08-01)4610 fix bug in GIF palette transparency (SpartanJ)4611 1.27 (2010-08-01)4612 cast-to-stbi__uint8 to fix warnings4613 1.26 (2010-07-24)4614 fix bug in file buffering for PNG reported by SpartanJ4615 1.25 (2010-07-17)4616 refix trans_data warning (Won Chun)4617 1.24 (2010-07-12)4618 perf improvements reading from files on platforms with lock-heavy fgetc()4619 minor perf improvements for jpeg4620 deprecated type-specific functions so we'll get feedback if they're needed4621 attempt to fix trans_data warning (Won Chun)4622 1.23 fixed bug in iPhone support4623 1.22 (2010-07-10)4624 removed image *writing* support4625 stbi_info support from Jetro Lauha4626 GIF support from Jean-Marc Lienher4627 iPhone PNG-extensions from James Brown4628 warning-fixes from Nicolas Schulz and Janez Zemva (i.e. Janez (U+017D)emva)4629 1.21 fix use of 'stbi__uint8' in header (reported by jon blow)4630 1.20 added support for Softimage PIC, by Tom Seddon4631 1.19 bug in interlaced PNG corruption check (found by ryg)4632 1.18 2008-08-024633 fix a threading bug (local mutable static)4634 1.17 support interlaced PNG4635 1.16 major bugfix - convert_format converted one too many pixels4636 1.15 initialize some fields for thread safety4637 1.14 fix threadsafe conversion bug4638 header-file-only version (#define STBI_HEADER_FILE_ONLY before including)4639 1.13 threadsafe4640 1.12 const qualifiers in the API4641 1.11 Support installable IDCT, colorspace conversion routines4642 1.10 Fixes for 64-bit (don't use "unsigned long")4643 optimized upsampling by Fabian "ryg" Giesen4644 1.09 Fix format-conversion for PSD code (bad global variables!)4645 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz4646 1.07 attempt to fix C++ warning/errors again4647 1.06 attempt to fix C++ warning/errors again4648 1.05 fix TGA loading to return correct *comp and use good luminance calc4649 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free4650 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR4651 1.02 support for (subset of) HDR files, float interface for preferred access to them4652 1.01 fix bug: possible bug in handling right-side up bmps... not sure4653 fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all4654 1.00 interface to zlib that skips zlib header4655 0.99 correct handling of alpha in palette4656 0.98 TGA loader by lonesock; dynamically add loaders (untested)4657 0.97 jpeg errors on too large a file; also catch another malloc failure4658 0.96 fix detection of invalid v value - particleman@mollyrocket forum4659 0.95 during header scan, seek to markers in case of padding4660 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same4661 0.93 handle jpegtran output; verbose errors4662 0.92 read 4,8,16,24,32-bit BMP files of several formats4663 0.91 output 24-bit Windows 3.0 BMP files4664 0.90 fix a few more warnings; bump version number to approach 1.04665 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd4666 0.60 fix compiling as c++4667 0.59 fix warnings: merge Dave Moore's -Wall fixes4668 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian4669 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available4670 0.56 fix bug: zlib uncompressed mode len vs. nlen4671 0.55 fix bug: restart_interval not initialized to 04672 0.54 allow NULL for 'int *comp'4673 0.53 fix bug in png 3->4; speedup png decoding4674 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments4675 0.51 obey req_comp requests, 1-component jpegs return as 1-component,4676 on 'test' only check type, not whether we support this variant4677 0.50 first released version4678*/
modified:tests/image_test.c+35 added-5 removed
1#define STB_IMAGE_WRITE_IMPLEMENTATION2#include "stb_image_write.h"34#define STBI_HEADER_FILE_ONLY5#include "stb_image.c"4#define STB_IMAGE_IMPLEMENTATION5#include "stb_image.h"67#define STB_DEFINE8#include "stb.h"910int main(int argc, char **argv)11{12 int w,h;11 unsigned char *data = stbi_load(argv[1], &w, &h, 0, 4);12 if (data)13 stbi_write_png("c:/x/result.png", w, h, 4, data, w*4);13 if (argc > 1) {14 int i;15 for (i=1; i < argc; ++i) {16 unsigned char *data;17 printf("%s\n", argv[i]);18 data = stbi_load(argv[i], &w, &h, 0, 4);19 assert(data);20 if (data) {21 char fname[512];22 stb_splitpath(fname, argv[i], STB_FILE);23 stbi_write_png(stb_sprintf("output/%s.png", fname), w, h, 4, data, w*4);24 free(data);25 }26 }27 } else {28 int i;29 char **files = stb_readdir_files("images");30 for (i=0; i < stb_arr_len(files); ++i) {31 unsigned char *data;32 printf("%s\n", files[i]);33 data = stbi_load(files[i], &w, &h, 0, 4);34 //assert(data);35 if (data) {36 char fname[512];37 stb_splitpath(fname, files[i], STB_FILE);38 stbi_write_png(stb_sprintf("output/%s.png", fname), w, h, 4, data, w*4);39 free(data);40 } else41 printf("FAILED\n");42 }43 }44 return 0;45}
modified:tests/image_test.dsp-4 removed
84 unmodified lines
85SOURCE=.\image_test.c86# End Source File87# Begin Source File8889SOURCE=..\stb_image.c90# End Source File91# Begin Source File9289SOURCE=..\..\stb_image_write.h90# End Source File91# End Target92# End Project
modified:tests/stb_cpp.dsp-4 removed
85 unmodified lines
86SOURCE=.\stb_cpp.cpp87# End Source File88# Begin Source File8990SOURCE=..\stb_image.c91# End Source File92# Begin Source File9390SOURCE=..\stb_vorbis.c91# End Source File92# Begin Source File93
4 unmodified lines
modified:tests/stb.dsp-4 removed
88 unmodified lines
89SOURCE=.\stb.c90# End Source File91# Begin Source File9293SOURCE=..\stb_image.c94# End Source File95# Begin Source File9693SOURCE=..\stb_vorbis.c94# End Source File95# Begin Source File96
16 unmodified lines
modified:tests/stretch_test.dsp+5 added-5 removed
39 unmodified lines
40# PROP Output_Dir "Release"41# PROP Intermediate_Dir "Release"42# PROP Target_Dir ""43# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c44# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c44# ADD CPP /nologo /W3 /GX /O2 /I "..\.." /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c45# ADD BASE RSC /l 0x409 /d "NDEBUG"46# ADD RSC /l 0x409 /d "NDEBUG"47BSC32=bscmake.exe48# ADD BASE BSC32 /nologo49# ADD BSC32 /nologo50LINK32=link.exe51# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I38652# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I38651# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I38652# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I3865354!ELSEIF "$(CFG)" == "stretch_test - Win32 Debug"5556# PROP BASE Use_MFC 0
13 unmodified lines
70BSC32=bscmake.exe71# ADD BASE BSC32 /nologo72# ADD BSC32 /nologo73LINK32=link.exe74# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept75# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept74# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept75# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept7677!ENDIF 7879# Begin Target
9 unmodified lines
modified:tests/test_c_compilation.c+2 added
1 unmodified line
2#define STB_IMAGE_WRITE_IMPLEMENTATION3#define STB_DXT_IMPLEMENATION4#define STB_C_LEXER_IMPLEMENTATIOn5#define STB_DIVIDE_IMPLEMENTATION6#define STB_IMAGE_IMPLEMENTATION78#include "stb_image.h"9#include "stb_image_write.h"10#include "stb_perlin.h"11#include "stb_dxt.h"12#include "stb_c_lexer.h"
1 unmodified line
modified:tests/test_cpp_compilation.cpp+4 added
2 unmodified lines
3#define STB_IMAGE_WRITE_IMPLEMENTATION4#define STB_DXT_IMPLEMENATION5#define STB_C_LEXER_IMPLEMENTATIOn6#define STB_DIVIDE_IMPLEMENTATION7#define STB_IMAGE_IMPLEMENTATION89#include "stb_truetype.h"10#include "stb_image_write.h"11#include "stb_perlin.h"12#include "stb_dxt.h"13#include "stb_c_lexer.h"14#include "stb_divide.h"15#include "stb_image.h"1617
modified:stb_image_write.h+87 added-85 removed
1/* stb_image_write - v0.93 - public domain - http://nothings.org/stb/stb_image_write.h1/* stb_image_write - v0.94 - public domain - http://nothings.org/stb/stb_image_write.h2 writes out PNG/BMP/TGA images to C stdio - Sean Barrett 20103 no warranty implied; use at your own risk45
176 unmodified lines
182 return outfile(filename, -1,-1, x, y, comp, (void *) data, has_alpha, 0,183 "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);184}185186// stretchy buffer; stbi__sbpush() == vector<>::push_back() -- stbi__sbcount() == vector<>::size()187#define stbi__sbraw(a) ((int *) (a) - 2)188#define stbi__sbm(a) stbi__sbraw(a)[0]189#define stbi__sbn(a) stbi__sbraw(a)[1]186// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size()187#define stbiw__sbraw(a) ((int *) (a) - 2)188#define stbiw__sbm(a) stbiw__sbraw(a)[0]189#define stbiw__sbn(a) stbiw__sbraw(a)[1]190191#define stbi__sbneedgrow(a,n) ((a)==0 || stbi__sbn(a)+n >= stbi__sbm(a))192#define stbi__sbmaybegrow(a,n) (stbi__sbneedgrow(a,(n)) ? stbi__sbgrow(a,n) : 0)193#define stbi__sbgrow(a,n) stbi__sbgrowf((void **) &(a), (n), sizeof(*(a)))191#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a))192#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0)193#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a)))194195#define stbi__sbpush(a, v) (stbi__sbmaybegrow(a,1), (a)[stbi__sbn(a)++] = (v))196#define stbi__sbcount(a) ((a) ? stbi__sbn(a) : 0)197#define stbi__sbfree(a) ((a) ? free(stbi__sbraw(a)),0 : 0)195#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v))196#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0)197#define stbiw__sbfree(a) ((a) ? free(stbiw__sbraw(a)),0 : 0)198199static void *stbi__sbgrowf(void **arr, int increment, int itemsize)199static void *stbiw__sbgrowf(void **arr, int increment, int itemsize)200{201 int m = *arr ? 2*stbi__sbm(*arr)+increment : increment+1;202 void *p = realloc(*arr ? stbi__sbraw(*arr) : 0, itemsize * m + sizeof(int)*2);201 int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1;202 void *p = realloc(*arr ? stbiw__sbraw(*arr) : 0, itemsize * m + sizeof(int)*2);203 assert(p);204 if (p) {205 if (!*arr) ((int *) p)[1] = 0;206 *arr = (void *) ((int *) p + 2);207 stbi__sbm(*arr) = m;207 stbiw__sbm(*arr) = m;208 }209 return *arr;210}211212static unsigned char *stbi__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)212static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)213{214 while (*bitcount >= 8) {215 stbi__sbpush(data, (unsigned char) *bitbuffer);215 stbiw__sbpush(data, (unsigned char) *bitbuffer);216 *bitbuffer >>= 8;217 *bitcount -= 8;218 }219 return data;220}221222static int stbi__zlib_bitrev(int code, int codebits)222static int stbiw__zlib_bitrev(int code, int codebits)223{224 int res=0;225 while (codebits--) {226 res = (res << 1) | (code & 1);
1 unmodified line
228 }229 return res;230}231232static unsigned int stbi__zlib_countm(unsigned char *a, unsigned char *b, int limit)232static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit)233{234 int i;235 for (i=0; i < limit && i < 258; ++i)236 if (a[i] != b[i]) break;237 return i;238}239240static unsigned int stbi__zhash(unsigned char *data)240static unsigned int stbiw__zhash(unsigned char *data)241{242 stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);243 hash ^= hash << 3;244 hash += hash >> 5;
3 unmodified lines
248 hash += hash >> 6;249 return hash;250}251252#define stbi__zlib_flush() (out = stbi__zlib_flushf(out, &bitbuf, &bitcount))253#define stbi__zlib_add(code,codebits) \254 (bitbuf |= (code) << bitcount, bitcount += (codebits), stbi__zlib_flush())255#define stbi__zlib_huffa(b,c) stbi__zlib_add(stbi__zlib_bitrev(b,c),c)252#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount))253#define stbiw__zlib_add(code,codebits) \254 (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush())255#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c)256// default huffman tables257#define stbi__zlib_huff1(n) stbi__zlib_huffa(0x30 + (n), 8)258#define stbi__zlib_huff2(n) stbi__zlib_huffa(0x190 + (n)-144, 9)259#define stbi__zlib_huff3(n) stbi__zlib_huffa(0 + (n)-256,7)260#define stbi__zlib_huff4(n) stbi__zlib_huffa(0xc0 + (n)-280,8)261#define stbi__zlib_huff(n) ((n) <= 143 ? stbi__zlib_huff1(n) : (n) <= 255 ? stbi__zlib_huff2(n) : (n) <= 279 ? stbi__zlib_huff3(n) : stbi__zlib_huff4(n))262#define stbi__zlib_huffb(n) ((n) <= 143 ? stbi__zlib_huff1(n) : stbi__zlib_huff2(n))257#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8)258#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9)259#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7)260#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8)261#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n))262#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n))263264#define stbi__ZHASH 16384264#define stbiw__ZHASH 16384265266unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)267{268 static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };
2 unmodified lines
271 static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };272 unsigned int bitbuf=0;273 int i,j, bitcount=0;274 unsigned char *out = NULL;275 unsigned char **hash_table[stbi__ZHASH]; // 64KB on the stack!275 unsigned char **hash_table[stbiw__ZHASH]; // 64KB on the stack!276 if (quality < 5) quality = 5;277278 stbi__sbpush(out, 0x78); // DEFLATE 32K window279 stbi__sbpush(out, 0x5e); // FLEVEL = 1280 stbi__zlib_add(1,1); // BFINAL = 1281 stbi__zlib_add(1,2); // BTYPE = 1 -- fixed huffman278 stbiw__sbpush(out, 0x78); // DEFLATE 32K window279 stbiw__sbpush(out, 0x5e); // FLEVEL = 1280 stbiw__zlib_add(1,1); // BFINAL = 1281 stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman282283 for (i=0; i < stbi__ZHASH; ++i)283 for (i=0; i < stbiw__ZHASH; ++i)284 hash_table[i] = NULL;285286 i=0;287 while (i < data_len-3) {288 // hash next 3 bytes of data to be compressed 289 int h = stbi__zhash(data+i)&(stbi__ZHASH-1), best=3;289 int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3;290 unsigned char *bestloc = 0;291 unsigned char **hlist = hash_table[h];292 int n = stbi__sbcount(hlist);292 int n = stbiw__sbcount(hlist);293 for (j=0; j < n; ++j) {294 if (hlist[j]-data > i-32768) { // if entry lies within window295 int d = stbi__zlib_countm(hlist[j], data+i, data_len-i);295 int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i);296 if (d >= best) best=d,bestloc=hlist[j];297 }298 }299 // when hash table entry is too long, delete half the entries300 if (hash_table[h] && stbi__sbn(hash_table[h]) == 2*quality) {300 if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) {301 memcpy(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);302 stbi__sbn(hash_table[h]) = quality;302 stbiw__sbn(hash_table[h]) = quality;303 }304 stbi__sbpush(hash_table[h],data+i);304 stbiw__sbpush(hash_table[h],data+i);305306 if (bestloc) {307 // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal308 h = stbi__zhash(data+i+1)&(stbi__ZHASH-1);308 h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1);309 hlist = hash_table[h];310 n = stbi__sbcount(hlist);310 n = stbiw__sbcount(hlist);311 for (j=0; j < n; ++j) {312 if (hlist[j]-data > i-32767) {313 int e = stbi__zlib_countm(hlist[j], data+i+1, data_len-i-1);313 int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1);314 if (e > best) { // if next match is better, bail on current match315 bestloc = NULL;316 break;317 }
4 unmodified lines
322 if (bestloc) {323 int d = (int) (data+i - bestloc); // distance back324 assert(d <= 32767 && best <= 258);325 for (j=0; best > lengthc[j+1]-1; ++j);326 stbi__zlib_huff(j+257);327 if (lengtheb[j]) stbi__zlib_add(best - lengthc[j], lengtheb[j]);326 stbiw__zlib_huff(j+257);327 if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]);328 for (j=0; d > distc[j+1]-1; ++j);329 stbi__zlib_add(stbi__zlib_bitrev(j,5),5);330 if (disteb[j]) stbi__zlib_add(d - distc[j], disteb[j]);329 stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5);330 if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]);331 i += best;332 } else {333 stbi__zlib_huffb(data[i]);333 stbiw__zlib_huffb(data[i]);334 ++i;335 }336 }337 // write out final bytes338 for (;i < data_len; ++i)339 stbi__zlib_huffb(data[i]);340 stbi__zlib_huff(256); // end of block339 stbiw__zlib_huffb(data[i]);340 stbiw__zlib_huff(256); // end of block341 // pad with 0 bits to byte boundary342 while (bitcount)343 stbi__zlib_add(0,1);343 stbiw__zlib_add(0,1);344345 for (i=0; i < stbi__ZHASH; ++i)346 (void) stbi__sbfree(hash_table[i]);345 for (i=0; i < stbiw__ZHASH; ++i)346 (void) stbiw__sbfree(hash_table[i]);347348 {349 // compute adler32 on input350 unsigned int i=0, s1=1, s2=0, blocklen = data_len % 5552;
3 unmodified lines
354 s1 %= 65521, s2 %= 65521;355 j += blocklen;356 blocklen = 5552;357 }358 stbi__sbpush(out, (unsigned char) (s2 >> 8));359 stbi__sbpush(out, (unsigned char) s2);360 stbi__sbpush(out, (unsigned char) (s1 >> 8));361 stbi__sbpush(out, (unsigned char) s1);358 stbiw__sbpush(out, (unsigned char) (s2 >> 8));359 stbiw__sbpush(out, (unsigned char) s2);360 stbiw__sbpush(out, (unsigned char) (s1 >> 8));361 stbiw__sbpush(out, (unsigned char) s1);362 }363 *out_len = stbi__sbn(out);363 *out_len = stbiw__sbn(out);364 // make returned pointer freeable365 memmove(stbi__sbraw(out), out, *out_len);366 return (unsigned char *) stbi__sbraw(out);365 memmove(stbiw__sbraw(out), out, *out_len);366 return (unsigned char *) stbiw__sbraw(out);367}368369unsigned int stbi__crc32(unsigned char *buffer, int len)369unsigned int stbiw__crc32(unsigned char *buffer, int len)370{371 static unsigned int crc_table[256];372 unsigned int crc = ~0u;373 int i,j;
5 unmodified lines
379 crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];380 return ~crc;381}382383#define stbi__wpng4(o,a,b,c,d) ((o)[0]=(unsigned char)(a),(o)[1]=(unsigned char)(b),(o)[2]=(unsigned char)(c),(o)[3]=(unsigned char)(d),(o)+=4)384#define stbi__wp32(data,v) stbi__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));385#define stbi__wptag(data,s) stbi__wpng4(data, s[0],s[1],s[2],s[3])383#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=(unsigned char)(a),(o)[1]=(unsigned char)(b),(o)[2]=(unsigned char)(c),(o)[3]=(unsigned char)(d),(o)+=4)384#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));385#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3])386387static void stbi__wpcrc(unsigned char **data, int len)387static void stbiw__wpcrc(unsigned char **data, int len)388{389 unsigned int crc = stbi__crc32(*data - len - 4, len+4);390 stbi__wp32(*data, crc);389 unsigned int crc = stbiw__crc32(*data - len - 4, len+4);390 stbiw__wp32(*data, crc);391}392393static unsigned char stbi__paeth(int a, int b, int c)393static unsigned char stbiw__paeth(int a, int b, int c)394{395 int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);396 if (pa <= pb && pa <= pc) return (unsigned char) a;397 if (pb <= pc) return (unsigned char) b;
27 unmodified lines
425 case 0: line_buffer[i] = z[i]; break;426 case 1: line_buffer[i] = z[i]; break;427 case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;428 case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break;429 case 4: line_buffer[i] = (signed char) (z[i] - stbi__paeth(0,z[i-stride_bytes],0)); break;429 case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-stride_bytes],0)); break;430 case 5: line_buffer[i] = z[i]; break;431 case 6: line_buffer[i] = z[i]; break;432 }433 for (i=n; i < x*n; ++i) {
1 unmodified line
435 case 0: line_buffer[i] = z[i]; break;436 case 1: line_buffer[i] = z[i] - z[i-n]; break;437 case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;438 case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break;439 case 4: line_buffer[i] = z[i] - stbi__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break;439 case 4: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break;440 case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break;441 case 6: line_buffer[i] = z[i] - stbi__paeth(z[i-n], 0,0); break;441 case 6: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break;442 }443 }444 if (p) break;445 for (i=0; i < x*n; ++i)
16 unmodified lines
462 *out_len = 8 + 12+13 + 12+zlen + 12;463464 o=out;465 memcpy(o,sig,8); o+= 8;466 stbi__wp32(o, 13); // header length467 stbi__wptag(o, "IHDR");468 stbi__wp32(o, x);469 stbi__wp32(o, y);466 stbiw__wp32(o, 13); // header length467 stbiw__wptag(o, "IHDR");468 stbiw__wp32(o, x);469 stbiw__wp32(o, y);470 *o++ = 8;471 *o++ = (unsigned char) ctype[n];472 *o++ = 0;473 *o++ = 0;474 *o++ = 0;475 stbi__wpcrc(&o,13);475 stbiw__wpcrc(&o,13);476477 stbi__wp32(o, zlen);478 stbi__wptag(o, "IDAT");477 stbiw__wp32(o, zlen);478 stbiw__wptag(o, "IDAT");479 memcpy(o, zlib, zlen); o += zlen; free(zlib);480 stbi__wpcrc(&o, zlen);480 stbiw__wpcrc(&o, zlen);481482 stbi__wp32(o,0);483 stbi__wptag(o, "IEND");484 stbi__wpcrc(&o,0);482 stbiw__wp32(o,0);483 stbiw__wptag(o, "IEND");484 stbiw__wpcrc(&o,0);485486 assert(o == out + *out_len);487488 return out;
15 unmodified lines
504#endif // STB_IMAGE_WRITE_IMPLEMENTATION505506/* Revision history507508 0.94 (2014-05-31)509 rename private functions to avoid conflicts with stb_image.h510 0.93 (2014-05-27)511 warning fixes512 0.92 (2010-08-01)513 casts to unsigned char to fix warnings
4 unmodified lines
deleted:stb_image.c-4678 removed
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{2001 assert(bits <= 16);2002 // to bit reverse n bits, reverse 16 and shift2003 // e.g. 11 bits, bit reverse and shift away 52004 return bitreverse16(v) >> (16-bits);2005}20062007static int zbuild_huffman(zhuffman *z, stbi__uint8 *sizelist, int num)2008{2009 int i,k=0;2010 int code, next_code[16], sizes[17];20112012 // DEFLATE spec for generating codes2013 memset(sizes, 0, sizeof(sizes));2014 memset(z->fast, 255, sizeof(z->fast));2015 for (i=0; i < num; ++i) 2016 ++sizes[sizelist[i]];2017 sizes[0] = 0;2018 for (i=1; i < 16; ++i)2019 assert(sizes[i] <= (1 << i));2020 code = 0;2021 for (i=1; i < 16; ++i) {2022 next_code[i] = code;2023 z->firstcode[i] = (stbi__uint16) code;2024 z->firstsymbol[i] = (stbi__uint16) k;2025 code = (code + sizes[i]);2026 if (sizes[i])2027 if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");2028 z->maxcode[i] = code << (16-i); // preshift for inner loop2029 code <<= 1;2030 k += sizes[i];2031 }2032 z->maxcode[16] = 0x10000; // sentinel2033 for (i=0; i < num; ++i) {2034 int s = sizelist[i];2035 if (s) {2036 int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];2037 z->size[c] = (stbi__uint8)s;2038 z->value[c] = (stbi__uint16)i;2039 if (s <= ZFAST_BITS) {2040 int k = bit_reverse(next_code[s],s);2041 while (k < (1 << ZFAST_BITS)) {2042 z->fast[k] = (stbi__uint16) c;2043 k += (1 << s);2044 }2045 }2046 ++next_code[s];2047 }2048 }2049 return 1;2050}20512052// zlib-from-memory implementation for PNG reading2053// because PNG allows splitting the zlib stream arbitrarily,2054// and it's annoying structurally to have PNG call ZLIB call PNG,2055// we require PNG read all the IDATs and combine them into a single2056// memory buffer20572058typedef struct2059{2060 stbi__uint8 *zbuffer, *zbuffer_end;2061 int num_bits;2062 stbi__uint32 code_buffer;20632064 char *zout;2065 char *zout_start;2066 char *zout_end;2067 int z_expandable;20682069 zhuffman z_length, z_distance;2070} zbuf;20712072stbi_inline static int zget8(zbuf *z)2073{2074 if (z->zbuffer >= z->zbuffer_end) return 0;2075 return *z->zbuffer++;2076}20772078static void fill_bits(zbuf *z)2079{2080 do {2081 assert(z->code_buffer < (1U << z->num_bits));2082 z->code_buffer |= zget8(z) << z->num_bits;2083 z->num_bits += 8;2084 } while (z->num_bits <= 24);2085}20862087stbi_inline static unsigned int zreceive(zbuf *z, int n)2088{2089 unsigned int k;2090 if (z->num_bits < n) fill_bits(z);2091 k = z->code_buffer & ((1 << n) - 1);2092 z->code_buffer >>= n;2093 z->num_bits -= n;2094 return k; 2095}20962097stbi_inline static int zhuffman_decode(zbuf *a, zhuffman *z)2098{2099 int b,s,k;2100 if (a->num_bits < 16) fill_bits(a);2101 b = z->fast[a->code_buffer & ZFAST_MASK];2102 if (b < 0xffff) {2103 s = z->size[b];2104 a->code_buffer >>= s;2105 a->num_bits -= s;2106 return z->value[b];2107 }21082109 // not resolved by fast table, so compute it the slow way2110 // use jpeg approach, which requires MSbits at top2111 k = bit_reverse(a->code_buffer, 16);2112 for (s=ZFAST_BITS+1; ; ++s)2113 if (k < z->maxcode[s])2114 break;2115 if (s == 16) return -1; // invalid code!2116 // code size is s, so:2117 b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];2118 assert(z->size[b] == s);2119 a->code_buffer >>= s;2120 a->num_bits -= s;2121 return z->value[b];2122}21232124static int expand(zbuf *z, int n) // need to make room for n bytes2125{2126 char *q;2127 int cur, limit;2128 if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");2129 cur = (int) (z->zout - z->zout_start);2130 limit = (int) (z->zout_end - z->zout_start);2131 while (cur + n > limit)2132 limit *= 2;2133 q = (char *) realloc(z->zout_start, limit);2134 if (q == NULL) return e("outofmem", "Out of memory");2135 z->zout_start = q;2136 z->zout = q + cur;2137 z->zout_end = q + limit;2138 return 1;2139}21402141static int length_base[31] = {2142 3,4,5,6,7,8,9,10,11,13,2143 15,17,19,23,27,31,35,43,51,59,2144 67,83,99,115,131,163,195,227,258,0,0 };21452146static int length_extra[31]= 2147{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };21482149static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,2150257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};21512152static int dist_extra[32] =2153{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};21542155static int parse_huffman_block(zbuf *a)2156{2157 for(;;) {2158 int z = zhuffman_decode(a, &a->z_length);2159 if (z < 256) {2160 if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes2161 if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;2162 *a->zout++ = (char) z;2163 } else {2164 stbi__uint8 *p;2165 int len,dist;2166 if (z == 256) return 1;2167 z -= 257;2168 len = length_base[z];2169 if (length_extra[z]) len += zreceive(a, length_extra[z]);2170 z = zhuffman_decode(a, &a->z_distance);2171 if (z < 0) return e("bad huffman code","Corrupt PNG");2172 dist = dist_base[z];2173 if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);2174 if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");2175 if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;2176 p = (stbi__uint8 *) (a->zout - dist);2177 while (len--)2178 *a->zout++ = *p++;2179 }2180 }2181}21822183static int compute_huffman_codes(zbuf *a)2184{2185 static stbi__uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };2186 zhuffman z_codelength;2187 stbi__uint8 lencodes[286+32+137];//padding for maximum single op2188 stbi__uint8 codelength_sizes[19];2189 int i,n;21902191 int hlit = zreceive(a,5) + 257;2192 int hdist = zreceive(a,5) + 1;2193 int hclen = zreceive(a,4) + 4;21942195 memset(codelength_sizes, 0, sizeof(codelength_sizes));2196 for (i=0; i < hclen; ++i) {2197 int s = zreceive(a,3);2198 codelength_sizes[length_dezigzag[i]] = (stbi__uint8) s;2199 }2200 if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;22012202 n = 0;2203 while (n < hlit + hdist) {2204 int c = zhuffman_decode(a, &z_codelength);2205 assert(c >= 0 && c < 19);2206 if (c < 16)2207 lencodes[n++] = (stbi__uint8) c;2208 else if (c == 16) {2209 c = zreceive(a,2)+3;2210 memset(lencodes+n, lencodes[n-1], c);2211 n += c;2212 } else if (c == 17) {2213 c = zreceive(a,3)+3;2214 memset(lencodes+n, 0, c);2215 n += c;2216 } else {2217 assert(c == 18);2218 c = zreceive(a,7)+11;2219 memset(lencodes+n, 0, c);2220 n += c;2221 }2222 }2223 if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");2224 if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;2225 if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;2226 return 1;2227}22282229static int parse_uncompressed_block(zbuf *a)2230{2231 stbi__uint8 header[4];2232 int len,nlen,k;2233 if (a->num_bits & 7)2234 zreceive(a, a->num_bits & 7); // discard2235 // drain the bit-packed data into header2236 k = 0;2237 while (a->num_bits > 0) {2238 header[k++] = (stbi__uint8) (a->code_buffer & 255); // wtf this warns?2239 a->code_buffer >>= 8;2240 a->num_bits -= 8;2241 }2242 assert(a->num_bits == 0);2243 // now fill header the normal way2244 while (k < 4)2245 header[k++] = (stbi__uint8) zget8(a);2246 len = header[1] * 256 + header[0];2247 nlen = header[3] * 256 + header[2];2248 if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");2249 if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");2250 if (a->zout + len > a->zout_end)2251 if (!expand(a, len)) return 0;2252 memcpy(a->zout, a->zbuffer, len);2253 a->zbuffer += len;2254 a->zout += len;2255 return 1;2256}22572258static int parse_zlib_header(zbuf *a)2259{2260 int cmf = zget8(a);2261 int cm = cmf & 15;2262 /* int cinfo = cmf >> 4; */2263 int flg = zget8(a);2264 if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec2265 if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png2266 if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png2267 // window = 1 << (8 + cinfo)... but who cares, we fully buffer output2268 return 1;2269}22702271// @TODO: should statically initialize these for optimal thread safety2272static stbi__uint8 default_length[288], default_distance[32];2273static void init_defaults(void)2274{2275 int i; // use <= to match clearly with spec2276 for (i=0; i <= 143; ++i) default_length[i] = 8;2277 for ( ; i <= 255; ++i) default_length[i] = 9;2278 for ( ; i <= 279; ++i) default_length[i] = 7;2279 for ( ; i <= 287; ++i) default_length[i] = 8;22802281 for (i=0; i <= 31; ++i) default_distance[i] = 5;2282}22832284int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead2285static int parse_zlib(zbuf *a, int parse_header)2286{2287 int final, type;2288 if (parse_header)2289 if (!parse_zlib_header(a)) return 0;2290 a->num_bits = 0;2291 a->code_buffer = 0;2292 do {2293 final = zreceive(a,1);2294 type = zreceive(a,2);2295 if (type == 0) {2296 if (!parse_uncompressed_block(a)) return 0;2297 } else if (type == 3) {2298 return 0;2299 } else {2300 if (type == 1) {2301 // use fixed code lengths2302 if (!default_distance[31]) init_defaults();2303 if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0;2304 if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0;2305 } else {2306 if (!compute_huffman_codes(a)) return 0;2307 }2308 if (!parse_huffman_block(a)) return 0;2309 }2310 if (stbi_png_partial && a->zout - a->zout_start > 65536)2311 break;2312 } while (!final);2313 return 1;2314}23152316static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)2317{2318 a->zout_start = obuf;2319 a->zout = obuf;2320 a->zout_end = obuf + olen;2321 a->z_expandable = exp;23222323 return parse_zlib(a, parse_header);2324}23252326char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)2327{2328 zbuf a;2329 char *p = (char *) malloc(initial_size);2330 if (p == NULL) return NULL;2331 a.zbuffer = (stbi__uint8 *) buffer;2332 a.zbuffer_end = (stbi__uint8 *) buffer + len;2333 if (do_zlib(&a, p, initial_size, 1, 1)) {2334 if (outlen) *outlen = (int) (a.zout - a.zout_start);2335 return a.zout_start;2336 } else {2337 free(a.zout_start);2338 return NULL;2339 }2340}23412342char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)2343{2344 return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);2345}23462347char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)2348{2349 zbuf a;2350 char *p = (char *) malloc(initial_size);2351 if (p == NULL) return NULL;2352 a.zbuffer = (stbi__uint8 *) buffer;2353 a.zbuffer_end = (stbi__uint8 *) buffer + len;2354 if (do_zlib(&a, p, initial_size, 1, parse_header)) {2355 if (outlen) *outlen = (int) (a.zout - a.zout_start);2356 return a.zout_start;2357 } else {2358 free(a.zout_start);2359 return NULL;2360 }2361}23622363int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)2364{2365 zbuf a;2366 a.zbuffer = (stbi__uint8 *) ibuffer;2367 a.zbuffer_end = (stbi__uint8 *) ibuffer + ilen;2368 if (do_zlib(&a, obuffer, olen, 0, 1))2369 return (int) (a.zout - a.zout_start);2370 else2371 return -1;2372}23732374char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)2375{2376 zbuf a;2377 char *p = (char *) malloc(16384);2378 if (p == NULL) return NULL;2379 a.zbuffer = (stbi__uint8 *) buffer;2380 a.zbuffer_end = (stbi__uint8 *) buffer+len;2381 if (do_zlib(&a, p, 16384, 1, 0)) {2382 if (outlen) *outlen = (int) (a.zout - a.zout_start);2383 return a.zout_start;2384 } else {2385 free(a.zout_start);2386 return NULL;2387 }2388}23892390int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)2391{2392 zbuf a;2393 a.zbuffer = (stbi__uint8 *) ibuffer;2394 a.zbuffer_end = (stbi__uint8 *) ibuffer + ilen;2395 if (do_zlib(&a, obuffer, olen, 0, 0))2396 return (int) (a.zout - a.zout_start);2397 else2398 return -1;2399}24002401// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-182402// simple implementation2403// - only 8-bit samples2404// - no CRC checking2405// - allocates lots of intermediate memory2406// - avoids problem of streaming data between subsystems2407// - avoids explicit window management2408// performance2409// - uses stb_zlib, a PD zlib implementation with fast huffman decoding241024112412typedef struct2413{2414 stbi__uint32 length;2415 stbi__uint32 type;2416} chunk;24172418#define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))24192420static chunk get_chunk_header(stbi *s)2421{2422 chunk c;2423 c.length = get32(s);2424 c.type = get32(s);2425 return c;2426}24272428static int check_png_header(stbi *s)2429{2430 static stbi__uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };2431 int i;2432 for (i=0; i < 8; ++i)2433 if (get8u(s) != png_sig[i]) return e("bad png sig","Not a PNG");2434 return 1;2435}24362437typedef struct2438{2439 stbi *s;2440 stbi__uint8 *idata, *expanded, *out;2441} png;244224432444enum {2445 F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,2446 F_avg_first, F_paeth_first2447};24482449static stbi__uint8 first_row_filter[5] =2450{2451 F_none, F_sub, F_none, F_avg_first, F_paeth_first2452};24532454static int paeth(int a, int b, int c)2455{2456 int p = a + b - c;2457 int pa = abs(p-a);2458 int pb = abs(p-b);2459 int pc = abs(p-c);2460 if (pa <= pb && pa <= pc) return a;2461 if (pb <= pc) return b;2462 return c;2463}24642465// create the png data from post-deflated data2466static int create_png_image_raw(png *a, stbi__uint8 *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y)2467{2468 stbi *s = a->s;2469 stbi__uint32 i,j,stride = x*out_n;2470 int k;2471 int img_n = s->img_n; // copy it into a local for later2472 assert(out_n == s->img_n || out_n == s->img_n+1);2473 if (stbi_png_partial) y = 1;2474 a->out = (stbi__uint8 *) malloc(x * y * out_n);2475 if (!a->out) return e("outofmem", "Out of memory");2476 if (!stbi_png_partial) {2477 if (s->img_x == x && s->img_y == y) {2478 if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");2479 } else { // interlaced:2480 if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");2481 }2482 }2483 for (j=0; j < y; ++j) {2484 stbi__uint8 *cur = a->out + stride*j;2485 stbi__uint8 *prior = cur - stride;2486 int filter = *raw++;2487 if (filter > 4) return e("invalid filter","Corrupt PNG");2488 // if first row, use special filter that doesn't sample previous row2489 if (j == 0) filter = first_row_filter[filter];2490 // handle first pixel explicitly2491 for (k=0; k < img_n; ++k) {2492 switch (filter) {2493 case F_none : cur[k] = raw[k]; break;2494 case F_sub : cur[k] = raw[k]; break;2495 case F_up : cur[k] = raw[k] + prior[k]; break;2496 case F_avg : cur[k] = raw[k] + (prior[k]>>1); break;2497 case F_paeth : cur[k] = (stbi__uint8) (raw[k] + paeth(0,prior[k],0)); break;2498 case F_avg_first : cur[k] = raw[k]; break;2499 case F_paeth_first: cur[k] = raw[k]; break;2500 }2501 }2502 if (img_n != out_n) cur[img_n] = 255;2503 raw += img_n;2504 cur += out_n;2505 prior += out_n;2506 // this is a little gross, so that we don't switch per-pixel or per-component2507 if (img_n == out_n) {2508 #define CASE(f) \2509 case f: \2510 for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \2511 for (k=0; k < img_n; ++k)2512 switch (filter) {2513 CASE(F_none) cur[k] = raw[k]; break;2514 CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break;2515 CASE(F_up) cur[k] = raw[k] + prior[k]; break;2516 CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;2517 CASE(F_paeth) cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;2518 CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;2519 CASE(F_paeth_first) cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;2520 }2521 #undef CASE2522 } else {2523 assert(img_n+1 == out_n);2524 #define CASE(f) \2525 case f: \2526 for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \2527 for (k=0; k < img_n; ++k)2528 switch (filter) {2529 CASE(F_none) cur[k] = raw[k]; break;2530 CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break;2531 CASE(F_up) cur[k] = raw[k] + prior[k]; break;2532 CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;2533 CASE(F_paeth) cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;2534 CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;2535 CASE(F_paeth_first) cur[k] = (stbi__uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;2536 }2537 #undef CASE2538 }2539 }2540 return 1;2541}25422543static int create_png_image(png *a, stbi__uint8 *raw, stbi__uint32 raw_len, int out_n, int interlaced)2544{2545 stbi__uint8 *final;2546 int p;2547 int save;2548 if (!interlaced)2549 return create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);2550 save = stbi_png_partial;2551 stbi_png_partial = 0;25522553 // de-interlacing2554 final = (stbi__uint8 *) malloc(a->s->img_x * a->s->img_y * out_n);2555 for (p=0; p < 7; ++p) {2556 int xorig[] = { 0,4,0,2,0,1,0 };2557 int yorig[] = { 0,0,4,0,2,0,1 };2558 int xspc[] = { 8,8,4,4,2,2,1 };2559 int yspc[] = { 8,8,8,4,4,2,2 };2560 int i,j,x,y;2561 // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 12562 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];2563 y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];2564 if (x && y) {2565 if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {2566 free(final);2567 return 0;2568 }2569 for (j=0; j < y; ++j)2570 for (i=0; i < x; ++i)2571 memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,2572 a->out + (j*x+i)*out_n, out_n);2573 free(a->out);2574 raw += (x*out_n+1)*y;2575 raw_len -= (x*out_n+1)*y;2576 }2577 }2578 a->out = final;25792580 stbi_png_partial = save;2581 return 1;2582}25832584static int compute_transparency(png *z, stbi__uint8 tc[3], int out_n)2585{2586 stbi *s = z->s;2587 stbi__uint32 i, pixel_count = s->img_x * s->img_y;2588 stbi__uint8 *p = z->out;25892590 // compute color-based transparency, assuming we've2591 // already got 255 as the alpha value in the output2592 assert(out_n == 2 || out_n == 4);25932594 if (out_n == 2) {2595 for (i=0; i < pixel_count; ++i) {2596 p[1] = (p[0] == tc[0] ? 0 : 255);2597 p += 2;2598 }2599 } else {2600 for (i=0; i < pixel_count; ++i) {2601 if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])2602 p[3] = 0;2603 p += 4;2604 }2605 }2606 return 1;2607}26082609static int expand_palette(png *a, stbi__uint8 *palette, int len, int pal_img_n)2610{2611 stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;2612 stbi__uint8 *p, *temp_out, *orig = a->out;26132614 p = (stbi__uint8 *) malloc(pixel_count * pal_img_n);2615 if (p == NULL) return e("outofmem", "Out of memory");26162617 // between here and free(out) below, exitting would leak2618 temp_out = p;26192620 if (pal_img_n == 3) {2621 for (i=0; i < pixel_count; ++i) {2622 int n = orig[i]*4;2623 p[0] = palette[n ];2624 p[1] = palette[n+1];2625 p[2] = palette[n+2];2626 p += 3;2627 }2628 } else {2629 for (i=0; i < pixel_count; ++i) {2630 int n = orig[i]*4;2631 p[0] = palette[n ];2632 p[1] = palette[n+1];2633 p[2] = palette[n+2];2634 p[3] = palette[n+3];2635 p += 4;2636 }2637 }2638 free(a->out);2639 a->out = temp_out;26402641 STBI_NOTUSED(len);26422643 return 1;2644}26452646static int stbi_unpremultiply_on_load = 0;2647static int stbi_de_iphone_flag = 0;26482649void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)2650{2651 stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply;2652}2653void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)2654{2655 stbi_de_iphone_flag = flag_true_if_should_convert;2656}26572658static void stbi_de_iphone(png *z)2659{2660 stbi *s = z->s;2661 stbi__uint32 i, pixel_count = s->img_x * s->img_y;2662 stbi__uint8 *p = z->out;26632664 if (s->img_out_n == 3) { // convert bgr to rgb2665 for (i=0; i < pixel_count; ++i) {2666 stbi__uint8 t = p[0];2667 p[0] = p[2];2668 p[2] = t;2669 p += 3;2670 }2671 } else {2672 assert(s->img_out_n == 4);2673 if (stbi_unpremultiply_on_load) {2674 // convert bgr to rgb and unpremultiply2675 for (i=0; i < pixel_count; ++i) {2676 stbi__uint8 a = p[3];2677 stbi__uint8 t = p[0];2678 if (a) {2679 p[0] = p[2] * 255 / a;2680 p[1] = p[1] * 255 / a;2681 p[2] = t * 255 / a;2682 } else {2683 p[0] = p[2];2684 p[2] = t;2685 } 2686 p += 4;2687 }2688 } else {2689 // convert bgr to rgb2690 for (i=0; i < pixel_count; ++i) {2691 stbi__uint8 t = p[0];2692 p[0] = p[2];2693 p[2] = t;2694 p += 4;2695 }2696 }2697 }2698}26992700static int parse_png_file(png *z, int scan, int req_comp)2701{2702 stbi__uint8 palette[1024], pal_img_n=0;2703 stbi__uint8 has_trans=0, tc[3];2704 stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;2705 int first=1,k,interlace=0, iphone=0;2706 stbi *s = z->s;27072708 z->expanded = NULL;2709 z->idata = NULL;2710 z->out = NULL;27112712 if (!check_png_header(s)) return 0;27132714 if (scan == SCAN_type) return 1;27152716 for (;;) {2717 chunk c = get_chunk_header(s);2718 switch (c.type) {2719 case PNG_TYPE('C','g','B','I'):2720 iphone = stbi_de_iphone_flag;2721 skip(s, c.length);2722 break;2723 case PNG_TYPE('I','H','D','R'): {2724 int depth,color,comp,filter;2725 if (!first) return e("multiple IHDR","Corrupt PNG");2726 first = 0;2727 if (c.length != 13) return e("bad IHDR len","Corrupt PNG");2728 s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");2729 s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");2730 depth = get8(s); if (depth != 8) return e("8bit only","PNG not supported: 8-bit only");2731 color = get8(s); if (color > 6) return e("bad ctype","Corrupt PNG");2732 if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");2733 comp = get8(s); if (comp) return e("bad comp method","Corrupt PNG");2734 filter= get8(s); if (filter) return e("bad filter method","Corrupt PNG");2735 interlace = get8(s); if (interlace>1) return e("bad interlace method","Corrupt PNG");2736 if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG");2737 if (!pal_img_n) {2738 s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);2739 if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");2740 if (scan == SCAN_header) return 1;2741 } else {2742 // if paletted, then pal_n is our final components, and2743 // img_n is # components to decompress/filter.2744 s->img_n = 1;2745 if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG");2746 // if SCAN_header, have to scan to see if we have a tRNS2747 }2748 break;2749 }27502751 case PNG_TYPE('P','L','T','E'): {2752 if (first) return e("first not IHDR", "Corrupt PNG");2753 if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");2754 pal_len = c.length / 3;2755 if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");2756 for (i=0; i < pal_len; ++i) {2757 palette[i*4+0] = get8u(s);2758 palette[i*4+1] = get8u(s);2759 palette[i*4+2] = get8u(s);2760 palette[i*4+3] = 255;2761 }2762 break;2763 }27642765 case PNG_TYPE('t','R','N','S'): {2766 if (first) return e("first not IHDR", "Corrupt PNG");2767 if (z->idata) return e("tRNS after IDAT","Corrupt PNG");2768 if (pal_img_n) {2769 if (scan == SCAN_header) { s->img_n = 4; return 1; }2770 if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");2771 if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");2772 pal_img_n = 4;2773 for (i=0; i < c.length; ++i)2774 palette[i*4+3] = get8u(s);2775 } else {2776 if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");2777 if (c.length != (stbi__uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");2778 has_trans = 1;2779 for (k=0; k < s->img_n; ++k)2780 tc[k] = (stbi__uint8) get16(s); // non 8-bit images will be larger2781 }2782 break;2783 }27842785 case PNG_TYPE('I','D','A','T'): {2786 if (first) return e("first not IHDR", "Corrupt PNG");2787 if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");2788 if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }2789 if (ioff + c.length > idata_limit) {2790 stbi__uint8 *p;2791 if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;2792 while (ioff + c.length > idata_limit)2793 idata_limit *= 2;2794 p = (stbi__uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");2795 z->idata = p;2796 }2797 if (!getn(s, z->idata+ioff,c.length)) return e("outofdata","Corrupt PNG");2798 ioff += c.length;2799 break;2800 }28012802 case PNG_TYPE('I','E','N','D'): {2803 stbi__uint32 raw_len;2804 if (first) return e("first not IHDR", "Corrupt PNG");2805 if (scan != SCAN_load) return 1;2806 if (z->idata == NULL) return e("no IDAT","Corrupt PNG");2807 z->expanded = (stbi__uint8 *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone);2808 if (z->expanded == NULL) return 0; // zlib should set error2809 free(z->idata); z->idata = NULL;2810 if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)2811 s->img_out_n = s->img_n+1;2812 else2813 s->img_out_n = s->img_n;2814 if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;2815 if (has_trans)2816 if (!compute_transparency(z, tc, s->img_out_n)) return 0;2817 if (iphone && s->img_out_n > 2)2818 stbi_de_iphone(z);2819 if (pal_img_n) {2820 // pal_img_n == 3 or 42821 s->img_n = pal_img_n; // record the actual colors we had2822 s->img_out_n = pal_img_n;2823 if (req_comp >= 3) s->img_out_n = req_comp;2824 if (!expand_palette(z, palette, pal_len, s->img_out_n))2825 return 0;2826 }2827 free(z->expanded); z->expanded = NULL;2828 return 1;2829 }28302831 default:2832 // if critical, fail2833 if (first) return e("first not IHDR", "Corrupt PNG");2834 if ((c.type & (1 << 29)) == 0) {2835 #ifndef STBI_NO_FAILURE_STRINGS2836 // not threadsafe2837 static char invalid_chunk[] = "XXXX chunk not known";2838 invalid_chunk[0] = (stbi__uint8) (c.type >> 24);2839 invalid_chunk[1] = (stbi__uint8) (c.type >> 16);2840 invalid_chunk[2] = (stbi__uint8) (c.type >> 8);2841 invalid_chunk[3] = (stbi__uint8) (c.type >> 0);2842 #endif2843 return e(invalid_chunk, "PNG not supported: unknown chunk type");2844 }2845 skip(s, c.length);2846 break;2847 }2848 // end of chunk, read and skip CRC2849 get32(s);2850 }2851}28522853static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)2854{2855 unsigned char *result=NULL;2856 if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");2857 if (parse_png_file(p, SCAN_load, req_comp)) {2858 result = p->out;2859 p->out = NULL;2860 if (req_comp && req_comp != p->s->img_out_n) {2861 result = convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);2862 p->s->img_out_n = req_comp;2863 if (result == NULL) return result;2864 }2865 *x = p->s->img_x;2866 *y = p->s->img_y;2867 if (n) *n = p->s->img_n;2868 }2869 free(p->out); p->out = NULL;2870 free(p->expanded); p->expanded = NULL;2871 free(p->idata); p->idata = NULL;28722873 return result;2874}28752876static unsigned char *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp)2877{2878 png p;2879 p.s = s;2880 return do_png(&p, x,y,comp,req_comp);2881}28822883static int stbi_png_test(stbi *s)2884{2885 int r;2886 r = check_png_header(s);2887 stbi_rewind(s);2888 return r;2889}28902891static int stbi_png_info_raw(png *p, int *x, int *y, int *comp)2892{2893 if (!parse_png_file(p, SCAN_header, 0)) {2894 stbi_rewind( p->s );2895 return 0;2896 }2897 if (x) *x = p->s->img_x;2898 if (y) *y = p->s->img_y;2899 if (comp) *comp = p->s->img_n;2900 return 1;2901}29022903static int stbi_png_info(stbi *s, int *x, int *y, int *comp)2904{2905 png p;2906 p.s = s;2907 return stbi_png_info_raw(&p, x, y, comp);2908}29092910// Microsoft/Windows BMP image29112912static int bmp_test(stbi *s)2913{2914 int sz;2915 if (get8(s) != 'B') return 0;2916 if (get8(s) != 'M') return 0;2917 get32le(s); // discard filesize2918 get16le(s); // discard reserved2919 get16le(s); // discard reserved2920 get32le(s); // discard data offset2921 sz = get32le(s);2922 if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;2923 return 0;2924}29252926static int stbi_bmp_test(stbi *s)2927{2928 int r = bmp_test(s);2929 stbi_rewind(s);2930 return r;2931}293229332934// returns 0..31 for the highest set bit2935static int high_bit(unsigned int z)2936{2937 int n=0;2938 if (z == 0) return -1;2939 if (z >= 0x10000) n += 16, z >>= 16;2940 if (z >= 0x00100) n += 8, z >>= 8;2941 if (z >= 0x00010) n += 4, z >>= 4;2942 if (z >= 0x00004) n += 2, z >>= 2;2943 if (z >= 0x00002) n += 1, z >>= 1;2944 return n;2945}29462947static int bitcount(unsigned int a)2948{2949 a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 22950 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 42951 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits2952 a = (a + (a >> 8)); // max 16 per 8 bits2953 a = (a + (a >> 16)); // max 32 per 8 bits2954 return a & 0xff;2955}29562957static int shiftsigned(int v, int shift, int bits)2958{2959 int result;2960 int z=0;29612962 if (shift < 0) v <<= -shift;2963 else v >>= shift;2964 result = v;29652966 z = bits;2967 while (z < 8) {2968 result += v >> z;2969 z += bits;2970 }2971 return result;2972}29732974static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)2975{2976 stbi__uint8 *out;2977 unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;2978 stbi_uc pal[256][4];2979 int psize=0,i,j,compress=0,width;2980 int bpp, flip_vertically, pad, target, offset, hsz;2981 if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");2982 get32le(s); // discard filesize2983 get16le(s); // discard reserved2984 get16le(s); // discard reserved2985 offset = get32le(s);2986 hsz = get32le(s);2987 if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");2988 if (hsz == 12) {2989 s->img_x = get16le(s);2990 s->img_y = get16le(s);2991 } else {2992 s->img_x = get32le(s);2993 s->img_y = get32le(s);2994 }2995 if (get16le(s) != 1) return epuc("bad BMP", "bad BMP");2996 bpp = get16le(s);2997 if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");2998 flip_vertically = ((int) s->img_y) > 0;2999 s->img_y = abs((int) s->img_y);3000 if (hsz == 12) {3001 if (bpp < 24)3002 psize = (offset - 14 - 24) / 3;3003 } else {3004 compress = get32le(s);3005 if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");3006 get32le(s); // discard sizeof3007 get32le(s); // discard hres3008 get32le(s); // discard vres3009 get32le(s); // discard colorsused3010 get32le(s); // discard max important3011 if (hsz == 40 || hsz == 56) {3012 if (hsz == 56) {3013 get32le(s);3014 get32le(s);3015 get32le(s);3016 get32le(s);3017 }3018 if (bpp == 16 || bpp == 32) {3019 mr = mg = mb = 0;3020 if (compress == 0) {3021 if (bpp == 32) {3022 mr = 0xffu << 16;3023 mg = 0xffu << 8;3024 mb = 0xffu << 0;3025 ma = 0xffu << 24;3026 fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 2553027 STBI_NOTUSED(fake_a);3028 } else {3029 mr = 31u << 10;3030 mg = 31u << 5;3031 mb = 31u << 0;3032 }3033 } else if (compress == 3) {3034 mr = get32le(s);3035 mg = get32le(s);3036 mb = get32le(s);3037 // not documented, but generated by photoshop and handled by mspaint3038 if (mr == mg && mg == mb) {3039 // ?!?!?3040 return epuc("bad BMP", "bad BMP");3041 }3042 } else3043 return epuc("bad BMP", "bad BMP");3044 }3045 } else {3046 assert(hsz == 108);3047 mr = get32le(s);3048 mg = get32le(s);3049 mb = get32le(s);3050 ma = get32le(s);3051 get32le(s); // discard color space3052 for (i=0; i < 12; ++i)3053 get32le(s); // discard color space parameters3054 }3055 if (bpp < 16)3056 psize = (offset - 14 - hsz) >> 2;3057 }3058 s->img_n = ma ? 4 : 3;3059 if (req_comp && req_comp >= 3) // we can directly decode 3 or 43060 target = req_comp;3061 else3062 target = s->img_n; // if they want monochrome, we'll post-convert3063 out = (stbi_uc *) malloc(target * s->img_x * s->img_y);3064 if (!out) return epuc("outofmem", "Out of memory");3065 if (bpp < 16) {3066 int z=0;3067 if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }3068 for (i=0; i < psize; ++i) {3069 pal[i][2] = get8u(s);3070 pal[i][1] = get8u(s);3071 pal[i][0] = get8u(s);3072 if (hsz != 12) get8(s);3073 pal[i][3] = 255;3074 }3075 skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));3076 if (bpp == 4) width = (s->img_x + 1) >> 1;3077 else if (bpp == 8) width = s->img_x;3078 else { free(out); return epuc("bad bpp", "Corrupt BMP"); }3079 pad = (-width)&3;3080 for (j=0; j < (int) s->img_y; ++j) {3081 for (i=0; i < (int) s->img_x; i += 2) {3082 int v=get8(s),v2=0;3083 if (bpp == 4) {3084 v2 = v & 15;3085 v >>= 4;3086 }3087 out[z++] = pal[v][0];3088 out[z++] = pal[v][1];3089 out[z++] = pal[v][2];3090 if (target == 4) out[z++] = 255;3091 if (i+1 == (int) s->img_x) break;3092 v = (bpp == 8) ? get8(s) : v2;3093 out[z++] = pal[v][0];3094 out[z++] = pal[v][1];3095 out[z++] = pal[v][2];3096 if (target == 4) out[z++] = 255;3097 }3098 skip(s, pad);3099 }3100 } else {3101 int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;3102 int z = 0;3103 int easy=0;3104 skip(s, offset - 14 - hsz);3105 if (bpp == 24) width = 3 * s->img_x;3106 else if (bpp == 16) width = 2*s->img_x;3107 else /* bpp = 32 and pad = 0 */ width=0;3108 pad = (-width) & 3;3109 if (bpp == 24) {3110 easy = 1;3111 } else if (bpp == 32) {3112 if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)3113 easy = 2;3114 }3115 if (!easy) {3116 if (!mr || !mg || !mb) { free(out); return epuc("bad masks", "Corrupt BMP"); }3117 // right shift amt to put high bit in position #73118 rshift = high_bit(mr)-7; rcount = bitcount(mr);3119 gshift = high_bit(mg)-7; gcount = bitcount(mg);3120 bshift = high_bit(mb)-7; bcount = bitcount(mb);3121 ashift = high_bit(ma)-7; acount = bitcount(ma);3122 }3123 for (j=0; j < (int) s->img_y; ++j) {3124 if (easy) {3125 for (i=0; i < (int) s->img_x; ++i) {3126 int a;3127 out[z+2] = get8u(s);3128 out[z+1] = get8u(s);3129 out[z+0] = get8u(s);3130 z += 3;3131 a = (easy == 2 ? get8(s) : 255);3132 if (target == 4) out[z++] = (stbi__uint8) a;3133 }3134 } else {3135 for (i=0; i < (int) s->img_x; ++i) {3136 stbi__uint32 v = (stbi__uint32) (bpp == 16 ? get16le(s) : get32le(s));3137 int a;3138 out[z++] = (stbi__uint8) shiftsigned(v & mr, rshift, rcount);3139 out[z++] = (stbi__uint8) shiftsigned(v & mg, gshift, gcount);3140 out[z++] = (stbi__uint8) shiftsigned(v & mb, bshift, bcount);3141 a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);3142 if (target == 4) out[z++] = (stbi__uint8) a; 3143 }3144 }3145 skip(s, pad);3146 }3147 }3148 if (flip_vertically) {3149 stbi_uc t;3150 for (j=0; j < (int) s->img_y>>1; ++j) {3151 stbi_uc *p1 = out + j *s->img_x*target;3152 stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;3153 for (i=0; i < (int) s->img_x*target; ++i) {3154 t = p1[i], p1[i] = p2[i], p2[i] = t;3155 }3156 }3157 }31583159 if (req_comp && req_comp != target) {3160 out = convert_format(out, target, req_comp, s->img_x, s->img_y);3161 if (out == NULL) return out; // convert_format frees input on failure3162 }31633164 *x = s->img_x;3165 *y = s->img_y;3166 if (comp) *comp = s->img_n;3167 return out;3168}31693170static stbi_uc *stbi_bmp_load(stbi *s,int *x, int *y, int *comp, int req_comp)3171{3172 return bmp_load(s, x,y,comp,req_comp);3173}317431753176// Targa Truevision - TGA3177// by Jonathan Dummer31783179static int tga_info(stbi *s, int *x, int *y, int *comp)3180{3181 int tga_w, tga_h, tga_comp;3182 int sz;3183 get8u(s); // discard Offset3184 sz = get8u(s); // color type3185 if( sz > 1 ) {3186 stbi_rewind(s);3187 return 0; // only RGB or indexed allowed3188 }3189 sz = get8u(s); // image type3190 // only RGB or grey allowed, +/- RLE3191 if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;3192 skip(s,9);3193 tga_w = get16le(s);3194 if( tga_w < 1 ) {3195 stbi_rewind(s);3196 return 0; // test width3197 }3198 tga_h = get16le(s);3199 if( tga_h < 1 ) {3200 stbi_rewind(s);3201 return 0; // test height3202 }3203 sz = get8(s); // bits per pixel3204 // only RGB or RGBA or grey allowed3205 if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {3206 stbi_rewind(s);3207 return 0;3208 }3209 tga_comp = sz;3210 if (x) *x = tga_w;3211 if (y) *y = tga_h;3212 if (comp) *comp = tga_comp / 8;3213 return 1; // seems to have passed everything3214}32153216int stbi_tga_info(stbi *s, int *x, int *y, int *comp)3217{3218 return tga_info(s, x, y, comp);3219}32203221static int tga_test(stbi *s)3222{3223 int sz;3224 get8u(s); // discard Offset3225 sz = get8u(s); // color type3226 if ( sz > 1 ) return 0; // only RGB or indexed allowed3227 sz = get8u(s); // image type3228 if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE3229 get16(s); // discard palette start3230 get16(s); // discard palette length3231 get8(s); // discard bits per palette color entry3232 get16(s); // discard x origin3233 get16(s); // discard y origin3234 if ( get16(s) < 1 ) return 0; // test width3235 if ( get16(s) < 1 ) return 0; // test height3236 sz = get8(s); // bits per pixel3237 if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed3238 return 1; // seems to have passed everything3239}32403241static int stbi_tga_test(stbi *s)3242{3243 int res = tga_test(s);3244 stbi_rewind(s);3245 return res;3246}32473248static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)3249{3250 // read in the TGA header stuff3251 int tga_offset = get8u(s);3252 int tga_indexed = get8u(s);3253 int tga_image_type = get8u(s);3254 int tga_is_RLE = 0;3255 int tga_palette_start = get16le(s);3256 int tga_palette_len = get16le(s);3257 int tga_palette_bits = get8u(s);3258 int tga_x_origin = get16le(s);3259 int tga_y_origin = get16le(s);3260 int tga_width = get16le(s);3261 int tga_height = get16le(s);3262 int tga_bits_per_pixel = get8u(s);3263 int tga_comp = tga_bits_per_pixel / 8;3264 int tga_inverted = get8u(s);3265 // image data3266 unsigned char *tga_data;3267 unsigned char *tga_palette = NULL;3268 int i, j;3269 unsigned char raw_data[4];3270 int RLE_count = 0;3271 int RLE_repeating = 0;3272 int read_next_pixel = 1;32733274 // do a tiny bit of precessing3275 if ( tga_image_type >= 8 )3276 {3277 tga_image_type -= 8;3278 tga_is_RLE = 1;3279 }3280 /* int tga_alpha_bits = tga_inverted & 15; */3281 tga_inverted = 1 - ((tga_inverted >> 5) & 1);32823283 // error check3284 if ( //(tga_indexed) ||3285 (tga_width < 1) || (tga_height < 1) ||3286 (tga_image_type < 1) || (tga_image_type > 3) ||3287 ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&3288 (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))3289 )3290 {3291 return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA3292 }32933294 // If I'm paletted, then I'll use the number of bits from the palette3295 if ( tga_indexed )3296 {3297 tga_comp = tga_palette_bits / 8;3298 }32993300 // tga info3301 *x = tga_width;3302 *y = tga_height;3303 if (comp) *comp = tga_comp;33043305 tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );3306 if (!tga_data) return epuc("outofmem", "Out of memory");33073308 // skip to the data's starting position (offset usually = 0)3309 skip(s, tga_offset );33103311 if ( !tga_indexed && !tga_is_RLE) {3312 for (i=0; i < tga_height; ++i) {3313 int y = tga_inverted ? tga_height -i - 1 : i;3314 stbi__uint8 *tga_row = tga_data + y*tga_width*tga_comp;3315 getn(s, tga_row, tga_width * tga_comp);3316 }3317 } else {3318 // do I need to load a palette?3319 if ( tga_indexed)3320 {3321 // any data to skip? (offset usually = 0)3322 skip(s, tga_palette_start );3323 // load the palette3324 tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );3325 if (!tga_palette) {3326 free(tga_data);3327 return epuc("outofmem", "Out of memory");3328 }3329 if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {3330 free(tga_data);3331 free(tga_palette);3332 return epuc("bad palette", "Corrupt TGA");3333 }3334 }3335 // load the data3336 for (i=0; i < tga_width * tga_height; ++i)3337 {3338 // if I'm in RLE mode, do I need to get a RLE chunk?3339 if ( tga_is_RLE )3340 {3341 if ( RLE_count == 0 )3342 {3343 // yep, get the next byte as a RLE command3344 int RLE_cmd = get8u(s);3345 RLE_count = 1 + (RLE_cmd & 127);3346 RLE_repeating = RLE_cmd >> 7;3347 read_next_pixel = 1;3348 } else if ( !RLE_repeating )3349 {3350 read_next_pixel = 1;3351 }3352 } else3353 {3354 read_next_pixel = 1;3355 }3356 // OK, if I need to read a pixel, do it now3357 if ( read_next_pixel )3358 {3359 // load however much data we did have3360 if ( tga_indexed )3361 {3362 // read in 1 byte, then perform the lookup3363 int pal_idx = get8u(s);3364 if ( pal_idx >= tga_palette_len )3365 {3366 // invalid index3367 pal_idx = 0;3368 }3369 pal_idx *= tga_bits_per_pixel / 8;3370 for (j = 0; j*8 < tga_bits_per_pixel; ++j)3371 {3372 raw_data[j] = tga_palette[pal_idx+j];3373 }3374 } else3375 {3376 // read in the data raw3377 for (j = 0; j*8 < tga_bits_per_pixel; ++j)3378 {3379 raw_data[j] = get8u(s);3380 }3381 }3382 // clear the reading flag for the next pixel3383 read_next_pixel = 0;3384 } // end of reading a pixel33853386 // copy data3387 for (j = 0; j < tga_comp; ++j)3388 tga_data[i*tga_comp+j] = raw_data[j];33893390 // in case we're in RLE mode, keep counting down3391 --RLE_count;3392 }3393 // do I need to invert the image?3394 if ( tga_inverted )3395 {3396 for (j = 0; j*2 < tga_height; ++j)3397 {3398 int index1 = j * tga_width * req_comp;3399 int index2 = (tga_height - 1 - j) * tga_width * req_comp;3400 for (i = tga_width * req_comp; i > 0; --i)3401 {3402 unsigned char temp = tga_data[index1];3403 tga_data[index1] = tga_data[index2];3404 tga_data[index2] = temp;3405 ++index1;3406 ++index2;3407 }3408 }3409 }3410 // clear my palette, if I had one3411 if ( tga_palette != NULL )3412 {3413 free( tga_palette );3414 }3415 }34163417 // swap RGB3418 if (tga_comp >= 3)3419 {3420 unsigned char* tga_pixel = tga_data;3421 for (i=0; i < tga_width * tga_height; ++i)3422 {3423 unsigned char temp = tga_pixel[0];3424 tga_pixel[0] = tga_pixel[2];3425 tga_pixel[2] = temp;3426 tga_pixel += tga_comp;3427 }3428 }34293430 // convert to target component count3431 if (req_comp && req_comp != tga_comp)3432 tga_data = convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);34333434 // the things I do to get rid of an error message, and yet keep3435 // Microsoft's C compilers happy... [8^(3436 tga_palette_start = tga_palette_len = tga_palette_bits =3437 tga_x_origin = tga_y_origin = 0;3438 // OK, done3439 return tga_data;3440}34413442static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)3443{3444 return tga_load(s,x,y,comp,req_comp);3445}344634473448// *************************************************************************************************3449// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB34503451static int psd_test(stbi *s)3452{3453 if (get32(s) != 0x38425053) return 0; // "8BPS"3454 else return 1;3455}34563457static int stbi_psd_test(stbi *s)3458{3459 int r = psd_test(s);3460 stbi_rewind(s);3461 return r;3462}34633464static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)3465{3466 int pixelCount;3467 int channelCount, compression;3468 int channel, i, count, len;3469 int w,h;3470 stbi__uint8 *out;34713472 // Check identifier3473 if (get32(s) != 0x38425053) // "8BPS"3474 return epuc("not PSD", "Corrupt PSD image");34753476 // Check file type version.3477 if (get16(s) != 1)3478 return epuc("wrong version", "Unsupported version of PSD image");34793480 // Skip 6 reserved bytes.3481 skip(s, 6 );34823483 // Read the number of channels (R, G, B, A, etc).3484 channelCount = get16(s);3485 if (channelCount < 0 || channelCount > 16)3486 return epuc("wrong channel count", "Unsupported number of channels in PSD image");34873488 // Read the rows and columns of the image.3489 h = get32(s);3490 w = get32(s);3491 3492 // Make sure the depth is 8 bits.3493 if (get16(s) != 8)3494 return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");34953496 // Make sure the color mode is RGB.3497 // Valid options are:3498 // 0: Bitmap3499 // 1: Grayscale3500 // 2: Indexed color3501 // 3: RGB color3502 // 4: CMYK color3503 // 7: Multichannel3504 // 8: Duotone3505 // 9: Lab color3506 if (get16(s) != 3)3507 return epuc("wrong color format", "PSD is not in RGB color format");35083509 // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)3510 skip(s,get32(s) );35113512 // Skip the image resources. (resolution, pen tool paths, etc)3513 skip(s, get32(s) );35143515 // Skip the reserved data.3516 skip(s, get32(s) );35173518 // Find out if the data is compressed.3519 // Known values:3520 // 0: no compression3521 // 1: RLE compressed3522 compression = get16(s);3523 if (compression > 1)3524 return epuc("bad compression", "PSD has an unknown compression format");35253526 // Create the destination image.3527 out = (stbi_uc *) malloc(4 * w*h);3528 if (!out) return epuc("outofmem", "Out of memory");3529 pixelCount = w*h;35303531 // Initialize the data to zero.3532 //memset( out, 0, pixelCount * 4 );3533 3534 // Finally, the image data.3535 if (compression) {3536 // RLE as used by .PSD and .TIFF3537 // Loop until you get the number of unpacked bytes you are expecting:3538 // Read the next source byte into n.3539 // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.3540 // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.3541 // Else if n is 128, noop.3542 // Endloop35433544 // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,3545 // which we're going to just skip.3546 skip(s, h * channelCount * 2 );35473548 // Read the RLE data by channel.3549 for (channel = 0; channel < 4; channel++) {3550 stbi__uint8 *p;3551 3552 p = out+channel;3553 if (channel >= channelCount) {3554 // Fill this channel with default data.3555 for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;3556 } else {3557 // Read the RLE data.3558 count = 0;3559 while (count < pixelCount) {3560 len = get8(s);3561 if (len == 128) {3562 // No-op.3563 } else if (len < 128) {3564 // Copy next len+1 bytes literally.3565 len++;3566 count += len;3567 while (len) {3568 *p = get8u(s);3569 p += 4;3570 len--;3571 }3572 } else if (len > 128) {3573 stbi__uint8 val;3574 // Next -len+1 bytes in the dest are replicated from next source byte.3575 // (Interpret len as a negative 8-bit int.)3576 len ^= 0x0FF;3577 len += 2;3578 val = get8u(s);3579 count += len;3580 while (len) {3581 *p = val;3582 p += 4;3583 len--;3584 }3585 }3586 }3587 }3588 }3589 3590 } else {3591 // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)3592 // where each channel consists of an 8-bit value for each pixel in the image.3593 3594 // Read the data by channel.3595 for (channel = 0; channel < 4; channel++) {3596 stbi__uint8 *p;3597 3598 p = out + channel;3599 if (channel > channelCount) {3600 // Fill this channel with default data.3601 for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;3602 } else {3603 // Read the data.3604 for (i = 0; i < pixelCount; i++)3605 *p = get8u(s), p += 4;3606 }3607 }3608 }36093610 if (req_comp && req_comp != 4) {3611 out = convert_format(out, 4, req_comp, w, h);3612 if (out == NULL) return out; // convert_format frees input on failure3613 }36143615 if (comp) *comp = channelCount;3616 *y = h;3617 *x = w;3618 3619 return out;3620}36213622static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)3623{3624 return psd_load(s,x,y,comp,req_comp);3625}36263627// *************************************************************************************************3628// Softimage PIC loader3629// by Tom Seddon3630//3631// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format3632// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/36333634static int pic_is4(stbi *s,const char *str)3635{3636 int i;3637 for (i=0; i<4; ++i)3638 if (get8(s) != (stbi_uc)str[i])3639 return 0;36403641 return 1;3642}36433644static int pic_test(stbi *s)3645{3646 int i;36473648 if (!pic_is4(s,"\x53\x80\xF6\x34"))3649 return 0;36503651 for(i=0;i<84;++i)3652 get8(s);36533654 if (!pic_is4(s,"PICT"))3655 return 0;36563657 return 1;3658}36593660typedef struct3661{3662 stbi_uc size,type,channel;3663} pic_packet_t;36643665static stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest)3666{3667 int mask=0x80, i;36683669 for (i=0; i<4; ++i, mask>>=1) {3670 if (channel & mask) {3671 if (at_eof(s)) return epuc("bad file","PIC file too short");3672 dest[i]=get8u(s);3673 }3674 }36753676 return dest;3677}36783679static void pic_copyval(int channel,stbi_uc *dest,const stbi_uc *src)3680{3681 int mask=0x80,i;36823683 for (i=0;i<4; ++i, mask>>=1)3684 if (channel&mask)3685 dest[i]=src[i];3686}36873688static stbi_uc *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result)3689{3690 int act_comp=0,num_packets=0,y,chained;3691 pic_packet_t packets[10];36923693 // this will (should...) cater for even some bizarre stuff like having data3694 // for the same channel in multiple packets.3695 do {3696 pic_packet_t *packet;36973698 if (num_packets==sizeof(packets)/sizeof(packets[0]))3699 return epuc("bad format","too many packets");37003701 packet = &packets[num_packets++];37023703 chained = get8(s);3704 packet->size = get8u(s);3705 packet->type = get8u(s);3706 packet->channel = get8u(s);37073708 act_comp |= packet->channel;37093710 if (at_eof(s)) return epuc("bad file","file too short (reading packets)");3711 if (packet->size != 8) return epuc("bad format","packet isn't 8bpp");3712 } while (chained);37133714 *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?37153716 for(y=0; y<height; ++y) {3717 int packet_idx;37183719 for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {3720 pic_packet_t *packet = &packets[packet_idx];3721 stbi_uc *dest = result+y*width*4;37223723 switch (packet->type) {3724 default:3725 return epuc("bad format","packet has bad compression type");37263727 case 0: {//uncompressed3728 int x;37293730 for(x=0;x<width;++x, dest+=4)3731 if (!pic_readval(s,packet->channel,dest))3732 return 0;3733 break;3734 }37353736 case 1://Pure RLE3737 {3738 int left=width, i;37393740 while (left>0) {3741 stbi_uc count,value[4];37423743 count=get8u(s);3744 if (at_eof(s)) return epuc("bad file","file too short (pure read count)");37453746 if (count > left)3747 count = (stbi__uint8) left;37483749 if (!pic_readval(s,packet->channel,value)) return 0;37503751 for(i=0; i<count; ++i,dest+=4)3752 pic_copyval(packet->channel,dest,value);3753 left -= count;3754 }3755 }3756 break;37573758 case 2: {//Mixed RLE3759 int left=width;3760 while (left>0) {3761 int count = get8(s), i;3762 if (at_eof(s)) return epuc("bad file","file too short (mixed read count)");37633764 if (count >= 128) { // Repeated3765 stbi_uc value[4];3766 int i;37673768 if (count==128)3769 count = get16(s);3770 else3771 count -= 127;3772 if (count > left)3773 return epuc("bad file","scanline overrun");37743775 if (!pic_readval(s,packet->channel,value))3776 return 0;37773778 for(i=0;i<count;++i, dest += 4)3779 pic_copyval(packet->channel,dest,value);3780 } else { // Raw3781 ++count;3782 if (count>left) return epuc("bad file","scanline overrun");37833784 for(i=0;i<count;++i, dest+=4)3785 if (!pic_readval(s,packet->channel,dest))3786 return 0;3787 }3788 left-=count;3789 }3790 break;3791 }3792 }3793 }3794 }37953796 return result;3797}37983799static stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp)3800{3801 stbi_uc *result;3802 int i, x,y;38033804 for (i=0; i<92; ++i)3805 get8(s);38063807 x = get16(s);3808 y = get16(s);3809 if (at_eof(s)) return epuc("bad file","file too short (pic header)");3810 if ((1 << 28) / x < y) return epuc("too large", "Image too large to decode");38113812 get32(s); //skip `ratio'3813 get16(s); //skip `fields'3814 get16(s); //skip `pad'38153816 // intermediate buffer is RGBA3817 result = (stbi_uc *) malloc(x*y*4);3818 memset(result, 0xff, x*y*4);38193820 if (!pic_load2(s,x,y,comp, result)) {3821 free(result);3822 result=0;3823 }3824 *px = x;3825 *py = y;3826 if (req_comp == 0) req_comp = *comp;3827 result=convert_format(result,4,req_comp,x,y);38283829 return result;3830}38313832static int stbi_pic_test(stbi *s)3833{3834 int r = pic_test(s);3835 stbi_rewind(s);3836 return r;3837}38383839static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp)3840{3841 return pic_load(s,x,y,comp,req_comp);3842}38433844// *************************************************************************************************3845// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb3846typedef struct stbi_gif_lzw_struct {3847 stbi__int16 prefix;3848 stbi__uint8 first;3849 stbi__uint8 suffix;3850} stbi_gif_lzw;38513852typedef struct stbi_gif_struct3853{3854 int w,h;3855 stbi_uc *out; // output buffer (always 4 components)3856 int flags, bgindex, ratio, transparent, eflags;3857 stbi__uint8 pal[256][4];3858 stbi__uint8 lpal[256][4];3859 stbi_gif_lzw codes[4096];3860 stbi__uint8 *color_table;3861 int parse, step;3862 int lflags;3863 int start_x, start_y;3864 int max_x, max_y;3865 int cur_x, cur_y;3866 int line_size;3867} stbi_gif;38683869static int gif_test(stbi *s)3870{3871 int sz;3872 if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0;3873 sz = get8(s);3874 if (sz != '9' && sz != '7') return 0;3875 if (get8(s) != 'a') return 0;3876 return 1;3877}38783879static int stbi_gif_test(stbi *s)3880{3881 int r = gif_test(s);3882 stbi_rewind(s);3883 return r;3884}38853886static void stbi_gif_parse_colortable(stbi *s, stbi__uint8 pal[256][4], int num_entries, int transp)3887{3888 int i;3889 for (i=0; i < num_entries; ++i) {3890 pal[i][2] = get8u(s);3891 pal[i][1] = get8u(s);3892 pal[i][0] = get8u(s);3893 pal[i][3] = transp ? 0 : 255;3894 } 3895}38963897static int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info)3898{3899 stbi__uint8 version;3900 if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8')3901 return e("not GIF", "Corrupt GIF");39023903 version = get8u(s);3904 if (version != '7' && version != '9') return e("not GIF", "Corrupt GIF");3905 if (get8(s) != 'a') return e("not GIF", "Corrupt GIF");3906 3907 failure_reason = "";3908 g->w = get16le(s);3909 g->h = get16le(s);3910 g->flags = get8(s);3911 g->bgindex = get8(s);3912 g->ratio = get8(s);3913 g->transparent = -1;39143915 if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments39163917 if (is_info) return 1;39183919 if (g->flags & 0x80)3920 stbi_gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);39213922 return 1;3923}39243925static int stbi_gif_info_raw(stbi *s, int *x, int *y, int *comp)3926{3927 stbi_gif g; 3928 if (!stbi_gif_header(s, &g, comp, 1)) {3929 stbi_rewind( s );3930 return 0;3931 }3932 if (x) *x = g.w;3933 if (y) *y = g.h;3934 return 1;3935}39363937static void stbi_out_gif_code(stbi_gif *g, stbi__uint16 code)3938{3939 stbi__uint8 *p, *c;39403941 // recurse to decode the prefixes, since the linked-list is backwards,3942 // and working backwards through an interleaved image would be nasty3943 if (g->codes[code].prefix >= 0)3944 stbi_out_gif_code(g, g->codes[code].prefix);39453946 if (g->cur_y >= g->max_y) return;3947 3948 p = &g->out[g->cur_x + g->cur_y];3949 c = &g->color_table[g->codes[code].suffix * 4];39503951 if (c[3] >= 128) {3952 p[0] = c[2];3953 p[1] = c[1];3954 p[2] = c[0];3955 p[3] = c[3];3956 }3957 g->cur_x += 4;39583959 if (g->cur_x >= g->max_x) {3960 g->cur_x = g->start_x;3961 g->cur_y += g->step;39623963 while (g->cur_y >= g->max_y && g->parse > 0) {3964 g->step = (1 << g->parse) * g->line_size;3965 g->cur_y = g->start_y + (g->step >> 1);3966 --g->parse;3967 }3968 }3969}39703971static stbi__uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g)3972{3973 stbi__uint8 lzw_cs;3974 stbi__int32 len, code;3975 stbi__uint32 first;3976 stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;3977 stbi_gif_lzw *p;39783979 lzw_cs = get8u(s);3980 clear = 1 << lzw_cs;3981 first = 1;3982 codesize = lzw_cs + 1;3983 codemask = (1 << codesize) - 1;3984 bits = 0;3985 valid_bits = 0;3986 for (code = 0; code < clear; code++) {3987 g->codes[code].prefix = -1;3988 g->codes[code].first = (stbi__uint8) code;3989 g->codes[code].suffix = (stbi__uint8) code;3990 }39913992 // support no starting clear code3993 avail = clear+2;3994 oldcode = -1;39953996 len = 0;3997 for(;;) {3998 if (valid_bits < codesize) {3999 if (len == 0) {4000 len = get8(s); // start new block4001 if (len == 0) 4002 return g->out;4003 }4004 --len;4005 bits |= (stbi__int32) get8(s) << valid_bits;4006 valid_bits += 8;4007 } else {4008 stbi__int32 code = bits & codemask;4009 bits >>= codesize;4010 valid_bits -= codesize;4011 // @OPTIMIZE: is there some way we can accelerate the non-clear path?4012 if (code == clear) { // clear code4013 codesize = lzw_cs + 1;4014 codemask = (1 << codesize) - 1;4015 avail = clear + 2;4016 oldcode = -1;4017 first = 0;4018 } else if (code == clear + 1) { // end of stream code4019 skip(s, len);4020 while ((len = get8(s)) > 0)4021 skip(s,len);4022 return g->out;4023 } else if (code <= avail) {4024 if (first) return epuc("no clear code", "Corrupt GIF");40254026 if (oldcode >= 0) {4027 p = &g->codes[avail++];4028 if (avail > 4096) return epuc("too many codes", "Corrupt GIF");4029 p->prefix = (stbi__int16) oldcode;4030 p->first = g->codes[oldcode].first;4031 p->suffix = (code == avail) ? p->first : g->codes[code].first;4032 } else if (code == avail)4033 return epuc("illegal code in raster", "Corrupt GIF");40344035 stbi_out_gif_code(g, (stbi__uint16) code);40364037 if ((avail & codemask) == 0 && avail <= 0x0FFF) {4038 codesize++;4039 codemask = (1 << codesize) - 1;4040 }40414042 oldcode = code;4043 } else {4044 return epuc("illegal code in raster", "Corrupt GIF");4045 }4046 } 4047 }4048}40494050static void stbi_fill_gif_background(stbi_gif *g)4051{4052 int i;4053 stbi__uint8 *c = g->pal[g->bgindex];4054 // @OPTIMIZE: write a dword at a time4055 for (i = 0; i < g->w * g->h * 4; i += 4) {4056 stbi__uint8 *p = &g->out[i];4057 p[0] = c[2];4058 p[1] = c[1];4059 p[2] = c[0];4060 p[3] = c[3];4061 }4062}40634064// this function is designed to support animated gifs, although stb_image doesn't support it4065static stbi__uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp)4066{4067 int i;4068 stbi__uint8 *old_out = 0;40694070 if (g->out == 0) {4071 if (!stbi_gif_header(s, g, comp,0)) return 0; // failure_reason set by stbi_gif_header4072 g->out = (stbi__uint8 *) malloc(4 * g->w * g->h);4073 if (g->out == 0) return epuc("outofmem", "Out of memory");4074 stbi_fill_gif_background(g);4075 } else {4076 // animated-gif-only path4077 if (((g->eflags & 0x1C) >> 2) == 3) {4078 old_out = g->out;4079 g->out = (stbi__uint8 *) malloc(4 * g->w * g->h);4080 if (g->out == 0) return epuc("outofmem", "Out of memory");4081 memcpy(g->out, old_out, g->w*g->h*4);4082 }4083 }4084 4085 for (;;) {4086 switch (get8(s)) {4087 case 0x2C: /* Image Descriptor */4088 {4089 stbi__int32 x, y, w, h;4090 stbi__uint8 *o;40914092 x = get16le(s);4093 y = get16le(s);4094 w = get16le(s);4095 h = get16le(s);4096 if (((x + w) > (g->w)) || ((y + h) > (g->h)))4097 return epuc("bad Image Descriptor", "Corrupt GIF");40984099 g->line_size = g->w * 4;4100 g->start_x = x * 4;4101 g->start_y = y * g->line_size;4102 g->max_x = g->start_x + w * 4;4103 g->max_y = g->start_y + h * g->line_size;4104 g->cur_x = g->start_x;4105 g->cur_y = g->start_y;41064107 g->lflags = get8(s);41084109 if (g->lflags & 0x40) {4110 g->step = 8 * g->line_size; // first interlaced spacing4111 g->parse = 3;4112 } else {4113 g->step = g->line_size;4114 g->parse = 0;4115 }41164117 if (g->lflags & 0x80) {4118 stbi_gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);4119 g->color_table = (stbi__uint8 *) g->lpal; 4120 } else if (g->flags & 0x80) {4121 for (i=0; i < 256; ++i) // @OPTIMIZE: reset only the previous transparent4122 g->pal[i][3] = 255; 4123 if (g->transparent >= 0 && (g->eflags & 0x01))4124 g->pal[g->transparent][3] = 0;4125 g->color_table = (stbi__uint8 *) g->pal;4126 } else4127 return epuc("missing color table", "Corrupt GIF");4128 4129 o = stbi_process_gif_raster(s, g);4130 if (o == NULL) return NULL;41314132 if (req_comp && req_comp != 4)4133 o = convert_format(o, 4, req_comp, g->w, g->h);4134 return o;4135 }41364137 case 0x21: // Comment Extension.4138 {4139 int len;4140 if (get8(s) == 0xF9) { // Graphic Control Extension.4141 len = get8(s);4142 if (len == 4) {4143 g->eflags = get8(s);4144 get16le(s); // delay4145 g->transparent = get8(s);4146 } else {4147 skip(s, len);4148 break;4149 }4150 }4151 while ((len = get8(s)) != 0)4152 skip(s, len);4153 break;4154 }41554156 case 0x3B: // gif stream termination code4157 return (stbi__uint8 *) 1;41584159 default:4160 return epuc("unknown code", "Corrupt GIF");4161 }4162 }4163}41644165static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp)4166{4167 stbi__uint8 *u = 0;4168 stbi_gif g={0};41694170 u = stbi_gif_load_next(s, &g, comp, req_comp);4171 if (u == (void *) 1) u = 0; // end of animated gif marker4172 if (u) {4173 *x = g.w;4174 *y = g.h;4175 }41764177 return u;4178}41794180static int stbi_gif_info(stbi *s, int *x, int *y, int *comp)4181{4182 return stbi_gif_info_raw(s,x,y,comp);4183}418441854186// *************************************************************************************************4187// Radiance RGBE HDR loader4188// originally by Nicolas Schulz4189#ifndef STBI_NO_HDR4190static int hdr_test(stbi *s)4191{4192 const char *signature = "#?RADIANCE\n";4193 int i;4194 for (i=0; signature[i]; ++i)4195 if (get8(s) != signature[i])4196 return 0;4197 return 1;4198}41994200static int stbi_hdr_test(stbi* s)4201{4202 int r = hdr_test(s);4203 stbi_rewind(s);4204 return r;4205}42064207#define HDR_BUFLEN 10244208static char *hdr_gettoken(stbi *z, char *buffer)4209{4210 int len=0;4211 char c = '\0';42124213 c = (char) get8(z);42144215 while (!at_eof(z) && c != '\n') {4216 buffer[len++] = c;4217 if (len == HDR_BUFLEN-1) {4218 // flush to end of line4219 while (!at_eof(z) && get8(z) != '\n')4220 ;4221 break;4222 }4223 c = (char) get8(z);4224 }42254226 buffer[len] = 0;4227 return buffer;4228}42294230static void hdr_convert(float *output, stbi_uc *input, int req_comp)4231{4232 if ( input[3] != 0 ) {4233 float f1;4234 // Exponent4235 f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));4236 if (req_comp <= 2)4237 output[0] = (input[0] + input[1] + input[2]) * f1 / 3;4238 else {4239 output[0] = input[0] * f1;4240 output[1] = input[1] * f1;4241 output[2] = input[2] * f1;4242 }4243 if (req_comp == 2) output[1] = 1;4244 if (req_comp == 4) output[3] = 1;4245 } else {4246 switch (req_comp) {4247 case 4: output[3] = 1; /* fallthrough */4248 case 3: output[0] = output[1] = output[2] = 0;4249 break;4250 case 2: output[1] = 1; /* fallthrough */4251 case 1: output[0] = 0;4252 break;4253 }4254 }4255}42564257static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)4258{4259 char buffer[HDR_BUFLEN];4260 char *token;4261 int valid = 0;4262 int width, height;4263 stbi_uc *scanline;4264 float *hdr_data;4265 int len;4266 unsigned char count, value;4267 int i, j, k, c1,c2, z;426842694270 // Check identifier4271 if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)4272 return epf("not HDR", "Corrupt HDR image");4273 4274 // Parse header4275 for(;;) {4276 token = hdr_gettoken(s,buffer);4277 if (token[0] == 0) break;4278 if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;4279 }42804281 if (!valid) return epf("unsupported format", "Unsupported HDR format");42824283 // Parse width and height4284 // can't use sscanf() if we're not using stdio!4285 token = hdr_gettoken(s,buffer);4286 if (strncmp(token, "-Y ", 3)) return epf("unsupported data layout", "Unsupported HDR format");4287 token += 3;4288 height = (int) strtol(token, &token, 10);4289 while (*token == ' ') ++token;4290 if (strncmp(token, "+X ", 3)) return epf("unsupported data layout", "Unsupported HDR format");4291 token += 3;4292 width = (int) strtol(token, NULL, 10);42934294 *x = width;4295 *y = height;42964297 *comp = 3;4298 if (req_comp == 0) req_comp = 3;42994300 // Read data4301 hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));43024303 // Load image data4304 // image data is stored as some number of sca4305 if ( width < 8 || width >= 32768) {4306 // Read flat data4307 for (j=0; j < height; ++j) {4308 for (i=0; i < width; ++i) {4309 stbi_uc rgbe[4];4310 main_decode_loop:4311 getn(s, rgbe, 4);4312 hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);4313 }4314 }4315 } else {4316 // Read RLE-encoded data4317 scanline = NULL;43184319 for (j = 0; j < height; ++j) {4320 c1 = get8(s);4321 c2 = get8(s);4322 len = get8(s);4323 if (c1 != 2 || c2 != 2 || (len & 0x80)) {4324 // not run-length encoded, so we have to actually use THIS data as a decoded4325 // pixel (note this can't be a valid pixel--one of RGB must be >= 128)4326 stbi__uint8 rgbe[4];4327 rgbe[0] = (stbi__uint8) c1;4328 rgbe[1] = (stbi__uint8) c2;4329 rgbe[2] = (stbi__uint8) len;4330 rgbe[3] = (stbi__uint8) get8u(s);4331 hdr_convert(hdr_data, rgbe, req_comp);4332 i = 1;4333 j = 0;4334 free(scanline);4335 goto main_decode_loop; // yes, this makes no sense4336 }4337 len <<= 8;4338 len |= get8(s);4339 if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }4340 if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);4341 4342 for (k = 0; k < 4; ++k) {4343 i = 0;4344 while (i < width) {4345 count = get8u(s);4346 if (count > 128) {4347 // Run4348 value = get8u(s);4349 count -= 128;4350 for (z = 0; z < count; ++z)4351 scanline[i++ * 4 + k] = value;4352 } else {4353 // Dump4354 for (z = 0; z < count; ++z)4355 scanline[i++ * 4 + k] = get8u(s);4356 }4357 }4358 }4359 for (i=0; i < width; ++i)4360 hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);4361 }4362 free(scanline);4363 }43644365 return hdr_data;4366}43674368static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)4369{4370 return hdr_load(s,x,y,comp,req_comp);4371}43724373static int stbi_hdr_info(stbi *s, int *x, int *y, int *comp)4374{4375 char buffer[HDR_BUFLEN];4376 char *token;4377 int valid = 0;43784379 if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {4380 stbi_rewind( s );4381 return 0;4382 }43834384 for(;;) {4385 token = hdr_gettoken(s,buffer);4386 if (token[0] == 0) break;4387 if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;4388 }43894390 if (!valid) {4391 stbi_rewind( s );4392 return 0;4393 }4394 token = hdr_gettoken(s,buffer);4395 if (strncmp(token, "-Y ", 3)) {4396 stbi_rewind( s );4397 return 0;4398 }4399 token += 3;4400 *y = (int) strtol(token, &token, 10);4401 while (*token == ' ') ++token;4402 if (strncmp(token, "+X ", 3)) {4403 stbi_rewind( s );4404 return 0;4405 }4406 token += 3;4407 *x = (int) strtol(token, NULL, 10);4408 *comp = 3;4409 return 1;4410}4411#endif // STBI_NO_HDR44124413static int stbi_bmp_info(stbi *s, int *x, int *y, int *comp)4414{4415 int hsz;4416 if (get8(s) != 'B' || get8(s) != 'M') {4417 stbi_rewind( s );4418 return 0;4419 }4420 skip(s,12);4421 hsz = get32le(s);4422 if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {4423 stbi_rewind( s );4424 return 0;4425 }4426 if (hsz == 12) {4427 *x = get16le(s);4428 *y = get16le(s);4429 } else {4430 *x = get32le(s);4431 *y = get32le(s);4432 }4433 if (get16le(s) != 1) {4434 stbi_rewind( s );4435 return 0;4436 }4437 *comp = get16le(s) / 8;4438 return 1;4439}44404441static int stbi_psd_info(stbi *s, int *x, int *y, int *comp)4442{4443 int channelCount;4444 if (get32(s) != 0x38425053) {4445 stbi_rewind( s );4446 return 0;4447 }4448 if (get16(s) != 1) {4449 stbi_rewind( s );4450 return 0;4451 }4452 skip(s, 6);4453 channelCount = get16(s);4454 if (channelCount < 0 || channelCount > 16) {4455 stbi_rewind( s );4456 return 0;4457 }4458 *y = get32(s);4459 *x = get32(s);4460 if (get16(s) != 8) {4461 stbi_rewind( s );4462 return 0;4463 }4464 if (get16(s) != 3) {4465 stbi_rewind( s );4466 return 0;4467 }4468 *comp = 4;4469 return 1;4470}44714472static int stbi_pic_info(stbi *s, int *x, int *y, int *comp)4473{4474 int act_comp=0,num_packets=0,chained;4475 pic_packet_t packets[10];44764477 skip(s, 92);44784479 *x = get16(s);4480 *y = get16(s);4481 if (at_eof(s)) return 0;4482 if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {4483 stbi_rewind( s );4484 return 0;4485 }44864487 skip(s, 8);44884489 do {4490 pic_packet_t *packet;44914492 if (num_packets==sizeof(packets)/sizeof(packets[0]))4493 return 0;44944495 packet = &packets[num_packets++];4496 chained = get8(s);4497 packet->size = get8u(s);4498 packet->type = get8u(s);4499 packet->channel = get8u(s);4500 act_comp |= packet->channel;45014502 if (at_eof(s)) {4503 stbi_rewind( s );4504 return 0;4505 }4506 if (packet->size != 8) {4507 stbi_rewind( s );4508 return 0;4509 }4510 } while (chained);45114512 *comp = (act_comp & 0x10 ? 4 : 3);45134514 return 1;4515}45164517static int stbi_info_main(stbi *s, int *x, int *y, int *comp)4518{4519 if (stbi_jpeg_info(s, x, y, comp))4520 return 1;4521 if (stbi_png_info(s, x, y, comp))4522 return 1;4523 if (stbi_gif_info(s, x, y, comp))4524 return 1;4525 if (stbi_bmp_info(s, x, y, comp))4526 return 1;4527 if (stbi_psd_info(s, x, y, comp))4528 return 1;4529 if (stbi_pic_info(s, x, y, comp))4530 return 1;4531 #ifndef STBI_NO_HDR4532 if (stbi_hdr_info(s, x, y, comp))4533 return 1;4534 #endif4535 // test tga last because it's a crappy test!4536 if (stbi_tga_info(s, x, y, comp))4537 return 1;4538 return e("unknown image type", "Image not of any known type, or corrupt");4539}45404541#ifndef STBI_NO_STDIO4542int stbi_info(char const *filename, int *x, int *y, int *comp)4543{4544 FILE *f = fopen(filename, "rb");4545 int result;4546 if (!f) return e("can't fopen", "Unable to open file");4547 result = stbi_info_from_file(f, x, y, comp);4548 fclose(f);4549 return result;4550}45514552int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)4553{4554 int r;4555 stbi s;4556 long pos = ftell(f);4557 start_file(&s, f);4558 r = stbi_info_main(&s,x,y,comp);4559 fseek(f,pos,SEEK_SET);4560 return r;4561}4562#endif // !STBI_NO_STDIO45634564int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)4565{4566 stbi s;4567 start_mem(&s,buffer,len);4568 return stbi_info_main(&s,x,y,comp);4569}45704571int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)4572{4573 stbi s;4574 start_callbacks(&s, (stbi_io_callbacks *) c, user);4575 return stbi_info_main(&s,x,y,comp);4576}45774578#endif // STBI_HEADER_FILE_ONLY45794580#if !defined(STBI_NO_STDIO) && defined(_MSC_VER) && _MSC_VER >= 14004581#pragma warning(pop)4582#endif458345844585/*4586 revision history:4587 1.35 (2014-05-27)4588 various warnings4589 fix broken STBI_SIMD path4590 fix bug where stbi_load_from_file no longer left file pointer in correct place4591 fix broken non-easy path for 32-bit BMP (possibly never used)4592 TGA optimization by Arseny Kapoulkine4593 1.34 (unknown)4594 use STBI_NOTUSED in resample_row_generic(), fix one more leak in tga failure case4595 1.33 (2011-07-14)4596 make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements4597 1.32 (2011-07-13)4598 support for "info" function for all supported filetypes (SpartanJ)4599 1.31 (2011-06-20)4600 a few more leak fixes, bug in PNG handling (SpartanJ)4601 1.30 (2011-06-11)4602 added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)4603 removed deprecated format-specific test/load functions4604 removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway4605 error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)4606 fix inefficiency in decoding 32-bit BMP (David Woo)4607 1.29 (2010-08-16)4608 various warning fixes from Aurelien Pocheville 4609 1.28 (2010-08-01)4610 fix bug in GIF palette transparency (SpartanJ)4611 1.27 (2010-08-01)4612 cast-to-stbi__uint8 to fix warnings4613 1.26 (2010-07-24)4614 fix bug in file buffering for PNG reported by SpartanJ4615 1.25 (2010-07-17)4616 refix trans_data warning (Won Chun)4617 1.24 (2010-07-12)4618 perf improvements reading from files on platforms with lock-heavy fgetc()4619 minor perf improvements for jpeg4620 deprecated type-specific functions so we'll get feedback if they're needed4621 attempt to fix trans_data warning (Won Chun)4622 1.23 fixed bug in iPhone support4623 1.22 (2010-07-10)4624 removed image *writing* support4625 stbi_info support from Jetro Lauha4626 GIF support from Jean-Marc Lienher4627 iPhone PNG-extensions from James Brown4628 warning-fixes from Nicolas Schulz and Janez Zemva (i.e. Janez (U+017D)emva)4629 1.21 fix use of 'stbi__uint8' in header (reported by jon blow)4630 1.20 added support for Softimage PIC, by Tom Seddon4631 1.19 bug in interlaced PNG corruption check (found by ryg)4632 1.18 2008-08-024633 fix a threading bug (local mutable static)4634 1.17 support interlaced PNG4635 1.16 major bugfix - convert_format converted one too many pixels4636 1.15 initialize some fields for thread safety4637 1.14 fix threadsafe conversion bug4638 header-file-only version (#define STBI_HEADER_FILE_ONLY before including)4639 1.13 threadsafe4640 1.12 const qualifiers in the API4641 1.11 Support installable IDCT, colorspace conversion routines4642 1.10 Fixes for 64-bit (don't use "unsigned long")4643 optimized upsampling by Fabian "ryg" Giesen4644 1.09 Fix format-conversion for PSD code (bad global variables!)4645 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz4646 1.07 attempt to fix C++ warning/errors again4647 1.06 attempt to fix C++ warning/errors again4648 1.05 fix TGA loading to return correct *comp and use good luminance calc4649 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free4650 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR4651 1.02 support for (subset of) HDR files, float interface for preferred access to them4652 1.01 fix bug: possible bug in handling right-side up bmps... not sure4653 fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all4654 1.00 interface to zlib that skips zlib header4655 0.99 correct handling of alpha in palette4656 0.98 TGA loader by lonesock; dynamically add loaders (untested)4657 0.97 jpeg errors on too large a file; also catch another malloc failure4658 0.96 fix detection of invalid v value - particleman@mollyrocket forum4659 0.95 during header scan, seek to markers in case of padding4660 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same4661 0.93 handle jpegtran output; verbose errors4662 0.92 read 4,8,16,24,32-bit BMP files of several formats4663 0.91 output 24-bit Windows 3.0 BMP files4664 0.90 fix a few more warnings; bump version number to approach 1.04665 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd4666 0.60 fix compiling as c++4667 0.59 fix warnings: merge Dave Moore's -Wall fixes4668 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian4669 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available4670 0.56 fix bug: zlib uncompressed mode len vs. nlen4671 0.55 fix bug: restart_interval not initialized to 04672 0.54 allow NULL for 'int *comp'4673 0.53 fix bug in png 3->4; speedup png decoding4674 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments4675 0.51 obey req_comp requests, 1-component jpegs return as 1-component,4676 on 'test' only check type, not whether we support this variant4677 0.50 first released version4678*/
added:stb_image.h+4632 added
1/* stb_image - v1.36 - 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 Do this:6 #define STB_IMAGE_IMPLEMENTATION7 before you include this file in *one* C or C++ file to create the implementation.89 QUICK NOTES:10 Primarily of interest to game developers and other people who can11 avoid problematic images and only need the trivial interface1213 JPEG baseline (no JPEG progressive)14 PNG 8-bit-per-channel only1516 TGA (not sure what subset, if a subset)17 BMP non-1bpp, non-RLE18 PSD (composited view only, no extra channels)1920 GIF (*comp always reports as 4-channel)21 HDR (radiance rgbE format)22 PIC (Softimage PIC)2324 - stbi__jpeg_huff_decode from memory or through FILE (define STBI_NO_STDIO to remove code)25 - stbi__jpeg_huff_decode from arbitrary I/O callbacks26 - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)2728 Latest revisions:29 1.36 (2014-06-03) converted to header file, allow reading incorrect iphoned-images without iphone flag30 1.35 (2014-05-27) warnings, bugfixes, TGA optimization, etc31 1.34 (unknown ) warning fix32 1.33 (2011-07-14) minor fixes suggested by Dave Moore33 1.32 (2011-07-13) info support for all filetypes (SpartanJ)34 1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ)35 1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger)36 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 37 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)3839 See end of file for full revision history.4041 TODO:42 stbi_info support for BMP,PSD,HDR,PIC434445 ============================ Contributors =========================46 47 Image formats Bug fixes & warning fixes48 Sean Barrett (jpeg, png, bmp) Marc LeBlanc49 Nicolas Schulz (hdr, psd) Christpher Lloyd50 Jonathan Dummer (tga) Dave Moore51 Jean-Marc Lienher (gif) Won Chun52 Tom Seddon (pic) the Horde3D community53 Thatcher Ulrich (psd) Janez Zemva54 Jonathan Blow55 Laurent Gomila56 Extensions, features Aruelien Pocheville57 Jetro Lauha (stbi_info) Ryamond Barbiero58 James "moose2000" Brown (iPhone PNG) David Woo59 Ben "Disch" Wenger (io callbacks) Roy Eltham60 Martin "SpartanJ" Golini Luke Graham61 Thomas Ruf62 John Bartholomew63 Optimizations & bugfixes Ken Hamada64 Fabian "ryg" Giesen Cort Stratton65 Arseny Kapoulkine Blazej Dariusz Roszkowski66 Thibault Reuille67 If your name should be here but Paul Du Bois68 isn't let Sean know. Guillaume George6970*/7172#ifndef STBI_INCLUDE_STB_IMAGE_H73#define STBI_INCLUDE_STB_IMAGE_H7475// Limitations:76// - no jpeg progressive support77// - non-HDR formats support 8-bit samples only (jpeg, png)78// - no delayed line count (jpeg) -- IJG doesn't support either79// - no 1-bit BMP80// - GIF always returns *comp=481//82// Basic usage (see HDR discussion below):83// int x,y,n;84// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);85// // ... process data if not NULL ... 86// // ... x = width, y = height, n = # 8-bit components per pixel ...87// // ... replace '0' with '1'..'4' to force that many components per pixel88// // ... but 'n' will always be the number that it would have been if you said 089// stbi_image_free(data)90//91// Standard parameters:92// int *x -- outputs image width in pixels93// int *y -- outputs image height in pixels94// int *comp -- outputs # of image components in image file95// int req_comp -- if non-zero, # of image components requested in result96//97// The return value from an image loader is an 'unsigned char *' which points98// to the pixel data. The pixel data consists of *y scanlines of *x pixels,99// with each pixel consisting of N interleaved 8-bit components; the first100// pixel pointed to is top-left-most in the image. There is no padding between101// image scanlines or between pixels, regardless of format. The number of102// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.103// If req_comp is non-zero, *comp has the number of components that _would_104// have been output otherwise. E.g. if you set req_comp to 4, you will always105// get RGBA output, but you can check *comp to easily see if it's opaque.106//107// An output image with N components has the following components interleaved108// in this order in each pixel:109//110// N=#comp components111// 1 grey112// 2 grey, alpha113// 3 red, green, blue114// 4 red, green, blue, alpha115//116// If image loading fails for any reason, the return value will be NULL,117// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()118// can be queried for an extremely brief, end-user unfriendly explanation119// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid120// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly121// more user-friendly ones.122//123// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.124//125// ===========================================================================126//127// iPhone PNG support:128//129// By default we convert iphone-formatted PNGs back to RGB; nominally they130// would silently load as BGR, except the existing code should have just131// failed on such iPhone PNGs. But you can disable this conversion by132// by calling stbi_convert_iphone_png_to_rgb(0), in which case133// you will always just get the native iphone "format" through.134//135// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per136// pixel to remove any premultiplied alpha *only* if the image file explicitly137// says there's premultiplied data (currently only happens in iPhone images,138// and only if iPhone convert-to-rgb processing is on).139//140// ===========================================================================141//142// HDR image support (disable by defining STBI_NO_HDR)143//144// stb_image now supports loading HDR images in general, and currently145// the Radiance .HDR file format, although the support is provided146// generically. You can still load any file through the existing interface;147// if you attempt to load an HDR file, it will be automatically remapped to148// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;149// both of these constants can be reconfigured through this interface:150//151// stbi_hdr_to_ldr_gamma(2.2f);152// stbi_hdr_to_ldr_scale(1.0f);153//154// (note, do not use _inverse_ constants; stbi_image will invert them155// appropriately).156//157// Additionally, there is a new, parallel interface for loading files as158// (linear) floats to preserve the full dynamic range:159//160// float *data = stbi_loadf(filename, &x, &y, &n, 0);161// 162// If you load LDR images through this interface, those images will163// be promoted to floating point values, run through the inverse of164// constants corresponding to the above:165//166// stbi_ldr_to_hdr_scale(1.0f);167// stbi_ldr_to_hdr_gamma(2.2f);168//169// Finally, given a filename (or an open file or memory block--see header170// file for details) containing image data, you can query for the "most171// appropriate" interface to use (that is, whether the image is HDR or172// not), using:173//174// stbi_is_hdr(char *filename);175//176// ===========================================================================177//178// I/O callbacks179//180// I/O callbacks allow you to read from arbitrary sources, like packaged181// files or some other source. Data read from callbacks are processed182// through a small internal buffer (currently 128 bytes) to try to reduce183// overhead. 184//185// The three functions you must define are "read" (reads some bytes of data),186// "stbi__skip" (skips some bytes of data), "eof" (reports if the stream is at the end).187188189#ifndef STBI_NO_STDIO190191#if defined(_MSC_VER) && _MSC_VER >= 1400192#define _CRT_SECURE_NO_WARNINGS // suppress warnings about fopen()193#pragma warning(push)194#pragma warning(disable:4996) // suppress even more warnings about fopen()195#endif196#include <stdio.h>197#endif // STBI_NO_STDIO198199#define STBI_VERSION 1200201enum202{203 STBI_default = 0, // only used for req_comp204205 STBI_grey = 1,206 STBI_grey_alpha = 2,207 STBI_rgb = 3,208 STBI_rgb_alpha = 4209};210211typedef unsigned char stbi_uc;212213#ifdef __cplusplus214extern "C" {215#endif216217#ifdef STB_IMAGE_STATIC218#define STBIDEF static219#else220#define STBIDEF extern221#endif222223//////////////////////////////////////////////////////////////////////////////224//225// PRIMARY API - works on images of any type226//227228//229// load image by filename, open file, or memory buffer230//231232STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);233234#ifndef STBI_NO_STDIO235STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);236STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);237// for stbi_load_from_file, file pointer is left pointing immediately after image238#endif239240typedef struct241{242 int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read 243 void (*stbi__skip) (void *user,int n); // stbi__skip the next 'n' bytes, or 'unget' the last -n bytes if negative244 int (*eof) (void *user); // returns nonzero if we are at end of file/data245} stbi_io_callbacks;246247STBIDEF stbi_uc *stbi_load_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);248249#ifndef STBI_NO_HDR250 STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);251252 #ifndef STBI_NO_STDIO253 STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);254 STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);255 #endif256 257 STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);258259 STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);260 STBIDEF void stbi_hdr_to_ldr_scale(float scale);261262 STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);263 STBIDEF void stbi_ldr_to_hdr_scale(float scale);264#endif // STBI_NO_HDR265266// stbi_is_hdr is always defined267STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);268STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);269#ifndef STBI_NO_STDIO270STBIDEF int stbi_is_hdr (char const *filename);271STBIDEF int stbi_is_hdr_from_file(FILE *f);272#endif // STBI_NO_STDIO273274275// get a VERY brief reason for failure276// NOT THREADSAFE277STBIDEF const char *stbi_failure_reason (void); 278279// free the loaded image -- this is just free()280STBIDEF void stbi_image_free (void *retval_from_stbi_load);281282// get image dimensions & components without fully decoding283STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);284STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);285286#ifndef STBI_NO_STDIO287STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);288STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);289290#endif291292293294// for image formats that explicitly notate that they have premultiplied alpha,295// we just return the colors as stored in the file. set this flag to force296// unpremultiplication. results are undefined if the unpremultiply overflow.297STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);298299// indicate whether we should process iphone images back to canonical format,300// or just pass them through "as-is"301STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);302303304// ZLIB client - used by PNG, available for other purposes305306STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);307STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);308STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);309STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);310311STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);312STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);313314315// define faster low-level operations (typically SIMD support)316#ifdef STBI_SIMD317typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);318// compute an integer IDCT on "input"319// input[x] = data[x] * dequantize[x]320// write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'321// CLAMP results to 0..255322typedef 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);323// compute a conversion from YCbCr to RGB324// 'count' pixels325// write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B326// y: Y input channel327// cb: Cb input channel; scale/biased to be 0..255328// cr: Cr input channel; scale/biased to be 0..255329330STBIDEF void stbi_install_idct(stbi_idct_8x8 func);331STBIDEF void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);332#endif // STBI_SIMD333334335#ifdef __cplusplus336}337#endif338339//340//341//// end header file /////////////////////////////////////////////////////342#endif // STBI_INCLUDE_STB_IMAGE_H343344#ifdef STB_IMAGE_IMPLEMENTATION345346#ifndef STBI_NO_HDR347#include <math.h> // ldexp348#include <string.h> // strcmp, strtok349#endif350351#ifndef STBI_NO_STDIO352#include <stdio.h>353#endif354#include <stdlib.h>355#include <memory.h>356#include <assert.h>357#include <stdarg.h>358#include <stddef.h> // ptrdiff_t on osx359360#ifndef _MSC_VER361 #ifdef __cplusplus362 #define stbi_inline inline363 #else364 #define stbi_inline365 #endif366#else367 #define stbi_inline __forceinline368#endif369370371#ifdef _MSC_VER372typedef unsigned char stbi_uc;373typedef unsigned short stbi__uint16;374typedef signed short stbi__int16;375typedef unsigned int stbi__uint32;376typedef signed int stbi__int32;377#else378#include <stdint.h>379typedef uint8_t stbi_uc;380typedef uint16_t stbi__uint16;381typedef int16_t stbi__int16;382typedef uint32_t stbi__uint32;383typedef int32_t stbi__int32;384#endif385386// should produce compiler error if size is wrong387typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];388389#ifdef _MSC_VER390#define STBI_NOTUSED(v) (void)(v)391#else392#define STBI_NOTUSED(v) (void)sizeof(v)393#endif394395#ifdef _MSC_VER396#define STBI_HAS_LROTL397#endif398399#ifdef STBI_HAS_LROTL400 #define stbi_lrot(x,y) _lrotl(x,y)401#else402 #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))403#endif404405///////////////////////////////////////////////406//407// stbi__context struct and start_xxx functions408409// stbi__context structure is our basic context used by all images, so it410// contains all the IO context, plus some basic image information411typedef struct412{413 stbi__uint32 img_x, img_y;414 int img_n, img_out_n;415 416 stbi_io_callbacks io;417 void *io_user_data;418419 int read_from_callbacks;420 int buflen;421 stbi_uc buffer_start[128];422423 stbi_uc *img_buffer, *img_buffer_end;424 stbi_uc *img_buffer_original;425} stbi__context;426427428static void stbi__refill_buffer(stbi__context *s);429430// initialize a memory-stbi__jpeg_huff_decode context431static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)432{433 s->io.read = NULL;434 s->read_from_callbacks = 0;435 s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;436 s->img_buffer_end = (stbi_uc *) buffer+len;437}438439// initialize a callback-based context440static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)441{442 s->io = *c;443 s->io_user_data = user;444 s->buflen = sizeof(s->buffer_start);445 s->read_from_callbacks = 1;446 s->img_buffer_original = s->buffer_start;447 stbi__refill_buffer(s);448}449450#ifndef STBI_NO_STDIO451452static int stbi__stdio_read(void *user, char *data, int size)453{454 return (int) fread(data,1,size,(FILE*) user);455}456457static void stbi__stdio_skip(void *user, int n)458{459 fseek((FILE*) user, n, SEEK_CUR);460}461462static int stbi__stdio_eof(void *user)463{464 return feof((FILE*) user);465}466467static stbi_io_callbacks stbi__stdio_callbacks =468{469 stbi__stdio_read,470 stbi__stdio_skip,471 stbi__stdio_eof,472};473474static void stbi__start_file(stbi__context *s, FILE *f)475{476 stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);477}478479//static void stop_file(stbi__context *s) { }480481#endif // !STBI_NO_STDIO482483static void stbi__rewind(stbi__context *s)484{485 // conceptually rewind SHOULD rewind to the beginning of the stream,486 // but we just rewind to the beginning of the initial buffer, because487 // we only use it after doing 'test', which only ever looks at at most 92 bytes488 s->img_buffer = s->img_buffer_original;489}490491static int stbi__jpeg_test(stbi__context *s);492static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);493static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);494static int stbi__png_test(stbi__context *s);495static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);496static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);497static int stbi__bmp_test(stbi__context *s);498static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);499static int stbi__tga_test(stbi__context *s);500static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);501static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);502static int stbi__psd_test(stbi__context *s);503static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);504#ifndef STBI_NO_HDR505static int stbi__hdr_test(stbi__context *s);506static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);507#endif508static int stbi__pic_test(stbi__context *s);509static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);510static int stbi__gif_test(stbi__context *s);511static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);512static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);513514515// this is not threadsafe516static const char *stbi__g_failure_reason;517518STBIDEF const char *stbi_failure_reason(void)519{520 return stbi__g_failure_reason;521}522523static int stbi__err(const char *str)524{525 stbi__g_failure_reason = str;526 return 0;527}528529// stbi__err - error530// stbi__errpf - error returning pointer to float531// stbi__errpuc - error returning pointer to unsigned char532533#ifdef STBI_NO_FAILURE_STRINGS534 #define stbi__err(x,y) 0535#elif defined(STBI_FAILURE_USERMSG)536 #define stbi__err(x,y) stbi__err(y)537#else538 #define stbi__err(x,y) stbi__err(x)539#endif540541#define stbi__errpf(x,y) ((float *) (stbi__err(x,y)?NULL:NULL))542#define stbi__errpuc(x,y) ((unsigned char *) (stbi__err(x,y)?NULL:NULL))543544STBIDEF void stbi_image_free(void *retval_from_stbi_load)545{546 free(retval_from_stbi_load);547}548549#ifndef STBI_NO_HDR550static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);551static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp);552#endif553554static unsigned char *stbi_load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)555{556 if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp);557 if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp);558 if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp);559 if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp);560 if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp);561 if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp);562563 #ifndef STBI_NO_HDR564 if (stbi__hdr_test(s)) {565 float *hdr = stbi__hdr_load(s, x,y,comp,req_comp);566 return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);567 }568 #endif569570 // test tga last because it's a crappy test!571 if (stbi__tga_test(s))572 return stbi__tga_load(s,x,y,comp,req_comp);573 return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");574}575576#ifndef STBI_NO_STDIO577STBIDEF unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)578{579 FILE *f = fopen(filename, "rb");580 unsigned char *result;581 if (!f) return stbi__errpuc("can't fopen", "Unable to open file");582 result = stbi_load_from_file(f,x,y,comp,req_comp);583 fclose(f);584 return result;585}586587STBIDEF unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)588{589 unsigned char *result;590 stbi__context s;591 stbi__start_file(&s,f);592 result = stbi_load_main(&s,x,y,comp,req_comp);593 if (result) {594 // need to 'unget' all the characters in the IO buffer595 fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);596 }597 return result;598}599#endif //!STBI_NO_STDIO600601STBIDEF unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)602{603 stbi__context s;604 stbi__start_mem(&s,buffer,len);605 return stbi_load_main(&s,x,y,comp,req_comp);606}607608unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)609{610 stbi__context s;611 stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);612 return stbi_load_main(&s,x,y,comp,req_comp);613}614615#ifndef STBI_NO_HDR616617float *stbi_loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)618{619 unsigned char *data;620 #ifndef STBI_NO_HDR621 if (stbi__hdr_test(s))622 return stbi__hdr_load(s,x,y,comp,req_comp);623 #endif624 data = stbi_load_main(s, x, y, comp, req_comp);625 if (data)626 return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);627 return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");628}629630float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)631{632 stbi__context s;633 stbi__start_mem(&s,buffer,len);634 return stbi_loadf_main(&s,x,y,comp,req_comp);635}636637float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)638{639 stbi__context s;640 stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);641 return stbi_loadf_main(&s,x,y,comp,req_comp);642}643644#ifndef STBI_NO_STDIO645float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)646{647 FILE *f = fopen(filename, "rb");648 float *result;649 if (!f) return stbi__errpf("can't fopen", "Unable to open file");650 result = stbi_loadf_from_file(f,x,y,comp,req_comp);651 fclose(f);652 return result;653}654655float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)656{657 stbi__context s;658 stbi__start_file(&s,f);659 return stbi_loadf_main(&s,x,y,comp,req_comp);660}661#endif // !STBI_NO_STDIO662663#endif // !STBI_NO_HDR664665// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is666// defined, for API simplicity; if STBI_NO_HDR is defined, it always667// reports false!668669int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)670{671 #ifndef STBI_NO_HDR672 stbi__context s;673 stbi__start_mem(&s,buffer,len);674 return stbi__hdr_test(&s);675 #else676 STBI_NOTUSED(buffer);677 STBI_NOTUSED(len);678 return 0;679 #endif680}681682#ifndef STBI_NO_STDIO683STBIDEF int stbi_is_hdr (char const *filename)684{685 FILE *f = fopen(filename, "rb");686 int result=0;687 if (f) {688 result = stbi_is_hdr_from_file(f);689 fclose(f);690 }691 return result;692}693694STBIDEF int stbi_is_hdr_from_file(FILE *f)695{696 #ifndef STBI_NO_HDR697 stbi__context s;698 stbi__start_file(&s,f);699 return stbi__hdr_test(&s);700 #else701 return 0;702 #endif703}704#endif // !STBI_NO_STDIO705706STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)707{708 #ifndef STBI_NO_HDR709 stbi__context s;710 stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);711 return stbi__hdr_test(&s);712 #else713 return 0;714 #endif715}716717#ifndef STBI_NO_HDR718static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;719static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;720721void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }722void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }723724void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }725void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }726#endif727728729//////////////////////////////////////////////////////////////////////////////730//731// Common code used by all image loaders732//733734enum735{736 SCAN_load=0,737 SCAN_type,738 SCAN_header739};740741static void stbi__refill_buffer(stbi__context *s)742{743 int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);744 if (n == 0) {745 // at end of file, treat same as if from memory, but need to handle case746 // where s->img_buffer isn't pointing to safe memory, stbi__err.g. 0-byte file747 s->read_from_callbacks = 0;748 s->img_buffer = s->buffer_start;749 s->img_buffer_end = s->buffer_start+1;750 *s->img_buffer = 0;751 } else {752 s->img_buffer = s->buffer_start;753 s->img_buffer_end = s->buffer_start + n;754 }755}756757stbi_inline static int stbi__get8(stbi__context *s)758{759 if (s->img_buffer < s->img_buffer_end)760 return *s->img_buffer++;761 if (s->read_from_callbacks) {762 stbi__refill_buffer(s);763 return *s->img_buffer++;764 }765 return 0;766}767768stbi_inline static int stbi__at_eof(stbi__context *s)769{770 if (s->io.read) {771 if (!(s->io.eof)(s->io_user_data)) return 0;772 // if feof() is true, check if buffer = end773 // special case: we've only got the special 0 character at the end774 if (s->read_from_callbacks == 0) return 1;775 }776777 return s->img_buffer >= s->img_buffer_end; 778}779780stbi_inline static stbi_uc stbi__get8u(stbi__context *s)781{782 return (stbi_uc) stbi__get8(s);783}784785static void stbi__skip(stbi__context *s, int n)786{787 if (s->io.read) {788 int blen = (int) (s->img_buffer_end - s->img_buffer);789 if (blen < n) {790 s->img_buffer = s->img_buffer_end;791 (s->io.stbi__skip)(s->io_user_data, n - blen);792 return;793 }794 }795 s->img_buffer += n;796}797798static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)799{800 if (s->io.read) {801 int blen = (int) (s->img_buffer_end - s->img_buffer);802 if (blen < n) {803 int res, count;804805 memcpy(buffer, s->img_buffer, blen);806 807 count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);808 res = (count == (n-blen));809 s->img_buffer = s->img_buffer_end;810 return res;811 }812 }813814 if (s->img_buffer+n <= s->img_buffer_end) {815 memcpy(buffer, s->img_buffer, n);816 s->img_buffer += n;817 return 1;818 } else819 return 0;820}821822static int stbi__get16be(stbi__context *s)823{824 int z = stbi__get8(s);825 return (z << 8) + stbi__get8(s);826}827828static stbi__uint32 stbi__get32be(stbi__context *s)829{830 stbi__uint32 z = stbi__get16be(s);831 return (z << 16) + stbi__get16be(s);832}833834static int stbi__get16le(stbi__context *s)835{836 int z = stbi__get8(s);837 return z + (stbi__get8(s) << 8);838}839840static stbi__uint32 stbi__get32le(stbi__context *s)841{842 stbi__uint32 z = stbi__get16le(s);843 return z + (stbi__get16le(s) << 16);844}845846//////////////////////////////////////////////////////////////////////////////847//848// generic converter from built-in img_n to req_comp849// individual types do this automatically as much as possible (stbi__err.g. jpeg850// does all cases internally since it needs to colorspace convert anyway,851// and it never has alpha, so very few cases ). png can automatically852// interleave an alpha=255 channel, but falls back to this for other cases853//854// assume data buffer is malloced, so malloc a new one and free that one855// only failure mode is malloc failing856857static stbi_uc stbi__compute_y(int r, int g, int b)858{859 return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);860}861862static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)863{864 int i,j;865 unsigned char *good;866867 if (req_comp == img_n) return data;868 assert(req_comp >= 1 && req_comp <= 4);869870 good = (unsigned char *) malloc(req_comp * x * y);871 if (good == NULL) {872 free(data);873 return stbi__errpuc("outofmem", "Out of memory");874 }875876 for (j=0; j < (int) y; ++j) {877 unsigned char *src = data + j * x * img_n ;878 unsigned char *dest = good + j * x * req_comp;879880 #define COMBO(a,b) ((a)*8+(b))881 #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)882 // convert source image with img_n components to one with req_comp components;883 // avoid switch per pixel, so use switch per scanline and massive macros884 switch (COMBO(img_n, req_comp)) {885 CASE(1,2) dest[0]=src[0], dest[1]=255; break;886 CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;887 CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;888 CASE(2,1) dest[0]=src[0]; break;889 CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;890 CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;891 CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;892 CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;893 CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break;894 CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;895 CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;896 CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;897 default: assert(0);898 }899 #undef CASE900 }901902 free(data);903 return good;904}905906#ifndef STBI_NO_HDR907static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)908{909 int i,k,n;910 float *output = (float *) malloc(x * y * comp * sizeof(float));911 if (output == NULL) { free(data); return stbi__errpf("outofmem", "Out of memory"); }912 // compute number of non-alpha components913 if (comp & 1) n = comp; else n = comp-1;914 for (i=0; i < x*y; ++i) {915 for (k=0; k < n; ++k) {916 output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale;917 }918 if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;919 }920 free(data);921 return output;922}923924#define stbi__float2int(x) ((int) (x))925static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)926{927 int i,k,n;928 stbi_uc *output = (stbi_uc *) malloc(x * y * comp);929 if (output == NULL) { free(data); return stbi__errpuc("outofmem", "Out of memory"); }930 // compute number of non-alpha components931 if (comp & 1) n = comp; else n = comp-1;932 for (i=0; i < x*y; ++i) {933 for (k=0; k < n; ++k) {934 float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;935 if (z < 0) z = 0;936 if (z > 255) z = 255;937 output[i*comp + k] = (stbi_uc) stbi__float2int(z);938 }939 if (k < comp) {940 float z = data[i*comp+k] * 255 + 0.5f;941 if (z < 0) z = 0;942 if (z > 255) z = 255;943 output[i*comp + k] = (stbi_uc) stbi__float2int(z);944 }945 }946 free(data);947 return output;948}949#endif950951//////////////////////////////////////////////////////////////////////////////952//953// "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)954//955// simple implementation956// - channel subsampling of at most 2 in each dimension957// - doesn't support delayed output of y-dimension958// - simple interface (only one output format: 8-bit interleaved RGB)959// - doesn't try to recover corrupt jpegs960// - doesn't allow partial loading, loading multiple at once961// - still fast on x86 (copying globals into locals doesn't help x86)962// - allocates lots of intermediate memory (full size of all components)963// - non-interleaved case requires this anyway964// - allows good upsampling (see next)965// high-quality966// - upsampled channels are bilinearly interpolated, even across blocks967// - quality integer IDCT derived from IJG's 'slow'968// performance969// - fast huffman; reasonable integer IDCT970// - uses a lot of intermediate memory, could cache poorly971// - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4972// stb_jpeg: 1.34 seconds (MSVC6, default release build)973// stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)974// IJL11.dll: 1.08 seconds (compiled by intel)975// IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)976// IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)977978// huffman decoding acceleration979#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache980981typedef struct982{983 stbi_uc fast[1 << FAST_BITS];984 // weirdly, repacking this into AoS is a 10% speed loss, instead of a win985 stbi__uint16 code[256];986 stbi_uc values[256];987 stbi_uc size[257];988 unsigned int maxcode[18];989 int delta[17]; // old 'firstsymbol' - old 'firstcode'990} stbi__huffman;991992typedef struct993{994 #ifdef STBI_SIMD995 unsigned short dequant2[4][64];996 #endif997 stbi__context *s;998 stbi__huffman huff_dc[4];999 stbi__huffman huff_ac[4];1000 stbi_uc dequant[4][64];10011002// sizes for components, interleaved MCUs1003 int img_h_max, img_v_max;1004 int img_mcu_x, img_mcu_y;1005 int img_mcu_w, img_mcu_h;10061007// definition of jpeg image component1008 struct1009 {1010 int id;1011 int h,v;1012 int tq;1013 int hd,ha;1014 int dc_pred;10151016 int x,y,w2,h2;1017 stbi_uc *data;1018 void *raw_data;1019 stbi_uc *linebuf;1020 } img_comp[4];10211022 stbi__uint32 code_buffer; // jpeg entropy-coded buffer1023 int code_bits; // number of valid bits1024 unsigned char marker; // marker seen while filling entropy buffer1025 int nomore; // flag if we saw a marker so must stop10261027 int scan_n, order[4];1028 int restart_interval, todo;1029} stbi__jpeg;10301031static int stbi__build_huffman(stbi__huffman *h, int *count)1032{1033 int i,j,k=0,code;1034 // build size list for each symbol (from JPEG spec)1035 for (i=0; i < 16; ++i)1036 for (j=0; j < count[i]; ++j)1037 h->size[k++] = (stbi_uc) (i+1);1038 h->size[k] = 0;10391040 // compute actual symbols (from jpeg spec)1041 code = 0;1042 k = 0;1043 for(j=1; j <= 16; ++j) {1044 // compute delta to add to code to compute symbol id1045 h->delta[j] = k - code;1046 if (h->size[k] == j) {1047 while (h->size[k] == j)1048 h->code[k++] = (stbi__uint16) (code++);1049 if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG");1050 }1051 // compute largest code + 1 for this size, preshifted as needed later1052 h->maxcode[j] = code << (16-j);1053 code <<= 1;1054 }1055 h->maxcode[j] = 0xffffffff;10561057 // build non-spec acceleration table; 255 is flag for not-accelerated1058 memset(h->fast, 255, 1 << FAST_BITS);1059 for (i=0; i < k; ++i) {1060 int s = h->size[i];1061 if (s <= FAST_BITS) {1062 int c = h->code[i] << (FAST_BITS-s);1063 int m = 1 << (FAST_BITS-s);1064 for (j=0; j < m; ++j) {1065 h->fast[c+j] = (stbi_uc) i;1066 }1067 }1068 }1069 return 1;1070}10711072static void stbi__grow_buffer_unsafe(stbi__jpeg *j)1073{1074 do {1075 int b = j->nomore ? 0 : stbi__get8(j->s);1076 if (b == 0xff) {1077 int c = stbi__get8(j->s);1078 if (c != 0) {1079 j->marker = (unsigned char) c;1080 j->nomore = 1;1081 return;1082 }1083 }1084 j->code_buffer |= b << (24 - j->code_bits);1085 j->code_bits += 8;1086 } while (j->code_bits <= 24);1087}10881089// (1 << n) - 11090static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};10911092// stbi__jpeg_huff_decode a jpeg huffman value from the bitstream1093stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)1094{1095 unsigned int temp;1096 int c,k;10971098 if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);10991100 // look at the top FAST_BITS and determine what symbol ID it is,1101 // if the code is <= FAST_BITS1102 c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);1103 k = h->fast[c];1104 if (k < 255) {1105 int s = h->size[k];1106 if (s > j->code_bits)1107 return -1;1108 j->code_buffer <<= s;1109 j->code_bits -= s;1110 return h->values[k];1111 }11121113 // naive test is to shift the code_buffer down so k bits are1114 // valid, then test against maxcode. To speed this up, we've1115 // preshifted maxcode left so that it has (16-k) 0s at the1116 // end; in other words, regardless of the number of bits, it1117 // wants to be compared against something shifted to have 16;1118 // that way we don't need to shift inside the loop.1119 temp = j->code_buffer >> 16;1120 for (k=FAST_BITS+1 ; ; ++k)1121 if (temp < h->maxcode[k])1122 break;1123 if (k == 17) {1124 // error! code not found1125 j->code_bits -= 16;1126 return -1;1127 }11281129 if (k > j->code_bits)1130 return -1;11311132 // convert the huffman code to the symbol id1133 c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];1134 assert((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);11351136 // convert the id to a symbol1137 j->code_bits -= k;1138 j->code_buffer <<= k;1139 return h->values[c];1140}11411142// combined JPEG 'receive' and JPEG 'extend', since baseline1143// always extends everything it receives.1144stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)1145{1146 unsigned int m = 1 << (n-1);1147 unsigned int k;1148 if (j->code_bits < n) stbi__grow_buffer_unsafe(j);11491150 #if 11151 k = stbi_lrot(j->code_buffer, n);1152 j->code_buffer = k & ~stbi__bmask[n];1153 k &= stbi__bmask[n];1154 j->code_bits -= n;1155 #else1156 k = (j->code_buffer >> (32 - n)) & stbi__bmask[n];1157 j->code_bits -= n;1158 j->code_buffer <<= n;1159 #endif1160 // the following test is probably a random branch that won't1161 // predict well. I tried to table accelerate it but failed.1162 // maybe it's compiling as a conditional move?1163 if (k < m)1164 return (-1 << n) + k + 1;1165 else1166 return k;1167}11681169// given a value that's at position X in the zigzag stream,1170// where does it appear in the 8x8 matrix coded as row-major?1171static stbi_uc stbi__jpeg_dezigzag[64+15] =1172{1173 0, 1, 8, 16, 9, 2, 3, 10,1174 17, 24, 32, 25, 18, 11, 4, 5,1175 12, 19, 26, 33, 40, 48, 41, 34,1176 27, 20, 13, 6, 7, 14, 21, 28,1177 35, 42, 49, 56, 57, 50, 43, 36,1178 29, 22, 15, 23, 30, 37, 44, 51,1179 58, 59, 52, 45, 38, 31, 39, 46,1180 53, 60, 61, 54, 47, 55, 62, 63,1181 // let corrupt input sample past end1182 63, 63, 63, 63, 63, 63, 63, 63,1183 63, 63, 63, 63, 63, 63, 631184};11851186// stbi__jpeg_huff_decode one 64-entry block--1187static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, int b)1188{1189 int diff,dc,k;1190 int t = stbi__jpeg_huff_decode(j, hdc);1191 if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG");11921193 // 0 all the ac values now so we can do it 32-bits at a time1194 memset(data,0,64*sizeof(data[0]));11951196 diff = t ? stbi__extend_receive(j, t) : 0;1197 dc = j->img_comp[b].dc_pred + diff;1198 j->img_comp[b].dc_pred = dc;1199 data[0] = (short) dc;12001201 // stbi__jpeg_huff_decode AC components, see JPEG spec1202 k = 1;1203 do {1204 int r,s;1205 int rs = stbi__jpeg_huff_decode(j, hac);1206 if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");1207 s = rs & 15;1208 r = rs >> 4;1209 if (s == 0) {1210 if (rs != 0xf0) break; // end block1211 k += 16;1212 } else {1213 k += r;1214 // stbi__jpeg_huff_decode into unzigzag'd location1215 data[stbi__jpeg_dezigzag[k++]] = (short) stbi__extend_receive(j,s);1216 }1217 } while (k < 64);1218 return 1;1219}12201221// take a -128..127 value and stbi__clamp it and convert to 0..2551222stbi_inline static stbi_uc stbi__clamp(int x)1223{1224 // trick to use a single test to catch both cases1225 if ((unsigned int) x > 255) {1226 if (x < 0) return 0;1227 if (x > 255) return 255;1228 }1229 return (stbi_uc) x;1230}12311232#define stbi__f2f(x) (int) (((x) * 4096 + 0.5))1233#define stbi__fsh(x) ((x) << 12)12341235// derived from jidctint -- DCT_ISLOW1236#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \1237 int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \1238 p2 = s2; \1239 p3 = s6; \1240 p1 = (p2+p3) * stbi__f2f(0.5411961f); \1241 t2 = p1 + p3*stbi__f2f(-1.847759065f); \1242 t3 = p1 + p2*stbi__f2f( 0.765366865f); \1243 p2 = s0; \1244 p3 = s4; \1245 t0 = stbi__fsh(p2+p3); \1246 t1 = stbi__fsh(p2-p3); \1247 x0 = t0+t3; \1248 x3 = t0-t3; \1249 x1 = t1+t2; \1250 x2 = t1-t2; \1251 t0 = s7; \1252 t1 = s5; \1253 t2 = s3; \1254 t3 = s1; \1255 p3 = t0+t2; \1256 p4 = t1+t3; \1257 p1 = t0+t3; \1258 p2 = t1+t2; \1259 p5 = (p3+p4)*stbi__f2f( 1.175875602f); \1260 t0 = t0*stbi__f2f( 0.298631336f); \1261 t1 = t1*stbi__f2f( 2.053119869f); \1262 t2 = t2*stbi__f2f( 3.072711026f); \1263 t3 = t3*stbi__f2f( 1.501321110f); \1264 p1 = p5 + p1*stbi__f2f(-0.899976223f); \1265 p2 = p5 + p2*stbi__f2f(-2.562915447f); \1266 p3 = p3*stbi__f2f(-1.961570560f); \1267 p4 = p4*stbi__f2f(-0.390180644f); \1268 t3 += p1+p4; \1269 t2 += p2+p3; \1270 t1 += p2+p4; \1271 t0 += p1+p3;12721273#ifdef STBI_SIMD1274typedef unsigned short stbi_dequantize_t;1275#else1276typedef stbi_uc stbi_dequantize_t;1277#endif12781279// .344 seconds on 3*anemones.jpg1280static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)1281{1282 int i,val[64],*v=val;1283 stbi_dequantize_t *dq = dequantize;1284 stbi_uc *o;1285 short *d = data;12861287 // columns1288 for (i=0; i < 8; ++i,++d,++dq, ++v) {1289 // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing1290 if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==01291 && d[40]==0 && d[48]==0 && d[56]==0) {1292 // no shortcut 0 seconds1293 // (1|2|3|4|5|6|7)==0 0 seconds1294 // all separate -0.047 seconds1295 // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds1296 int dcterm = d[0] * dq[0] << 2;1297 v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;1298 } else {1299 STBI__IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],1300 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])1301 // constants scaled things up by 1<<12; let's bring them back1302 // down, but keep 2 extra bits of precision1303 x0 += 512; x1 += 512; x2 += 512; x3 += 512;1304 v[ 0] = (x0+t3) >> 10;1305 v[56] = (x0-t3) >> 10;1306 v[ 8] = (x1+t2) >> 10;1307 v[48] = (x1-t2) >> 10;1308 v[16] = (x2+t1) >> 10;1309 v[40] = (x2-t1) >> 10;1310 v[24] = (x3+t0) >> 10;1311 v[32] = (x3-t0) >> 10;1312 }1313 }13141315 for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {1316 // no fast case since the first 1D IDCT spread components out1317 STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])1318 // constants scaled things up by 1<<12, plus we had 1<<2 from first1319 // loop, plus horizontal and vertical each scale by sqrt(8) so together1320 // we've got an extra 1<<3, so 1<<17 total we need to remove.1321 // so we want to round that, which means adding 0.5 * 1<<17,1322 // aka 65536. Also, we'll end up with -128 to 127 that we want1323 // to encode as 0..255 by adding 128, so we'll add that before the shift1324 x0 += 65536 + (128<<17);1325 x1 += 65536 + (128<<17);1326 x2 += 65536 + (128<<17);1327 x3 += 65536 + (128<<17);1328 // tried computing the shifts into temps, or'ing the temps to see1329 // if any were out of range, but that was slower1330 o[0] = stbi__clamp((x0+t3) >> 17);1331 o[7] = stbi__clamp((x0-t3) >> 17);1332 o[1] = stbi__clamp((x1+t2) >> 17);1333 o[6] = stbi__clamp((x1-t2) >> 17);1334 o[2] = stbi__clamp((x2+t1) >> 17);1335 o[5] = stbi__clamp((x2-t1) >> 17);1336 o[3] = stbi__clamp((x3+t0) >> 17);1337 o[4] = stbi__clamp((x3-t0) >> 17);1338 }1339}13401341#ifdef STBI_SIMD1342static stbi_idct_8x8 stbi__idct_installed = stbi__idct_block;13431344STBIDEF void stbi_install_idct(stbi_idct_8x8 func)1345{1346 stbi__idct_installed = func;1347}1348#endif13491350#define STBI__MARKER_none 0xff1351// if there's a pending marker from the entropy stream, return that1352// otherwise, fetch from the stream and get a marker. if there's no1353// marker, return 0xff, which is never a valid marker value1354static stbi_uc stbi__get_marker(stbi__jpeg *j)1355{1356 stbi_uc x;1357 if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }1358 x = stbi__get8u(j->s);1359 if (x != 0xff) return STBI__MARKER_none;1360 while (x == 0xff)1361 x = stbi__get8u(j->s);1362 return x;1363}13641365// in each scan, we'll have scan_n components, and the order1366// of the components is specified by order[]1367#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)13681369// after a restart interval, stbi__jpeg_reset the entropy decoder and1370// the dc prediction1371static void stbi__jpeg_reset(stbi__jpeg *j)1372{1373 j->code_bits = 0;1374 j->code_buffer = 0;1375 j->nomore = 0;1376 j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;1377 j->marker = STBI__MARKER_none;1378 j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;1379 // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,1380 // since we don't even allow 1<<30 pixels1381}13821383static int stbi__parse_entropy_coded_data(stbi__jpeg *z)1384{1385 stbi__jpeg_reset(z);1386 if (z->scan_n == 1) {1387 int i,j;1388 #ifdef STBI_SIMD1389 __declspec(align(16))1390 #endif1391 short data[64];1392 int n = z->order[0];1393 // non-interleaved data, we just need to process one block at a time,1394 // in trivial scanline order1395 // number of blocks to do just depends on how many actual "pixels" this1396 // component has, independent of interleaved MCU blocking and such1397 int w = (z->img_comp[n].x+7) >> 3;1398 int h = (z->img_comp[n].y+7) >> 3;1399 for (j=0; j < h; ++j) {1400 for (i=0; i < w; ++i) {1401 if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;1402 #ifdef STBI_SIMD1403 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]);1404 #else1405 stbi__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]);1406 #endif1407 // every data block is an MCU, so countdown the restart interval1408 if (--z->todo <= 0) {1409 if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);1410 // if it's NOT a restart, then just bail, so we get corrupt data1411 // rather than no data1412 if (!STBI__RESTART(z->marker)) return 1;1413 stbi__jpeg_reset(z);1414 }1415 }1416 }1417 } else { // interleaved!1418 int i,j,k,x,y;1419 short data[64];1420 for (j=0; j < z->img_mcu_y; ++j) {1421 for (i=0; i < z->img_mcu_x; ++i) {1422 // scan an interleaved mcu... process scan_n components in order1423 for (k=0; k < z->scan_n; ++k) {1424 int n = z->order[k];1425 // scan out an mcu's worth of this component; that's just determined1426 // by the basic H and V specified for the component1427 for (y=0; y < z->img_comp[n].v; ++y) {1428 for (x=0; x < z->img_comp[n].h; ++x) {1429 int x2 = (i*z->img_comp[n].h + x)*8;1430 int y2 = (j*z->img_comp[n].v + y)*8;1431 if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;1432 #ifdef STBI_SIMD1433 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]);1434 #else1435 stbi__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]);1436 #endif1437 }1438 }1439 }1440 // after all interleaved components, that's an interleaved MCU,1441 // so now count down the restart interval1442 if (--z->todo <= 0) {1443 if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);1444 // if it's NOT a restart, then just bail, so we get corrupt data1445 // rather than no data1446 if (!STBI__RESTART(z->marker)) return 1;1447 stbi__jpeg_reset(z);1448 }1449 }1450 }1451 }1452 return 1;1453}14541455static int stbi__process_marker(stbi__jpeg *z, int m)1456{1457 int L;1458 switch (m) {1459 case STBI__MARKER_none: // no marker found1460 return stbi__err("expected marker","Corrupt JPEG");14611462 case 0xC2: // stbi__SOF - progressive1463 return stbi__err("progressive jpeg","JPEG format not supported (progressive)");14641465 case 0xDD: // DRI - specify restart interval1466 if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG");1467 z->restart_interval = stbi__get16be(z->s);1468 return 1;14691470 case 0xDB: // DQT - define quantization table1471 L = stbi__get16be(z->s)-2;1472 while (L > 0) {1473 int q = stbi__get8(z->s);1474 int p = q >> 4;1475 int t = q & 15,i;1476 if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG");1477 if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG");1478 for (i=0; i < 64; ++i)1479 z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8u(z->s);1480 #ifdef STBI_SIMD1481 for (i=0; i < 64; ++i)1482 z->dequant2[t][i] = z->dequant[t][i];1483 #endif1484 L -= 65;1485 }1486 return L==0;14871488 case 0xC4: // DHT - define huffman table1489 L = stbi__get16be(z->s)-2;1490 while (L > 0) {1491 stbi_uc *v;1492 int sizes[16],i,n=0;1493 int q = stbi__get8(z->s);1494 int tc = q >> 4;1495 int th = q & 15;1496 if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG");1497 for (i=0; i < 16; ++i) {1498 sizes[i] = stbi__get8(z->s);1499 n += sizes[i];1500 }1501 L -= 17;1502 if (tc == 0) {1503 if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;1504 v = z->huff_dc[th].values;1505 } else {1506 if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;1507 v = z->huff_ac[th].values;1508 }1509 for (i=0; i < n; ++i)1510 v[i] = stbi__get8u(z->s);1511 L -= n;1512 }1513 return L==0;1514 }1515 // check for comment block or APP blocks1516 if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {1517 stbi__skip(z->s, stbi__get16be(z->s)-2);1518 return 1;1519 }1520 return 0;1521}15221523// after we see stbi__SOS1524static int stbi__process_scan_header(stbi__jpeg *z)1525{1526 int i;1527 int Ls = stbi__get16be(z->s);1528 z->scan_n = stbi__get8(z->s);1529 if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad stbi__SOS component count","Corrupt JPEG");1530 if (Ls != 6+2*z->scan_n) return stbi__err("bad stbi__SOS len","Corrupt JPEG");1531 for (i=0; i < z->scan_n; ++i) {1532 int id = stbi__get8(z->s), which;1533 int q = stbi__get8(z->s);1534 for (which = 0; which < z->s->img_n; ++which)1535 if (z->img_comp[which].id == id)1536 break;1537 if (which == z->s->img_n) return 0;1538 z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG");1539 z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG");1540 z->order[i] = which;1541 }1542 if (stbi__get8(z->s) != 0) return stbi__err("bad stbi__SOS","Corrupt JPEG");1543 stbi__get8(z->s); // should be 63, but might be 01544 if (stbi__get8(z->s) != 0) return stbi__err("bad stbi__SOS","Corrupt JPEG");15451546 return 1;1547}15481549static int stbi__process_frame_header(stbi__jpeg *z, int scan)1550{1551 stbi__context *s = z->s;1552 int Lf,p,i,q, h_max=1,v_max=1,c;1553 Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad stbi__SOF len","Corrupt JPEG"); // JPEG1554 p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline1555 s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG1556 s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires1557 c = stbi__get8(s);1558 if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires1559 s->img_n = c;1560 for (i=0; i < c; ++i) {1561 z->img_comp[i].data = NULL;1562 z->img_comp[i].linebuf = NULL;1563 }15641565 if (Lf != 8+3*s->img_n) return stbi__err("bad stbi__SOF len","Corrupt JPEG");15661567 for (i=0; i < s->img_n; ++i) {1568 z->img_comp[i].id = stbi__get8(s);1569 if (z->img_comp[i].id != i+1) // JFIF requires1570 if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!1571 return stbi__err("bad component ID","Corrupt JPEG");1572 q = stbi__get8(s);1573 z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG");1574 z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG");1575 z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");1576 }15771578 if (scan != SCAN_load) return 1;15791580 if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to stbi__jpeg_huff_decode");15811582 for (i=0; i < s->img_n; ++i) {1583 if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;1584 if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;1585 }15861587 // compute interleaved mcu info1588 z->img_h_max = h_max;1589 z->img_v_max = v_max;1590 z->img_mcu_w = h_max * 8;1591 z->img_mcu_h = v_max * 8;1592 z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;1593 z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;15941595 for (i=0; i < s->img_n; ++i) {1596 // number of effective pixels (stbi__err.g. for non-interleaved MCU)1597 z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;1598 z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;1599 // to simplify generation, we'll allocate enough memory to stbi__jpeg_huff_decode1600 // the bogus oversized data from using interleaved MCUs and their1601 // big blocks (stbi__err.g. a 16x16 iMCU on an image of width 33); we won't1602 // discard the extra data until colorspace conversion1603 z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;1604 z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;1605 z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);1606 if (z->img_comp[i].raw_data == NULL) {1607 for(--i; i >= 0; --i) {1608 free(z->img_comp[i].raw_data);1609 z->img_comp[i].data = NULL;1610 }1611 return stbi__err("outofmem", "Out of memory");1612 }1613 // align blocks for installable-idct using mmx/sse1614 z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);1615 z->img_comp[i].linebuf = NULL;1616 }16171618 return 1;1619}16201621// use comparisons since in some cases we handle more than one case (stbi__err.g. stbi__SOF)1622#define stbi__DNL(x) ((x) == 0xdc)1623#define stbi__SOI(x) ((x) == 0xd8)1624#define stbi__EOI(x) ((x) == 0xd9)1625#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1)1626#define stbi__SOS(x) ((x) == 0xda)16271628static int decode_jpeg_header(stbi__jpeg *z, int scan)1629{1630 int m;1631 z->marker = STBI__MARKER_none; // initialize cached marker to empty1632 m = stbi__get_marker(z);1633 if (!stbi__SOI(m)) return stbi__err("no stbi__SOI","Corrupt JPEG");1634 if (scan == SCAN_type) return 1;1635 m = stbi__get_marker(z);1636 while (!stbi__SOF(m)) {1637 if (!stbi__process_marker(z,m)) return 0;1638 m = stbi__get_marker(z);1639 while (m == STBI__MARKER_none) {1640 // some files have extra padding after their blocks, so ok, we'll scan1641 if (stbi__at_eof(z->s)) return stbi__err("no stbi__SOF", "Corrupt JPEG");1642 m = stbi__get_marker(z);1643 }1644 }1645 if (!stbi__process_frame_header(z, scan)) return 0;1646 return 1;1647}16481649static int decode_jpeg_image(stbi__jpeg *j)1650{1651 int m;1652 j->restart_interval = 0;1653 if (!decode_jpeg_header(j, SCAN_load)) return 0;1654 m = stbi__get_marker(j);1655 while (!stbi__EOI(m)) {1656 if (stbi__SOS(m)) {1657 if (!stbi__process_scan_header(j)) return 0;1658 if (!stbi__parse_entropy_coded_data(j)) return 0;1659 if (j->marker == STBI__MARKER_none ) {1660 // handle 0s at the end of image data from IP Kamera 90601661 while (!stbi__at_eof(j->s)) {1662 int x = stbi__get8(j->s);1663 if (x == 255) {1664 j->marker = stbi__get8u(j->s);1665 break;1666 } else if (x != 0) {1667 return 0;1668 }1669 }1670 // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 01671 }1672 } else {1673 if (!stbi__process_marker(j, m)) return 0;1674 }1675 m = stbi__get_marker(j);1676 }1677 return 1;1678}16791680// static jfif-centered resampling (across block boundaries)16811682typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,1683 int w, int hs);16841685#define stbi__div4(x) ((stbi_uc) ((x) >> 2))16861687static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)1688{1689 STBI_NOTUSED(out);1690 STBI_NOTUSED(in_far);1691 STBI_NOTUSED(w);1692 STBI_NOTUSED(hs);1693 return in_near;1694}16951696static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)1697{1698 // need to generate two samples vertically for every one in input1699 int i;1700 STBI_NOTUSED(hs);1701 for (i=0; i < w; ++i)1702 out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);1703 return out;1704}17051706static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)1707{1708 // need to generate two samples horizontally for every one in input1709 int i;1710 stbi_uc *input = in_near;17111712 if (w == 1) {1713 // if only one sample, can't do any interpolation1714 out[0] = out[1] = input[0];1715 return out;1716 }17171718 out[0] = input[0];1719 out[1] = stbi__div4(input[0]*3 + input[1] + 2);1720 for (i=1; i < w-1; ++i) {1721 int n = 3*input[i]+2;1722 out[i*2+0] = stbi__div4(n+input[i-1]);1723 out[i*2+1] = stbi__div4(n+input[i+1]);1724 }1725 out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);1726 out[i*2+1] = input[w-1];17271728 STBI_NOTUSED(in_far);1729 STBI_NOTUSED(hs);17301731 return out;1732}17331734#define stbi__div16(x) ((stbi_uc) ((x) >> 4))17351736static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)1737{1738 // need to generate 2x2 samples for every one in input1739 int i,t0,t1;1740 if (w == 1) {1741 out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);1742 return out;1743 }17441745 t1 = 3*in_near[0] + in_far[0];1746 out[0] = stbi__div4(t1+2);1747 for (i=1; i < w; ++i) {1748 t0 = t1;1749 t1 = 3*in_near[i]+in_far[i];1750 out[i*2-1] = stbi__div16(3*t0 + t1 + 8);1751 out[i*2 ] = stbi__div16(3*t1 + t0 + 8);1752 }1753 out[w*2-1] = stbi__div4(t1+2);17541755 STBI_NOTUSED(hs);17561757 return out;1758}17591760static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)1761{1762 // resample with nearest-neighbor1763 int i,j;1764 STBI_NOTUSED(in_far);1765 for (i=0; i < w; ++i)1766 for (j=0; j < hs; ++j)1767 out[i*hs+j] = in_near[i];1768 return out;1769}17701771#define float2fixed(x) ((int) ((x) * 65536 + 0.5))17721773// 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro)1774// VC6 without processor=Pro is generating multiple LEAs per multiply!1775static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)1776{1777 int i;1778 for (i=0; i < count; ++i) {1779 int y_fixed = (y[i] << 16) + 32768; // rounding1780 int r,g,b;1781 int cr = pcr[i] - 128;1782 int cb = pcb[i] - 128;1783 r = y_fixed + cr*float2fixed(1.40200f);1784 g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);1785 b = y_fixed + cb*float2fixed(1.77200f);1786 r >>= 16;1787 g >>= 16;1788 b >>= 16;1789 if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }1790 if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }1791 if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }1792 out[0] = (stbi_uc)r;1793 out[1] = (stbi_uc)g;1794 out[2] = (stbi_uc)b;1795 out[3] = 255;1796 out += step;1797 }1798}17991800#ifdef STBI_SIMD1801static stbi_YCbCr_to_RGB_run stbi__YCbCr_installed = stbi__YCbCr_to_RGB_row;18021803STBIDEF void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)1804{1805 stbi__YCbCr_installed = func;1806}1807#endif180818091810// clean up the temporary component buffers1811static void stbi__cleanup_jpeg(stbi__jpeg *j)1812{1813 int i;1814 for (i=0; i < j->s->img_n; ++i) {1815 if (j->img_comp[i].data) {1816 free(j->img_comp[i].raw_data);1817 j->img_comp[i].data = NULL;1818 }1819 if (j->img_comp[i].linebuf) {1820 free(j->img_comp[i].linebuf);1821 j->img_comp[i].linebuf = NULL;1822 }1823 }1824}18251826typedef struct1827{1828 resample_row_func resample;1829 stbi_uc *line0,*line1;1830 int hs,vs; // expansion factor in each axis1831 int w_lores; // horizontal pixels pre-expansion 1832 int ystep; // how far through vertical expansion we are1833 int ypos; // which pre-expansion row we're on1834} stbi__resample;18351836static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)1837{1838 int n, decode_n;1839 // validate req_comp1840 if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");1841 z->s->img_n = 0;18421843 // load a jpeg image from whichever source1844 if (!decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }18451846 // determine actual number of components to generate1847 n = req_comp ? req_comp : z->s->img_n;18481849 if (z->s->img_n == 3 && n < 3)1850 decode_n = 1;1851 else1852 decode_n = z->s->img_n;18531854 // resample and color-convert1855 {1856 int k;1857 unsigned int i,j;1858 stbi_uc *output;1859 stbi_uc *coutput[4];18601861 stbi__resample res_comp[4];18621863 for (k=0; k < decode_n; ++k) {1864 stbi__resample *r = &res_comp[k];18651866 // allocate line buffer big enough for upsampling off the edges1867 // with upsample factor of 41868 z->img_comp[k].linebuf = (stbi_uc *) malloc(z->s->img_x + 3);1869 if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }18701871 r->hs = z->img_h_max / z->img_comp[k].h;1872 r->vs = z->img_v_max / z->img_comp[k].v;1873 r->ystep = r->vs >> 1;1874 r->w_lores = (z->s->img_x + r->hs-1) / r->hs;1875 r->ypos = 0;1876 r->line0 = r->line1 = z->img_comp[k].data;18771878 if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;1879 else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;1880 else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;1881 else if (r->hs == 2 && r->vs == 2) r->resample = stbi__resample_row_hv_2;1882 else r->resample = stbi__resample_row_generic;1883 }18841885 // can't error after this so, this is safe1886 output = (stbi_uc *) malloc(n * z->s->img_x * z->s->img_y + 1);1887 if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }18881889 // now go ahead and resample1890 for (j=0; j < z->s->img_y; ++j) {1891 stbi_uc *out = output + n * z->s->img_x * j;1892 for (k=0; k < decode_n; ++k) {1893 stbi__resample *r = &res_comp[k];1894 int y_bot = r->ystep >= (r->vs >> 1);1895 coutput[k] = r->resample(z->img_comp[k].linebuf,1896 y_bot ? r->line1 : r->line0,1897 y_bot ? r->line0 : r->line1,1898 r->w_lores, r->hs);1899 if (++r->ystep >= r->vs) {1900 r->ystep = 0;1901 r->line0 = r->line1;1902 if (++r->ypos < z->img_comp[k].y)1903 r->line1 += z->img_comp[k].w2;1904 }1905 }1906 if (n >= 3) {1907 stbi_uc *y = coutput[0];1908 if (z->s->img_n == 3) {1909 #ifdef STBI_SIMD1910 stbi__YCbCr_installed(out, y, coutput[1], coutput[2], z->s->img_x, n);1911 #else1912 stbi__YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);1913 #endif1914 } else1915 for (i=0; i < z->s->img_x; ++i) {1916 out[0] = out[1] = out[2] = y[i];1917 out[3] = 255; // not used if n==31918 out += n;1919 }1920 } else {1921 stbi_uc *y = coutput[0];1922 if (n == 1)1923 for (i=0; i < z->s->img_x; ++i) out[i] = y[i];1924 else1925 for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;1926 }1927 }1928 stbi__cleanup_jpeg(z);1929 *out_x = z->s->img_x;1930 *out_y = z->s->img_y;1931 if (comp) *comp = z->s->img_n; // report original components, not output1932 return output;1933 }1934}19351936static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)1937{1938 stbi__jpeg j;1939 j.s = s;1940 return load_jpeg_image(&j, x,y,comp,req_comp);1941}19421943static int stbi__jpeg_test(stbi__context *s)1944{1945 int r;1946 stbi__jpeg j;1947 j.s = s;1948 r = decode_jpeg_header(&j, SCAN_type);1949 stbi__rewind(s);1950 return r;1951}19521953static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)1954{1955 if (!decode_jpeg_header(j, SCAN_header)) {1956 stbi__rewind( j->s );1957 return 0;1958 }1959 if (x) *x = j->s->img_x;1960 if (y) *y = j->s->img_y;1961 if (comp) *comp = j->s->img_n;1962 return 1;1963}19641965static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)1966{1967 stbi__jpeg j;1968 j.s = s;1969 return stbi__jpeg_info_raw(&j, x, y, comp);1970}19711972// public domain zlib stbi__jpeg_huff_decode v0.2 Sean Barrett 2006-11-181973// simple implementation1974// - all input must be provided in an upfront buffer1975// - all output is written to a single output buffer (can malloc/realloc)1976// performance1977// - fast huffman19781979// fast-way is faster to check than jpeg huffman, but slow way is slower1980#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables1981#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)19821983// zlib-style huffman encoding1984// (jpegs packs from left, zlib from right, so can't share code)1985typedef struct1986{1987 stbi__uint16 fast[1 << STBI__ZFAST_BITS];1988 stbi__uint16 firstcode[16];1989 int maxcode[17];1990 stbi__uint16 firstsymbol[16];1991 stbi_uc size[288];1992 stbi__uint16 value[288]; 1993} stbi__zhuffman;19941995stbi_inline static int stbi__bitreverse16(int n)1996{1997 n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);1998 n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);1999 n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);2000 n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);2001 return n;2002}20032004stbi_inline static int stbi__bit_reverse(int v, int bits)2005{2006 assert(bits <= 16);2007 // to bit reverse n bits, reverse 16 and shift2008 // stbi__err.g. 11 bits, bit reverse and shift away 52009 return stbi__bitreverse16(v) >> (16-bits);2010}20112012static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num)2013{2014 int i,k=0;2015 int code, next_code[16], sizes[17];20162017 // DEFLATE spec for generating codes2018 memset(sizes, 0, sizeof(sizes));2019 memset(z->fast, 255, sizeof(z->fast));2020 for (i=0; i < num; ++i) 2021 ++sizes[sizelist[i]];2022 sizes[0] = 0;2023 for (i=1; i < 16; ++i)2024 assert(sizes[i] <= (1 << i));2025 code = 0;2026 for (i=1; i < 16; ++i) {2027 next_code[i] = code;2028 z->firstcode[i] = (stbi__uint16) code;2029 z->firstsymbol[i] = (stbi__uint16) k;2030 code = (code + sizes[i]);2031 if (sizes[i])2032 if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt JPEG");2033 z->maxcode[i] = code << (16-i); // preshift for inner loop2034 code <<= 1;2035 k += sizes[i];2036 }2037 z->maxcode[16] = 0x10000; // sentinel2038 for (i=0; i < num; ++i) {2039 int s = sizelist[i];2040 if (s) {2041 int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];2042 z->size[c] = (stbi_uc)s;2043 z->value[c] = (stbi__uint16)i;2044 if (s <= STBI__ZFAST_BITS) {2045 int k = stbi__bit_reverse(next_code[s],s);2046 while (k < (1 << STBI__ZFAST_BITS)) {2047 z->fast[k] = (stbi__uint16) c;2048 k += (1 << s);2049 }2050 }2051 ++next_code[s];2052 }2053 }2054 return 1;2055}20562057// zlib-from-memory implementation for PNG reading2058// because PNG allows splitting the zlib stream arbitrarily,2059// and it's annoying structurally to have PNG call ZLIB call PNG,2060// we require PNG read all the IDATs and combine them into a single2061// memory buffer20622063typedef struct2064{2065 stbi_uc *zbuffer, *zbuffer_end;2066 int num_bits;2067 stbi__uint32 code_buffer;20682069 char *zout;2070 char *zout_start;2071 char *zout_end;2072 int z_expandable;20732074 stbi__zhuffman z_length, z_distance;2075} stbi__zbuf;20762077stbi_inline static int stbi__zget8(stbi__zbuf *z)2078{2079 if (z->zbuffer >= z->zbuffer_end) return 0;2080 return *z->zbuffer++;2081}20822083static void stbi__fill_bits(stbi__zbuf *z)2084{2085 do {2086 assert(z->code_buffer < (1U << z->num_bits));2087 z->code_buffer |= stbi__zget8(z) << z->num_bits;2088 z->num_bits += 8;2089 } while (z->num_bits <= 24);2090}20912092stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)2093{2094 unsigned int k;2095 if (z->num_bits < n) stbi__fill_bits(z);2096 k = z->code_buffer & ((1 << n) - 1);2097 z->code_buffer >>= n;2098 z->num_bits -= n;2099 return k; 2100}21012102stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)2103{2104 int b,s,k;2105 if (a->num_bits < 16) stbi__fill_bits(a);2106 b = z->fast[a->code_buffer & STBI__ZFAST_MASK];2107 if (b < 0xffff) {2108 s = z->size[b];2109 a->code_buffer >>= s;2110 a->num_bits -= s;2111 return z->value[b];2112 }21132114 // not resolved by fast table, so compute it the slow way2115 // use jpeg approach, which requires MSbits at top2116 k = stbi__bit_reverse(a->code_buffer, 16);2117 for (s=STBI__ZFAST_BITS+1; ; ++s)2118 if (k < z->maxcode[s])2119 break;2120 if (s == 16) return -1; // invalid code!2121 // code size is s, so:2122 b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];2123 assert(z->size[b] == s);2124 a->code_buffer >>= s;2125 a->num_bits -= s;2126 return z->value[b];2127}21282129static int stbi__zexpand(stbi__zbuf *z, int n) // need to make room for n bytes2130{2131 char *q;2132 int cur, limit;2133 if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");2134 cur = (int) (z->zout - z->zout_start);2135 limit = (int) (z->zout_end - z->zout_start);2136 while (cur + n > limit)2137 limit *= 2;2138 q = (char *) realloc(z->zout_start, limit);2139 if (q == NULL) return stbi__err("outofmem", "Out of memory");2140 z->zout_start = q;2141 z->zout = q + cur;2142 z->zout_end = q + limit;2143 return 1;2144}21452146static int stbi__zlength_base[31] = {2147 3,4,5,6,7,8,9,10,11,13,2148 15,17,19,23,27,31,35,43,51,59,2149 67,83,99,115,131,163,195,227,258,0,0 };21502151static int stbi__zlength_extra[31]= 2152{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };21532154static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,2155257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};21562157static int stbi__zdist_extra[32] =2158{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};21592160static int stbi__parse_huffman_block(stbi__zbuf *a)2161{2162 for(;;) {2163 int z = stbi__zhuffman_decode(a, &a->z_length);2164 if (z < 256) {2165 if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes2166 if (a->zout >= a->zout_end) if (!stbi__zexpand(a, 1)) return 0;2167 *a->zout++ = (char) z;2168 } else {2169 stbi_uc *p;2170 int len,dist;2171 if (z == 256) return 1;2172 z -= 257;2173 len = stbi__zlength_base[z];2174 if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);2175 z = stbi__zhuffman_decode(a, &a->z_distance);2176 if (z < 0) return stbi__err("bad huffman code","Corrupt PNG");2177 dist = stbi__zdist_base[z];2178 if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);2179 if (a->zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");2180 if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, len)) return 0;2181 p = (stbi_uc *) (a->zout - dist);2182 while (len--)2183 *a->zout++ = *p++;2184 }2185 }2186}21872188static int stbi__compute_huffman_codes(stbi__zbuf *a)2189{2190 static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };2191 stbi__zhuffman z_codelength;2192 stbi_uc lencodes[286+32+137];//padding for maximum single op2193 stbi_uc codelength_sizes[19];2194 int i,n;21952196 int hlit = stbi__zreceive(a,5) + 257;2197 int hdist = stbi__zreceive(a,5) + 1;2198 int hclen = stbi__zreceive(a,4) + 4;21992200 memset(codelength_sizes, 0, sizeof(codelength_sizes));2201 for (i=0; i < hclen; ++i) {2202 int s = stbi__zreceive(a,3);2203 codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;2204 }2205 if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;22062207 n = 0;2208 while (n < hlit + hdist) {2209 int c = stbi__zhuffman_decode(a, &z_codelength);2210 assert(c >= 0 && c < 19);2211 if (c < 16)2212 lencodes[n++] = (stbi_uc) c;2213 else if (c == 16) {2214 c = stbi__zreceive(a,2)+3;2215 memset(lencodes+n, lencodes[n-1], c);2216 n += c;2217 } else if (c == 17) {2218 c = stbi__zreceive(a,3)+3;2219 memset(lencodes+n, 0, c);2220 n += c;2221 } else {2222 assert(c == 18);2223 c = stbi__zreceive(a,7)+11;2224 memset(lencodes+n, 0, c);2225 n += c;2226 }2227 }2228 if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG");2229 if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;2230 if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;2231 return 1;2232}22332234static int stbi__parse_uncomperssed_block(stbi__zbuf *a)2235{2236 stbi_uc header[4];2237 int len,nlen,k;2238 if (a->num_bits & 7)2239 stbi__zreceive(a, a->num_bits & 7); // discard2240 // drain the bit-packed data into header2241 k = 0;2242 while (a->num_bits > 0) {2243 header[k++] = (stbi_uc) (a->code_buffer & 255); // wtf this warns?2244 a->code_buffer >>= 8;2245 a->num_bits -= 8;2246 }2247 assert(a->num_bits == 0);2248 // now fill header the normal way2249 while (k < 4)2250 header[k++] = (stbi_uc) stbi__zget8(a);2251 len = header[1] * 256 + header[0];2252 nlen = header[3] * 256 + header[2];2253 if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");2254 if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");2255 if (a->zout + len > a->zout_end)2256 if (!stbi__zexpand(a, len)) return 0;2257 memcpy(a->zout, a->zbuffer, len);2258 a->zbuffer += len;2259 a->zout += len;2260 return 1;2261}22622263static int stbi__parse_zlib_header(stbi__zbuf *a)2264{2265 int cmf = stbi__zget8(a);2266 int cm = cmf & 15;2267 /* int cinfo = cmf >> 4; */2268 int flg = stbi__zget8(a);2269 if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec2270 if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png2271 if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png2272 // window = 1 << (8 + cinfo)... but who cares, we fully buffer output2273 return 1;2274}22752276// @TODO: should statically initialize these for optimal thread safety2277static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32];2278static void stbi__init_zdefaults(void)2279{2280 int i; // use <= to match clearly with spec2281 for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;2282 for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;2283 for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;2284 for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;22852286 for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;2287}22882289static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)2290{2291 int final, type;2292 if (parse_header)2293 if (!stbi__parse_zlib_header(a)) return 0;2294 a->num_bits = 0;2295 a->code_buffer = 0;2296 do {2297 final = stbi__zreceive(a,1);2298 type = stbi__zreceive(a,2);2299 if (type == 0) {2300 if (!stbi__parse_uncomperssed_block(a)) return 0;2301 } else if (type == 3) {2302 return 0;2303 } else {2304 if (type == 1) {2305 // use fixed code lengths2306 if (!stbi__zdefault_distance[31]) stbi__init_zdefaults();2307 if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0;2308 if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;2309 } else {2310 if (!stbi__compute_huffman_codes(a)) return 0;2311 }2312 if (!stbi__parse_huffman_block(a)) return 0;2313 }2314 } while (!final);2315 return 1;2316}23172318static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)2319{2320 a->zout_start = obuf;2321 a->zout = obuf;2322 a->zout_end = obuf + olen;2323 a->z_expandable = exp;23242325 return stbi__parse_zlib(a, parse_header);2326}23272328STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)2329{2330 stbi__zbuf a;2331 char *p = (char *) malloc(initial_size);2332 if (p == NULL) return NULL;2333 a.zbuffer = (stbi_uc *) buffer;2334 a.zbuffer_end = (stbi_uc *) buffer + len;2335 if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {2336 if (outlen) *outlen = (int) (a.zout - a.zout_start);2337 return a.zout_start;2338 } else {2339 free(a.zout_start);2340 return NULL;2341 }2342}23432344STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)2345{2346 return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);2347}23482349STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)2350{2351 stbi__zbuf a;2352 char *p = (char *) malloc(initial_size);2353 if (p == NULL) return NULL;2354 a.zbuffer = (stbi_uc *) buffer;2355 a.zbuffer_end = (stbi_uc *) buffer + len;2356 if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {2357 if (outlen) *outlen = (int) (a.zout - a.zout_start);2358 return a.zout_start;2359 } else {2360 free(a.zout_start);2361 return NULL;2362 }2363}23642365STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)2366{2367 stbi__zbuf a;2368 a.zbuffer = (stbi_uc *) ibuffer;2369 a.zbuffer_end = (stbi_uc *) ibuffer + ilen;2370 if (stbi__do_zlib(&a, obuffer, olen, 0, 1))2371 return (int) (a.zout - a.zout_start);2372 else2373 return -1;2374}23752376STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)2377{2378 stbi__zbuf a;2379 char *p = (char *) malloc(16384);2380 if (p == NULL) return NULL;2381 a.zbuffer = (stbi_uc *) buffer;2382 a.zbuffer_end = (stbi_uc *) buffer+len;2383 if (stbi__do_zlib(&a, p, 16384, 1, 0)) {2384 if (outlen) *outlen = (int) (a.zout - a.zout_start);2385 return a.zout_start;2386 } else {2387 free(a.zout_start);2388 return NULL;2389 }2390}23912392STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)2393{2394 stbi__zbuf a;2395 a.zbuffer = (stbi_uc *) ibuffer;2396 a.zbuffer_end = (stbi_uc *) ibuffer + ilen;2397 if (stbi__do_zlib(&a, obuffer, olen, 0, 0))2398 return (int) (a.zout - a.zout_start);2399 else2400 return -1;2401}24022403// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-182404// simple implementation2405// - only 8-bit samples2406// - no CRC checking2407// - allocates lots of intermediate memory2408// - avoids problem of streaming data between subsystems2409// - avoids explicit window management2410// performance2411// - uses stb_zlib, a PD zlib implementation with fast huffman decoding241224132414typedef struct2415{2416 stbi__uint32 length;2417 stbi__uint32 type;2418} stbi__pngchunk;24192420#define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))24212422static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)2423{2424 stbi__pngchunk c;2425 c.length = stbi__get32be(s);2426 c.type = stbi__get32be(s);2427 return c;2428}24292430static int stbi__check_png_header(stbi__context *s)2431{2432 static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };2433 int i;2434 for (i=0; i < 8; ++i)2435 if (stbi__get8u(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");2436 return 1;2437}24382439typedef struct2440{2441 stbi__context *s;2442 stbi_uc *idata, *expanded, *out;2443} stbi__png;244424452446enum {2447 STBI__F_none=0, STBI__F_sub=1, STBI__F_up=2, STBI__F_avg=3, STBI__F_paeth=4,2448 STBI__F_avg_first, STBI__F_paeth_first2449};24502451static stbi_uc first_row_filter[5] =2452{2453 STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first2454};24552456static int stbi__paeth(int a, int b, int c)2457{2458 int p = a + b - c;2459 int pa = abs(p-a);2460 int pb = abs(p-b);2461 int pc = abs(p-c);2462 if (pa <= pb && pa <= pc) return a;2463 if (pb <= pc) return b;2464 return c;2465}24662467// create the png data from post-deflated data2468static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y)2469{2470 stbi__context *s = a->s;2471 stbi__uint32 i,j,stride = x*out_n;2472 int k;2473 int img_n = s->img_n; // copy it into a local for later2474 assert(out_n == s->img_n || out_n == s->img_n+1);2475 a->out = (stbi_uc *) malloc(x * y * out_n);2476 if (!a->out) return stbi__err("outofmem", "Out of memory");2477 if (s->img_x == x && s->img_y == y) {2478 if (raw_len != (img_n * x + 1) * y) return stbi__err("not enough pixels","Corrupt PNG");2479 } else { // interlaced:2480 if (raw_len < (img_n * x + 1) * y) return stbi__err("not enough pixels","Corrupt PNG");2481 }2482 for (j=0; j < y; ++j) {2483 stbi_uc *cur = a->out + stride*j;2484 stbi_uc *prior = cur - stride;2485 int filter = *raw++;2486 if (filter > 4) return stbi__err("invalid filter","Corrupt PNG");2487 // if first row, use special filter that doesn't sample previous row2488 if (j == 0) filter = first_row_filter[filter];2489 // handle first pixel explicitly2490 for (k=0; k < img_n; ++k) {2491 switch (filter) {2492 case STBI__F_none : cur[k] = raw[k]; break;2493 case STBI__F_sub : cur[k] = raw[k]; break;2494 case STBI__F_up : cur[k] = raw[k] + prior[k]; break;2495 case STBI__F_avg : cur[k] = raw[k] + (prior[k]>>1); break;2496 case STBI__F_paeth : cur[k] = (stbi_uc) (raw[k] + stbi__paeth(0,prior[k],0)); break;2497 case STBI__F_avg_first : cur[k] = raw[k]; break;2498 case STBI__F_paeth_first: cur[k] = raw[k]; break;2499 }2500 }2501 if (img_n != out_n) cur[img_n] = 255;2502 raw += img_n;2503 cur += out_n;2504 prior += out_n;2505 // this is a little gross, so that we don't switch per-pixel or per-component2506 if (img_n == out_n) {2507 #define CASE(f) \2508 case f: \2509 for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \2510 for (k=0; k < img_n; ++k)2511 switch (filter) {2512 CASE(STBI__F_none) cur[k] = raw[k]; break;2513 CASE(STBI__F_sub) cur[k] = raw[k] + cur[k-img_n]; break;2514 CASE(STBI__F_up) cur[k] = raw[k] + prior[k]; break;2515 CASE(STBI__F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;2516 CASE(STBI__F_paeth) cur[k] = (stbi_uc) (raw[k] + stbi__paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;2517 CASE(STBI__F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;2518 CASE(STBI__F_paeth_first) cur[k] = (stbi_uc) (raw[k] + stbi__paeth(cur[k-img_n],0,0)); break;2519 }2520 #undef CASE2521 } else {2522 assert(img_n+1 == out_n);2523 #define CASE(f) \2524 case f: \2525 for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \2526 for (k=0; k < img_n; ++k)2527 switch (filter) {2528 CASE(STBI__F_none) cur[k] = raw[k]; break;2529 CASE(STBI__F_sub) cur[k] = raw[k] + cur[k-out_n]; break;2530 CASE(STBI__F_up) cur[k] = raw[k] + prior[k]; break;2531 CASE(STBI__F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;2532 CASE(STBI__F_paeth) cur[k] = (stbi_uc) (raw[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;2533 CASE(STBI__F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;2534 CASE(STBI__F_paeth_first) cur[k] = (stbi_uc) (raw[k] + stbi__paeth(cur[k-out_n],0,0)); break;2535 }2536 #undef CASE2537 }2538 }2539 return 1;2540}25412542static int stbi__create_png_image(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, int interlaced)2543{2544 stbi_uc *final;2545 int p;2546 if (!interlaced)2547 return stbi__create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);25482549 // de-interlacing2550 final = (stbi_uc *) malloc(a->s->img_x * a->s->img_y * out_n);2551 for (p=0; p < 7; ++p) {2552 int xorig[] = { 0,4,0,2,0,1,0 };2553 int yorig[] = { 0,0,4,0,2,0,1 };2554 int xspc[] = { 8,8,4,4,2,2,1 };2555 int yspc[] = { 8,8,8,4,4,2,2 };2556 int i,j,x,y;2557 // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 12558 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];2559 y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];2560 if (x && y) {2561 if (!stbi__create_png_image_raw(a, raw, raw_len, out_n, x, y)) {2562 free(final);2563 return 0;2564 }2565 for (j=0; j < y; ++j)2566 for (i=0; i < x; ++i)2567 memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,2568 a->out + (j*x+i)*out_n, out_n);2569 free(a->out);2570 raw += (x*out_n+1)*y;2571 raw_len -= (x*out_n+1)*y;2572 }2573 }2574 a->out = final;25752576 return 1;2577}25782579static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)2580{2581 stbi__context *s = z->s;2582 stbi__uint32 i, pixel_count = s->img_x * s->img_y;2583 stbi_uc *p = z->out;25842585 // compute color-based transparency, assuming we've2586 // already got 255 as the alpha value in the output2587 assert(out_n == 2 || out_n == 4);25882589 if (out_n == 2) {2590 for (i=0; i < pixel_count; ++i) {2591 p[1] = (p[0] == tc[0] ? 0 : 255);2592 p += 2;2593 }2594 } else {2595 for (i=0; i < pixel_count; ++i) {2596 if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])2597 p[3] = 0;2598 p += 4;2599 }2600 }2601 return 1;2602}26032604static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)2605{2606 stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;2607 stbi_uc *p, *temp_out, *orig = a->out;26082609 p = (stbi_uc *) malloc(pixel_count * pal_img_n);2610 if (p == NULL) return stbi__err("outofmem", "Out of memory");26112612 // between here and free(out) below, exitting would leak2613 temp_out = p;26142615 if (pal_img_n == 3) {2616 for (i=0; i < pixel_count; ++i) {2617 int n = orig[i]*4;2618 p[0] = palette[n ];2619 p[1] = palette[n+1];2620 p[2] = palette[n+2];2621 p += 3;2622 }2623 } else {2624 for (i=0; i < pixel_count; ++i) {2625 int n = orig[i]*4;2626 p[0] = palette[n ];2627 p[1] = palette[n+1];2628 p[2] = palette[n+2];2629 p[3] = palette[n+3];2630 p += 4;2631 }2632 }2633 free(a->out);2634 a->out = temp_out;26352636 STBI_NOTUSED(len);26372638 return 1;2639}26402641static int stbi__unpremultiply_on_load = 0;2642static int stbi__de_iphone_flag = 0;26432644STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)2645{2646 stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply;2647}26482649STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)2650{2651 stbi__de_iphone_flag = flag_true_if_should_convert;2652}26532654static void stbi__de_iphone(stbi__png *z)2655{2656 stbi__context *s = z->s;2657 stbi__uint32 i, pixel_count = s->img_x * s->img_y;2658 stbi_uc *p = z->out;26592660 if (s->img_out_n == 3) { // convert bgr to rgb2661 for (i=0; i < pixel_count; ++i) {2662 stbi_uc t = p[0];2663 p[0] = p[2];2664 p[2] = t;2665 p += 3;2666 }2667 } else {2668 assert(s->img_out_n == 4);2669 if (stbi__unpremultiply_on_load) {2670 // convert bgr to rgb and unpremultiply2671 for (i=0; i < pixel_count; ++i) {2672 stbi_uc a = p[3];2673 stbi_uc t = p[0];2674 if (a) {2675 p[0] = p[2] * 255 / a;2676 p[1] = p[1] * 255 / a;2677 p[2] = t * 255 / a;2678 } else {2679 p[0] = p[2];2680 p[2] = t;2681 } 2682 p += 4;2683 }2684 } else {2685 // convert bgr to rgb2686 for (i=0; i < pixel_count; ++i) {2687 stbi_uc t = p[0];2688 p[0] = p[2];2689 p[2] = t;2690 p += 4;2691 }2692 }2693 }2694}26952696static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)2697{2698 stbi_uc palette[1024], pal_img_n=0;2699 stbi_uc has_trans=0, tc[3];2700 stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;2701 int first=1,k,interlace=0, is_iphone=0;2702 stbi__context *s = z->s;27032704 z->expanded = NULL;2705 z->idata = NULL;2706 z->out = NULL;27072708 if (!stbi__check_png_header(s)) return 0;27092710 if (scan == SCAN_type) return 1;27112712 for (;;) {2713 stbi__pngchunk c = stbi__get_chunk_header(s);2714 switch (c.type) {2715 case PNG_TYPE('C','g','B','I'):2716 is_iphone = 1;2717 stbi__skip(s, c.length);2718 break;2719 case PNG_TYPE('I','H','D','R'): {2720 int depth,color,comp,filter;2721 if (!first) return stbi__err("multiple IHDR","Corrupt PNG");2722 first = 0;2723 if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");2724 s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");2725 s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");2726 depth = stbi__get8(s); if (depth != 8) return stbi__err("8bit only","PNG not supported: 8-bit only");2727 color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");2728 if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");2729 comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");2730 filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");2731 interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");2732 if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");2733 if (!pal_img_n) {2734 s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);2735 if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to stbi__jpeg_huff_decode");2736 if (scan == SCAN_header) return 1;2737 } else {2738 // if paletted, then pal_n is our final components, and2739 // img_n is # components to decompress/filter.2740 s->img_n = 1;2741 if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");2742 // if SCAN_header, have to scan to see if we have a tRNS2743 }2744 break;2745 }27462747 case PNG_TYPE('P','L','T','E'): {2748 if (first) return stbi__err("first not IHDR", "Corrupt PNG");2749 if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");2750 pal_len = c.length / 3;2751 if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");2752 for (i=0; i < pal_len; ++i) {2753 palette[i*4+0] = stbi__get8u(s);2754 palette[i*4+1] = stbi__get8u(s);2755 palette[i*4+2] = stbi__get8u(s);2756 palette[i*4+3] = 255;2757 }2758 break;2759 }27602761 case PNG_TYPE('t','R','N','S'): {2762 if (first) return stbi__err("first not IHDR", "Corrupt PNG");2763 if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");2764 if (pal_img_n) {2765 if (scan == SCAN_header) { s->img_n = 4; return 1; }2766 if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");2767 if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");2768 pal_img_n = 4;2769 for (i=0; i < c.length; ++i)2770 palette[i*4+3] = stbi__get8u(s);2771 } else {2772 if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");2773 if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");2774 has_trans = 1;2775 for (k=0; k < s->img_n; ++k)2776 tc[k] = (stbi_uc) stbi__get16be(s); // non 8-bit images will be larger2777 }2778 break;2779 }27802781 case PNG_TYPE('I','D','A','T'): {2782 if (first) return stbi__err("first not IHDR", "Corrupt PNG");2783 if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");2784 if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }2785 if (ioff + c.length > idata_limit) {2786 stbi_uc *p;2787 if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;2788 while (ioff + c.length > idata_limit)2789 idata_limit *= 2;2790 p = (stbi_uc *) realloc(z->idata, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");2791 z->idata = p;2792 }2793 if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");2794 ioff += c.length;2795 break;2796 }27972798 case PNG_TYPE('I','E','N','D'): {2799 stbi__uint32 raw_len;2800 if (first) return stbi__err("first not IHDR", "Corrupt PNG");2801 if (scan != SCAN_load) return 1;2802 if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");2803 z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !is_iphone);2804 if (z->expanded == NULL) return 0; // zlib should set error2805 free(z->idata); z->idata = NULL;2806 if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)2807 s->img_out_n = s->img_n+1;2808 else2809 s->img_out_n = s->img_n;2810 if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;2811 if (has_trans)2812 if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;2813 if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)2814 stbi__de_iphone(z);2815 if (pal_img_n) {2816 // pal_img_n == 3 or 42817 s->img_n = pal_img_n; // record the actual colors we had2818 s->img_out_n = pal_img_n;2819 if (req_comp >= 3) s->img_out_n = req_comp;2820 if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))2821 return 0;2822 }2823 free(z->expanded); z->expanded = NULL;2824 return 1;2825 }28262827 default:2828 // if critical, fail2829 if (first) return stbi__err("first not IHDR", "Corrupt PNG");2830 if ((c.type & (1 << 29)) == 0) {2831 #ifndef STBI_NO_FAILURE_STRINGS2832 // not threadsafe2833 static char invalid_chunk[] = "XXXX stbi__pngchunk not known";2834 invalid_chunk[0] = (stbi_uc) (c.type >> 24);2835 invalid_chunk[1] = (stbi_uc) (c.type >> 16);2836 invalid_chunk[2] = (stbi_uc) (c.type >> 8);2837 invalid_chunk[3] = (stbi_uc) (c.type >> 0);2838 #endif2839 return stbi__err(invalid_chunk, "PNG not supported: unknown stbi__pngchunk type");2840 }2841 stbi__skip(s, c.length);2842 break;2843 }2844 // end of stbi__pngchunk, read and stbi__skip CRC2845 stbi__get32be(s);2846 }2847}28482849static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp)2850{2851 unsigned char *result=NULL;2852 if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");2853 if (stbi__parse_png_file(p, SCAN_load, req_comp)) {2854 result = p->out;2855 p->out = NULL;2856 if (req_comp && req_comp != p->s->img_out_n) {2857 result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);2858 p->s->img_out_n = req_comp;2859 if (result == NULL) return result;2860 }2861 *x = p->s->img_x;2862 *y = p->s->img_y;2863 if (n) *n = p->s->img_n;2864 }2865 free(p->out); p->out = NULL;2866 free(p->expanded); p->expanded = NULL;2867 free(p->idata); p->idata = NULL;28682869 return result;2870}28712872static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)2873{2874 stbi__png p;2875 p.s = s;2876 return stbi__do_png(&p, x,y,comp,req_comp);2877}28782879static int stbi__png_test(stbi__context *s)2880{2881 int r;2882 r = stbi__check_png_header(s);2883 stbi__rewind(s);2884 return r;2885}28862887static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)2888{2889 if (!stbi__parse_png_file(p, SCAN_header, 0)) {2890 stbi__rewind( p->s );2891 return 0;2892 }2893 if (x) *x = p->s->img_x;2894 if (y) *y = p->s->img_y;2895 if (comp) *comp = p->s->img_n;2896 return 1;2897}28982899static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)2900{2901 stbi__png p;2902 p.s = s;2903 return stbi__png_info_raw(&p, x, y, comp);2904}29052906// Microsoft/Windows BMP image2907static int stbi__bmp_test(stbi__context *s)2908{2909 int r;2910 int sz;2911 if (stbi__get8(s) != 'B') return 0;2912 if (stbi__get8(s) != 'M') return 0;2913 stbi__get32le(s); // discard filesize2914 stbi__get16le(s); // discard reserved2915 stbi__get16le(s); // discard reserved2916 stbi__get32le(s); // discard data offset2917 sz = stbi__get32le(s);2918 r = (sz == 12 || sz == 40 || sz == 56 || sz == 108);2919 stbi__rewind(s);2920 return r;2921}292229232924// returns 0..31 for the highest set bit2925static int stbi__high_bit(unsigned int z)2926{2927 int n=0;2928 if (z == 0) return -1;2929 if (z >= 0x10000) n += 16, z >>= 16;2930 if (z >= 0x00100) n += 8, z >>= 8;2931 if (z >= 0x00010) n += 4, z >>= 4;2932 if (z >= 0x00004) n += 2, z >>= 2;2933 if (z >= 0x00002) n += 1, z >>= 1;2934 return n;2935}29362937static int stbi__bitcount(unsigned int a)2938{2939 a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 22940 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 42941 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits2942 a = (a + (a >> 8)); // max 16 per 8 bits2943 a = (a + (a >> 16)); // max 32 per 8 bits2944 return a & 0xff;2945}29462947static int stbi__shiftsigned(int v, int shift, int bits)2948{2949 int result;2950 int z=0;29512952 if (shift < 0) v <<= -shift;2953 else v >>= shift;2954 result = v;29552956 z = bits;2957 while (z < 8) {2958 result += v >> z;2959 z += bits;2960 }2961 return result;2962}29632964static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)2965{2966 stbi_uc *out;2967 unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;2968 stbi_uc pal[256][4];2969 int psize=0,i,j,compress=0,width;2970 int bpp, flip_vertically, pad, target, offset, hsz;2971 if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");2972 stbi__get32le(s); // discard filesize2973 stbi__get16le(s); // discard reserved2974 stbi__get16le(s); // discard reserved2975 offset = stbi__get32le(s);2976 hsz = stbi__get32le(s);2977 if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");2978 if (hsz == 12) {2979 s->img_x = stbi__get16le(s);2980 s->img_y = stbi__get16le(s);2981 } else {2982 s->img_x = stbi__get32le(s);2983 s->img_y = stbi__get32le(s);2984 }2985 if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP");2986 bpp = stbi__get16le(s);2987 if (bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit");2988 flip_vertically = ((int) s->img_y) > 0;2989 s->img_y = abs((int) s->img_y);2990 if (hsz == 12) {2991 if (bpp < 24)2992 psize = (offset - 14 - 24) / 3;2993 } else {2994 compress = stbi__get32le(s);2995 if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");2996 stbi__get32le(s); // discard sizeof2997 stbi__get32le(s); // discard hres2998 stbi__get32le(s); // discard vres2999 stbi__get32le(s); // discard colorsused3000 stbi__get32le(s); // discard max important3001 if (hsz == 40 || hsz == 56) {3002 if (hsz == 56) {3003 stbi__get32le(s);3004 stbi__get32le(s);3005 stbi__get32le(s);3006 stbi__get32le(s);3007 }3008 if (bpp == 16 || bpp == 32) {3009 mr = mg = mb = 0;3010 if (compress == 0) {3011 if (bpp == 32) {3012 mr = 0xffu << 16;3013 mg = 0xffu << 8;3014 mb = 0xffu << 0;3015 ma = 0xffu << 24;3016 fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 2553017 STBI_NOTUSED(fake_a);3018 } else {3019 mr = 31u << 10;3020 mg = 31u << 5;3021 mb = 31u << 0;3022 }3023 } else if (compress == 3) {3024 mr = stbi__get32le(s);3025 mg = stbi__get32le(s);3026 mb = stbi__get32le(s);3027 // not documented, but generated by photoshop and handled by mspaint3028 if (mr == mg && mg == mb) {3029 // ?!?!?3030 return stbi__errpuc("bad BMP", "bad BMP");3031 }3032 } else3033 return stbi__errpuc("bad BMP", "bad BMP");3034 }3035 } else {3036 assert(hsz == 108);3037 mr = stbi__get32le(s);3038 mg = stbi__get32le(s);3039 mb = stbi__get32le(s);3040 ma = stbi__get32le(s);3041 stbi__get32le(s); // discard color space3042 for (i=0; i < 12; ++i)3043 stbi__get32le(s); // discard color space parameters3044 }3045 if (bpp < 16)3046 psize = (offset - 14 - hsz) >> 2;3047 }3048 s->img_n = ma ? 4 : 3;3049 if (req_comp && req_comp >= 3) // we can directly stbi__jpeg_huff_decode 3 or 43050 target = req_comp;3051 else3052 target = s->img_n; // if they want monochrome, we'll post-convert3053 out = (stbi_uc *) malloc(target * s->img_x * s->img_y);3054 if (!out) return stbi__errpuc("outofmem", "Out of memory");3055 if (bpp < 16) {3056 int z=0;3057 if (psize == 0 || psize > 256) { free(out); return stbi__errpuc("invalid", "Corrupt BMP"); }3058 for (i=0; i < psize; ++i) {3059 pal[i][2] = stbi__get8u(s);3060 pal[i][1] = stbi__get8u(s);3061 pal[i][0] = stbi__get8u(s);3062 if (hsz != 12) stbi__get8(s);3063 pal[i][3] = 255;3064 }3065 stbi__skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));3066 if (bpp == 4) width = (s->img_x + 1) >> 1;3067 else if (bpp == 8) width = s->img_x;3068 else { free(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); }3069 pad = (-width)&3;3070 for (j=0; j < (int) s->img_y; ++j) {3071 for (i=0; i < (int) s->img_x; i += 2) {3072 int v=stbi__get8(s),v2=0;3073 if (bpp == 4) {3074 v2 = v & 15;3075 v >>= 4;3076 }3077 out[z++] = pal[v][0];3078 out[z++] = pal[v][1];3079 out[z++] = pal[v][2];3080 if (target == 4) out[z++] = 255;3081 if (i+1 == (int) s->img_x) break;3082 v = (bpp == 8) ? stbi__get8(s) : v2;3083 out[z++] = pal[v][0];3084 out[z++] = pal[v][1];3085 out[z++] = pal[v][2];3086 if (target == 4) out[z++] = 255;3087 }3088 stbi__skip(s, pad);3089 }3090 } else {3091 int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;3092 int z = 0;3093 int easy=0;3094 stbi__skip(s, offset - 14 - hsz);3095 if (bpp == 24) width = 3 * s->img_x;3096 else if (bpp == 16) width = 2*s->img_x;3097 else /* bpp = 32 and pad = 0 */ width=0;3098 pad = (-width) & 3;3099 if (bpp == 24) {3100 easy = 1;3101 } else if (bpp == 32) {3102 if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)3103 easy = 2;3104 }3105 if (!easy) {3106 if (!mr || !mg || !mb) { free(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }3107 // right shift amt to put high bit in position #73108 rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);3109 gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);3110 bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);3111 ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);3112 }3113 for (j=0; j < (int) s->img_y; ++j) {3114 if (easy) {3115 for (i=0; i < (int) s->img_x; ++i) {3116 int a;3117 out[z+2] = stbi__get8u(s);3118 out[z+1] = stbi__get8u(s);3119 out[z+0] = stbi__get8u(s);3120 z += 3;3121 a = (easy == 2 ? stbi__get8(s) : 255);3122 if (target == 4) out[z++] = (stbi_uc) a;3123 }3124 } else {3125 for (i=0; i < (int) s->img_x; ++i) {3126 stbi__uint32 v = (stbi__uint32) (bpp == 16 ? stbi__get16le(s) : stbi__get32le(s));3127 int a;3128 out[z++] = (stbi_uc) stbi__shiftsigned(v & mr, rshift, rcount);3129 out[z++] = (stbi_uc) stbi__shiftsigned(v & mg, gshift, gcount);3130 out[z++] = (stbi_uc) stbi__shiftsigned(v & mb, bshift, bcount);3131 a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);3132 if (target == 4) out[z++] = (stbi_uc) a; 3133 }3134 }3135 stbi__skip(s, pad);3136 }3137 }3138 if (flip_vertically) {3139 stbi_uc t;3140 for (j=0; j < (int) s->img_y>>1; ++j) {3141 stbi_uc *p1 = out + j *s->img_x*target;3142 stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;3143 for (i=0; i < (int) s->img_x*target; ++i) {3144 t = p1[i], p1[i] = p2[i], p2[i] = t;3145 }3146 }3147 }31483149 if (req_comp && req_comp != target) {3150 out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);3151 if (out == NULL) return out; // stbi__convert_format frees input on failure3152 }31533154 *x = s->img_x;3155 *y = s->img_y;3156 if (comp) *comp = s->img_n;3157 return out;3158}31593160// Targa Truevision - TGA3161// by Jonathan Dummer31623163static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)3164{3165 int tga_w, tga_h, tga_comp;3166 int sz;3167 stbi__get8u(s); // discard Offset3168 sz = stbi__get8u(s); // color type3169 if( sz > 1 ) {3170 stbi__rewind(s);3171 return 0; // only RGB or indexed allowed3172 }3173 sz = stbi__get8u(s); // image type3174 // only RGB or grey allowed, +/- RLE3175 if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;3176 stbi__skip(s,9);3177 tga_w = stbi__get16le(s);3178 if( tga_w < 1 ) {3179 stbi__rewind(s);3180 return 0; // test width3181 }3182 tga_h = stbi__get16le(s);3183 if( tga_h < 1 ) {3184 stbi__rewind(s);3185 return 0; // test height3186 }3187 sz = stbi__get8(s); // bits per pixel3188 // only RGB or RGBA or grey allowed3189 if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {3190 stbi__rewind(s);3191 return 0;3192 }3193 tga_comp = sz;3194 if (x) *x = tga_w;3195 if (y) *y = tga_h;3196 if (comp) *comp = tga_comp / 8;3197 return 1; // seems to have passed everything3198}31993200static int stbi__tga_test(stbi__context *s)3201{3202 int res;3203 int sz;3204 stbi__get8u(s); // discard Offset3205 sz = stbi__get8u(s); // color type3206 if ( sz > 1 ) return 0; // only RGB or indexed allowed3207 sz = stbi__get8u(s); // image type3208 if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE3209 stbi__get16be(s); // discard palette start3210 stbi__get16be(s); // discard palette length3211 stbi__get8(s); // discard bits per palette color entry3212 stbi__get16be(s); // discard x origin3213 stbi__get16be(s); // discard y origin3214 if ( stbi__get16be(s) < 1 ) return 0; // test width3215 if ( stbi__get16be(s) < 1 ) return 0; // test height3216 sz = stbi__get8(s); // bits per pixel3217 if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) )3218 res = 0;3219 else3220 res = 1;3221 stbi__rewind(s);3222 return res;3223}32243225static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)3226{3227 // read in the TGA header stuff3228 int tga_offset = stbi__get8u(s);3229 int tga_indexed = stbi__get8u(s);3230 int tga_image_type = stbi__get8u(s);3231 int tga_is_RLE = 0;3232 int tga_palette_start = stbi__get16le(s);3233 int tga_palette_len = stbi__get16le(s);3234 int tga_palette_bits = stbi__get8u(s);3235 int tga_x_origin = stbi__get16le(s);3236 int tga_y_origin = stbi__get16le(s);3237 int tga_width = stbi__get16le(s);3238 int tga_height = stbi__get16le(s);3239 int tga_bits_per_pixel = stbi__get8u(s);3240 int tga_comp = tga_bits_per_pixel / 8;3241 int tga_inverted = stbi__get8u(s);3242 // image data3243 unsigned char *tga_data;3244 unsigned char *tga_palette = NULL;3245 int i, j;3246 unsigned char raw_data[4];3247 int RLE_count = 0;3248 int RLE_repeating = 0;3249 int read_next_pixel = 1;32503251 // do a tiny bit of precessing3252 if ( tga_image_type >= 8 )3253 {3254 tga_image_type -= 8;3255 tga_is_RLE = 1;3256 }3257 /* int tga_alpha_bits = tga_inverted & 15; */3258 tga_inverted = 1 - ((tga_inverted >> 5) & 1);32593260 // error check3261 if ( //(tga_indexed) ||3262 (tga_width < 1) || (tga_height < 1) ||3263 (tga_image_type < 1) || (tga_image_type > 3) ||3264 ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&3265 (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))3266 )3267 {3268 return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA3269 }32703271 // If I'm paletted, then I'll use the number of bits from the palette3272 if ( tga_indexed )3273 {3274 tga_comp = tga_palette_bits / 8;3275 }32763277 // tga info3278 *x = tga_width;3279 *y = tga_height;3280 if (comp) *comp = tga_comp;32813282 tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );3283 if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");32843285 // stbi__skip to the data's starting position (offset usually = 0)3286 stbi__skip(s, tga_offset );32873288 if ( !tga_indexed && !tga_is_RLE) {3289 for (i=0; i < tga_height; ++i) {3290 int y = tga_inverted ? tga_height -i - 1 : i;3291 stbi_uc *tga_row = tga_data + y*tga_width*tga_comp;3292 stbi__getn(s, tga_row, tga_width * tga_comp);3293 }3294 } else {3295 // do I need to load a palette?3296 if ( tga_indexed)3297 {3298 // any data to stbi__skip? (offset usually = 0)3299 stbi__skip(s, tga_palette_start );3300 // load the palette3301 tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );3302 if (!tga_palette) {3303 free(tga_data);3304 return stbi__errpuc("outofmem", "Out of memory");3305 }3306 if (!stbi__getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {3307 free(tga_data);3308 free(tga_palette);3309 return stbi__errpuc("bad palette", "Corrupt TGA");3310 }3311 }3312 // load the data3313 for (i=0; i < tga_width * tga_height; ++i)3314 {3315 // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?3316 if ( tga_is_RLE )3317 {3318 if ( RLE_count == 0 )3319 {3320 // yep, get the next byte as a RLE command3321 int RLE_cmd = stbi__get8u(s);3322 RLE_count = 1 + (RLE_cmd & 127);3323 RLE_repeating = RLE_cmd >> 7;3324 read_next_pixel = 1;3325 } else if ( !RLE_repeating )3326 {3327 read_next_pixel = 1;3328 }3329 } else3330 {3331 read_next_pixel = 1;3332 }3333 // OK, if I need to read a pixel, do it now3334 if ( read_next_pixel )3335 {3336 // load however much data we did have3337 if ( tga_indexed )3338 {3339 // read in 1 byte, then perform the lookup3340 int pal_idx = stbi__get8u(s);3341 if ( pal_idx >= tga_palette_len )3342 {3343 // invalid index3344 pal_idx = 0;3345 }3346 pal_idx *= tga_bits_per_pixel / 8;3347 for (j = 0; j*8 < tga_bits_per_pixel; ++j)3348 {3349 raw_data[j] = tga_palette[pal_idx+j];3350 }3351 } else3352 {3353 // read in the data raw3354 for (j = 0; j*8 < tga_bits_per_pixel; ++j)3355 {3356 raw_data[j] = stbi__get8u(s);3357 }3358 }3359 // clear the reading flag for the next pixel3360 read_next_pixel = 0;3361 } // end of reading a pixel33623363 // copy data3364 for (j = 0; j < tga_comp; ++j)3365 tga_data[i*tga_comp+j] = raw_data[j];33663367 // in case we're in RLE mode, keep counting down3368 --RLE_count;3369 }3370 // do I need to invert the image?3371 if ( tga_inverted )3372 {3373 for (j = 0; j*2 < tga_height; ++j)3374 {3375 int index1 = j * tga_width * req_comp;3376 int index2 = (tga_height - 1 - j) * tga_width * req_comp;3377 for (i = tga_width * req_comp; i > 0; --i)3378 {3379 unsigned char temp = tga_data[index1];3380 tga_data[index1] = tga_data[index2];3381 tga_data[index2] = temp;3382 ++index1;3383 ++index2;3384 }3385 }3386 }3387 // clear my palette, if I had one3388 if ( tga_palette != NULL )3389 {3390 free( tga_palette );3391 }3392 }33933394 // swap RGB3395 if (tga_comp >= 3)3396 {3397 unsigned char* tga_pixel = tga_data;3398 for (i=0; i < tga_width * tga_height; ++i)3399 {3400 unsigned char temp = tga_pixel[0];3401 tga_pixel[0] = tga_pixel[2];3402 tga_pixel[2] = temp;3403 tga_pixel += tga_comp;3404 }3405 }34063407 // convert to target component count3408 if (req_comp && req_comp != tga_comp)3409 tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);34103411 // the things I do to get rid of an error message, and yet keep3412 // Microsoft's C compilers happy... [8^(3413 tga_palette_start = tga_palette_len = tga_palette_bits =3414 tga_x_origin = tga_y_origin = 0;3415 // OK, done3416 return tga_data;3417}34183419// *************************************************************************************************3420// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB34213422static int stbi__psd_test(stbi__context *s)3423{3424 int r = (stbi__get32be(s) == 0x38425053);3425 stbi__rewind(s);3426 return r;3427}34283429static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)3430{3431 int pixelCount;3432 int channelCount, compression;3433 int channel, i, count, len;3434 int w,h;3435 stbi_uc *out;34363437 // Check identifier3438 if (stbi__get32be(s) != 0x38425053) // "8BPS"3439 return stbi__errpuc("not PSD", "Corrupt PSD image");34403441 // Check file type version.3442 if (stbi__get16be(s) != 1)3443 return stbi__errpuc("wrong version", "Unsupported version of PSD image");34443445 // Skip 6 reserved bytes.3446 stbi__skip(s, 6 );34473448 // Read the number of channels (R, G, B, A, etc).3449 channelCount = stbi__get16be(s);3450 if (channelCount < 0 || channelCount > 16)3451 return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");34523453 // Read the rows and columns of the image.3454 h = stbi__get32be(s);3455 w = stbi__get32be(s);3456 3457 // Make sure the depth is 8 bits.3458 if (stbi__get16be(s) != 8)3459 return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 bit");34603461 // Make sure the color mode is RGB.3462 // Valid options are:3463 // 0: Bitmap3464 // 1: Grayscale3465 // 2: Indexed color3466 // 3: RGB color3467 // 4: CMYK color3468 // 7: Multichannel3469 // 8: Duotone3470 // 9: Lab color3471 if (stbi__get16be(s) != 3)3472 return stbi__errpuc("wrong color format", "PSD is not in RGB color format");34733474 // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)3475 stbi__skip(s,stbi__get32be(s) );34763477 // Skip the image resources. (resolution, pen tool paths, etc)3478 stbi__skip(s, stbi__get32be(s) );34793480 // Skip the reserved data.3481 stbi__skip(s, stbi__get32be(s) );34823483 // Find out if the data is compressed.3484 // Known values:3485 // 0: no compression3486 // 1: RLE compressed3487 compression = stbi__get16be(s);3488 if (compression > 1)3489 return stbi__errpuc("bad compression", "PSD has an unknown compression format");34903491 // Create the destination image.3492 out = (stbi_uc *) malloc(4 * w*h);3493 if (!out) return stbi__errpuc("outofmem", "Out of memory");3494 pixelCount = w*h;34953496 // Initialize the data to zero.3497 //memset( out, 0, pixelCount * 4 );3498 3499 // Finally, the image data.3500 if (compression) {3501 // RLE as used by .PSD and .TIFF3502 // Loop until you get the number of unpacked bytes you are expecting:3503 // Read the next source byte into n.3504 // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.3505 // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.3506 // Else if n is 128, noop.3507 // Endloop35083509 // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,3510 // which we're going to just stbi__skip.3511 stbi__skip(s, h * channelCount * 2 );35123513 // Read the RLE data by channel.3514 for (channel = 0; channel < 4; channel++) {3515 stbi_uc *p;3516 3517 p = out+channel;3518 if (channel >= channelCount) {3519 // Fill this channel with default data.3520 for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;3521 } else {3522 // Read the RLE data.3523 count = 0;3524 while (count < pixelCount) {3525 len = stbi__get8(s);3526 if (len == 128) {3527 // No-op.3528 } else if (len < 128) {3529 // Copy next len+1 bytes literally.3530 len++;3531 count += len;3532 while (len) {3533 *p = stbi__get8u(s);3534 p += 4;3535 len--;3536 }3537 } else if (len > 128) {3538 stbi_uc val;3539 // Next -len+1 bytes in the dest are replicated from next source byte.3540 // (Interpret len as a negative 8-bit int.)3541 len ^= 0x0FF;3542 len += 2;3543 val = stbi__get8u(s);3544 count += len;3545 while (len) {3546 *p = val;3547 p += 4;3548 len--;3549 }3550 }3551 }3552 }3553 }3554 3555 } else {3556 // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)3557 // where each channel consists of an 8-bit value for each pixel in the image.3558 3559 // Read the data by channel.3560 for (channel = 0; channel < 4; channel++) {3561 stbi_uc *p;3562 3563 p = out + channel;3564 if (channel > channelCount) {3565 // Fill this channel with default data.3566 for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;3567 } else {3568 // Read the data.3569 for (i = 0; i < pixelCount; i++)3570 *p = stbi__get8u(s), p += 4;3571 }3572 }3573 }35743575 if (req_comp && req_comp != 4) {3576 out = stbi__convert_format(out, 4, req_comp, w, h);3577 if (out == NULL) return out; // stbi__convert_format frees input on failure3578 }35793580 if (comp) *comp = channelCount;3581 *y = h;3582 *x = w;3583 3584 return out;3585}35863587// *************************************************************************************************3588// Softimage PIC loader3589// by Tom Seddon3590//3591// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format3592// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/35933594static int stbi__pic_is4(stbi__context *s,const char *str)3595{3596 int i;3597 for (i=0; i<4; ++i)3598 if (stbi__get8(s) != (stbi_uc)str[i])3599 return 0;36003601 return 1;3602}36033604static int stbi__pic_test_core(stbi__context *s)3605{3606 int i;36073608 if (!stbi__pic_is4(s,"\x53\x80\xF6\x34"))3609 return 0;36103611 for(i=0;i<84;++i)3612 stbi__get8(s);36133614 if (!stbi__pic_is4(s,"PICT"))3615 return 0;36163617 return 1;3618}36193620typedef struct3621{3622 stbi_uc size,type,channel;3623} stbi__pic_packet;36243625static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)3626{3627 int mask=0x80, i;36283629 for (i=0; i<4; ++i, mask>>=1) {3630 if (channel & mask) {3631 if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short");3632 dest[i]=stbi__get8u(s);3633 }3634 }36353636 return dest;3637}36383639static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)3640{3641 int mask=0x80,i;36423643 for (i=0;i<4; ++i, mask>>=1)3644 if (channel&mask)3645 dest[i]=src[i];3646}36473648static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)3649{3650 int act_comp=0,num_packets=0,y,chained;3651 stbi__pic_packet packets[10];36523653 // this will (should...) cater for even some bizarre stuff like having data3654 // for the same channel in multiple packets.3655 do {3656 stbi__pic_packet *packet;36573658 if (num_packets==sizeof(packets)/sizeof(packets[0]))3659 return stbi__errpuc("bad format","too many packets");36603661 packet = &packets[num_packets++];36623663 chained = stbi__get8(s);3664 packet->size = stbi__get8u(s);3665 packet->type = stbi__get8u(s);3666 packet->channel = stbi__get8u(s);36673668 act_comp |= packet->channel;36693670 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)");3671 if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp");3672 } while (chained);36733674 *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?36753676 for(y=0; y<height; ++y) {3677 int packet_idx;36783679 for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {3680 stbi__pic_packet *packet = &packets[packet_idx];3681 stbi_uc *dest = result+y*width*4;36823683 switch (packet->type) {3684 default:3685 return stbi__errpuc("bad format","packet has bad compression type");36863687 case 0: {//uncompressed3688 int x;36893690 for(x=0;x<width;++x, dest+=4)3691 if (!stbi__readval(s,packet->channel,dest))3692 return 0;3693 break;3694 }36953696 case 1://Pure RLE3697 {3698 int left=width, i;36993700 while (left>0) {3701 stbi_uc count,value[4];37023703 count=stbi__get8u(s);3704 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)");37053706 if (count > left)3707 count = (stbi_uc) left;37083709 if (!stbi__readval(s,packet->channel,value)) return 0;37103711 for(i=0; i<count; ++i,dest+=4)3712 stbi__copyval(packet->channel,dest,value);3713 left -= count;3714 }3715 }3716 break;37173718 case 2: {//Mixed RLE3719 int left=width;3720 while (left>0) {3721 int count = stbi__get8(s), i;3722 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)");37233724 if (count >= 128) { // Repeated3725 stbi_uc value[4];3726 int i;37273728 if (count==128)3729 count = stbi__get16be(s);3730 else3731 count -= 127;3732 if (count > left)3733 return stbi__errpuc("bad file","scanline overrun");37343735 if (!stbi__readval(s,packet->channel,value))3736 return 0;37373738 for(i=0;i<count;++i, dest += 4)3739 stbi__copyval(packet->channel,dest,value);3740 } else { // Raw3741 ++count;3742 if (count>left) return stbi__errpuc("bad file","scanline overrun");37433744 for(i=0;i<count;++i, dest+=4)3745 if (!stbi__readval(s,packet->channel,dest))3746 return 0;3747 }3748 left-=count;3749 }3750 break;3751 }3752 }3753 }3754 }37553756 return result;3757}37583759static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp)3760{3761 stbi_uc *result;3762 int i, x,y;37633764 for (i=0; i<92; ++i)3765 stbi__get8(s);37663767 x = stbi__get16be(s);3768 y = stbi__get16be(s);3769 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");3770 if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to stbi__jpeg_huff_decode");37713772 stbi__get32be(s); //stbi__skip `ratio'3773 stbi__get16be(s); //stbi__skip `fields'3774 stbi__get16be(s); //stbi__skip `pad'37753776 // intermediate buffer is RGBA3777 result = (stbi_uc *) malloc(x*y*4);3778 memset(result, 0xff, x*y*4);37793780 if (!stbi__pic_load_core(s,x,y,comp, result)) {3781 free(result);3782 result=0;3783 }3784 *px = x;3785 *py = y;3786 if (req_comp == 0) req_comp = *comp;3787 result=stbi__convert_format(result,4,req_comp,x,y);37883789 return result;3790}37913792static int stbi__pic_test(stbi__context *s)3793{3794 int r = stbi__pic_test_core(s);3795 stbi__rewind(s);3796 return r;3797}37983799// *************************************************************************************************3800// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb3801typedef struct 3802{3803 stbi__int16 prefix;3804 stbi_uc first;3805 stbi_uc suffix;3806} stbi__gif_lzw;38073808typedef struct3809{3810 int w,h;3811 stbi_uc *out; // output buffer (always 4 components)3812 int flags, bgindex, ratio, transparent, eflags;3813 stbi_uc pal[256][4];3814 stbi_uc lpal[256][4];3815 stbi__gif_lzw codes[4096];3816 stbi_uc *color_table;3817 int parse, step;3818 int lflags;3819 int start_x, start_y;3820 int max_x, max_y;3821 int cur_x, cur_y;3822 int line_size;3823} stbi__gif;38243825static int stbi__gif_test_raw(stbi__context *s)3826{3827 int sz;3828 if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;3829 sz = stbi__get8(s);3830 if (sz != '9' && sz != '7') return 0;3831 if (stbi__get8(s) != 'a') return 0;3832 return 1;3833}38343835static int stbi__gif_test(stbi__context *s)3836{3837 int r = stbi__gif_test_raw(s);3838 stbi__rewind(s);3839 return r;3840}38413842static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)3843{3844 int i;3845 for (i=0; i < num_entries; ++i) {3846 pal[i][2] = stbi__get8u(s);3847 pal[i][1] = stbi__get8u(s);3848 pal[i][0] = stbi__get8u(s);3849 pal[i][3] = transp ? 0 : 255;3850 } 3851}38523853static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)3854{3855 stbi_uc version;3856 if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')3857 return stbi__err("not GIF", "Corrupt GIF");38583859 version = stbi__get8u(s);3860 if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");3861 if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");3862 3863 stbi__g_failure_reason = "";3864 g->w = stbi__get16le(s);3865 g->h = stbi__get16le(s);3866 g->flags = stbi__get8(s);3867 g->bgindex = stbi__get8(s);3868 g->ratio = stbi__get8(s);3869 g->transparent = -1;38703871 if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments38723873 if (is_info) return 1;38743875 if (g->flags & 0x80)3876 stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);38773878 return 1;3879}38803881static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)3882{3883 stbi__gif g; 3884 if (!stbi__gif_header(s, &g, comp, 1)) {3885 stbi__rewind( s );3886 return 0;3887 }3888 if (x) *x = g.w;3889 if (y) *y = g.h;3890 return 1;3891}38923893static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)3894{3895 stbi_uc *p, *c;38963897 // recurse to stbi__jpeg_huff_decode the prefixes, since the linked-list is backwards,3898 // and working backwards through an interleaved image would be nasty3899 if (g->codes[code].prefix >= 0)3900 stbi__out_gif_code(g, g->codes[code].prefix);39013902 if (g->cur_y >= g->max_y) return;3903 3904 p = &g->out[g->cur_x + g->cur_y];3905 c = &g->color_table[g->codes[code].suffix * 4];39063907 if (c[3] >= 128) {3908 p[0] = c[2];3909 p[1] = c[1];3910 p[2] = c[0];3911 p[3] = c[3];3912 }3913 g->cur_x += 4;39143915 if (g->cur_x >= g->max_x) {3916 g->cur_x = g->start_x;3917 g->cur_y += g->step;39183919 while (g->cur_y >= g->max_y && g->parse > 0) {3920 g->step = (1 << g->parse) * g->line_size;3921 g->cur_y = g->start_y + (g->step >> 1);3922 --g->parse;3923 }3924 }3925}39263927static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)3928{3929 stbi_uc lzw_cs;3930 stbi__int32 len, code;3931 stbi__uint32 first;3932 stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;3933 stbi__gif_lzw *p;39343935 lzw_cs = stbi__get8u(s);3936 clear = 1 << lzw_cs;3937 first = 1;3938 codesize = lzw_cs + 1;3939 codemask = (1 << codesize) - 1;3940 bits = 0;3941 valid_bits = 0;3942 for (code = 0; code < clear; code++) {3943 g->codes[code].prefix = -1;3944 g->codes[code].first = (stbi_uc) code;3945 g->codes[code].suffix = (stbi_uc) code;3946 }39473948 // support no starting clear code3949 avail = clear+2;3950 oldcode = -1;39513952 len = 0;3953 for(;;) {3954 if (valid_bits < codesize) {3955 if (len == 0) {3956 len = stbi__get8(s); // start new block3957 if (len == 0) 3958 return g->out;3959 }3960 --len;3961 bits |= (stbi__int32) stbi__get8(s) << valid_bits;3962 valid_bits += 8;3963 } else {3964 stbi__int32 code = bits & codemask;3965 bits >>= codesize;3966 valid_bits -= codesize;3967 // @OPTIMIZE: is there some way we can accelerate the non-clear path?3968 if (code == clear) { // clear code3969 codesize = lzw_cs + 1;3970 codemask = (1 << codesize) - 1;3971 avail = clear + 2;3972 oldcode = -1;3973 first = 0;3974 } else if (code == clear + 1) { // end of stream code3975 stbi__skip(s, len);3976 while ((len = stbi__get8(s)) > 0)3977 stbi__skip(s,len);3978 return g->out;3979 } else if (code <= avail) {3980 if (first) return stbi__errpuc("no clear code", "Corrupt GIF");39813982 if (oldcode >= 0) {3983 p = &g->codes[avail++];3984 if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF");3985 p->prefix = (stbi__int16) oldcode;3986 p->first = g->codes[oldcode].first;3987 p->suffix = (code == avail) ? p->first : g->codes[code].first;3988 } else if (code == avail)3989 return stbi__errpuc("illegal code in raster", "Corrupt GIF");39903991 stbi__out_gif_code(g, (stbi__uint16) code);39923993 if ((avail & codemask) == 0 && avail <= 0x0FFF) {3994 codesize++;3995 codemask = (1 << codesize) - 1;3996 }39973998 oldcode = code;3999 } else {4000 return stbi__errpuc("illegal code in raster", "Corrupt GIF");4001 }4002 } 4003 }4004}40054006static void stbi__fill_gif_background(stbi__gif *g)4007{4008 int i;4009 stbi_uc *c = g->pal[g->bgindex];4010 // @OPTIMIZE: write a dword at a time4011 for (i = 0; i < g->w * g->h * 4; i += 4) {4012 stbi_uc *p = &g->out[i];4013 p[0] = c[2];4014 p[1] = c[1];4015 p[2] = c[0];4016 p[3] = c[3];4017 }4018}40194020// this function is designed to support animated gifs, although stb_image doesn't support it4021static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp)4022{4023 int i;4024 stbi_uc *old_out = 0;40254026 if (g->out == 0) {4027 if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header4028 g->out = (stbi_uc *) malloc(4 * g->w * g->h);4029 if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");4030 stbi__fill_gif_background(g);4031 } else {4032 // animated-gif-only path4033 if (((g->eflags & 0x1C) >> 2) == 3) {4034 old_out = g->out;4035 g->out = (stbi_uc *) malloc(4 * g->w * g->h);4036 if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");4037 memcpy(g->out, old_out, g->w*g->h*4);4038 }4039 }4040 4041 for (;;) {4042 switch (stbi__get8(s)) {4043 case 0x2C: /* Image Descriptor */4044 {4045 stbi__int32 x, y, w, h;4046 stbi_uc *o;40474048 x = stbi__get16le(s);4049 y = stbi__get16le(s);4050 w = stbi__get16le(s);4051 h = stbi__get16le(s);4052 if (((x + w) > (g->w)) || ((y + h) > (g->h)))4053 return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");40544055 g->line_size = g->w * 4;4056 g->start_x = x * 4;4057 g->start_y = y * g->line_size;4058 g->max_x = g->start_x + w * 4;4059 g->max_y = g->start_y + h * g->line_size;4060 g->cur_x = g->start_x;4061 g->cur_y = g->start_y;40624063 g->lflags = stbi__get8(s);40644065 if (g->lflags & 0x40) {4066 g->step = 8 * g->line_size; // first interlaced spacing4067 g->parse = 3;4068 } else {4069 g->step = g->line_size;4070 g->parse = 0;4071 }40724073 if (g->lflags & 0x80) {4074 stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);4075 g->color_table = (stbi_uc *) g->lpal; 4076 } else if (g->flags & 0x80) {4077 for (i=0; i < 256; ++i) // @OPTIMIZE: stbi__jpeg_reset only the previous transparent4078 g->pal[i][3] = 255; 4079 if (g->transparent >= 0 && (g->eflags & 0x01))4080 g->pal[g->transparent][3] = 0;4081 g->color_table = (stbi_uc *) g->pal;4082 } else4083 return stbi__errpuc("missing color table", "Corrupt GIF");4084 4085 o = stbi__process_gif_raster(s, g);4086 if (o == NULL) return NULL;40874088 if (req_comp && req_comp != 4)4089 o = stbi__convert_format(o, 4, req_comp, g->w, g->h);4090 return o;4091 }40924093 case 0x21: // Comment Extension.4094 {4095 int len;4096 if (stbi__get8(s) == 0xF9) { // Graphic Control Extension.4097 len = stbi__get8(s);4098 if (len == 4) {4099 g->eflags = stbi__get8(s);4100 stbi__get16le(s); // delay4101 g->transparent = stbi__get8(s);4102 } else {4103 stbi__skip(s, len);4104 break;4105 }4106 }4107 while ((len = stbi__get8(s)) != 0)4108 stbi__skip(s, len);4109 break;4110 }41114112 case 0x3B: // gif stream termination code4113 return (stbi_uc *) 1;41144115 default:4116 return stbi__errpuc("unknown code", "Corrupt GIF");4117 }4118 }4119}41204121static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)4122{4123 stbi_uc *u = 0;4124 stbi__gif g={0};41254126 u = stbi__gif_load_next(s, &g, comp, req_comp);4127 if (u == (void *) 1) u = 0; // end of animated gif marker4128 if (u) {4129 *x = g.w;4130 *y = g.h;4131 }41324133 return u;4134}41354136static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)4137{4138 return stbi__gif_info_raw(s,x,y,comp);4139}414041414142// *************************************************************************************************4143// Radiance RGBE HDR loader4144// originally by Nicolas Schulz4145#ifndef STBI_NO_HDR4146static int stbi__hdr_test_core(stbi__context *s)4147{4148 const char *signature = "#?RADIANCE\n";4149 int i;4150 for (i=0; signature[i]; ++i)4151 if (stbi__get8(s) != signature[i])4152 return 0;4153 return 1;4154}41554156static int stbi__hdr_test(stbi__context* s)4157{4158 int r = stbi__hdr_test_core(s);4159 stbi__rewind(s);4160 return r;4161}41624163#define STBI__HDR_BUFLEN 10244164static char *stbi__hdr_gettoken(stbi__context *z, char *buffer)4165{4166 int len=0;4167 char c = '\0';41684169 c = (char) stbi__get8(z);41704171 while (!stbi__at_eof(z) && c != '\n') {4172 buffer[len++] = c;4173 if (len == STBI__HDR_BUFLEN-1) {4174 // flush to end of line4175 while (!stbi__at_eof(z) && stbi__get8(z) != '\n')4176 ;4177 break;4178 }4179 c = (char) stbi__get8(z);4180 }41814182 buffer[len] = 0;4183 return buffer;4184}41854186static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)4187{4188 if ( input[3] != 0 ) {4189 float f1;4190 // Exponent4191 f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));4192 if (req_comp <= 2)4193 output[0] = (input[0] + input[1] + input[2]) * f1 / 3;4194 else {4195 output[0] = input[0] * f1;4196 output[1] = input[1] * f1;4197 output[2] = input[2] * f1;4198 }4199 if (req_comp == 2) output[1] = 1;4200 if (req_comp == 4) output[3] = 1;4201 } else {4202 switch (req_comp) {4203 case 4: output[3] = 1; /* fallthrough */4204 case 3: output[0] = output[1] = output[2] = 0;4205 break;4206 case 2: output[1] = 1; /* fallthrough */4207 case 1: output[0] = 0;4208 break;4209 }4210 }4211}42124213static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)4214{4215 char buffer[STBI__HDR_BUFLEN];4216 char *token;4217 int valid = 0;4218 int width, height;4219 stbi_uc *scanline;4220 float *hdr_data;4221 int len;4222 unsigned char count, value;4223 int i, j, k, c1,c2, z;422442254226 // Check identifier4227 if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0)4228 return stbi__errpf("not HDR", "Corrupt HDR image");4229 4230 // Parse header4231 for(;;) {4232 token = stbi__hdr_gettoken(s,buffer);4233 if (token[0] == 0) break;4234 if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;4235 }42364237 if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");42384239 // Parse width and height4240 // can't use sscanf() if we're not using stdio!4241 token = stbi__hdr_gettoken(s,buffer);4242 if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");4243 token += 3;4244 height = (int) strtol(token, &token, 10);4245 while (*token == ' ') ++token;4246 if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");4247 token += 3;4248 width = (int) strtol(token, NULL, 10);42494250 *x = width;4251 *y = height;42524253 if (comp) *comp = 3;4254 if (req_comp == 0) req_comp = 3;42554256 // Read data4257 hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));42584259 // Load image data4260 // image data is stored as some number of sca4261 if ( width < 8 || width >= 32768) {4262 // Read flat data4263 for (j=0; j < height; ++j) {4264 for (i=0; i < width; ++i) {4265 stbi_uc rgbe[4];4266 main_decode_loop:4267 stbi__getn(s, rgbe, 4);4268 stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);4269 }4270 }4271 } else {4272 // Read RLE-encoded data4273 scanline = NULL;42744275 for (j = 0; j < height; ++j) {4276 c1 = stbi__get8(s);4277 c2 = stbi__get8(s);4278 len = stbi__get8(s);4279 if (c1 != 2 || c2 != 2 || (len & 0x80)) {4280 // not run-length encoded, so we have to actually use THIS data as a decoded4281 // pixel (note this can't be a valid pixel--one of RGB must be >= 128)4282 stbi_uc rgbe[4];4283 rgbe[0] = (stbi_uc) c1;4284 rgbe[1] = (stbi_uc) c2;4285 rgbe[2] = (stbi_uc) len;4286 rgbe[3] = (stbi_uc) stbi__get8u(s);4287 stbi__hdr_convert(hdr_data, rgbe, req_comp);4288 i = 1;4289 j = 0;4290 free(scanline);4291 goto main_decode_loop; // yes, this makes no sense4292 }4293 len <<= 8;4294 len |= stbi__get8(s);4295 if (len != width) { free(hdr_data); free(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }4296 if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);4297 4298 for (k = 0; k < 4; ++k) {4299 i = 0;4300 while (i < width) {4301 count = stbi__get8u(s);4302 if (count > 128) {4303 // Run4304 value = stbi__get8u(s);4305 count -= 128;4306 for (z = 0; z < count; ++z)4307 scanline[i++ * 4 + k] = value;4308 } else {4309 // Dump4310 for (z = 0; z < count; ++z)4311 scanline[i++ * 4 + k] = stbi__get8u(s);4312 }4313 }4314 }4315 for (i=0; i < width; ++i)4316 stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);4317 }4318 free(scanline);4319 }43204321 return hdr_data;4322}43234324static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)4325{4326 char buffer[STBI__HDR_BUFLEN];4327 char *token;4328 int valid = 0;43294330 if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {4331 stbi__rewind( s );4332 return 0;4333 }43344335 for(;;) {4336 token = stbi__hdr_gettoken(s,buffer);4337 if (token[0] == 0) break;4338 if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;4339 }43404341 if (!valid) {4342 stbi__rewind( s );4343 return 0;4344 }4345 token = stbi__hdr_gettoken(s,buffer);4346 if (strncmp(token, "-Y ", 3)) {4347 stbi__rewind( s );4348 return 0;4349 }4350 token += 3;4351 *y = (int) strtol(token, &token, 10);4352 while (*token == ' ') ++token;4353 if (strncmp(token, "+X ", 3)) {4354 stbi__rewind( s );4355 return 0;4356 }4357 token += 3;4358 *x = (int) strtol(token, NULL, 10);4359 *comp = 3;4360 return 1;4361}4362#endif // STBI_NO_HDR43634364static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)4365{4366 int hsz;4367 if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') {4368 stbi__rewind( s );4369 return 0;4370 }4371 stbi__skip(s,12);4372 hsz = stbi__get32le(s);4373 if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {4374 stbi__rewind( s );4375 return 0;4376 }4377 if (hsz == 12) {4378 *x = stbi__get16le(s);4379 *y = stbi__get16le(s);4380 } else {4381 *x = stbi__get32le(s);4382 *y = stbi__get32le(s);4383 }4384 if (stbi__get16le(s) != 1) {4385 stbi__rewind( s );4386 return 0;4387 }4388 *comp = stbi__get16le(s) / 8;4389 return 1;4390}43914392static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)4393{4394 int channelCount;4395 if (stbi__get32be(s) != 0x38425053) {4396 stbi__rewind( s );4397 return 0;4398 }4399 if (stbi__get16be(s) != 1) {4400 stbi__rewind( s );4401 return 0;4402 }4403 stbi__skip(s, 6);4404 channelCount = stbi__get16be(s);4405 if (channelCount < 0 || channelCount > 16) {4406 stbi__rewind( s );4407 return 0;4408 }4409 *y = stbi__get32be(s);4410 *x = stbi__get32be(s);4411 if (stbi__get16be(s) != 8) {4412 stbi__rewind( s );4413 return 0;4414 }4415 if (stbi__get16be(s) != 3) {4416 stbi__rewind( s );4417 return 0;4418 }4419 *comp = 4;4420 return 1;4421}44224423static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)4424{4425 int act_comp=0,num_packets=0,chained;4426 stbi__pic_packet packets[10];44274428 stbi__skip(s, 92);44294430 *x = stbi__get16be(s);4431 *y = stbi__get16be(s);4432 if (stbi__at_eof(s)) return 0;4433 if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {4434 stbi__rewind( s );4435 return 0;4436 }44374438 stbi__skip(s, 8);44394440 do {4441 stbi__pic_packet *packet;44424443 if (num_packets==sizeof(packets)/sizeof(packets[0]))4444 return 0;44454446 packet = &packets[num_packets++];4447 chained = stbi__get8(s);4448 packet->size = stbi__get8u(s);4449 packet->type = stbi__get8u(s);4450 packet->channel = stbi__get8u(s);4451 act_comp |= packet->channel;44524453 if (stbi__at_eof(s)) {4454 stbi__rewind( s );4455 return 0;4456 }4457 if (packet->size != 8) {4458 stbi__rewind( s );4459 return 0;4460 }4461 } while (chained);44624463 *comp = (act_comp & 0x10 ? 4 : 3);44644465 return 1;4466}44674468static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)4469{4470 if (stbi__jpeg_info(s, x, y, comp))4471 return 1;4472 if (stbi__png_info(s, x, y, comp))4473 return 1;4474 if (stbi__gif_info(s, x, y, comp))4475 return 1;4476 if (stbi__bmp_info(s, x, y, comp))4477 return 1;4478 if (stbi__psd_info(s, x, y, comp))4479 return 1;4480 if (stbi__pic_info(s, x, y, comp))4481 return 1;4482 #ifndef STBI_NO_HDR4483 if (stbi__hdr_info(s, x, y, comp))4484 return 1;4485 #endif4486 // test tga last because it's a crappy test!4487 if (stbi__tga_info(s, x, y, comp))4488 return 1;4489 return stbi__err("unknown image type", "Image not of any known type, or corrupt");4490}44914492#ifndef STBI_NO_STDIO4493STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)4494{4495 FILE *f = fopen(filename, "rb");4496 int result;4497 if (!f) return stbi__err("can't fopen", "Unable to open file");4498 result = stbi_info_from_file(f, x, y, comp);4499 fclose(f);4500 return result;4501}45024503STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)4504{4505 int r;4506 stbi__context s;4507 long pos = ftell(f);4508 stbi__start_file(&s, f);4509 r = stbi__info_main(&s,x,y,comp);4510 fseek(f,pos,SEEK_SET);4511 return r;4512}4513#endif // !STBI_NO_STDIO45144515STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)4516{4517 stbi__context s;4518 stbi__start_mem(&s,buffer,len);4519 return stbi__info_main(&s,x,y,comp);4520}45214522STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)4523{4524 stbi__context s;4525 stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);4526 return stbi__info_main(&s,x,y,comp);4527}45284529#endif // STB_IMAGE_IMPLEMENTATION45304531#if !defined(STBI_NO_STDIO) && defined(_MSC_VER) && _MSC_VER >= 14004532#pragma warning(pop)4533#endif453445354536/*4537 revision history:4538 1.36 (2014-06-03)4539 convert to header file single-file library4540 if de-iphone isn't set, load iphone images color-swapped instead of returning NULL4541 1.35 (2014-05-27)4542 various warnings4543 fix broken STBI_SIMD path4544 fix bug where stbi_load_from_file no longer left file pointer in correct place4545 fix broken non-easy path for 32-bit BMP (possibly never used)4546 TGA optimization by Arseny Kapoulkine4547 1.34 (unknown)4548 use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case4549 1.33 (2011-07-14)4550 make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements4551 1.32 (2011-07-13)4552 support for "info" function for all supported filetypes (SpartanJ)4553 1.31 (2011-06-20)4554 a few more leak fixes, bug in PNG handling (SpartanJ)4555 1.30 (2011-06-11)4556 added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)4557 removed deprecated format-specific test/load functions4558 removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway4559 error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)4560 fix inefficiency in decoding 32-bit BMP (David Woo)4561 1.29 (2010-08-16)4562 various warning fixes from Aurelien Pocheville 4563 1.28 (2010-08-01)4564 fix bug in GIF palette transparency (SpartanJ)4565 1.27 (2010-08-01)4566 cast-to-stbi_uc to fix warnings4567 1.26 (2010-07-24)4568 fix bug in file buffering for PNG reported by SpartanJ4569 1.25 (2010-07-17)4570 refix trans_data warning (Won Chun)4571 1.24 (2010-07-12)4572 perf improvements reading from files on platforms with lock-heavy fgetc()4573 minor perf improvements for jpeg4574 deprecated type-specific functions so we'll get feedback if they're needed4575 attempt to fix trans_data warning (Won Chun)4576 1.23 fixed bug in iPhone support4577 1.22 (2010-07-10)4578 removed image *writing* support4579 stbi_info support from Jetro Lauha4580 GIF support from Jean-Marc Lienher4581 iPhone PNG-extensions from James Brown4582 warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)4583 1.21 fix use of 'stbi_uc' in header (reported by jon blow)4584 1.20 added support for Softimage PIC, by Tom Seddon4585 1.19 bug in interlaced PNG corruption check (found by ryg)4586 1.18 2008-08-024587 fix a threading bug (local mutable static)4588 1.17 support interlaced PNG4589 1.16 major bugfix - stbi__convert_format converted one too many pixels4590 1.15 initialize some fields for thread safety4591 1.14 fix threadsafe conversion bug4592 header-file-only version (#define STBI_HEADER_FILE_ONLY before including)4593 1.13 threadsafe4594 1.12 const qualifiers in the API4595 1.11 Support installable IDCT, colorspace conversion routines4596 1.10 Fixes for 64-bit (don't use "unsigned long")4597 optimized upsampling by Fabian "ryg" Giesen4598 1.09 Fix format-conversion for PSD code (bad global variables!)4599 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz4600 1.07 attempt to fix C++ warning/errors again4601 1.06 attempt to fix C++ warning/errors again4602 1.05 fix TGA loading to return correct *comp and use good luminance calc4603 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free4604 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR4605 1.02 support for (subset of) HDR files, float interface for preferred access to them4606 1.01 fix bug: possible bug in handling right-side up bmps... not sure4607 fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all4608 1.00 interface to zlib that skips zlib header4609 0.99 correct handling of alpha in palette4610 0.98 TGA loader by lonesock; dynamically add loaders (untested)4611 0.97 jpeg errors on too large a file; also catch another malloc failure4612 0.96 fix detection of invalid v value - particleman@mollyrocket forum4613 0.95 during header scan, seek to markers in case of padding4614 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same4615 0.93 handle jpegtran output; verbose errors4616 0.92 read 4,8,16,24,32-bit BMP files of several formats4617 0.91 output 24-bit Windows 3.0 BMP files4618 0.90 fix a few more warnings; bump version number to approach 1.04619 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd4620 0.60 fix compiling as c++4621 0.59 fix warnings: merge Dave Moore's -Wall fixes4622 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian4623 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available4624 0.56 fix bug: zlib uncompressed mode len vs. nlen4625 0.55 fix bug: restart_interval not initialized to 04626 0.54 allow NULL for 'int *comp'4627 0.53 fix bug in png 3->4; speedup png decoding4628 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments4629 0.51 obey req_comp requests, 1-component jpegs return as 1-component,4630 on 'test' only check type, not whether we support this variant4631 0.50 first released version4632*/