DPF OpenGL examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4674 lines
148KB

  1. /* stbi-1.33 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
  2. when you control the images you're loading
  3. no warranty implied; use at your own risk
  4. QUICK NOTES:
  5. Primarily of interest to game developers and other people who can
  6. avoid problematic images and only need the trivial interface
  7. JPEG baseline (no JPEG progressive)
  8. PNG 8-bit-per-channel only
  9. TGA (not sure what subset, if a subset)
  10. BMP non-1bpp, non-RLE
  11. PSD (composited view only, no extra channels)
  12. GIF (*comp always reports as 4-channel)
  13. HDR (radiance rgbE format)
  14. PIC (Softimage PIC)
  15. - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
  16. - decode from arbitrary I/O callbacks
  17. - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
  18. Latest revisions:
  19. 1.33 (2011-07-14) minor fixes suggested by Dave Moore
  20. 1.32 (2011-07-13) info support for all filetypes (SpartanJ)
  21. 1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ)
  22. 1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger)
  23. 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville
  24. 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)
  25. 1.27 (2010-08-01) cast-to-uint8 to fix warnings (Laurent Gomila)
  26. allow trailing 0s at end of image data (Laurent Gomila)
  27. 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ
  28. See end of file for full revision history.
  29. TODO:
  30. stbi_info support for BMP,PSD,HDR,PIC
  31. ============================ Contributors =========================
  32. Image formats Optimizations & bugfixes
  33. Sean Barrett (jpeg, png, bmp) Fabian "ryg" Giesen
  34. Nicolas Schulz (hdr, psd)
  35. Jonathan Dummer (tga) Bug fixes & warning fixes
  36. Jean-Marc Lienher (gif) Marc LeBlanc
  37. Tom Seddon (pic) Christpher Lloyd
  38. Thatcher Ulrich (psd) Dave Moore
  39. Won Chun
  40. the Horde3D community
  41. Extensions, features Janez Zemva
  42. Jetro Lauha (stbi_info) Jonathan Blow
  43. James "moose2000" Brown (iPhone PNG) Laurent Gomila
  44. Ben "Disch" Wenger (io callbacks) Aruelien Pocheville
  45. Martin "SpartanJ" Golini Ryamond Barbiero
  46. David Woo
  47. If your name should be here but isn't, let Sean know.
  48. */
  49. #ifndef STBI_INCLUDE_STB_IMAGE_H
  50. #define STBI_INCLUDE_STB_IMAGE_H
  51. // To get a header file for this, either cut and paste the header,
  52. // or create stb_image.h, #define STBI_HEADER_FILE_ONLY, and
  53. // then include stb_image.c from it.
  54. //// begin header file ////////////////////////////////////////////////////
  55. //
  56. // Limitations:
  57. // - no jpeg progressive support
  58. // - non-HDR formats support 8-bit samples only (jpeg, png)
  59. // - no delayed line count (jpeg) -- IJG doesn't support either
  60. // - no 1-bit BMP
  61. // - GIF always returns *comp=4
  62. //
  63. // Basic usage (see HDR discussion below):
  64. // int x,y,n;
  65. // unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
  66. // // ... process data if not NULL ...
  67. // // ... x = width, y = height, n = # 8-bit components per pixel ...
  68. // // ... replace '0' with '1'..'4' to force that many components per pixel
  69. // // ... but 'n' will always be the number that it would have been if you said 0
  70. // stbi_image_free(data)
  71. //
  72. // Standard parameters:
  73. // int *x -- outputs image width in pixels
  74. // int *y -- outputs image height in pixels
  75. // int *comp -- outputs # of image components in image file
  76. // int req_comp -- if non-zero, # of image components requested in result
  77. //
  78. // The return value from an image loader is an 'unsigned char *' which points
  79. // to the pixel data. The pixel data consists of *y scanlines of *x pixels,
  80. // with each pixel consisting of N interleaved 8-bit components; the first
  81. // pixel pointed to is top-left-most in the image. There is no padding between
  82. // image scanlines or between pixels, regardless of format. The number of
  83. // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
  84. // If req_comp is non-zero, *comp has the number of components that _would_
  85. // have been output otherwise. E.g. if you set req_comp to 4, you will always
  86. // get RGBA output, but you can check *comp to easily see if it's opaque.
  87. //
  88. // An output image with N components has the following components interleaved
  89. // in this order in each pixel:
  90. //
  91. // N=#comp components
  92. // 1 grey
  93. // 2 grey, alpha
  94. // 3 red, green, blue
  95. // 4 red, green, blue, alpha
  96. //
  97. // If image loading fails for any reason, the return value will be NULL,
  98. // and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
  99. // can be queried for an extremely brief, end-user unfriendly explanation
  100. // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
  101. // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
  102. // more user-friendly ones.
  103. //
  104. // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
  105. //
  106. // ===========================================================================
  107. //
  108. // iPhone PNG support:
  109. //
  110. // By default we convert iphone-formatted PNGs back to RGB; nominally they
  111. // would silently load as BGR, except the existing code should have just
  112. // failed on such iPhone PNGs. But you can disable this conversion by
  113. // by calling stbi_convert_iphone_png_to_rgb(0), in which case
  114. // you will always just get the native iphone "format" through.
  115. //
  116. // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
  117. // pixel to remove any premultiplied alpha *only* if the image file explicitly
  118. // says there's premultiplied data (currently only happens in iPhone images,
  119. // and only if iPhone convert-to-rgb processing is on).
  120. //
  121. // ===========================================================================
  122. //
  123. // HDR image support (disable by defining STBI_NO_HDR)
  124. //
  125. // stb_image now supports loading HDR images in general, and currently
  126. // the Radiance .HDR file format, although the support is provided
  127. // generically. You can still load any file through the existing interface;
  128. // if you attempt to load an HDR file, it will be automatically remapped to
  129. // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
  130. // both of these constants can be reconfigured through this interface:
  131. //
  132. // stbi_hdr_to_ldr_gamma(2.2f);
  133. // stbi_hdr_to_ldr_scale(1.0f);
  134. //
  135. // (note, do not use _inverse_ constants; stbi_image will invert them
  136. // appropriately).
  137. //
  138. // Additionally, there is a new, parallel interface for loading files as
  139. // (linear) floats to preserve the full dynamic range:
  140. //
  141. // float *data = stbi_loadf(filename, &x, &y, &n, 0);
  142. //
  143. // If you load LDR images through this interface, those images will
  144. // be promoted to floating point values, run through the inverse of
  145. // constants corresponding to the above:
  146. //
  147. // stbi_ldr_to_hdr_scale(1.0f);
  148. // stbi_ldr_to_hdr_gamma(2.2f);
  149. //
  150. // Finally, given a filename (or an open file or memory block--see header
  151. // file for details) containing image data, you can query for the "most
  152. // appropriate" interface to use (that is, whether the image is HDR or
  153. // not), using:
  154. //
  155. // stbi_is_hdr(char *filename);
  156. //
  157. // ===========================================================================
  158. //
  159. // I/O callbacks
  160. //
  161. // I/O callbacks allow you to read from arbitrary sources, like packaged
  162. // files or some other source. Data read from callbacks are processed
  163. // through a small internal buffer (currently 128 bytes) to try to reduce
  164. // overhead.
  165. //
  166. // The three functions you must define are "read" (reads some bytes of data),
  167. // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
  168. #ifndef STBI_NO_STDIO
  169. #if defined(_MSC_VER) && _MSC_VER >= 0x1400
  170. #define _CRT_SECURE_NO_WARNINGS // suppress bogus warnings about fopen()
  171. #endif
  172. #include <stdio.h>
  173. #endif
  174. #define STBI_VERSION 1
  175. enum
  176. {
  177. STBI_default = 0, // only used for req_comp
  178. STBI_grey = 1,
  179. STBI_grey_alpha = 2,
  180. STBI_rgb = 3,
  181. STBI_rgb_alpha = 4
  182. };
  183. typedef unsigned char stbi_uc;
  184. #ifdef __cplusplus
  185. extern "C" {
  186. #endif
  187. //////////////////////////////////////////////////////////////////////////////
  188. //
  189. // PRIMARY API - works on images of any type
  190. //
  191. //
  192. // load image by filename, open file, or memory buffer
  193. //
  194. extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
  195. #ifndef STBI_NO_STDIO
  196. extern stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
  197. extern stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
  198. // for stbi_load_from_file, file pointer is left pointing immediately after image
  199. #endif
  200. typedef struct
  201. {
  202. int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
  203. void (*skip) (void *user,unsigned n); // skip the next 'n' bytes
  204. int (*eof) (void *user); // returns nonzero if we are at end of file/data
  205. } stbi_io_callbacks;
  206. extern stbi_uc *stbi_load_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
  207. #ifndef STBI_NO_HDR
  208. extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
  209. #ifndef STBI_NO_STDIO
  210. extern float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
  211. extern float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
  212. #endif
  213. extern float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
  214. extern void stbi_hdr_to_ldr_gamma(float gamma);
  215. extern void stbi_hdr_to_ldr_scale(float scale);
  216. extern void stbi_ldr_to_hdr_gamma(float gamma);
  217. extern void stbi_ldr_to_hdr_scale(float scale);
  218. #endif // STBI_NO_HDR
  219. // stbi_is_hdr is always defined
  220. extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
  221. extern int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
  222. #ifndef STBI_NO_STDIO
  223. extern int stbi_is_hdr (char const *filename);
  224. extern int stbi_is_hdr_from_file(FILE *f);
  225. #endif // STBI_NO_STDIO
  226. // get a VERY brief reason for failure
  227. // NOT THREADSAFE
  228. extern const char *stbi_failure_reason (void);
  229. // free the loaded image -- this is just free()
  230. extern void stbi_image_free (void *retval_from_stbi_load);
  231. // get image dimensions & components without fully decoding
  232. extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
  233. extern int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
  234. #ifndef STBI_NO_STDIO
  235. extern int stbi_info (char const *filename, int *x, int *y, int *comp);
  236. extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
  237. #endif
  238. // for image formats that explicitly notate that they have premultiplied alpha,
  239. // we just return the colors as stored in the file. set this flag to force
  240. // unpremultiplication. results are undefined if the unpremultiply overflow.
  241. extern void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
  242. // indicate whether we should process iphone images back to canonical format,
  243. // or just pass them through "as-is"
  244. extern void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
  245. // ZLIB client - used by PNG, available for other purposes
  246. extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
  247. extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
  248. extern int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  249. extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
  250. extern int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  251. // define faster low-level operations (typically SIMD support)
  252. #ifdef STBI_SIMD
  253. typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);
  254. // compute an integer IDCT on "input"
  255. // input[x] = data[x] * dequantize[x]
  256. // write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
  257. // CLAMP results to 0..255
  258. typedef 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);
  259. // compute a conversion from YCbCr to RGB
  260. // 'count' pixels
  261. // write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
  262. // y: Y input channel
  263. // cb: Cb input channel; scale/biased to be 0..255
  264. // cr: Cr input channel; scale/biased to be 0..255
  265. extern void stbi_install_idct(stbi_idct_8x8 func);
  266. extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
  267. #endif // STBI_SIMD
  268. #ifdef __cplusplus
  269. }
  270. #endif
  271. //
  272. //
  273. //// end header file /////////////////////////////////////////////////////
  274. #endif // STBI_INCLUDE_STB_IMAGE_H
  275. #ifndef STBI_HEADER_FILE_ONLY
  276. #ifndef STBI_NO_HDR
  277. #include <math.h> // ldexp
  278. #include <string.h> // strcmp, strtok
  279. #endif
  280. #ifndef STBI_NO_STDIO
  281. #include <stdio.h>
  282. #endif
  283. #include <stdlib.h>
  284. #include <memory.h>
  285. #include <assert.h>
  286. #include <stdarg.h>
  287. #ifndef _MSC_VER
  288. #ifdef __cplusplus
  289. #define stbi_inline inline
  290. #else
  291. #define stbi_inline
  292. #endif
  293. #else
  294. #define stbi_inline __forceinline
  295. #endif
  296. // implementation:
  297. typedef unsigned char uint8;
  298. typedef unsigned short uint16;
  299. typedef signed short int16;
  300. typedef unsigned int uint32;
  301. typedef signed int int32;
  302. typedef unsigned int uint;
  303. // should produce compiler error if size is wrong
  304. typedef unsigned char validate_uint32[sizeof(uint32)==4 ? 1 : -1];
  305. #if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
  306. #define STBI_NO_WRITE
  307. #endif
  308. #define STBI_NOTUSED(v) (void)sizeof(v)
  309. #ifdef _MSC_VER
  310. #define STBI_HAS_LROTL
  311. #endif
  312. #ifdef STBI_HAS_LROTL
  313. #define stbi_lrot(x,y) _lrotl(x,y)
  314. #else
  315. #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))
  316. #endif
  317. ///////////////////////////////////////////////
  318. //
  319. // stbi struct and start_xxx functions
  320. // stbi structure is our basic context used by all images, so it
  321. // contains all the IO context, plus some basic image information
  322. typedef struct
  323. {
  324. uint32 img_x, img_y;
  325. int img_n, img_out_n;
  326. stbi_io_callbacks io;
  327. void *io_user_data;
  328. int read_from_callbacks;
  329. int buflen;
  330. uint8 buffer_start[128];
  331. uint8 *img_buffer, *img_buffer_end;
  332. uint8 *img_buffer_original;
  333. } stbi;
  334. static void refill_buffer(stbi *s);
  335. // initialize a memory-decode context
  336. static void start_mem(stbi *s, uint8 const *buffer, int len)
  337. {
  338. s->io.read = NULL;
  339. s->read_from_callbacks = 0;
  340. s->img_buffer = s->img_buffer_original = (uint8 *) buffer;
  341. s->img_buffer_end = (uint8 *) buffer+len;
  342. }
  343. // initialize a callback-based context
  344. static void start_callbacks(stbi *s, stbi_io_callbacks *c, void *user)
  345. {
  346. s->io = *c;
  347. s->io_user_data = user;
  348. s->buflen = sizeof(s->buffer_start);
  349. s->read_from_callbacks = 1;
  350. s->img_buffer_original = s->buffer_start;
  351. refill_buffer(s);
  352. }
  353. #ifndef STBI_NO_STDIO
  354. static int stdio_read(void *user, char *data, int size)
  355. {
  356. return (int) fread(data,1,size,(FILE*) user);
  357. }
  358. static void stdio_skip(void *user, unsigned n)
  359. {
  360. fseek((FILE*) user, n, SEEK_CUR);
  361. }
  362. static int stdio_eof(void *user)
  363. {
  364. return feof((FILE*) user);
  365. }
  366. static stbi_io_callbacks stbi_stdio_callbacks =
  367. {
  368. stdio_read,
  369. stdio_skip,
  370. stdio_eof,
  371. };
  372. static void start_file(stbi *s, FILE *f)
  373. {
  374. start_callbacks(s, &stbi_stdio_callbacks, (void *) f);
  375. }
  376. //static void stop_file(stbi *s) { }
  377. #endif // !STBI_NO_STDIO
  378. static void stbi_rewind(stbi *s)
  379. {
  380. // conceptually rewind SHOULD rewind to the beginning of the stream,
  381. // but we just rewind to the beginning of the initial buffer, because
  382. // we only use it after doing 'test', which only ever looks at at most 92 bytes
  383. s->img_buffer = s->img_buffer_original;
  384. }
  385. static int stbi_jpeg_test(stbi *s);
  386. static stbi_uc *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp);
  387. static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp);
  388. static int stbi_png_test(stbi *s);
  389. static stbi_uc *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp);
  390. static int stbi_png_info(stbi *s, int *x, int *y, int *comp);
  391. static int stbi_bmp_test(stbi *s);
  392. static stbi_uc *stbi_bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp);
  393. static int stbi_tga_test(stbi *s);
  394. static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp);
  395. static int stbi_tga_info(stbi *s, int *x, int *y, int *comp);
  396. static int stbi_psd_test(stbi *s);
  397. static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp);
  398. static int stbi_hdr_test(stbi *s);
  399. static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);
  400. static int stbi_pic_test(stbi *s);
  401. static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp);
  402. static int stbi_gif_test(stbi *s);
  403. static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp);
  404. static int stbi_gif_info(stbi *s, int *x, int *y, int *comp);
  405. // this is not threadsafe
  406. static const char *failure_reason;
  407. const char *stbi_failure_reason(void)
  408. {
  409. return failure_reason;
  410. }
  411. static int e(const char *str)
  412. {
  413. failure_reason = str;
  414. return 0;
  415. }
  416. // e - error
  417. // epf - error returning pointer to float
  418. // epuc - error returning pointer to unsigned char
  419. #ifdef STBI_NO_FAILURE_STRINGS
  420. #define e(x,y) 0
  421. #elif defined(STBI_FAILURE_USERMSG)
  422. #define e(x,y) e(y)
  423. #else
  424. #define e(x,y) e(x)
  425. #endif
  426. #define epf(x,y) ((float *) (e(x,y)?NULL:NULL))
  427. #define epuc(x,y) ((unsigned char *) (e(x,y)?NULL:NULL))
  428. void stbi_image_free(void *retval_from_stbi_load)
  429. {
  430. free(retval_from_stbi_load);
  431. }
  432. #ifndef STBI_NO_HDR
  433. static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
  434. static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp);
  435. #endif
  436. static unsigned char *stbi_load_main(stbi *s, int *x, int *y, int *comp, int req_comp)
  437. {
  438. if (stbi_jpeg_test(s)) return stbi_jpeg_load(s,x,y,comp,req_comp);
  439. if (stbi_png_test(s)) return stbi_png_load(s,x,y,comp,req_comp);
  440. if (stbi_bmp_test(s)) return stbi_bmp_load(s,x,y,comp,req_comp);
  441. if (stbi_gif_test(s)) return stbi_gif_load(s,x,y,comp,req_comp);
  442. if (stbi_psd_test(s)) return stbi_psd_load(s,x,y,comp,req_comp);
  443. if (stbi_pic_test(s)) return stbi_pic_load(s,x,y,comp,req_comp);
  444. #ifndef STBI_NO_HDR
  445. if (stbi_hdr_test(s)) {
  446. float *hdr = stbi_hdr_load(s, x,y,comp,req_comp);
  447. return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
  448. }
  449. #endif
  450. // test tga last because it's a crappy test!
  451. if (stbi_tga_test(s))
  452. return stbi_tga_load(s,x,y,comp,req_comp);
  453. return epuc("unknown image type", "Image not of any known type, or corrupt");
  454. }
  455. #ifndef STBI_NO_STDIO
  456. unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
  457. {
  458. FILE *f = fopen(filename, "rb");
  459. unsigned char *result;
  460. if (!f) return epuc("can't fopen", "Unable to open file");
  461. result = stbi_load_from_file(f,x,y,comp,req_comp);
  462. fclose(f);
  463. return result;
  464. }
  465. unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
  466. {
  467. stbi s;
  468. start_file(&s,f);
  469. return stbi_load_main(&s,x,y,comp,req_comp);
  470. }
  471. #endif //!STBI_NO_STDIO
  472. unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  473. {
  474. stbi s;
  475. start_mem(&s,buffer,len);
  476. return stbi_load_main(&s,x,y,comp,req_comp);
  477. }
  478. unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  479. {
  480. stbi s;
  481. start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  482. return stbi_load_main(&s,x,y,comp,req_comp);
  483. }
  484. #ifndef STBI_NO_HDR
  485. float *stbi_loadf_main(stbi *s, int *x, int *y, int *comp, int req_comp)
  486. {
  487. unsigned char *data;
  488. #ifndef STBI_NO_HDR
  489. if (stbi_hdr_test(s))
  490. return stbi_hdr_load(s,x,y,comp,req_comp);
  491. #endif
  492. data = stbi_load_main(s, x, y, comp, req_comp);
  493. if (data)
  494. return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
  495. return epf("unknown image type", "Image not of any known type, or corrupt");
  496. }
  497. float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  498. {
  499. stbi s;
  500. start_mem(&s,buffer,len);
  501. return stbi_loadf_main(&s,x,y,comp,req_comp);
  502. }
  503. float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  504. {
  505. stbi s;
  506. start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  507. return stbi_loadf_main(&s,x,y,comp,req_comp);
  508. }
  509. #ifndef STBI_NO_STDIO
  510. float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
  511. {
  512. FILE *f = fopen(filename, "rb");
  513. float *result;
  514. if (!f) return epf("can't fopen", "Unable to open file");
  515. result = stbi_loadf_from_file(f,x,y,comp,req_comp);
  516. fclose(f);
  517. return result;
  518. }
  519. float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
  520. {
  521. stbi s;
  522. start_file(&s,f);
  523. return stbi_loadf_main(&s,x,y,comp,req_comp);
  524. }
  525. #endif // !STBI_NO_STDIO
  526. #endif // !STBI_NO_HDR
  527. // these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
  528. // defined, for API simplicity; if STBI_NO_HDR is defined, it always
  529. // reports false!
  530. int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
  531. {
  532. #ifndef STBI_NO_HDR
  533. stbi s;
  534. start_mem(&s,buffer,len);
  535. return stbi_hdr_test(&s);
  536. #else
  537. STBI_NOTUSED(buffer);
  538. STBI_NOTUSED(len);
  539. return 0;
  540. #endif
  541. }
  542. #ifndef STBI_NO_STDIO
  543. extern int stbi_is_hdr (char const *filename)
  544. {
  545. FILE *f = fopen(filename, "rb");
  546. int result=0;
  547. if (f) {
  548. result = stbi_is_hdr_from_file(f);
  549. fclose(f);
  550. }
  551. return result;
  552. }
  553. extern int stbi_is_hdr_from_file(FILE *f)
  554. {
  555. #ifndef STBI_NO_HDR
  556. stbi s;
  557. start_file(&s,f);
  558. return stbi_hdr_test(&s);
  559. #else
  560. return 0;
  561. #endif
  562. }
  563. #endif // !STBI_NO_STDIO
  564. extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
  565. {
  566. #ifndef STBI_NO_HDR
  567. stbi s;
  568. start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  569. return stbi_hdr_test(&s);
  570. #else
  571. return 0;
  572. #endif
  573. }
  574. #ifndef STBI_NO_HDR
  575. static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
  576. static float l2h_gamma=2.2f, l2h_scale=1.0f;
  577. void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
  578. void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
  579. void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
  580. void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
  581. #endif
  582. //////////////////////////////////////////////////////////////////////////////
  583. //
  584. // Common code used by all image loaders
  585. //
  586. enum
  587. {
  588. SCAN_load=0,
  589. SCAN_type,
  590. SCAN_header
  591. };
  592. static void refill_buffer(stbi *s)
  593. {
  594. int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
  595. if (n == 0) {
  596. // at end of file, treat same as if from memory
  597. s->read_from_callbacks = 0;
  598. s->img_buffer = s->img_buffer_end-1;
  599. *s->img_buffer = 0;
  600. } else {
  601. s->img_buffer = s->buffer_start;
  602. s->img_buffer_end = s->buffer_start + n;
  603. }
  604. }
  605. stbi_inline static int get8(stbi *s)
  606. {
  607. if (s->img_buffer < s->img_buffer_end)
  608. return *s->img_buffer++;
  609. if (s->read_from_callbacks) {
  610. refill_buffer(s);
  611. return *s->img_buffer++;
  612. }
  613. return 0;
  614. }
  615. stbi_inline static int at_eof(stbi *s)
  616. {
  617. if (s->io.read) {
  618. if (!(s->io.eof)(s->io_user_data)) return 0;
  619. // if feof() is true, check if buffer = end
  620. // special case: we've only got the special 0 character at the end
  621. if (s->read_from_callbacks == 0) return 1;
  622. }
  623. return s->img_buffer >= s->img_buffer_end;
  624. }
  625. stbi_inline static uint8 get8u(stbi *s)
  626. {
  627. return (uint8) get8(s);
  628. }
  629. static void skip(stbi *s, int n)
  630. {
  631. if (s->io.read) {
  632. int blen = s->img_buffer_end - s->img_buffer;
  633. if (blen < n) {
  634. s->img_buffer = s->img_buffer_end;
  635. (s->io.skip)(s->io_user_data, n - blen);
  636. return;
  637. }
  638. }
  639. s->img_buffer += n;
  640. }
  641. static int getn(stbi *s, stbi_uc *buffer, int n)
  642. {
  643. if (s->io.read) {
  644. int blen = s->img_buffer_end - s->img_buffer;
  645. if (blen < n) {
  646. int res, count;
  647. memcpy(buffer, s->img_buffer, blen);
  648. count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
  649. res = (count == (n-blen));
  650. s->img_buffer = s->img_buffer_end;
  651. return res;
  652. }
  653. }
  654. if (s->img_buffer+n <= s->img_buffer_end) {
  655. memcpy(buffer, s->img_buffer, n);
  656. s->img_buffer += n;
  657. return 1;
  658. } else
  659. return 0;
  660. }
  661. static int get16(stbi *s)
  662. {
  663. int z = get8(s);
  664. return (z << 8) + get8(s);
  665. }
  666. static uint32 get32(stbi *s)
  667. {
  668. uint32 z = get16(s);
  669. return (z << 16) + get16(s);
  670. }
  671. static int get16le(stbi *s)
  672. {
  673. int z = get8(s);
  674. return z + (get8(s) << 8);
  675. }
  676. static uint32 get32le(stbi *s)
  677. {
  678. uint32 z = get16le(s);
  679. return z + (get16le(s) << 16);
  680. }
  681. //////////////////////////////////////////////////////////////////////////////
  682. //
  683. // generic converter from built-in img_n to req_comp
  684. // individual types do this automatically as much as possible (e.g. jpeg
  685. // does all cases internally since it needs to colorspace convert anyway,
  686. // and it never has alpha, so very few cases ). png can automatically
  687. // interleave an alpha=255 channel, but falls back to this for other cases
  688. //
  689. // assume data buffer is malloced, so malloc a new one and free that one
  690. // only failure mode is malloc failing
  691. static uint8 compute_y(int r, int g, int b)
  692. {
  693. return (uint8) (((r*77) + (g*150) + (29*b)) >> 8);
  694. }
  695. static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
  696. {
  697. int i,j;
  698. unsigned char *good;
  699. if (req_comp == img_n) return data;
  700. assert(req_comp >= 1 && req_comp <= 4);
  701. good = (unsigned char *) malloc(req_comp * x * y);
  702. if (good == NULL) {
  703. free(data);
  704. return epuc("outofmem", "Out of memory");
  705. }
  706. for (j=0; j < (int) y; ++j) {
  707. unsigned char *src = data + j * x * img_n ;
  708. unsigned char *dest = good + j * x * req_comp;
  709. #define COMBO(a,b) ((a)*8+(b))
  710. #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
  711. // convert source image with img_n components to one with req_comp components;
  712. // avoid switch per pixel, so use switch per scanline and massive macros
  713. switch (COMBO(img_n, req_comp)) {
  714. CASE(1,2) dest[0]=src[0], dest[1]=255; break;
  715. CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
  716. CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
  717. CASE(2,1) dest[0]=src[0]; break;
  718. CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
  719. CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
  720. CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
  721. CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
  722. CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
  723. CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
  724. CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
  725. CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
  726. default: assert(0);
  727. }
  728. #undef CASE
  729. }
  730. free(data);
  731. return good;
  732. }
  733. #ifndef STBI_NO_HDR
  734. static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
  735. {
  736. int i,k,n;
  737. float *output = (float *) malloc(x * y * comp * sizeof(float));
  738. if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }
  739. // compute number of non-alpha components
  740. if (comp & 1) n = comp; else n = comp-1;
  741. for (i=0; i < x*y; ++i) {
  742. for (k=0; k < n; ++k) {
  743. output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
  744. }
  745. if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
  746. }
  747. free(data);
  748. return output;
  749. }
  750. #define float2int(x) ((int) (x))
  751. static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp)
  752. {
  753. int i,k,n;
  754. stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
  755. if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }
  756. // compute number of non-alpha components
  757. if (comp & 1) n = comp; else n = comp-1;
  758. for (i=0; i < x*y; ++i) {
  759. for (k=0; k < n; ++k) {
  760. float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
  761. if (z < 0) z = 0;
  762. if (z > 255) z = 255;
  763. output[i*comp + k] = (uint8) float2int(z);
  764. }
  765. if (k < comp) {
  766. float z = data[i*comp+k] * 255 + 0.5f;
  767. if (z < 0) z = 0;
  768. if (z > 255) z = 255;
  769. output[i*comp + k] = (uint8) float2int(z);
  770. }
  771. }
  772. free(data);
  773. return output;
  774. }
  775. #endif
  776. //////////////////////////////////////////////////////////////////////////////
  777. //
  778. // "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
  779. //
  780. // simple implementation
  781. // - channel subsampling of at most 2 in each dimension
  782. // - doesn't support delayed output of y-dimension
  783. // - simple interface (only one output format: 8-bit interleaved RGB)
  784. // - doesn't try to recover corrupt jpegs
  785. // - doesn't allow partial loading, loading multiple at once
  786. // - still fast on x86 (copying globals into locals doesn't help x86)
  787. // - allocates lots of intermediate memory (full size of all components)
  788. // - non-interleaved case requires this anyway
  789. // - allows good upsampling (see next)
  790. // high-quality
  791. // - upsampled channels are bilinearly interpolated, even across blocks
  792. // - quality integer IDCT derived from IJG's 'slow'
  793. // performance
  794. // - fast huffman; reasonable integer IDCT
  795. // - uses a lot of intermediate memory, could cache poorly
  796. // - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
  797. // stb_jpeg: 1.34 seconds (MSVC6, default release build)
  798. // stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
  799. // IJL11.dll: 1.08 seconds (compiled by intel)
  800. // IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
  801. // IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
  802. // huffman decoding acceleration
  803. #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
  804. typedef struct
  805. {
  806. uint8 fast[1 << FAST_BITS];
  807. // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
  808. uint16 code[256];
  809. uint8 values[256];
  810. uint8 size[257];
  811. unsigned int maxcode[18];
  812. int delta[17]; // old 'firstsymbol' - old 'firstcode'
  813. } huffman;
  814. typedef struct
  815. {
  816. #ifdef STBI_SIMD
  817. unsigned short dequant2[4][64];
  818. #endif
  819. stbi *s;
  820. huffman huff_dc[4];
  821. huffman huff_ac[4];
  822. uint8 dequant[4][64];
  823. // sizes for components, interleaved MCUs
  824. int img_h_max, img_v_max;
  825. int img_mcu_x, img_mcu_y;
  826. int img_mcu_w, img_mcu_h;
  827. // definition of jpeg image component
  828. struct
  829. {
  830. int id;
  831. int h,v;
  832. int tq;
  833. int hd,ha;
  834. int dc_pred;
  835. int x,y,w2,h2;
  836. uint8 *data;
  837. void *raw_data;
  838. uint8 *linebuf;
  839. } img_comp[4];
  840. uint32 code_buffer; // jpeg entropy-coded buffer
  841. int code_bits; // number of valid bits
  842. unsigned char marker; // marker seen while filling entropy buffer
  843. int nomore; // flag if we saw a marker so must stop
  844. int scan_n, order[4];
  845. int restart_interval, todo;
  846. } jpeg;
  847. static int build_huffman(huffman *h, int *count)
  848. {
  849. int i,j,k=0,code;
  850. // build size list for each symbol (from JPEG spec)
  851. for (i=0; i < 16; ++i)
  852. for (j=0; j < count[i]; ++j)
  853. h->size[k++] = (uint8) (i+1);
  854. h->size[k] = 0;
  855. // compute actual symbols (from jpeg spec)
  856. code = 0;
  857. k = 0;
  858. for(j=1; j <= 16; ++j) {
  859. // compute delta to add to code to compute symbol id
  860. h->delta[j] = k - code;
  861. if (h->size[k] == j) {
  862. while (h->size[k] == j)
  863. h->code[k++] = (uint16) (code++);
  864. if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");
  865. }
  866. // compute largest code + 1 for this size, preshifted as needed later
  867. h->maxcode[j] = code << (16-j);
  868. code <<= 1;
  869. }
  870. h->maxcode[j] = 0xffffffff;
  871. // build non-spec acceleration table; 255 is flag for not-accelerated
  872. memset(h->fast, 255, 1 << FAST_BITS);
  873. for (i=0; i < k; ++i) {
  874. int s = h->size[i];
  875. if (s <= FAST_BITS) {
  876. int c = h->code[i] << (FAST_BITS-s);
  877. int m = 1 << (FAST_BITS-s);
  878. for (j=0; j < m; ++j) {
  879. h->fast[c+j] = (uint8) i;
  880. }
  881. }
  882. }
  883. return 1;
  884. }
  885. static void grow_buffer_unsafe(jpeg *j)
  886. {
  887. do {
  888. int b = j->nomore ? 0 : get8(j->s);
  889. if (b == 0xff) {
  890. int c = get8(j->s);
  891. if (c != 0) {
  892. j->marker = (unsigned char) c;
  893. j->nomore = 1;
  894. return;
  895. }
  896. }
  897. j->code_buffer |= b << (24 - j->code_bits);
  898. j->code_bits += 8;
  899. } while (j->code_bits <= 24);
  900. }
  901. // (1 << n) - 1
  902. static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
  903. // decode a jpeg huffman value from the bitstream
  904. stbi_inline static int decode(jpeg *j, huffman *h)
  905. {
  906. unsigned int temp;
  907. int c,k;
  908. if (j->code_bits < 16) grow_buffer_unsafe(j);
  909. // look at the top FAST_BITS and determine what symbol ID it is,
  910. // if the code is <= FAST_BITS
  911. c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
  912. k = h->fast[c];
  913. if (k < 255) {
  914. int s = h->size[k];
  915. if (s > j->code_bits)
  916. return -1;
  917. j->code_buffer <<= s;
  918. j->code_bits -= s;
  919. return h->values[k];
  920. }
  921. // naive test is to shift the code_buffer down so k bits are
  922. // valid, then test against maxcode. To speed this up, we've
  923. // preshifted maxcode left so that it has (16-k) 0s at the
  924. // end; in other words, regardless of the number of bits, it
  925. // wants to be compared against something shifted to have 16;
  926. // that way we don't need to shift inside the loop.
  927. temp = j->code_buffer >> 16;
  928. for (k=FAST_BITS+1 ; ; ++k)
  929. if (temp < h->maxcode[k])
  930. break;
  931. if (k == 17) {
  932. // error! code not found
  933. j->code_bits -= 16;
  934. return -1;
  935. }
  936. if (k > j->code_bits)
  937. return -1;
  938. // convert the huffman code to the symbol id
  939. c = ((j->code_buffer >> (32 - k)) & bmask[k]) + h->delta[k];
  940. assert((((j->code_buffer) >> (32 - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
  941. // convert the id to a symbol
  942. j->code_bits -= k;
  943. j->code_buffer <<= k;
  944. return h->values[c];
  945. }
  946. // combined JPEG 'receive' and JPEG 'extend', since baseline
  947. // always extends everything it receives.
  948. stbi_inline static int extend_receive(jpeg *j, int n)
  949. {
  950. unsigned int m = 1 << (n-1);
  951. unsigned int k;
  952. if (j->code_bits < n) grow_buffer_unsafe(j);
  953. #if 1
  954. k = stbi_lrot(j->code_buffer, n);
  955. j->code_buffer = k & ~bmask[n];
  956. k &= bmask[n];
  957. j->code_bits -= n;
  958. #else
  959. k = (j->code_buffer >> (32 - n)) & bmask[n];
  960. j->code_bits -= n;
  961. j->code_buffer <<= n;
  962. #endif
  963. // the following test is probably a random branch that won't
  964. // predict well. I tried to table accelerate it but failed.
  965. // maybe it's compiling as a conditional move?
  966. if (k < m)
  967. return (-1 << n) + k + 1;
  968. else
  969. return k;
  970. }
  971. // given a value that's at position X in the zigzag stream,
  972. // where does it appear in the 8x8 matrix coded as row-major?
  973. static uint8 dezigzag[64+15] =
  974. {
  975. 0, 1, 8, 16, 9, 2, 3, 10,
  976. 17, 24, 32, 25, 18, 11, 4, 5,
  977. 12, 19, 26, 33, 40, 48, 41, 34,
  978. 27, 20, 13, 6, 7, 14, 21, 28,
  979. 35, 42, 49, 56, 57, 50, 43, 36,
  980. 29, 22, 15, 23, 30, 37, 44, 51,
  981. 58, 59, 52, 45, 38, 31, 39, 46,
  982. 53, 60, 61, 54, 47, 55, 62, 63,
  983. // let corrupt input sample past end
  984. 63, 63, 63, 63, 63, 63, 63, 63,
  985. 63, 63, 63, 63, 63, 63, 63
  986. };
  987. // decode one 64-entry block--
  988. static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
  989. {
  990. int diff,dc,k;
  991. int t = decode(j, hdc);
  992. if (t < 0) return e("bad huffman code","Corrupt JPEG");
  993. // 0 all the ac values now so we can do it 32-bits at a time
  994. memset(data,0,64*sizeof(data[0]));
  995. diff = t ? extend_receive(j, t) : 0;
  996. dc = j->img_comp[b].dc_pred + diff;
  997. j->img_comp[b].dc_pred = dc;
  998. data[0] = (short) dc;
  999. // decode AC components, see JPEG spec
  1000. k = 1;
  1001. do {
  1002. int r,s;
  1003. int rs = decode(j, hac);
  1004. if (rs < 0) return e("bad huffman code","Corrupt JPEG");
  1005. s = rs & 15;
  1006. r = rs >> 4;
  1007. if (s == 0) {
  1008. if (rs != 0xf0) break; // end block
  1009. k += 16;
  1010. } else {
  1011. k += r;
  1012. // decode into unzigzag'd location
  1013. data[dezigzag[k++]] = (short) extend_receive(j,s);
  1014. }
  1015. } while (k < 64);
  1016. return 1;
  1017. }
  1018. // take a -128..127 value and clamp it and convert to 0..255
  1019. stbi_inline static uint8 clamp(int x)
  1020. {
  1021. // trick to use a single test to catch both cases
  1022. if ((unsigned int) x > 255) {
  1023. if (x < 0) return 0;
  1024. if (x > 255) return 255;
  1025. }
  1026. return (uint8) x;
  1027. }
  1028. #define f2f(x) (int) (((x) * 4096 + 0.5))
  1029. #define fsh(x) ((x) << 12)
  1030. // derived from jidctint -- DCT_ISLOW
  1031. #define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
  1032. int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
  1033. p2 = s2; \
  1034. p3 = s6; \
  1035. p1 = (p2+p3) * f2f(0.5411961f); \
  1036. t2 = p1 + p3*f2f(-1.847759065f); \
  1037. t3 = p1 + p2*f2f( 0.765366865f); \
  1038. p2 = s0; \
  1039. p3 = s4; \
  1040. t0 = fsh(p2+p3); \
  1041. t1 = fsh(p2-p3); \
  1042. x0 = t0+t3; \
  1043. x3 = t0-t3; \
  1044. x1 = t1+t2; \
  1045. x2 = t1-t2; \
  1046. t0 = s7; \
  1047. t1 = s5; \
  1048. t2 = s3; \
  1049. t3 = s1; \
  1050. p3 = t0+t2; \
  1051. p4 = t1+t3; \
  1052. p1 = t0+t3; \
  1053. p2 = t1+t2; \
  1054. p5 = (p3+p4)*f2f( 1.175875602f); \
  1055. t0 = t0*f2f( 0.298631336f); \
  1056. t1 = t1*f2f( 2.053119869f); \
  1057. t2 = t2*f2f( 3.072711026f); \
  1058. t3 = t3*f2f( 1.501321110f); \
  1059. p1 = p5 + p1*f2f(-0.899976223f); \
  1060. p2 = p5 + p2*f2f(-2.562915447f); \
  1061. p3 = p3*f2f(-1.961570560f); \
  1062. p4 = p4*f2f(-0.390180644f); \
  1063. t3 += p1+p4; \
  1064. t2 += p2+p3; \
  1065. t1 += p2+p4; \
  1066. t0 += p1+p3;
  1067. #ifdef STBI_SIMD
  1068. typedef unsigned short stbi_dequantize_t;
  1069. #else
  1070. typedef uint8 stbi_dequantize_t;
  1071. #endif
  1072. // .344 seconds on 3*anemones.jpg
  1073. static void idct_block(uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)
  1074. {
  1075. int i,val[64],*v=val;
  1076. stbi_dequantize_t *dq = dequantize;
  1077. uint8 *o;
  1078. short *d = data;
  1079. // columns
  1080. for (i=0; i < 8; ++i,++d,++dq, ++v) {
  1081. // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
  1082. if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
  1083. && d[40]==0 && d[48]==0 && d[56]==0) {
  1084. // no shortcut 0 seconds
  1085. // (1|2|3|4|5|6|7)==0 0 seconds
  1086. // all separate -0.047 seconds
  1087. // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
  1088. int dcterm = d[0] * dq[0] << 2;
  1089. v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
  1090. } else {
  1091. IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
  1092. d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
  1093. // constants scaled things up by 1<<12; let's bring them back
  1094. // down, but keep 2 extra bits of precision
  1095. x0 += 512; x1 += 512; x2 += 512; x3 += 512;
  1096. v[ 0] = (x0+t3) >> 10;
  1097. v[56] = (x0-t3) >> 10;
  1098. v[ 8] = (x1+t2) >> 10;
  1099. v[48] = (x1-t2) >> 10;
  1100. v[16] = (x2+t1) >> 10;
  1101. v[40] = (x2-t1) >> 10;
  1102. v[24] = (x3+t0) >> 10;
  1103. v[32] = (x3-t0) >> 10;
  1104. }
  1105. }
  1106. for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
  1107. // no fast case since the first 1D IDCT spread components out
  1108. IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
  1109. // constants scaled things up by 1<<12, plus we had 1<<2 from first
  1110. // loop, plus horizontal and vertical each scale by sqrt(8) so together
  1111. // we've got an extra 1<<3, so 1<<17 total we need to remove.
  1112. // so we want to round that, which means adding 0.5 * 1<<17,
  1113. // aka 65536. Also, we'll end up with -128 to 127 that we want
  1114. // to encode as 0..255 by adding 128, so we'll add that before the shift
  1115. x0 += 65536 + (128<<17);
  1116. x1 += 65536 + (128<<17);
  1117. x2 += 65536 + (128<<17);
  1118. x3 += 65536 + (128<<17);
  1119. // tried computing the shifts into temps, or'ing the temps to see
  1120. // if any were out of range, but that was slower
  1121. o[0] = clamp((x0+t3) >> 17);
  1122. o[7] = clamp((x0-t3) >> 17);
  1123. o[1] = clamp((x1+t2) >> 17);
  1124. o[6] = clamp((x1-t2) >> 17);
  1125. o[2] = clamp((x2+t1) >> 17);
  1126. o[5] = clamp((x2-t1) >> 17);
  1127. o[3] = clamp((x3+t0) >> 17);
  1128. o[4] = clamp((x3-t0) >> 17);
  1129. }
  1130. }
  1131. #ifdef STBI_SIMD
  1132. static stbi_idct_8x8 stbi_idct_installed = idct_block;
  1133. void stbi_install_idct(stbi_idct_8x8 func)
  1134. {
  1135. stbi_idct_installed = func;
  1136. }
  1137. #endif
  1138. #define MARKER_none 0xff
  1139. // if there's a pending marker from the entropy stream, return that
  1140. // otherwise, fetch from the stream and get a marker. if there's no
  1141. // marker, return 0xff, which is never a valid marker value
  1142. static uint8 get_marker(jpeg *j)
  1143. {
  1144. uint8 x;
  1145. if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }
  1146. x = get8u(j->s);
  1147. if (x != 0xff) return MARKER_none;
  1148. while (x == 0xff)
  1149. x = get8u(j->s);
  1150. return x;
  1151. }
  1152. // in each scan, we'll have scan_n components, and the order
  1153. // of the components is specified by order[]
  1154. #define RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
  1155. // after a restart interval, reset the entropy decoder and
  1156. // the dc prediction
  1157. static void reset(jpeg *j)
  1158. {
  1159. j->code_bits = 0;
  1160. j->code_buffer = 0;
  1161. j->nomore = 0;
  1162. j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
  1163. j->marker = MARKER_none;
  1164. j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
  1165. // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
  1166. // since we don't even allow 1<<30 pixels
  1167. }
  1168. static int parse_entropy_coded_data(jpeg *z)
  1169. {
  1170. reset(z);
  1171. if (z->scan_n == 1) {
  1172. int i,j;
  1173. #ifdef STBI_SIMD
  1174. __declspec(align(16))
  1175. #endif
  1176. short data[64];
  1177. int n = z->order[0];
  1178. // non-interleaved data, we just need to process one block at a time,
  1179. // in trivial scanline order
  1180. // number of blocks to do just depends on how many actual "pixels" this
  1181. // component has, independent of interleaved MCU blocking and such
  1182. int w = (z->img_comp[n].x+7) >> 3;
  1183. int h = (z->img_comp[n].y+7) >> 3;
  1184. for (j=0; j < h; ++j) {
  1185. for (i=0; i < w; ++i) {
  1186. if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
  1187. #ifdef STBI_SIMD
  1188. 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]);
  1189. #else
  1190. 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]);
  1191. #endif
  1192. // every data block is an MCU, so countdown the restart interval
  1193. if (--z->todo <= 0) {
  1194. if (z->code_bits < 24) grow_buffer_unsafe(z);
  1195. // if it's NOT a restart, then just bail, so we get corrupt data
  1196. // rather than no data
  1197. if (!RESTART(z->marker)) return 1;
  1198. reset(z);
  1199. }
  1200. }
  1201. }
  1202. } else { // interleaved!
  1203. int i,j,k,x,y;
  1204. short data[64];
  1205. for (j=0; j < z->img_mcu_y; ++j) {
  1206. for (i=0; i < z->img_mcu_x; ++i) {
  1207. // scan an interleaved mcu... process scan_n components in order
  1208. for (k=0; k < z->scan_n; ++k) {
  1209. int n = z->order[k];
  1210. // scan out an mcu's worth of this component; that's just determined
  1211. // by the basic H and V specified for the component
  1212. for (y=0; y < z->img_comp[n].v; ++y) {
  1213. for (x=0; x < z->img_comp[n].h; ++x) {
  1214. int x2 = (i*z->img_comp[n].h + x)*8;
  1215. int y2 = (j*z->img_comp[n].v + y)*8;
  1216. if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
  1217. #ifdef STBI_SIMD
  1218. 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]);
  1219. #else
  1220. 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]);
  1221. #endif
  1222. }
  1223. }
  1224. }
  1225. // after all interleaved components, that's an interleaved MCU,
  1226. // so now count down the restart interval
  1227. if (--z->todo <= 0) {
  1228. if (z->code_bits < 24) grow_buffer_unsafe(z);
  1229. // if it's NOT a restart, then just bail, so we get corrupt data
  1230. // rather than no data
  1231. if (!RESTART(z->marker)) return 1;
  1232. reset(z);
  1233. }
  1234. }
  1235. }
  1236. }
  1237. return 1;
  1238. }
  1239. static int process_marker(jpeg *z, int m)
  1240. {
  1241. int L;
  1242. switch (m) {
  1243. case MARKER_none: // no marker found
  1244. return e("expected marker","Corrupt JPEG");
  1245. case 0xC2: // SOF - progressive
  1246. return e("progressive jpeg","JPEG format not supported (progressive)");
  1247. case 0xDD: // DRI - specify restart interval
  1248. if (get16(z->s) != 4) return e("bad DRI len","Corrupt JPEG");
  1249. z->restart_interval = get16(z->s);
  1250. return 1;
  1251. case 0xDB: // DQT - define quantization table
  1252. L = get16(z->s)-2;
  1253. while (L > 0) {
  1254. int q = get8(z->s);
  1255. int p = q >> 4;
  1256. int t = q & 15,i;
  1257. if (p != 0) return e("bad DQT type","Corrupt JPEG");
  1258. if (t > 3) return e("bad DQT table","Corrupt JPEG");
  1259. for (i=0; i < 64; ++i)
  1260. z->dequant[t][dezigzag[i]] = get8u(z->s);
  1261. #ifdef STBI_SIMD
  1262. for (i=0; i < 64; ++i)
  1263. z->dequant2[t][i] = z->dequant[t][i];
  1264. #endif
  1265. L -= 65;
  1266. }
  1267. return L==0;
  1268. case 0xC4: // DHT - define huffman table
  1269. L = get16(z->s)-2;
  1270. while (L > 0) {
  1271. uint8 *v;
  1272. int sizes[16],i,m=0;
  1273. int q = get8(z->s);
  1274. int tc = q >> 4;
  1275. int th = q & 15;
  1276. if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");
  1277. for (i=0; i < 16; ++i) {
  1278. sizes[i] = get8(z->s);
  1279. m += sizes[i];
  1280. }
  1281. L -= 17;
  1282. if (tc == 0) {
  1283. if (!build_huffman(z->huff_dc+th, sizes)) return 0;
  1284. v = z->huff_dc[th].values;
  1285. } else {
  1286. if (!build_huffman(z->huff_ac+th, sizes)) return 0;
  1287. v = z->huff_ac[th].values;
  1288. }
  1289. for (i=0; i < m; ++i)
  1290. v[i] = get8u(z->s);
  1291. L -= m;
  1292. }
  1293. return L==0;
  1294. }
  1295. // check for comment block or APP blocks
  1296. if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
  1297. skip(z->s, get16(z->s)-2);
  1298. return 1;
  1299. }
  1300. return 0;
  1301. }
  1302. // after we see SOS
  1303. static int process_scan_header(jpeg *z)
  1304. {
  1305. int i;
  1306. int Ls = get16(z->s);
  1307. z->scan_n = get8(z->s);
  1308. 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");
  1309. if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG");
  1310. for (i=0; i < z->scan_n; ++i) {
  1311. int id = get8(z->s), which;
  1312. int q = get8(z->s);
  1313. for (which = 0; which < z->s->img_n; ++which)
  1314. if (z->img_comp[which].id == id)
  1315. break;
  1316. if (which == z->s->img_n) return 0;
  1317. z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");
  1318. z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");
  1319. z->order[i] = which;
  1320. }
  1321. if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG");
  1322. get8(z->s); // should be 63, but might be 0
  1323. if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG");
  1324. return 1;
  1325. }
  1326. static int process_frame_header(jpeg *z, int scan)
  1327. {
  1328. stbi *s = z->s;
  1329. int Lf,p,i,q, h_max=1,v_max=1,c;
  1330. Lf = get16(s); if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG
  1331. p = get8(s); if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
  1332. 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 IJG
  1333. s->img_x = get16(s); if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires
  1334. c = get8(s);
  1335. if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG"); // JFIF requires
  1336. s->img_n = c;
  1337. for (i=0; i < c; ++i) {
  1338. z->img_comp[i].data = NULL;
  1339. z->img_comp[i].linebuf = NULL;
  1340. }
  1341. if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG");
  1342. for (i=0; i < s->img_n; ++i) {
  1343. z->img_comp[i].id = get8(s);
  1344. if (z->img_comp[i].id != i+1) // JFIF requires
  1345. if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!
  1346. return e("bad component ID","Corrupt JPEG");
  1347. q = get8(s);
  1348. 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");
  1349. 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");
  1350. z->img_comp[i].tq = get8(s); if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");
  1351. }
  1352. if (scan != SCAN_load) return 1;
  1353. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");
  1354. for (i=0; i < s->img_n; ++i) {
  1355. if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
  1356. if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
  1357. }
  1358. // compute interleaved mcu info
  1359. z->img_h_max = h_max;
  1360. z->img_v_max = v_max;
  1361. z->img_mcu_w = h_max * 8;
  1362. z->img_mcu_h = v_max * 8;
  1363. z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
  1364. z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
  1365. for (i=0; i < s->img_n; ++i) {
  1366. // number of effective pixels (e.g. for non-interleaved MCU)
  1367. z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
  1368. z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
  1369. // to simplify generation, we'll allocate enough memory to decode
  1370. // the bogus oversized data from using interleaved MCUs and their
  1371. // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
  1372. // discard the extra data until colorspace conversion
  1373. z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
  1374. z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
  1375. z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
  1376. if (z->img_comp[i].raw_data == NULL) {
  1377. for(--i; i >= 0; --i) {
  1378. free(z->img_comp[i].raw_data);
  1379. z->img_comp[i].data = NULL;
  1380. }
  1381. return e("outofmem", "Out of memory");
  1382. }
  1383. // align blocks for installable-idct using mmx/sse
  1384. z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
  1385. z->img_comp[i].linebuf = NULL;
  1386. }
  1387. return 1;
  1388. }
  1389. // use comparisons since in some cases we handle more than one case (e.g. SOF)
  1390. #define DNL(x) ((x) == 0xdc)
  1391. #define SOI(x) ((x) == 0xd8)
  1392. #define EOI(x) ((x) == 0xd9)
  1393. #define SOF(x) ((x) == 0xc0 || (x) == 0xc1)
  1394. #define SOS(x) ((x) == 0xda)
  1395. static int decode_jpeg_header(jpeg *z, int scan)
  1396. {
  1397. int m;
  1398. z->marker = MARKER_none; // initialize cached marker to empty
  1399. m = get_marker(z);
  1400. if (!SOI(m)) return e("no SOI","Corrupt JPEG");
  1401. if (scan == SCAN_type) return 1;
  1402. m = get_marker(z);
  1403. while (!SOF(m)) {
  1404. if (!process_marker(z,m)) return 0;
  1405. m = get_marker(z);
  1406. while (m == MARKER_none) {
  1407. // some files have extra padding after their blocks, so ok, we'll scan
  1408. if (at_eof(z->s)) return e("no SOF", "Corrupt JPEG");
  1409. m = get_marker(z);
  1410. }
  1411. }
  1412. if (!process_frame_header(z, scan)) return 0;
  1413. return 1;
  1414. }
  1415. static int decode_jpeg_image(jpeg *j)
  1416. {
  1417. int m;
  1418. j->restart_interval = 0;
  1419. if (!decode_jpeg_header(j, SCAN_load)) return 0;
  1420. m = get_marker(j);
  1421. while (!EOI(m)) {
  1422. if (SOS(m)) {
  1423. if (!process_scan_header(j)) return 0;
  1424. if (!parse_entropy_coded_data(j)) return 0;
  1425. if (j->marker == MARKER_none ) {
  1426. // handle 0s at the end of image data from IP Kamera 9060
  1427. while (!at_eof(j->s)) {
  1428. int x = get8(j->s);
  1429. if (x == 255) {
  1430. j->marker = get8u(j->s);
  1431. break;
  1432. } else if (x != 0) {
  1433. return 0;
  1434. }
  1435. }
  1436. // if we reach eof without hitting a marker, get_marker() below will fail and we'll eventually return 0
  1437. }
  1438. } else {
  1439. if (!process_marker(j, m)) return 0;
  1440. }
  1441. m = get_marker(j);
  1442. }
  1443. return 1;
  1444. }
  1445. // static jfif-centered resampling (across block boundaries)
  1446. typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,
  1447. int w, int hs);
  1448. #define div4(x) ((uint8) ((x) >> 2))
  1449. static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
  1450. {
  1451. STBI_NOTUSED(out);
  1452. STBI_NOTUSED(in_far);
  1453. STBI_NOTUSED(w);
  1454. STBI_NOTUSED(hs);
  1455. return in_near;
  1456. }
  1457. static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
  1458. {
  1459. // need to generate two samples vertically for every one in input
  1460. int i;
  1461. STBI_NOTUSED(hs);
  1462. for (i=0; i < w; ++i)
  1463. out[i] = div4(3*in_near[i] + in_far[i] + 2);
  1464. return out;
  1465. }
  1466. static uint8* resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
  1467. {
  1468. // need to generate two samples horizontally for every one in input
  1469. int i;
  1470. uint8 *input = in_near;
  1471. if (w == 1) {
  1472. // if only one sample, can't do any interpolation
  1473. out[0] = out[1] = input[0];
  1474. return out;
  1475. }
  1476. out[0] = input[0];
  1477. out[1] = div4(input[0]*3 + input[1] + 2);
  1478. for (i=1; i < w-1; ++i) {
  1479. int n = 3*input[i]+2;
  1480. out[i*2+0] = div4(n+input[i-1]);
  1481. out[i*2+1] = div4(n+input[i+1]);
  1482. }
  1483. out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2);
  1484. out[i*2+1] = input[w-1];
  1485. STBI_NOTUSED(in_far);
  1486. STBI_NOTUSED(hs);
  1487. return out;
  1488. }
  1489. #define div16(x) ((uint8) ((x) >> 4))
  1490. static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
  1491. {
  1492. // need to generate 2x2 samples for every one in input
  1493. int i,t0,t1;
  1494. if (w == 1) {
  1495. out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2);
  1496. return out;
  1497. }
  1498. t1 = 3*in_near[0] + in_far[0];
  1499. out[0] = div4(t1+2);
  1500. for (i=1; i < w; ++i) {
  1501. t0 = t1;
  1502. t1 = 3*in_near[i]+in_far[i];
  1503. out[i*2-1] = div16(3*t0 + t1 + 8);
  1504. out[i*2 ] = div16(3*t1 + t0 + 8);
  1505. }
  1506. out[w*2-1] = div4(t1+2);
  1507. STBI_NOTUSED(hs);
  1508. return out;
  1509. }
  1510. static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
  1511. {
  1512. // resample with nearest-neighbor
  1513. int i,j;
  1514. STBI_NOTUSED(in_far);
  1515. for (i=0; i < w; ++i)
  1516. for (j=0; j < hs; ++j)
  1517. out[i*hs+j] = in_near[i];
  1518. return out;
  1519. }
  1520. #define float2fixed(x) ((int) ((x) * 65536 + 0.5))
  1521. // 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro)
  1522. // VC6 without processor=Pro is generating multiple LEAs per multiply!
  1523. static void YCbCr_to_RGB_row(uint8 *out, const uint8 *y, const uint8 *pcb, const uint8 *pcr, int count, int step)
  1524. {
  1525. int i;
  1526. for (i=0; i < count; ++i) {
  1527. int y_fixed = (y[i] << 16) + 32768; // rounding
  1528. int r,g,b;
  1529. int cr = pcr[i] - 128;
  1530. int cb = pcb[i] - 128;
  1531. r = y_fixed + cr*float2fixed(1.40200f);
  1532. g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
  1533. b = y_fixed + cb*float2fixed(1.77200f);
  1534. r >>= 16;
  1535. g >>= 16;
  1536. b >>= 16;
  1537. if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
  1538. if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
  1539. if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
  1540. out[0] = (uint8)r;
  1541. out[1] = (uint8)g;
  1542. out[2] = (uint8)b;
  1543. out[3] = 255;
  1544. out += step;
  1545. }
  1546. }
  1547. #ifdef STBI_SIMD
  1548. static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;
  1549. void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
  1550. {
  1551. stbi_YCbCr_installed = func;
  1552. }
  1553. #endif
  1554. // clean up the temporary component buffers
  1555. static void cleanup_jpeg(jpeg *j)
  1556. {
  1557. int i;
  1558. for (i=0; i < j->s->img_n; ++i) {
  1559. if (j->img_comp[i].data) {
  1560. free(j->img_comp[i].raw_data);
  1561. j->img_comp[i].data = NULL;
  1562. }
  1563. if (j->img_comp[i].linebuf) {
  1564. free(j->img_comp[i].linebuf);
  1565. j->img_comp[i].linebuf = NULL;
  1566. }
  1567. }
  1568. }
  1569. typedef struct
  1570. {
  1571. resample_row_func resample;
  1572. uint8 *line0,*line1;
  1573. int hs,vs; // expansion factor in each axis
  1574. int w_lores; // horizontal pixels pre-expansion
  1575. int ystep; // how far through vertical expansion we are
  1576. int ypos; // which pre-expansion row we're on
  1577. } stbi_resample;
  1578. static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
  1579. {
  1580. int n, decode_n;
  1581. // validate req_comp
  1582. if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
  1583. z->s->img_n = 0;
  1584. // load a jpeg image from whichever source
  1585. if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }
  1586. // determine actual number of components to generate
  1587. n = req_comp ? req_comp : z->s->img_n;
  1588. if (z->s->img_n == 3 && n < 3)
  1589. decode_n = 1;
  1590. else
  1591. decode_n = z->s->img_n;
  1592. // resample and color-convert
  1593. {
  1594. int k;
  1595. uint i,j;
  1596. uint8 *output;
  1597. uint8 *coutput[4];
  1598. stbi_resample res_comp[4];
  1599. for (k=0; k < decode_n; ++k) {
  1600. stbi_resample *r = &res_comp[k];
  1601. // allocate line buffer big enough for upsampling off the edges
  1602. // with upsample factor of 4
  1603. z->img_comp[k].linebuf = (uint8 *) malloc(z->s->img_x + 3);
  1604. if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
  1605. r->hs = z->img_h_max / z->img_comp[k].h;
  1606. r->vs = z->img_v_max / z->img_comp[k].v;
  1607. r->ystep = r->vs >> 1;
  1608. r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
  1609. r->ypos = 0;
  1610. r->line0 = r->line1 = z->img_comp[k].data;
  1611. if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
  1612. else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;
  1613. else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;
  1614. else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;
  1615. else r->resample = resample_row_generic;
  1616. }
  1617. // can't error after this so, this is safe
  1618. output = (uint8 *) malloc(n * z->s->img_x * z->s->img_y + 1);
  1619. if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
  1620. // now go ahead and resample
  1621. for (j=0; j < z->s->img_y; ++j) {
  1622. uint8 *out = output + n * z->s->img_x * j;
  1623. for (k=0; k < decode_n; ++k) {
  1624. stbi_resample *r = &res_comp[k];
  1625. int y_bot = r->ystep >= (r->vs >> 1);
  1626. coutput[k] = r->resample(z->img_comp[k].linebuf,
  1627. y_bot ? r->line1 : r->line0,
  1628. y_bot ? r->line0 : r->line1,
  1629. r->w_lores, r->hs);
  1630. if (++r->ystep >= r->vs) {
  1631. r->ystep = 0;
  1632. r->line0 = r->line1;
  1633. if (++r->ypos < z->img_comp[k].y)
  1634. r->line1 += z->img_comp[k].w2;
  1635. }
  1636. }
  1637. if (n >= 3) {
  1638. uint8 *y = coutput[0];
  1639. if (z->s->img_n == 3) {
  1640. #ifdef STBI_SIMD
  1641. stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n);
  1642. #else
  1643. YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);
  1644. #endif
  1645. } else
  1646. for (i=0; i < z->s->img_x; ++i) {
  1647. out[0] = out[1] = out[2] = y[i];
  1648. out[3] = 255; // not used if n==3
  1649. out += n;
  1650. }
  1651. } else {
  1652. uint8 *y = coutput[0];
  1653. if (n == 1)
  1654. for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
  1655. else
  1656. for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;
  1657. }
  1658. }
  1659. cleanup_jpeg(z);
  1660. *out_x = z->s->img_x;
  1661. *out_y = z->s->img_y;
  1662. if (comp) *comp = z->s->img_n; // report original components, not output
  1663. return output;
  1664. }
  1665. }
  1666. static unsigned char *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  1667. {
  1668. jpeg j;
  1669. j.s = s;
  1670. return load_jpeg_image(&j, x,y,comp,req_comp);
  1671. }
  1672. static int stbi_jpeg_test(stbi *s)
  1673. {
  1674. int r;
  1675. jpeg j;
  1676. j.s = s;
  1677. r = decode_jpeg_header(&j, SCAN_type);
  1678. stbi_rewind(s);
  1679. return r;
  1680. }
  1681. static int stbi_jpeg_info_raw(jpeg *j, int *x, int *y, int *comp)
  1682. {
  1683. if (!decode_jpeg_header(j, SCAN_header)) {
  1684. stbi_rewind( j->s );
  1685. return 0;
  1686. }
  1687. if (x) *x = j->s->img_x;
  1688. if (y) *y = j->s->img_y;
  1689. if (comp) *comp = j->s->img_n;
  1690. return 1;
  1691. }
  1692. static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp)
  1693. {
  1694. jpeg j;
  1695. j.s = s;
  1696. return stbi_jpeg_info_raw(&j, x, y, comp);
  1697. }
  1698. // public domain zlib decode v0.2 Sean Barrett 2006-11-18
  1699. // simple implementation
  1700. // - all input must be provided in an upfront buffer
  1701. // - all output is written to a single output buffer (can malloc/realloc)
  1702. // performance
  1703. // - fast huffman
  1704. // fast-way is faster to check than jpeg huffman, but slow way is slower
  1705. #define ZFAST_BITS 9 // accelerate all cases in default tables
  1706. #define ZFAST_MASK ((1 << ZFAST_BITS) - 1)
  1707. // zlib-style huffman encoding
  1708. // (jpegs packs from left, zlib from right, so can't share code)
  1709. typedef struct
  1710. {
  1711. uint16 fast[1 << ZFAST_BITS];
  1712. uint16 firstcode[16];
  1713. int maxcode[17];
  1714. uint16 firstsymbol[16];
  1715. uint8 size[288];
  1716. uint16 value[288];
  1717. } zhuffman;
  1718. stbi_inline static int bitreverse16(int n)
  1719. {
  1720. n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
  1721. n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
  1722. n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
  1723. n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
  1724. return n;
  1725. }
  1726. stbi_inline static int bit_reverse(int v, int bits)
  1727. {
  1728. assert(bits <= 16);
  1729. // to bit reverse n bits, reverse 16 and shift
  1730. // e.g. 11 bits, bit reverse and shift away 5
  1731. return bitreverse16(v) >> (16-bits);
  1732. }
  1733. static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)
  1734. {
  1735. int i,k=0;
  1736. int code, next_code[16], sizes[17];
  1737. // DEFLATE spec for generating codes
  1738. memset(sizes, 0, sizeof(sizes));
  1739. memset(z->fast, 255, sizeof(z->fast));
  1740. for (i=0; i < num; ++i)
  1741. ++sizes[sizelist[i]];
  1742. sizes[0] = 0;
  1743. for (i=1; i < 16; ++i)
  1744. assert(sizes[i] <= (1 << i));
  1745. code = 0;
  1746. for (i=1; i < 16; ++i) {
  1747. next_code[i] = code;
  1748. z->firstcode[i] = (uint16) code;
  1749. z->firstsymbol[i] = (uint16) k;
  1750. code = (code + sizes[i]);
  1751. if (sizes[i])
  1752. if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");
  1753. z->maxcode[i] = code << (16-i); // preshift for inner loop
  1754. code <<= 1;
  1755. k += sizes[i];
  1756. }
  1757. z->maxcode[16] = 0x10000; // sentinel
  1758. for (i=0; i < num; ++i) {
  1759. int s = sizelist[i];
  1760. if (s) {
  1761. int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
  1762. z->size[c] = (uint8)s;
  1763. z->value[c] = (uint16)i;
  1764. if (s <= ZFAST_BITS) {
  1765. int k = bit_reverse(next_code[s],s);
  1766. while (k < (1 << ZFAST_BITS)) {
  1767. z->fast[k] = (uint16) c;
  1768. k += (1 << s);
  1769. }
  1770. }
  1771. ++next_code[s];
  1772. }
  1773. }
  1774. return 1;
  1775. }
  1776. // zlib-from-memory implementation for PNG reading
  1777. // because PNG allows splitting the zlib stream arbitrarily,
  1778. // and it's annoying structurally to have PNG call ZLIB call PNG,
  1779. // we require PNG read all the IDATs and combine them into a single
  1780. // memory buffer
  1781. typedef struct
  1782. {
  1783. uint8 *zbuffer, *zbuffer_end;
  1784. int num_bits;
  1785. uint32 code_buffer;
  1786. char *zout;
  1787. char *zout_start;
  1788. char *zout_end;
  1789. int z_expandable;
  1790. zhuffman z_length, z_distance;
  1791. } zbuf;
  1792. stbi_inline static int zget8(zbuf *z)
  1793. {
  1794. if (z->zbuffer >= z->zbuffer_end) return 0;
  1795. return *z->zbuffer++;
  1796. }
  1797. static void fill_bits(zbuf *z)
  1798. {
  1799. do {
  1800. assert(z->code_buffer < (1U << z->num_bits));
  1801. z->code_buffer |= zget8(z) << z->num_bits;
  1802. z->num_bits += 8;
  1803. } while (z->num_bits <= 24);
  1804. }
  1805. stbi_inline static unsigned int zreceive(zbuf *z, int n)
  1806. {
  1807. unsigned int k;
  1808. if (z->num_bits < n) fill_bits(z);
  1809. k = z->code_buffer & ((1 << n) - 1);
  1810. z->code_buffer >>= n;
  1811. z->num_bits -= n;
  1812. return k;
  1813. }
  1814. stbi_inline static int zhuffman_decode(zbuf *a, zhuffman *z)
  1815. {
  1816. int b,s,k;
  1817. if (a->num_bits < 16) fill_bits(a);
  1818. b = z->fast[a->code_buffer & ZFAST_MASK];
  1819. if (b < 0xffff) {
  1820. s = z->size[b];
  1821. a->code_buffer >>= s;
  1822. a->num_bits -= s;
  1823. return z->value[b];
  1824. }
  1825. // not resolved by fast table, so compute it the slow way
  1826. // use jpeg approach, which requires MSbits at top
  1827. k = bit_reverse(a->code_buffer, 16);
  1828. for (s=ZFAST_BITS+1; ; ++s)
  1829. if (k < z->maxcode[s])
  1830. break;
  1831. if (s == 16) return -1; // invalid code!
  1832. // code size is s, so:
  1833. b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
  1834. assert(z->size[b] == s);
  1835. a->code_buffer >>= s;
  1836. a->num_bits -= s;
  1837. return z->value[b];
  1838. }
  1839. static int expand(zbuf *z, int n) // need to make room for n bytes
  1840. {
  1841. char *q;
  1842. int cur, limit;
  1843. if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");
  1844. cur = (int) (z->zout - z->zout_start);
  1845. limit = (int) (z->zout_end - z->zout_start);
  1846. while (cur + n > limit)
  1847. limit *= 2;
  1848. q = (char *) realloc(z->zout_start, limit);
  1849. if (q == NULL) return e("outofmem", "Out of memory");
  1850. z->zout_start = q;
  1851. z->zout = q + cur;
  1852. z->zout_end = q + limit;
  1853. return 1;
  1854. }
  1855. static int length_base[31] = {
  1856. 3,4,5,6,7,8,9,10,11,13,
  1857. 15,17,19,23,27,31,35,43,51,59,
  1858. 67,83,99,115,131,163,195,227,258,0,0 };
  1859. static int length_extra[31]=
  1860. { 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 };
  1861. static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
  1862. 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
  1863. static int dist_extra[32] =
  1864. { 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};
  1865. static int parse_huffman_block(zbuf *a)
  1866. {
  1867. for(;;) {
  1868. int z = zhuffman_decode(a, &a->z_length);
  1869. if (z < 256) {
  1870. if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes
  1871. if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;
  1872. *a->zout++ = (char) z;
  1873. } else {
  1874. uint8 *p;
  1875. int len,dist;
  1876. if (z == 256) return 1;
  1877. z -= 257;
  1878. len = length_base[z];
  1879. if (length_extra[z]) len += zreceive(a, length_extra[z]);
  1880. z = zhuffman_decode(a, &a->z_distance);
  1881. if (z < 0) return e("bad huffman code","Corrupt PNG");
  1882. dist = dist_base[z];
  1883. if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);
  1884. if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");
  1885. if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;
  1886. p = (uint8 *) (a->zout - dist);
  1887. while (len--)
  1888. *a->zout++ = *p++;
  1889. }
  1890. }
  1891. }
  1892. static int compute_huffman_codes(zbuf *a)
  1893. {
  1894. static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
  1895. zhuffman z_codelength;
  1896. uint8 lencodes[286+32+137];//padding for maximum single op
  1897. uint8 codelength_sizes[19];
  1898. int i,n;
  1899. int hlit = zreceive(a,5) + 257;
  1900. int hdist = zreceive(a,5) + 1;
  1901. int hclen = zreceive(a,4) + 4;
  1902. memset(codelength_sizes, 0, sizeof(codelength_sizes));
  1903. for (i=0; i < hclen; ++i) {
  1904. int s = zreceive(a,3);
  1905. codelength_sizes[length_dezigzag[i]] = (uint8) s;
  1906. }
  1907. if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
  1908. n = 0;
  1909. while (n < hlit + hdist) {
  1910. int c = zhuffman_decode(a, &z_codelength);
  1911. assert(c >= 0 && c < 19);
  1912. if (c < 16)
  1913. lencodes[n++] = (uint8) c;
  1914. else if (c == 16) {
  1915. c = zreceive(a,2)+3;
  1916. memset(lencodes+n, lencodes[n-1], c);
  1917. n += c;
  1918. } else if (c == 17) {
  1919. c = zreceive(a,3)+3;
  1920. memset(lencodes+n, 0, c);
  1921. n += c;
  1922. } else {
  1923. assert(c == 18);
  1924. c = zreceive(a,7)+11;
  1925. memset(lencodes+n, 0, c);
  1926. n += c;
  1927. }
  1928. }
  1929. if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");
  1930. if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
  1931. if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
  1932. return 1;
  1933. }
  1934. static int parse_uncompressed_block(zbuf *a)
  1935. {
  1936. uint8 header[4];
  1937. int len,nlen,k;
  1938. if (a->num_bits & 7)
  1939. zreceive(a, a->num_bits & 7); // discard
  1940. // drain the bit-packed data into header
  1941. k = 0;
  1942. while (a->num_bits > 0) {
  1943. header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns?
  1944. a->code_buffer >>= 8;
  1945. a->num_bits -= 8;
  1946. }
  1947. assert(a->num_bits == 0);
  1948. // now fill header the normal way
  1949. while (k < 4)
  1950. header[k++] = (uint8) zget8(a);
  1951. len = header[1] * 256 + header[0];
  1952. nlen = header[3] * 256 + header[2];
  1953. if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");
  1954. if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");
  1955. if (a->zout + len > a->zout_end)
  1956. if (!expand(a, len)) return 0;
  1957. memcpy(a->zout, a->zbuffer, len);
  1958. a->zbuffer += len;
  1959. a->zout += len;
  1960. return 1;
  1961. }
  1962. static int parse_zlib_header(zbuf *a)
  1963. {
  1964. int cmf = zget8(a);
  1965. int cm = cmf & 15;
  1966. /* int cinfo = cmf >> 4; */
  1967. int flg = zget8(a);
  1968. if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec
  1969. if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
  1970. if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png
  1971. // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
  1972. return 1;
  1973. }
  1974. // @TODO: should statically initialize these for optimal thread safety
  1975. static uint8 default_length[288], default_distance[32];
  1976. static void init_defaults(void)
  1977. {
  1978. int i; // use <= to match clearly with spec
  1979. for (i=0; i <= 143; ++i) default_length[i] = 8;
  1980. for ( ; i <= 255; ++i) default_length[i] = 9;
  1981. for ( ; i <= 279; ++i) default_length[i] = 7;
  1982. for ( ; i <= 287; ++i) default_length[i] = 8;
  1983. for (i=0; i <= 31; ++i) default_distance[i] = 5;
  1984. }
  1985. int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead
  1986. static int parse_zlib(zbuf *a, int parse_header)
  1987. {
  1988. int final, type;
  1989. if (parse_header)
  1990. if (!parse_zlib_header(a)) return 0;
  1991. a->num_bits = 0;
  1992. a->code_buffer = 0;
  1993. do {
  1994. final = zreceive(a,1);
  1995. type = zreceive(a,2);
  1996. if (type == 0) {
  1997. if (!parse_uncompressed_block(a)) return 0;
  1998. } else if (type == 3) {
  1999. return 0;
  2000. } else {
  2001. if (type == 1) {
  2002. // use fixed code lengths
  2003. if (!default_distance[31]) init_defaults();
  2004. if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0;
  2005. if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0;
  2006. } else {
  2007. if (!compute_huffman_codes(a)) return 0;
  2008. }
  2009. if (!parse_huffman_block(a)) return 0;
  2010. }
  2011. if (stbi_png_partial && a->zout - a->zout_start > 65536)
  2012. break;
  2013. } while (!final);
  2014. return 1;
  2015. }
  2016. static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)
  2017. {
  2018. a->zout_start = obuf;
  2019. a->zout = obuf;
  2020. a->zout_end = obuf + olen;
  2021. a->z_expandable = exp;
  2022. return parse_zlib(a, parse_header);
  2023. }
  2024. char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
  2025. {
  2026. zbuf a;
  2027. char *p = (char *) malloc(initial_size);
  2028. if (p == NULL) return NULL;
  2029. a.zbuffer = (uint8 *) buffer;
  2030. a.zbuffer_end = (uint8 *) buffer + len;
  2031. if (do_zlib(&a, p, initial_size, 1, 1)) {
  2032. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  2033. return a.zout_start;
  2034. } else {
  2035. free(a.zout_start);
  2036. return NULL;
  2037. }
  2038. }
  2039. char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
  2040. {
  2041. return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
  2042. }
  2043. char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
  2044. {
  2045. zbuf a;
  2046. char *p = (char *) malloc(initial_size);
  2047. if (p == NULL) return NULL;
  2048. a.zbuffer = (uint8 *) buffer;
  2049. a.zbuffer_end = (uint8 *) buffer + len;
  2050. if (do_zlib(&a, p, initial_size, 1, parse_header)) {
  2051. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  2052. return a.zout_start;
  2053. } else {
  2054. free(a.zout_start);
  2055. return NULL;
  2056. }
  2057. }
  2058. int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
  2059. {
  2060. zbuf a;
  2061. a.zbuffer = (uint8 *) ibuffer;
  2062. a.zbuffer_end = (uint8 *) ibuffer + ilen;
  2063. if (do_zlib(&a, obuffer, olen, 0, 1))
  2064. return (int) (a.zout - a.zout_start);
  2065. else
  2066. return -1;
  2067. }
  2068. char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
  2069. {
  2070. zbuf a;
  2071. char *p = (char *) malloc(16384);
  2072. if (p == NULL) return NULL;
  2073. a.zbuffer = (uint8 *) buffer;
  2074. a.zbuffer_end = (uint8 *) buffer+len;
  2075. if (do_zlib(&a, p, 16384, 1, 0)) {
  2076. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  2077. return a.zout_start;
  2078. } else {
  2079. free(a.zout_start);
  2080. return NULL;
  2081. }
  2082. }
  2083. int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
  2084. {
  2085. zbuf a;
  2086. a.zbuffer = (uint8 *) ibuffer;
  2087. a.zbuffer_end = (uint8 *) ibuffer + ilen;
  2088. if (do_zlib(&a, obuffer, olen, 0, 0))
  2089. return (int) (a.zout - a.zout_start);
  2090. else
  2091. return -1;
  2092. }
  2093. // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
  2094. // simple implementation
  2095. // - only 8-bit samples
  2096. // - no CRC checking
  2097. // - allocates lots of intermediate memory
  2098. // - avoids problem of streaming data between subsystems
  2099. // - avoids explicit window management
  2100. // performance
  2101. // - uses stb_zlib, a PD zlib implementation with fast huffman decoding
  2102. typedef struct
  2103. {
  2104. uint32 length;
  2105. uint32 type;
  2106. } chunk;
  2107. #define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
  2108. static chunk get_chunk_header(stbi *s)
  2109. {
  2110. chunk c;
  2111. c.length = get32(s);
  2112. c.type = get32(s);
  2113. return c;
  2114. }
  2115. static int check_png_header(stbi *s)
  2116. {
  2117. static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };
  2118. int i;
  2119. for (i=0; i < 8; ++i)
  2120. if (get8u(s) != png_sig[i]) return e("bad png sig","Not a PNG");
  2121. return 1;
  2122. }
  2123. typedef struct
  2124. {
  2125. stbi *s;
  2126. uint8 *idata, *expanded, *out;
  2127. } png;
  2128. enum {
  2129. F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,
  2130. F_avg_first, F_paeth_first
  2131. };
  2132. static uint8 first_row_filter[5] =
  2133. {
  2134. F_none, F_sub, F_none, F_avg_first, F_paeth_first
  2135. };
  2136. static int paeth(int a, int b, int c)
  2137. {
  2138. int p = a + b - c;
  2139. int pa = abs(p-a);
  2140. int pb = abs(p-b);
  2141. int pc = abs(p-c);
  2142. if (pa <= pb && pa <= pc) return a;
  2143. if (pb <= pc) return b;
  2144. return c;
  2145. }
  2146. // create the png data from post-deflated data
  2147. static int create_png_image_raw(png *a, uint8 *raw, uint32 raw_len, int out_n, uint32 x, uint32 y)
  2148. {
  2149. stbi *s = a->s;
  2150. uint32 i,j,stride = x*out_n;
  2151. int k;
  2152. int img_n = s->img_n; // copy it into a local for later
  2153. assert(out_n == s->img_n || out_n == s->img_n+1);
  2154. if (stbi_png_partial) y = 1;
  2155. a->out = (uint8 *) malloc(x * y * out_n);
  2156. if (!a->out) return e("outofmem", "Out of memory");
  2157. if (!stbi_png_partial) {
  2158. if (s->img_x == x && s->img_y == y) {
  2159. if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
  2160. } else { // interlaced:
  2161. if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
  2162. }
  2163. }
  2164. for (j=0; j < y; ++j) {
  2165. uint8 *cur = a->out + stride*j;
  2166. uint8 *prior = cur - stride;
  2167. int filter = *raw++;
  2168. if (filter > 4) return e("invalid filter","Corrupt PNG");
  2169. // if first row, use special filter that doesn't sample previous row
  2170. if (j == 0) filter = first_row_filter[filter];
  2171. // handle first pixel explicitly
  2172. for (k=0; k < img_n; ++k) {
  2173. switch (filter) {
  2174. case F_none : cur[k] = raw[k]; break;
  2175. case F_sub : cur[k] = raw[k]; break;
  2176. case F_up : cur[k] = raw[k] + prior[k]; break;
  2177. case F_avg : cur[k] = raw[k] + (prior[k]>>1); break;
  2178. case F_paeth : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;
  2179. case F_avg_first : cur[k] = raw[k]; break;
  2180. case F_paeth_first: cur[k] = raw[k]; break;
  2181. }
  2182. }
  2183. if (img_n != out_n) cur[img_n] = 255;
  2184. raw += img_n;
  2185. cur += out_n;
  2186. prior += out_n;
  2187. // this is a little gross, so that we don't switch per-pixel or per-component
  2188. if (img_n == out_n) {
  2189. #define CASE(f) \
  2190. case f: \
  2191. for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \
  2192. for (k=0; k < img_n; ++k)
  2193. switch (filter) {
  2194. CASE(F_none) cur[k] = raw[k]; break;
  2195. CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break;
  2196. CASE(F_up) cur[k] = raw[k] + prior[k]; break;
  2197. CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;
  2198. CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
  2199. CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;
  2200. CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;
  2201. }
  2202. #undef CASE
  2203. } else {
  2204. assert(img_n+1 == out_n);
  2205. #define CASE(f) \
  2206. case f: \
  2207. for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
  2208. for (k=0; k < img_n; ++k)
  2209. switch (filter) {
  2210. CASE(F_none) cur[k] = raw[k]; break;
  2211. CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break;
  2212. CASE(F_up) cur[k] = raw[k] + prior[k]; break;
  2213. CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;
  2214. CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
  2215. CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;
  2216. CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;
  2217. }
  2218. #undef CASE
  2219. }
  2220. }
  2221. return 1;
  2222. }
  2223. static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n, int interlaced)
  2224. {
  2225. uint8 *final;
  2226. int p;
  2227. int save;
  2228. if (!interlaced)
  2229. return create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);
  2230. save = stbi_png_partial;
  2231. stbi_png_partial = 0;
  2232. // de-interlacing
  2233. final = (uint8 *) malloc(a->s->img_x * a->s->img_y * out_n);
  2234. for (p=0; p < 7; ++p) {
  2235. int xorig[] = { 0,4,0,2,0,1,0 };
  2236. int yorig[] = { 0,0,4,0,2,0,1 };
  2237. int xspc[] = { 8,8,4,4,2,2,1 };
  2238. int yspc[] = { 8,8,8,4,4,2,2 };
  2239. int i,j,x,y;
  2240. // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
  2241. x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
  2242. y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
  2243. if (x && y) {
  2244. if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {
  2245. free(final);
  2246. return 0;
  2247. }
  2248. for (j=0; j < y; ++j)
  2249. for (i=0; i < x; ++i)
  2250. memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,
  2251. a->out + (j*x+i)*out_n, out_n);
  2252. free(a->out);
  2253. raw += (x*out_n+1)*y;
  2254. raw_len -= (x*out_n+1)*y;
  2255. }
  2256. }
  2257. a->out = final;
  2258. stbi_png_partial = save;
  2259. return 1;
  2260. }
  2261. static int compute_transparency(png *z, uint8 tc[3], int out_n)
  2262. {
  2263. stbi *s = z->s;
  2264. uint32 i, pixel_count = s->img_x * s->img_y;
  2265. uint8 *p = z->out;
  2266. // compute color-based transparency, assuming we've
  2267. // already got 255 as the alpha value in the output
  2268. assert(out_n == 2 || out_n == 4);
  2269. if (out_n == 2) {
  2270. for (i=0; i < pixel_count; ++i) {
  2271. p[1] = (p[0] == tc[0] ? 0 : 255);
  2272. p += 2;
  2273. }
  2274. } else {
  2275. for (i=0; i < pixel_count; ++i) {
  2276. if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
  2277. p[3] = 0;
  2278. p += 4;
  2279. }
  2280. }
  2281. return 1;
  2282. }
  2283. static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n)
  2284. {
  2285. uint32 i, pixel_count = a->s->img_x * a->s->img_y;
  2286. uint8 *p, *temp_out, *orig = a->out;
  2287. p = (uint8 *) malloc(pixel_count * pal_img_n);
  2288. if (p == NULL) return e("outofmem", "Out of memory");
  2289. // between here and free(out) below, exitting would leak
  2290. temp_out = p;
  2291. if (pal_img_n == 3) {
  2292. for (i=0; i < pixel_count; ++i) {
  2293. int n = orig[i]*4;
  2294. p[0] = palette[n ];
  2295. p[1] = palette[n+1];
  2296. p[2] = palette[n+2];
  2297. p += 3;
  2298. }
  2299. } else {
  2300. for (i=0; i < pixel_count; ++i) {
  2301. int n = orig[i]*4;
  2302. p[0] = palette[n ];
  2303. p[1] = palette[n+1];
  2304. p[2] = palette[n+2];
  2305. p[3] = palette[n+3];
  2306. p += 4;
  2307. }
  2308. }
  2309. free(a->out);
  2310. a->out = temp_out;
  2311. STBI_NOTUSED(len);
  2312. return 1;
  2313. }
  2314. static int stbi_unpremultiply_on_load = 0;
  2315. static int stbi_de_iphone_flag = 0;
  2316. void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
  2317. {
  2318. stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply;
  2319. }
  2320. void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
  2321. {
  2322. stbi_de_iphone_flag = flag_true_if_should_convert;
  2323. }
  2324. static void stbi_de_iphone(png *z)
  2325. {
  2326. stbi *s = z->s;
  2327. uint32 i, pixel_count = s->img_x * s->img_y;
  2328. uint8 *p = z->out;
  2329. if (s->img_out_n == 3) { // convert bgr to rgb
  2330. for (i=0; i < pixel_count; ++i) {
  2331. uint8 t = p[0];
  2332. p[0] = p[2];
  2333. p[2] = t;
  2334. p += 3;
  2335. }
  2336. } else {
  2337. assert(s->img_out_n == 4);
  2338. if (stbi_unpremultiply_on_load) {
  2339. // convert bgr to rgb and unpremultiply
  2340. for (i=0; i < pixel_count; ++i) {
  2341. uint8 a = p[3];
  2342. uint8 t = p[0];
  2343. if (a) {
  2344. p[0] = p[2] * 255 / a;
  2345. p[1] = p[1] * 255 / a;
  2346. p[2] = t * 255 / a;
  2347. } else {
  2348. p[0] = p[2];
  2349. p[2] = t;
  2350. }
  2351. p += 4;
  2352. }
  2353. } else {
  2354. // convert bgr to rgb
  2355. for (i=0; i < pixel_count; ++i) {
  2356. uint8 t = p[0];
  2357. p[0] = p[2];
  2358. p[2] = t;
  2359. p += 4;
  2360. }
  2361. }
  2362. }
  2363. }
  2364. static int parse_png_file(png *z, int scan, int req_comp)
  2365. {
  2366. uint8 palette[1024], pal_img_n=0;
  2367. uint8 has_trans=0, tc[3];
  2368. uint32 ioff=0, idata_limit=0, i, pal_len=0;
  2369. int first=1,k,interlace=0, iphone=0;
  2370. stbi *s = z->s;
  2371. z->expanded = NULL;
  2372. z->idata = NULL;
  2373. z->out = NULL;
  2374. if (!check_png_header(s)) return 0;
  2375. if (scan == SCAN_type) return 1;
  2376. for (;;) {
  2377. chunk c = get_chunk_header(s);
  2378. switch (c.type) {
  2379. case PNG_TYPE('C','g','B','I'):
  2380. iphone = stbi_de_iphone_flag;
  2381. skip(s, c.length);
  2382. break;
  2383. case PNG_TYPE('I','H','D','R'): {
  2384. int depth,color,comp,filter;
  2385. if (!first) return e("multiple IHDR","Corrupt PNG");
  2386. first = 0;
  2387. if (c.length != 13) return e("bad IHDR len","Corrupt PNG");
  2388. s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");
  2389. s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");
  2390. depth = get8(s); if (depth != 8) return e("8bit only","PNG not supported: 8-bit only");
  2391. color = get8(s); if (color > 6) return e("bad ctype","Corrupt PNG");
  2392. if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");
  2393. comp = get8(s); if (comp) return e("bad comp method","Corrupt PNG");
  2394. filter= get8(s); if (filter) return e("bad filter method","Corrupt PNG");
  2395. interlace = get8(s); if (interlace>1) return e("bad interlace method","Corrupt PNG");
  2396. if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG");
  2397. if (!pal_img_n) {
  2398. s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
  2399. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");
  2400. if (scan == SCAN_header) return 1;
  2401. } else {
  2402. // if paletted, then pal_n is our final components, and
  2403. // img_n is # components to decompress/filter.
  2404. s->img_n = 1;
  2405. if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG");
  2406. // if SCAN_header, have to scan to see if we have a tRNS
  2407. }
  2408. break;
  2409. }
  2410. case PNG_TYPE('P','L','T','E'): {
  2411. if (first) return e("first not IHDR", "Corrupt PNG");
  2412. if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");
  2413. pal_len = c.length / 3;
  2414. if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");
  2415. for (i=0; i < pal_len; ++i) {
  2416. palette[i*4+0] = get8u(s);
  2417. palette[i*4+1] = get8u(s);
  2418. palette[i*4+2] = get8u(s);
  2419. palette[i*4+3] = 255;
  2420. }
  2421. break;
  2422. }
  2423. case PNG_TYPE('t','R','N','S'): {
  2424. if (first) return e("first not IHDR", "Corrupt PNG");
  2425. if (z->idata) return e("tRNS after IDAT","Corrupt PNG");
  2426. if (pal_img_n) {
  2427. if (scan == SCAN_header) { s->img_n = 4; return 1; }
  2428. if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");
  2429. if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");
  2430. pal_img_n = 4;
  2431. for (i=0; i < c.length; ++i)
  2432. palette[i*4+3] = get8u(s);
  2433. } else {
  2434. if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");
  2435. if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");
  2436. has_trans = 1;
  2437. for (k=0; k < s->img_n; ++k)
  2438. tc[k] = (uint8) get16(s); // non 8-bit images will be larger
  2439. }
  2440. break;
  2441. }
  2442. case PNG_TYPE('I','D','A','T'): {
  2443. if (first) return e("first not IHDR", "Corrupt PNG");
  2444. if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");
  2445. if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }
  2446. if (ioff + c.length > idata_limit) {
  2447. uint8 *p;
  2448. if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
  2449. while (ioff + c.length > idata_limit)
  2450. idata_limit *= 2;
  2451. p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");
  2452. z->idata = p;
  2453. }
  2454. if (!getn(s, z->idata+ioff,c.length)) return e("outofdata","Corrupt PNG");
  2455. ioff += c.length;
  2456. break;
  2457. }
  2458. case PNG_TYPE('I','E','N','D'): {
  2459. uint32 raw_len;
  2460. if (first) return e("first not IHDR", "Corrupt PNG");
  2461. if (scan != SCAN_load) return 1;
  2462. if (z->idata == NULL) return e("no IDAT","Corrupt PNG");
  2463. z->expanded = (uint8 *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone);
  2464. if (z->expanded == NULL) return 0; // zlib should set error
  2465. free(z->idata); z->idata = NULL;
  2466. if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
  2467. s->img_out_n = s->img_n+1;
  2468. else
  2469. s->img_out_n = s->img_n;
  2470. if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;
  2471. if (has_trans)
  2472. if (!compute_transparency(z, tc, s->img_out_n)) return 0;
  2473. if (iphone && s->img_out_n > 2)
  2474. stbi_de_iphone(z);
  2475. if (pal_img_n) {
  2476. // pal_img_n == 3 or 4
  2477. s->img_n = pal_img_n; // record the actual colors we had
  2478. s->img_out_n = pal_img_n;
  2479. if (req_comp >= 3) s->img_out_n = req_comp;
  2480. if (!expand_palette(z, palette, pal_len, s->img_out_n))
  2481. return 0;
  2482. }
  2483. free(z->expanded); z->expanded = NULL;
  2484. return 1;
  2485. }
  2486. default:
  2487. // if critical, fail
  2488. if (first) return e("first not IHDR", "Corrupt PNG");
  2489. if ((c.type & (1 << 29)) == 0) {
  2490. #ifndef STBI_NO_FAILURE_STRINGS
  2491. // not threadsafe
  2492. static char invalid_chunk[] = "XXXX chunk not known";
  2493. invalid_chunk[0] = (uint8) (c.type >> 24);
  2494. invalid_chunk[1] = (uint8) (c.type >> 16);
  2495. invalid_chunk[2] = (uint8) (c.type >> 8);
  2496. invalid_chunk[3] = (uint8) (c.type >> 0);
  2497. #endif
  2498. return e(invalid_chunk, "PNG not supported: unknown chunk type");
  2499. }
  2500. skip(s, c.length);
  2501. break;
  2502. }
  2503. // end of chunk, read and skip CRC
  2504. get32(s);
  2505. }
  2506. }
  2507. static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)
  2508. {
  2509. unsigned char *result=NULL;
  2510. if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
  2511. if (parse_png_file(p, SCAN_load, req_comp)) {
  2512. result = p->out;
  2513. p->out = NULL;
  2514. if (req_comp && req_comp != p->s->img_out_n) {
  2515. result = convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
  2516. p->s->img_out_n = req_comp;
  2517. if (result == NULL) return result;
  2518. }
  2519. *x = p->s->img_x;
  2520. *y = p->s->img_y;
  2521. if (n) *n = p->s->img_n;
  2522. }
  2523. free(p->out); p->out = NULL;
  2524. free(p->expanded); p->expanded = NULL;
  2525. free(p->idata); p->idata = NULL;
  2526. return result;
  2527. }
  2528. static unsigned char *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  2529. {
  2530. png p;
  2531. p.s = s;
  2532. return do_png(&p, x,y,comp,req_comp);
  2533. }
  2534. static int stbi_png_test(stbi *s)
  2535. {
  2536. int r;
  2537. r = check_png_header(s);
  2538. stbi_rewind(s);
  2539. return r;
  2540. }
  2541. static int stbi_png_info_raw(png *p, int *x, int *y, int *comp)
  2542. {
  2543. if (!parse_png_file(p, SCAN_header, 0)) {
  2544. stbi_rewind( p->s );
  2545. return 0;
  2546. }
  2547. if (x) *x = p->s->img_x;
  2548. if (y) *y = p->s->img_y;
  2549. if (comp) *comp = p->s->img_n;
  2550. return 1;
  2551. }
  2552. static int stbi_png_info(stbi *s, int *x, int *y, int *comp)
  2553. {
  2554. png p;
  2555. p.s = s;
  2556. return stbi_png_info_raw(&p, x, y, comp);
  2557. }
  2558. // Microsoft/Windows BMP image
  2559. static int bmp_test(stbi *s)
  2560. {
  2561. int sz;
  2562. if (get8(s) != 'B') return 0;
  2563. if (get8(s) != 'M') return 0;
  2564. get32le(s); // discard filesize
  2565. get16le(s); // discard reserved
  2566. get16le(s); // discard reserved
  2567. get32le(s); // discard data offset
  2568. sz = get32le(s);
  2569. if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;
  2570. return 0;
  2571. }
  2572. static int stbi_bmp_test(stbi *s)
  2573. {
  2574. int r = bmp_test(s);
  2575. stbi_rewind(s);
  2576. return r;
  2577. }
  2578. // returns 0..31 for the highest set bit
  2579. static int high_bit(unsigned int z)
  2580. {
  2581. int n=0;
  2582. if (z == 0) return -1;
  2583. if (z >= 0x10000) n += 16, z >>= 16;
  2584. if (z >= 0x00100) n += 8, z >>= 8;
  2585. if (z >= 0x00010) n += 4, z >>= 4;
  2586. if (z >= 0x00004) n += 2, z >>= 2;
  2587. if (z >= 0x00002) n += 1, z >>= 1;
  2588. return n;
  2589. }
  2590. static int bitcount(unsigned int a)
  2591. {
  2592. a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
  2593. a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
  2594. a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
  2595. a = (a + (a >> 8)); // max 16 per 8 bits
  2596. a = (a + (a >> 16)); // max 32 per 8 bits
  2597. return a & 0xff;
  2598. }
  2599. static int shiftsigned(int v, int shift, int bits)
  2600. {
  2601. int result;
  2602. int z=0;
  2603. if (shift < 0) v <<= -shift;
  2604. else v >>= shift;
  2605. result = v;
  2606. z = bits;
  2607. while (z < 8) {
  2608. result += v >> z;
  2609. z += bits;
  2610. }
  2611. return result;
  2612. }
  2613. static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  2614. {
  2615. uint8 *out;
  2616. unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
  2617. stbi_uc pal[256][4];
  2618. int psize=0,i,j,compress=0,width;
  2619. int bpp, flip_vertically, pad, target, offset, hsz;
  2620. if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");
  2621. get32le(s); // discard filesize
  2622. get16le(s); // discard reserved
  2623. get16le(s); // discard reserved
  2624. offset = get32le(s);
  2625. hsz = get32le(s);
  2626. if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");
  2627. if (hsz == 12) {
  2628. s->img_x = get16le(s);
  2629. s->img_y = get16le(s);
  2630. } else {
  2631. s->img_x = get32le(s);
  2632. s->img_y = get32le(s);
  2633. }
  2634. if (get16le(s) != 1) return epuc("bad BMP", "bad BMP");
  2635. bpp = get16le(s);
  2636. if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");
  2637. flip_vertically = ((int) s->img_y) > 0;
  2638. s->img_y = abs((int) s->img_y);
  2639. if (hsz == 12) {
  2640. if (bpp < 24)
  2641. psize = (offset - 14 - 24) / 3;
  2642. } else {
  2643. compress = get32le(s);
  2644. if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");
  2645. get32le(s); // discard sizeof
  2646. get32le(s); // discard hres
  2647. get32le(s); // discard vres
  2648. get32le(s); // discard colorsused
  2649. get32le(s); // discard max important
  2650. if (hsz == 40 || hsz == 56) {
  2651. if (hsz == 56) {
  2652. get32le(s);
  2653. get32le(s);
  2654. get32le(s);
  2655. get32le(s);
  2656. }
  2657. if (bpp == 16 || bpp == 32) {
  2658. mr = mg = mb = 0;
  2659. if (compress == 0) {
  2660. if (bpp == 32) {
  2661. mr = 0xffu << 16;
  2662. mg = 0xffu << 8;
  2663. mb = 0xffu << 0;
  2664. ma = 0xffu << 24;
  2665. fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
  2666. } else {
  2667. mr = 31u << 10;
  2668. mg = 31u << 5;
  2669. mb = 31u << 0;
  2670. }
  2671. } else if (compress == 3) {
  2672. mr = get32le(s);
  2673. mg = get32le(s);
  2674. mb = get32le(s);
  2675. // not documented, but generated by photoshop and handled by mspaint
  2676. if (mr == mg && mg == mb) {
  2677. // ?!?!?
  2678. return epuc("bad BMP", "bad BMP");
  2679. }
  2680. } else
  2681. return epuc("bad BMP", "bad BMP");
  2682. }
  2683. } else {
  2684. assert(hsz == 108);
  2685. mr = get32le(s);
  2686. mg = get32le(s);
  2687. mb = get32le(s);
  2688. ma = get32le(s);
  2689. get32le(s); // discard color space
  2690. for (i=0; i < 12; ++i)
  2691. get32le(s); // discard color space parameters
  2692. }
  2693. if (bpp < 16)
  2694. psize = (offset - 14 - hsz) >> 2;
  2695. }
  2696. s->img_n = ma ? 4 : 3;
  2697. if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
  2698. target = req_comp;
  2699. else
  2700. target = s->img_n; // if they want monochrome, we'll post-convert
  2701. out = (stbi_uc *) malloc(target * s->img_x * s->img_y);
  2702. if (!out) return epuc("outofmem", "Out of memory");
  2703. if (bpp < 16) {
  2704. int z=0;
  2705. if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }
  2706. for (i=0; i < psize; ++i) {
  2707. pal[i][2] = get8u(s);
  2708. pal[i][1] = get8u(s);
  2709. pal[i][0] = get8u(s);
  2710. if (hsz != 12) get8(s);
  2711. pal[i][3] = 255;
  2712. }
  2713. skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
  2714. if (bpp == 4) width = (s->img_x + 1) >> 1;
  2715. else if (bpp == 8) width = s->img_x;
  2716. else { free(out); return epuc("bad bpp", "Corrupt BMP"); }
  2717. pad = (-width)&3;
  2718. for (j=0; j < (int) s->img_y; ++j) {
  2719. for (i=0; i < (int) s->img_x; i += 2) {
  2720. int v=get8(s),v2=0;
  2721. if (bpp == 4) {
  2722. v2 = v & 15;
  2723. v >>= 4;
  2724. }
  2725. out[z++] = pal[v][0];
  2726. out[z++] = pal[v][1];
  2727. out[z++] = pal[v][2];
  2728. if (target == 4) out[z++] = 255;
  2729. if (i+1 == (int) s->img_x) break;
  2730. v = (bpp == 8) ? get8(s) : v2;
  2731. out[z++] = pal[v][0];
  2732. out[z++] = pal[v][1];
  2733. out[z++] = pal[v][2];
  2734. if (target == 4) out[z++] = 255;
  2735. }
  2736. skip(s, pad);
  2737. }
  2738. } else {
  2739. int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
  2740. int z = 0;
  2741. int easy=0;
  2742. skip(s, offset - 14 - hsz);
  2743. if (bpp == 24) width = 3 * s->img_x;
  2744. else if (bpp == 16) width = 2*s->img_x;
  2745. else /* bpp = 32 and pad = 0 */ width=0;
  2746. pad = (-width) & 3;
  2747. if (bpp == 24) {
  2748. easy = 1;
  2749. } else if (bpp == 32) {
  2750. if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
  2751. easy = 2;
  2752. }
  2753. if (!easy) {
  2754. if (!mr || !mg || !mb) { free(out); return epuc("bad masks", "Corrupt BMP"); }
  2755. // right shift amt to put high bit in position #7
  2756. rshift = high_bit(mr)-7; rcount = bitcount(mr);
  2757. gshift = high_bit(mg)-7; gcount = bitcount(mr);
  2758. bshift = high_bit(mb)-7; bcount = bitcount(mr);
  2759. ashift = high_bit(ma)-7; acount = bitcount(mr);
  2760. }
  2761. for (j=0; j < (int) s->img_y; ++j) {
  2762. if (easy) {
  2763. for (i=0; i < (int) s->img_x; ++i) {
  2764. int a;
  2765. out[z+2] = get8u(s);
  2766. out[z+1] = get8u(s);
  2767. out[z+0] = get8u(s);
  2768. z += 3;
  2769. a = (easy == 2 ? get8(s) : 255);
  2770. if (target == 4) out[z++] = (uint8) a;
  2771. }
  2772. } else {
  2773. for (i=0; i < (int) s->img_x; ++i) {
  2774. uint32 v = (bpp == 16 ? get16le(s) : get32le(s));
  2775. int a;
  2776. out[z++] = (uint8) shiftsigned(v & mr, rshift, rcount);
  2777. out[z++] = (uint8) shiftsigned(v & mg, gshift, gcount);
  2778. out[z++] = (uint8) shiftsigned(v & mb, bshift, bcount);
  2779. a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);
  2780. if (target == 4) out[z++] = (uint8) a;
  2781. }
  2782. }
  2783. skip(s, pad);
  2784. }
  2785. }
  2786. if (flip_vertically) {
  2787. stbi_uc t;
  2788. for (j=0; j < (int) s->img_y>>1; ++j) {
  2789. stbi_uc *p1 = out + j *s->img_x*target;
  2790. stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
  2791. for (i=0; i < (int) s->img_x*target; ++i) {
  2792. t = p1[i], p1[i] = p2[i], p2[i] = t;
  2793. }
  2794. }
  2795. }
  2796. if (req_comp && req_comp != target) {
  2797. out = convert_format(out, target, req_comp, s->img_x, s->img_y);
  2798. if (out == NULL) return out; // convert_format frees input on failure
  2799. }
  2800. *x = s->img_x;
  2801. *y = s->img_y;
  2802. if (comp) *comp = s->img_n;
  2803. return out;
  2804. }
  2805. static stbi_uc *stbi_bmp_load(stbi *s,int *x, int *y, int *comp, int req_comp)
  2806. {
  2807. return bmp_load(s, x,y,comp,req_comp);
  2808. }
  2809. // Targa Truevision - TGA
  2810. // by Jonathan Dummer
  2811. static int tga_info(stbi *s, int *x, int *y, int *comp)
  2812. {
  2813. int tga_w, tga_h, tga_comp;
  2814. int sz;
  2815. get8u(s); // discard Offset
  2816. sz = get8u(s); // color type
  2817. if( sz > 1 ) {
  2818. stbi_rewind(s);
  2819. return 0; // only RGB or indexed allowed
  2820. }
  2821. sz = get8u(s); // image type
  2822. // only RGB or grey allowed, +/- RLE
  2823. if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;
  2824. skip(s,9);
  2825. tga_w = get16le(s);
  2826. if( tga_w < 1 ) {
  2827. stbi_rewind(s);
  2828. return 0; // test width
  2829. }
  2830. tga_h = get16le(s);
  2831. if( tga_h < 1 ) {
  2832. stbi_rewind(s);
  2833. return 0; // test height
  2834. }
  2835. sz = get8(s); // bits per pixel
  2836. // only RGB or RGBA or grey allowed
  2837. if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {
  2838. stbi_rewind(s);
  2839. return 0;
  2840. }
  2841. tga_comp = sz;
  2842. if (x) *x = tga_w;
  2843. if (y) *y = tga_h;
  2844. if (comp) *comp = tga_comp / 8;
  2845. return 1; // seems to have passed everything
  2846. }
  2847. int stbi_tga_info(stbi *s, int *x, int *y, int *comp)
  2848. {
  2849. return tga_info(s, x, y, comp);
  2850. }
  2851. static int tga_test(stbi *s)
  2852. {
  2853. int sz;
  2854. get8u(s); // discard Offset
  2855. sz = get8u(s); // color type
  2856. if ( sz > 1 ) return 0; // only RGB or indexed allowed
  2857. sz = get8u(s); // image type
  2858. if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE
  2859. get16(s); // discard palette start
  2860. get16(s); // discard palette length
  2861. get8(s); // discard bits per palette color entry
  2862. get16(s); // discard x origin
  2863. get16(s); // discard y origin
  2864. if ( get16(s) < 1 ) return 0; // test width
  2865. if ( get16(s) < 1 ) return 0; // test height
  2866. sz = get8(s); // bits per pixel
  2867. if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed
  2868. return 1; // seems to have passed everything
  2869. }
  2870. static int stbi_tga_test(stbi *s)
  2871. {
  2872. int res = tga_test(s);
  2873. stbi_rewind(s);
  2874. return res;
  2875. }
  2876. static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  2877. {
  2878. // read in the TGA header stuff
  2879. int tga_offset = get8u(s);
  2880. int tga_indexed = get8u(s);
  2881. int tga_image_type = get8u(s);
  2882. int tga_is_RLE = 0;
  2883. int tga_palette_start = get16le(s);
  2884. int tga_palette_len = get16le(s);
  2885. int tga_palette_bits = get8u(s);
  2886. int tga_x_origin = get16le(s);
  2887. int tga_y_origin = get16le(s);
  2888. int tga_width = get16le(s);
  2889. int tga_height = get16le(s);
  2890. int tga_bits_per_pixel = get8u(s);
  2891. int tga_inverted = get8u(s);
  2892. // image data
  2893. unsigned char *tga_data;
  2894. unsigned char *tga_palette = NULL;
  2895. int i, j;
  2896. unsigned char raw_data[4];
  2897. unsigned char trans_data[4];
  2898. int RLE_count = 0;
  2899. int RLE_repeating = 0;
  2900. int read_next_pixel = 1;
  2901. // do a tiny bit of precessing
  2902. if ( tga_image_type >= 8 )
  2903. {
  2904. tga_image_type -= 8;
  2905. tga_is_RLE = 1;
  2906. }
  2907. /* int tga_alpha_bits = tga_inverted & 15; */
  2908. tga_inverted = 1 - ((tga_inverted >> 5) & 1);
  2909. // error check
  2910. if ( //(tga_indexed) ||
  2911. (tga_width < 1) || (tga_height < 1) ||
  2912. (tga_image_type < 1) || (tga_image_type > 3) ||
  2913. ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
  2914. (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
  2915. )
  2916. {
  2917. return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA
  2918. }
  2919. // If I'm paletted, then I'll use the number of bits from the palette
  2920. if ( tga_indexed )
  2921. {
  2922. tga_bits_per_pixel = tga_palette_bits;
  2923. }
  2924. // tga info
  2925. *x = tga_width;
  2926. *y = tga_height;
  2927. if ( (req_comp < 1) || (req_comp > 4) )
  2928. {
  2929. // just use whatever the file was
  2930. req_comp = tga_bits_per_pixel / 8;
  2931. *comp = req_comp;
  2932. } else
  2933. {
  2934. // force a new number of components
  2935. *comp = tga_bits_per_pixel/8;
  2936. }
  2937. tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );
  2938. if (!tga_data) return epuc("outofmem", "Out of memory");
  2939. // skip to the data's starting position (offset usually = 0)
  2940. skip(s, tga_offset );
  2941. // do I need to load a palette?
  2942. if ( tga_indexed )
  2943. {
  2944. // any data to skip? (offset usually = 0)
  2945. skip(s, tga_palette_start );
  2946. // load the palette
  2947. tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );
  2948. if (!tga_palette) return epuc("outofmem", "Out of memory");
  2949. if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {
  2950. free(tga_data);
  2951. free(tga_palette);
  2952. return epuc("bad palette", "Corrupt TGA");
  2953. }
  2954. }
  2955. // load the data
  2956. trans_data[0] = trans_data[1] = trans_data[2] = trans_data[3] = 0;
  2957. for (i=0; i < tga_width * tga_height; ++i)
  2958. {
  2959. // if I'm in RLE mode, do I need to get a RLE chunk?
  2960. if ( tga_is_RLE )
  2961. {
  2962. if ( RLE_count == 0 )
  2963. {
  2964. // yep, get the next byte as a RLE command
  2965. int RLE_cmd = get8u(s);
  2966. RLE_count = 1 + (RLE_cmd & 127);
  2967. RLE_repeating = RLE_cmd >> 7;
  2968. read_next_pixel = 1;
  2969. } else if ( !RLE_repeating )
  2970. {
  2971. read_next_pixel = 1;
  2972. }
  2973. } else
  2974. {
  2975. read_next_pixel = 1;
  2976. }
  2977. // OK, if I need to read a pixel, do it now
  2978. if ( read_next_pixel )
  2979. {
  2980. // load however much data we did have
  2981. if ( tga_indexed )
  2982. {
  2983. // read in 1 byte, then perform the lookup
  2984. int pal_idx = get8u(s);
  2985. if ( pal_idx >= tga_palette_len )
  2986. {
  2987. // invalid index
  2988. pal_idx = 0;
  2989. }
  2990. pal_idx *= tga_bits_per_pixel / 8;
  2991. for (j = 0; j*8 < tga_bits_per_pixel; ++j)
  2992. {
  2993. raw_data[j] = tga_palette[pal_idx+j];
  2994. }
  2995. } else
  2996. {
  2997. // read in the data raw
  2998. for (j = 0; j*8 < tga_bits_per_pixel; ++j)
  2999. {
  3000. raw_data[j] = get8u(s);
  3001. }
  3002. }
  3003. // convert raw to the intermediate format
  3004. switch (tga_bits_per_pixel)
  3005. {
  3006. case 8:
  3007. // Luminous => RGBA
  3008. trans_data[0] = raw_data[0];
  3009. trans_data[1] = raw_data[0];
  3010. trans_data[2] = raw_data[0];
  3011. trans_data[3] = 255;
  3012. break;
  3013. case 16:
  3014. // Luminous,Alpha => RGBA
  3015. trans_data[0] = raw_data[0];
  3016. trans_data[1] = raw_data[0];
  3017. trans_data[2] = raw_data[0];
  3018. trans_data[3] = raw_data[1];
  3019. break;
  3020. case 24:
  3021. // BGR => RGBA
  3022. trans_data[0] = raw_data[2];
  3023. trans_data[1] = raw_data[1];
  3024. trans_data[2] = raw_data[0];
  3025. trans_data[3] = 255;
  3026. break;
  3027. case 32:
  3028. // BGRA => RGBA
  3029. trans_data[0] = raw_data[2];
  3030. trans_data[1] = raw_data[1];
  3031. trans_data[2] = raw_data[0];
  3032. trans_data[3] = raw_data[3];
  3033. break;
  3034. }
  3035. // clear the reading flag for the next pixel
  3036. read_next_pixel = 0;
  3037. } // end of reading a pixel
  3038. // convert to final format
  3039. switch (req_comp)
  3040. {
  3041. case 1:
  3042. // RGBA => Luminance
  3043. tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
  3044. break;
  3045. case 2:
  3046. // RGBA => Luminance,Alpha
  3047. tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
  3048. tga_data[i*req_comp+1] = trans_data[3];
  3049. break;
  3050. case 3:
  3051. // RGBA => RGB
  3052. tga_data[i*req_comp+0] = trans_data[0];
  3053. tga_data[i*req_comp+1] = trans_data[1];
  3054. tga_data[i*req_comp+2] = trans_data[2];
  3055. break;
  3056. case 4:
  3057. // RGBA => RGBA
  3058. tga_data[i*req_comp+0] = trans_data[0];
  3059. tga_data[i*req_comp+1] = trans_data[1];
  3060. tga_data[i*req_comp+2] = trans_data[2];
  3061. tga_data[i*req_comp+3] = trans_data[3];
  3062. break;
  3063. }
  3064. // in case we're in RLE mode, keep counting down
  3065. --RLE_count;
  3066. }
  3067. // do I need to invert the image?
  3068. if ( tga_inverted )
  3069. {
  3070. for (j = 0; j*2 < tga_height; ++j)
  3071. {
  3072. int index1 = j * tga_width * req_comp;
  3073. int index2 = (tga_height - 1 - j) * tga_width * req_comp;
  3074. for (i = tga_width * req_comp; i > 0; --i)
  3075. {
  3076. unsigned char temp = tga_data[index1];
  3077. tga_data[index1] = tga_data[index2];
  3078. tga_data[index2] = temp;
  3079. ++index1;
  3080. ++index2;
  3081. }
  3082. }
  3083. }
  3084. // clear my palette, if I had one
  3085. if ( tga_palette != NULL )
  3086. {
  3087. free( tga_palette );
  3088. }
  3089. // the things I do to get rid of an error message, and yet keep
  3090. // Microsoft's C compilers happy... [8^(
  3091. tga_palette_start = tga_palette_len = tga_palette_bits =
  3092. tga_x_origin = tga_y_origin = 0;
  3093. // OK, done
  3094. return tga_data;
  3095. }
  3096. static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  3097. {
  3098. return tga_load(s,x,y,comp,req_comp);
  3099. }
  3100. // *************************************************************************************************
  3101. // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
  3102. static int psd_test(stbi *s)
  3103. {
  3104. if (get32(s) != 0x38425053) return 0; // "8BPS"
  3105. else return 1;
  3106. }
  3107. static int stbi_psd_test(stbi *s)
  3108. {
  3109. int r = psd_test(s);
  3110. stbi_rewind(s);
  3111. return r;
  3112. }
  3113. static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  3114. {
  3115. int pixelCount;
  3116. int channelCount, compression;
  3117. int channel, i, count, len;
  3118. int w,h;
  3119. uint8 *out;
  3120. // Check identifier
  3121. if (get32(s) != 0x38425053) // "8BPS"
  3122. return epuc("not PSD", "Corrupt PSD image");
  3123. // Check file type version.
  3124. if (get16(s) != 1)
  3125. return epuc("wrong version", "Unsupported version of PSD image");
  3126. // Skip 6 reserved bytes.
  3127. skip(s, 6 );
  3128. // Read the number of channels (R, G, B, A, etc).
  3129. channelCount = get16(s);
  3130. if (channelCount < 0 || channelCount > 16)
  3131. return epuc("wrong channel count", "Unsupported number of channels in PSD image");
  3132. // Read the rows and columns of the image.
  3133. h = get32(s);
  3134. w = get32(s);
  3135. // Make sure the depth is 8 bits.
  3136. if (get16(s) != 8)
  3137. return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");
  3138. // Make sure the color mode is RGB.
  3139. // Valid options are:
  3140. // 0: Bitmap
  3141. // 1: Grayscale
  3142. // 2: Indexed color
  3143. // 3: RGB color
  3144. // 4: CMYK color
  3145. // 7: Multichannel
  3146. // 8: Duotone
  3147. // 9: Lab color
  3148. if (get16(s) != 3)
  3149. return epuc("wrong color format", "PSD is not in RGB color format");
  3150. // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
  3151. skip(s,get32(s) );
  3152. // Skip the image resources. (resolution, pen tool paths, etc)
  3153. skip(s, get32(s) );
  3154. // Skip the reserved data.
  3155. skip(s, get32(s) );
  3156. // Find out if the data is compressed.
  3157. // Known values:
  3158. // 0: no compression
  3159. // 1: RLE compressed
  3160. compression = get16(s);
  3161. if (compression > 1)
  3162. return epuc("bad compression", "PSD has an unknown compression format");
  3163. // Create the destination image.
  3164. out = (stbi_uc *) malloc(4 * w*h);
  3165. if (!out) return epuc("outofmem", "Out of memory");
  3166. pixelCount = w*h;
  3167. // Initialize the data to zero.
  3168. //memset( out, 0, pixelCount * 4 );
  3169. // Finally, the image data.
  3170. if (compression) {
  3171. // RLE as used by .PSD and .TIFF
  3172. // Loop until you get the number of unpacked bytes you are expecting:
  3173. // Read the next source byte into n.
  3174. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
  3175. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
  3176. // Else if n is 128, noop.
  3177. // Endloop
  3178. // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
  3179. // which we're going to just skip.
  3180. skip(s, h * channelCount * 2 );
  3181. // Read the RLE data by channel.
  3182. for (channel = 0; channel < 4; channel++) {
  3183. uint8 *p;
  3184. p = out+channel;
  3185. if (channel >= channelCount) {
  3186. // Fill this channel with default data.
  3187. for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
  3188. } else {
  3189. // Read the RLE data.
  3190. count = 0;
  3191. while (count < pixelCount) {
  3192. len = get8(s);
  3193. if (len == 128) {
  3194. // No-op.
  3195. } else if (len < 128) {
  3196. // Copy next len+1 bytes literally.
  3197. len++;
  3198. count += len;
  3199. while (len) {
  3200. *p = get8u(s);
  3201. p += 4;
  3202. len--;
  3203. }
  3204. } else if (len > 128) {
  3205. uint8 val;
  3206. // Next -len+1 bytes in the dest are replicated from next source byte.
  3207. // (Interpret len as a negative 8-bit int.)
  3208. len ^= 0x0FF;
  3209. len += 2;
  3210. val = get8u(s);
  3211. count += len;
  3212. while (len) {
  3213. *p = val;
  3214. p += 4;
  3215. len--;
  3216. }
  3217. }
  3218. }
  3219. }
  3220. }
  3221. } else {
  3222. // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
  3223. // where each channel consists of an 8-bit value for each pixel in the image.
  3224. // Read the data by channel.
  3225. for (channel = 0; channel < 4; channel++) {
  3226. uint8 *p;
  3227. p = out + channel;
  3228. if (channel > channelCount) {
  3229. // Fill this channel with default data.
  3230. for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
  3231. } else {
  3232. // Read the data.
  3233. for (i = 0; i < pixelCount; i++)
  3234. *p = get8u(s), p += 4;
  3235. }
  3236. }
  3237. }
  3238. if (req_comp && req_comp != 4) {
  3239. out = convert_format(out, 4, req_comp, w, h);
  3240. if (out == NULL) return out; // convert_format frees input on failure
  3241. }
  3242. if (comp) *comp = channelCount;
  3243. *y = h;
  3244. *x = w;
  3245. return out;
  3246. }
  3247. static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  3248. {
  3249. return psd_load(s,x,y,comp,req_comp);
  3250. }
  3251. // *************************************************************************************************
  3252. // Softimage PIC loader
  3253. // by Tom Seddon
  3254. //
  3255. // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
  3256. // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
  3257. static int pic_is4(stbi *s,const char *str)
  3258. {
  3259. int i;
  3260. for (i=0; i<4; ++i)
  3261. if (get8(s) != (stbi_uc)str[i])
  3262. return 0;
  3263. return 1;
  3264. }
  3265. static int pic_test(stbi *s)
  3266. {
  3267. int i;
  3268. if (!pic_is4(s,"\x53\x80\xF6\x34"))
  3269. return 0;
  3270. for(i=0;i<84;++i)
  3271. get8(s);
  3272. if (!pic_is4(s,"PICT"))
  3273. return 0;
  3274. return 1;
  3275. }
  3276. typedef struct
  3277. {
  3278. stbi_uc size,type,channel;
  3279. } pic_packet_t;
  3280. static stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest)
  3281. {
  3282. int mask=0x80, i;
  3283. for (i=0; i<4; ++i, mask>>=1) {
  3284. if (channel & mask) {
  3285. if (at_eof(s)) return epuc("bad file","PIC file too short");
  3286. dest[i]=get8u(s);
  3287. }
  3288. }
  3289. return dest;
  3290. }
  3291. static void pic_copyval(int channel,stbi_uc *dest,const stbi_uc *src)
  3292. {
  3293. int mask=0x80,i;
  3294. for (i=0;i<4; ++i, mask>>=1)
  3295. if (channel&mask)
  3296. dest[i]=src[i];
  3297. }
  3298. static stbi_uc *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result)
  3299. {
  3300. int act_comp=0,num_packets=0,y,chained;
  3301. pic_packet_t packets[10];
  3302. // this will (should...) cater for even some bizarre stuff like having data
  3303. // for the same channel in multiple packets.
  3304. do {
  3305. pic_packet_t *packet;
  3306. if (num_packets==sizeof(packets)/sizeof(packets[0]))
  3307. return epuc("bad format","too many packets");
  3308. packet = &packets[num_packets++];
  3309. chained = get8(s);
  3310. packet->size = get8u(s);
  3311. packet->type = get8u(s);
  3312. packet->channel = get8u(s);
  3313. act_comp |= packet->channel;
  3314. if (at_eof(s)) return epuc("bad file","file too short (reading packets)");
  3315. if (packet->size != 8) return epuc("bad format","packet isn't 8bpp");
  3316. } while (chained);
  3317. *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
  3318. for(y=0; y<height; ++y) {
  3319. int packet_idx;
  3320. for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
  3321. pic_packet_t *packet = &packets[packet_idx];
  3322. stbi_uc *dest = result+y*width*4;
  3323. switch (packet->type) {
  3324. default:
  3325. return epuc("bad format","packet has bad compression type");
  3326. case 0: {//uncompressed
  3327. int x;
  3328. for(x=0;x<width;++x, dest+=4)
  3329. if (!pic_readval(s,packet->channel,dest))
  3330. return 0;
  3331. break;
  3332. }
  3333. case 1://Pure RLE
  3334. {
  3335. int left=width, i;
  3336. while (left>0) {
  3337. stbi_uc count,value[4];
  3338. count=get8u(s);
  3339. if (at_eof(s)) return epuc("bad file","file too short (pure read count)");
  3340. if (count > left)
  3341. count = (uint8) left;
  3342. if (!pic_readval(s,packet->channel,value)) return 0;
  3343. for(i=0; i<count; ++i,dest+=4)
  3344. pic_copyval(packet->channel,dest,value);
  3345. left -= count;
  3346. }
  3347. }
  3348. break;
  3349. case 2: {//Mixed RLE
  3350. int left=width;
  3351. while (left>0) {
  3352. int count = get8(s), i;
  3353. if (at_eof(s)) return epuc("bad file","file too short (mixed read count)");
  3354. if (count >= 128) { // Repeated
  3355. stbi_uc value[4];
  3356. int i;
  3357. if (count==128)
  3358. count = get16(s);
  3359. else
  3360. count -= 127;
  3361. if (count > left)
  3362. return epuc("bad file","scanline overrun");
  3363. if (!pic_readval(s,packet->channel,value))
  3364. return 0;
  3365. for(i=0;i<count;++i, dest += 4)
  3366. pic_copyval(packet->channel,dest,value);
  3367. } else { // Raw
  3368. ++count;
  3369. if (count>left) return epuc("bad file","scanline overrun");
  3370. for(i=0;i<count;++i, dest+=4)
  3371. if (!pic_readval(s,packet->channel,dest))
  3372. return 0;
  3373. }
  3374. left-=count;
  3375. }
  3376. break;
  3377. }
  3378. }
  3379. }
  3380. }
  3381. return result;
  3382. }
  3383. static stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp)
  3384. {
  3385. stbi_uc *result;
  3386. int i, x,y;
  3387. for (i=0; i<92; ++i)
  3388. get8(s);
  3389. x = get16(s);
  3390. y = get16(s);
  3391. if (at_eof(s)) return epuc("bad file","file too short (pic header)");
  3392. if ((1 << 28) / x < y) return epuc("too large", "Image too large to decode");
  3393. get32(s); //skip `ratio'
  3394. get16(s); //skip `fields'
  3395. get16(s); //skip `pad'
  3396. // intermediate buffer is RGBA
  3397. result = (stbi_uc *) malloc(x*y*4);
  3398. memset(result, 0xff, x*y*4);
  3399. if (!pic_load2(s,x,y,comp, result)) {
  3400. free(result);
  3401. result=0;
  3402. }
  3403. *px = x;
  3404. *py = y;
  3405. if (req_comp == 0) req_comp = *comp;
  3406. result=convert_format(result,4,req_comp,x,y);
  3407. return result;
  3408. }
  3409. static int stbi_pic_test(stbi *s)
  3410. {
  3411. int r = pic_test(s);
  3412. stbi_rewind(s);
  3413. return r;
  3414. }
  3415. static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  3416. {
  3417. return pic_load(s,x,y,comp,req_comp);
  3418. }
  3419. // *************************************************************************************************
  3420. // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
  3421. typedef struct stbi_gif_lzw_struct {
  3422. int16 prefix;
  3423. uint8 first;
  3424. uint8 suffix;
  3425. } stbi_gif_lzw;
  3426. typedef struct stbi_gif_struct
  3427. {
  3428. int w,h;
  3429. stbi_uc *out; // output buffer (always 4 components)
  3430. int flags, bgindex, ratio, transparent, eflags;
  3431. uint8 pal[256][4];
  3432. uint8 lpal[256][4];
  3433. stbi_gif_lzw codes[4096];
  3434. uint8 *color_table;
  3435. int parse, step;
  3436. int lflags;
  3437. int start_x, start_y;
  3438. int max_x, max_y;
  3439. int cur_x, cur_y;
  3440. int line_size;
  3441. } stbi_gif;
  3442. static int gif_test(stbi *s)
  3443. {
  3444. int sz;
  3445. if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0;
  3446. sz = get8(s);
  3447. if (sz != '9' && sz != '7') return 0;
  3448. if (get8(s) != 'a') return 0;
  3449. return 1;
  3450. }
  3451. static int stbi_gif_test(stbi *s)
  3452. {
  3453. int r = gif_test(s);
  3454. stbi_rewind(s);
  3455. return r;
  3456. }
  3457. static void stbi_gif_parse_colortable(stbi *s, uint8 pal[256][4], int num_entries, int transp)
  3458. {
  3459. int i;
  3460. for (i=0; i < num_entries; ++i) {
  3461. pal[i][2] = get8u(s);
  3462. pal[i][1] = get8u(s);
  3463. pal[i][0] = get8u(s);
  3464. pal[i][3] = transp ? 0 : 255;
  3465. }
  3466. }
  3467. static int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info)
  3468. {
  3469. uint8 version;
  3470. if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8')
  3471. return e("not GIF", "Corrupt GIF");
  3472. version = get8u(s);
  3473. if (version != '7' && version != '9') return e("not GIF", "Corrupt GIF");
  3474. if (get8(s) != 'a') return e("not GIF", "Corrupt GIF");
  3475. failure_reason = "";
  3476. g->w = get16le(s);
  3477. g->h = get16le(s);
  3478. g->flags = get8(s);
  3479. g->bgindex = get8(s);
  3480. g->ratio = get8(s);
  3481. g->transparent = -1;
  3482. if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
  3483. if (is_info) return 1;
  3484. if (g->flags & 0x80)
  3485. stbi_gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
  3486. return 1;
  3487. }
  3488. static int stbi_gif_info_raw(stbi *s, int *x, int *y, int *comp)
  3489. {
  3490. stbi_gif g;
  3491. if (!stbi_gif_header(s, &g, comp, 1)) {
  3492. stbi_rewind( s );
  3493. return 0;
  3494. }
  3495. if (x) *x = g.w;
  3496. if (y) *y = g.h;
  3497. return 1;
  3498. }
  3499. static void stbi_out_gif_code(stbi_gif *g, uint16 code)
  3500. {
  3501. uint8 *p, *c;
  3502. // recurse to decode the prefixes, since the linked-list is backwards,
  3503. // and working backwards through an interleaved image would be nasty
  3504. if (g->codes[code].prefix >= 0)
  3505. stbi_out_gif_code(g, g->codes[code].prefix);
  3506. if (g->cur_y >= g->max_y) return;
  3507. p = &g->out[g->cur_x + g->cur_y];
  3508. c = &g->color_table[g->codes[code].suffix * 4];
  3509. if (c[3] >= 128) {
  3510. p[0] = c[2];
  3511. p[1] = c[1];
  3512. p[2] = c[0];
  3513. p[3] = c[3];
  3514. }
  3515. g->cur_x += 4;
  3516. if (g->cur_x >= g->max_x) {
  3517. g->cur_x = g->start_x;
  3518. g->cur_y += g->step;
  3519. while (g->cur_y >= g->max_y && g->parse > 0) {
  3520. g->step = (1 << g->parse) * g->line_size;
  3521. g->cur_y = g->start_y + (g->step >> 1);
  3522. --g->parse;
  3523. }
  3524. }
  3525. }
  3526. static uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g)
  3527. {
  3528. uint8 lzw_cs;
  3529. int32 len, code;
  3530. uint32 first;
  3531. int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
  3532. stbi_gif_lzw *p;
  3533. lzw_cs = get8u(s);
  3534. clear = 1 << lzw_cs;
  3535. first = 1;
  3536. codesize = lzw_cs + 1;
  3537. codemask = (1 << codesize) - 1;
  3538. bits = 0;
  3539. valid_bits = 0;
  3540. for (code = 0; code < clear; code++) {
  3541. g->codes[code].prefix = -1;
  3542. g->codes[code].first = (uint8) code;
  3543. g->codes[code].suffix = (uint8) code;
  3544. }
  3545. // support no starting clear code
  3546. avail = clear+2;
  3547. oldcode = -1;
  3548. len = 0;
  3549. for(;;) {
  3550. if (valid_bits < codesize) {
  3551. if (len == 0) {
  3552. len = get8(s); // start new block
  3553. if (len == 0)
  3554. return g->out;
  3555. }
  3556. --len;
  3557. bits |= (int32) get8(s) << valid_bits;
  3558. valid_bits += 8;
  3559. } else {
  3560. int32 code = bits & codemask;
  3561. bits >>= codesize;
  3562. valid_bits -= codesize;
  3563. // @OPTIMIZE: is there some way we can accelerate the non-clear path?
  3564. if (code == clear) { // clear code
  3565. codesize = lzw_cs + 1;
  3566. codemask = (1 << codesize) - 1;
  3567. avail = clear + 2;
  3568. oldcode = -1;
  3569. first = 0;
  3570. } else if (code == clear + 1) { // end of stream code
  3571. skip(s, len);
  3572. while ((len = get8(s)) > 0)
  3573. skip(s,len);
  3574. return g->out;
  3575. } else if (code <= avail) {
  3576. if (first) return epuc("no clear code", "Corrupt GIF");
  3577. if (oldcode >= 0) {
  3578. p = &g->codes[avail++];
  3579. if (avail > 4096) return epuc("too many codes", "Corrupt GIF");
  3580. p->prefix = (int16) oldcode;
  3581. p->first = g->codes[oldcode].first;
  3582. p->suffix = (code == avail) ? p->first : g->codes[code].first;
  3583. } else if (code == avail)
  3584. return epuc("illegal code in raster", "Corrupt GIF");
  3585. stbi_out_gif_code(g, (uint16) code);
  3586. if ((avail & codemask) == 0 && avail <= 0x0FFF) {
  3587. codesize++;
  3588. codemask = (1 << codesize) - 1;
  3589. }
  3590. oldcode = code;
  3591. } else {
  3592. return epuc("illegal code in raster", "Corrupt GIF");
  3593. }
  3594. }
  3595. }
  3596. }
  3597. static void stbi_fill_gif_background(stbi_gif *g)
  3598. {
  3599. int i;
  3600. uint8 *c = g->pal[g->bgindex];
  3601. // @OPTIMIZE: write a dword at a time
  3602. for (i = 0; i < g->w * g->h * 4; i += 4) {
  3603. uint8 *p = &g->out[i];
  3604. p[0] = c[2];
  3605. p[1] = c[1];
  3606. p[2] = c[0];
  3607. p[3] = c[3];
  3608. }
  3609. }
  3610. // this function is designed to support animated gifs, although stb_image doesn't support it
  3611. static uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp)
  3612. {
  3613. int i;
  3614. uint8 *old_out = 0;
  3615. if (g->out == 0) {
  3616. if (!stbi_gif_header(s, g, comp,0)) return 0; // failure_reason set by stbi_gif_header
  3617. g->out = (uint8 *) malloc(4 * g->w * g->h);
  3618. if (g->out == 0) return epuc("outofmem", "Out of memory");
  3619. stbi_fill_gif_background(g);
  3620. } else {
  3621. // animated-gif-only path
  3622. if (((g->eflags & 0x1C) >> 2) == 3) {
  3623. old_out = g->out;
  3624. g->out = (uint8 *) malloc(4 * g->w * g->h);
  3625. if (g->out == 0) return epuc("outofmem", "Out of memory");
  3626. memcpy(g->out, old_out, g->w*g->h*4);
  3627. }
  3628. }
  3629. for (;;) {
  3630. switch (get8(s)) {
  3631. case 0x2C: /* Image Descriptor */
  3632. {
  3633. int32 x, y, w, h;
  3634. uint8 *o;
  3635. x = get16le(s);
  3636. y = get16le(s);
  3637. w = get16le(s);
  3638. h = get16le(s);
  3639. if (((x + w) > (g->w)) || ((y + h) > (g->h)))
  3640. return epuc("bad Image Descriptor", "Corrupt GIF");
  3641. g->line_size = g->w * 4;
  3642. g->start_x = x * 4;
  3643. g->start_y = y * g->line_size;
  3644. g->max_x = g->start_x + w * 4;
  3645. g->max_y = g->start_y + h * g->line_size;
  3646. g->cur_x = g->start_x;
  3647. g->cur_y = g->start_y;
  3648. g->lflags = get8(s);
  3649. if (g->lflags & 0x40) {
  3650. g->step = 8 * g->line_size; // first interlaced spacing
  3651. g->parse = 3;
  3652. } else {
  3653. g->step = g->line_size;
  3654. g->parse = 0;
  3655. }
  3656. if (g->lflags & 0x80) {
  3657. stbi_gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
  3658. g->color_table = (uint8 *) g->lpal;
  3659. } else if (g->flags & 0x80) {
  3660. for (i=0; i < 256; ++i) // @OPTIMIZE: reset only the previous transparent
  3661. g->pal[i][3] = 255;
  3662. if (g->transparent >= 0 && (g->eflags & 0x01))
  3663. g->pal[g->transparent][3] = 0;
  3664. g->color_table = (uint8 *) g->pal;
  3665. } else
  3666. return epuc("missing color table", "Corrupt GIF");
  3667. o = stbi_process_gif_raster(s, g);
  3668. if (o == NULL) return NULL;
  3669. if (req_comp && req_comp != 4)
  3670. o = convert_format(o, 4, req_comp, g->w, g->h);
  3671. return o;
  3672. }
  3673. case 0x21: // Comment Extension.
  3674. {
  3675. int len;
  3676. if (get8(s) == 0xF9) { // Graphic Control Extension.
  3677. len = get8(s);
  3678. if (len == 4) {
  3679. g->eflags = get8(s);
  3680. get16le(s); // delay
  3681. g->transparent = get8(s);
  3682. } else {
  3683. skip(s, len);
  3684. break;
  3685. }
  3686. }
  3687. while ((len = get8(s)) != 0)
  3688. skip(s, len);
  3689. break;
  3690. }
  3691. case 0x3B: // gif stream termination code
  3692. return (uint8 *) 1;
  3693. default:
  3694. return epuc("unknown code", "Corrupt GIF");
  3695. }
  3696. }
  3697. }
  3698. static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  3699. {
  3700. uint8 *u = 0;
  3701. stbi_gif g={0};
  3702. u = stbi_gif_load_next(s, &g, comp, req_comp);
  3703. if (u == (void *) 1) u = 0; // end of animated gif marker
  3704. if (u) {
  3705. *x = g.w;
  3706. *y = g.h;
  3707. }
  3708. return u;
  3709. }
  3710. static int stbi_gif_info(stbi *s, int *x, int *y, int *comp)
  3711. {
  3712. return stbi_gif_info_raw(s,x,y,comp);
  3713. }
  3714. // *************************************************************************************************
  3715. // Radiance RGBE HDR loader
  3716. // originally by Nicolas Schulz
  3717. #ifndef STBI_NO_HDR
  3718. static int hdr_test(stbi *s)
  3719. {
  3720. const char *signature = "#?RADIANCE\n";
  3721. int i;
  3722. for (i=0; signature[i]; ++i)
  3723. if (get8(s) != signature[i])
  3724. return 0;
  3725. return 1;
  3726. }
  3727. static int stbi_hdr_test(stbi* s)
  3728. {
  3729. int r = hdr_test(s);
  3730. stbi_rewind(s);
  3731. return r;
  3732. }
  3733. #define HDR_BUFLEN 1024
  3734. static char *hdr_gettoken(stbi *z, char *buffer)
  3735. {
  3736. int len=0;
  3737. char c = '\0';
  3738. c = (char) get8(z);
  3739. while (!at_eof(z) && c != '\n') {
  3740. buffer[len++] = c;
  3741. if (len == HDR_BUFLEN-1) {
  3742. // flush to end of line
  3743. while (!at_eof(z) && get8(z) != '\n')
  3744. ;
  3745. break;
  3746. }
  3747. c = (char) get8(z);
  3748. }
  3749. buffer[len] = 0;
  3750. return buffer;
  3751. }
  3752. static void hdr_convert(float *output, stbi_uc *input, int req_comp)
  3753. {
  3754. if ( input[3] != 0 ) {
  3755. float f1;
  3756. // Exponent
  3757. f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
  3758. if (req_comp <= 2)
  3759. output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
  3760. else {
  3761. output[0] = input[0] * f1;
  3762. output[1] = input[1] * f1;
  3763. output[2] = input[2] * f1;
  3764. }
  3765. if (req_comp == 2) output[1] = 1;
  3766. if (req_comp == 4) output[3] = 1;
  3767. } else {
  3768. switch (req_comp) {
  3769. case 4: output[3] = 1; /* fallthrough */
  3770. case 3: output[0] = output[1] = output[2] = 0;
  3771. break;
  3772. case 2: output[1] = 1; /* fallthrough */
  3773. case 1: output[0] = 0;
  3774. break;
  3775. }
  3776. }
  3777. }
  3778. static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  3779. {
  3780. char buffer[HDR_BUFLEN];
  3781. char *token;
  3782. int valid = 0;
  3783. int width, height;
  3784. stbi_uc *scanline;
  3785. float *hdr_data;
  3786. int len;
  3787. unsigned char count, value;
  3788. int i, j, k, c1,c2, z;
  3789. // Check identifier
  3790. if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
  3791. return epf("not HDR", "Corrupt HDR image");
  3792. // Parse header
  3793. for(;;) {
  3794. token = hdr_gettoken(s,buffer);
  3795. if (token[0] == 0) break;
  3796. if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
  3797. }
  3798. if (!valid) return epf("unsupported format", "Unsupported HDR format");
  3799. // Parse width and height
  3800. // can't use sscanf() if we're not using stdio!
  3801. token = hdr_gettoken(s,buffer);
  3802. if (strncmp(token, "-Y ", 3)) return epf("unsupported data layout", "Unsupported HDR format");
  3803. token += 3;
  3804. height = strtol(token, &token, 10);
  3805. while (*token == ' ') ++token;
  3806. if (strncmp(token, "+X ", 3)) return epf("unsupported data layout", "Unsupported HDR format");
  3807. token += 3;
  3808. width = strtol(token, NULL, 10);
  3809. *x = width;
  3810. *y = height;
  3811. *comp = 3;
  3812. if (req_comp == 0) req_comp = 3;
  3813. // Read data
  3814. hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));
  3815. // Load image data
  3816. // image data is stored as some number of sca
  3817. if ( width < 8 || width >= 32768) {
  3818. // Read flat data
  3819. for (j=0; j < height; ++j) {
  3820. for (i=0; i < width; ++i) {
  3821. stbi_uc rgbe[4];
  3822. main_decode_loop:
  3823. getn(s, rgbe, 4);
  3824. hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
  3825. }
  3826. }
  3827. } else {
  3828. // Read RLE-encoded data
  3829. scanline = NULL;
  3830. for (j = 0; j < height; ++j) {
  3831. c1 = get8(s);
  3832. c2 = get8(s);
  3833. len = get8(s);
  3834. if (c1 != 2 || c2 != 2 || (len & 0x80)) {
  3835. // not run-length encoded, so we have to actually use THIS data as a decoded
  3836. // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
  3837. uint8 rgbe[4];
  3838. rgbe[0] = (uint8) c1;
  3839. rgbe[1] = (uint8) c2;
  3840. rgbe[2] = (uint8) len;
  3841. rgbe[3] = (uint8) get8u(s);
  3842. hdr_convert(hdr_data, rgbe, req_comp);
  3843. i = 1;
  3844. j = 0;
  3845. free(scanline);
  3846. goto main_decode_loop; // yes, this makes no sense
  3847. }
  3848. len <<= 8;
  3849. len |= get8(s);
  3850. if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }
  3851. if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);
  3852. for (k = 0; k < 4; ++k) {
  3853. i = 0;
  3854. while (i < width) {
  3855. count = get8u(s);
  3856. if (count > 128) {
  3857. // Run
  3858. value = get8u(s);
  3859. count -= 128;
  3860. for (z = 0; z < count; ++z)
  3861. scanline[i++ * 4 + k] = value;
  3862. } else {
  3863. // Dump
  3864. for (z = 0; z < count; ++z)
  3865. scanline[i++ * 4 + k] = get8u(s);
  3866. }
  3867. }
  3868. }
  3869. for (i=0; i < width; ++i)
  3870. hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
  3871. }
  3872. free(scanline);
  3873. }
  3874. return hdr_data;
  3875. }
  3876. static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
  3877. {
  3878. return hdr_load(s,x,y,comp,req_comp);
  3879. }
  3880. static int stbi_hdr_info(stbi *s, int *x, int *y, int *comp)
  3881. {
  3882. char buffer[HDR_BUFLEN];
  3883. char *token;
  3884. int valid = 0;
  3885. if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {
  3886. stbi_rewind( s );
  3887. return 0;
  3888. }
  3889. for(;;) {
  3890. token = hdr_gettoken(s,buffer);
  3891. if (token[0] == 0) break;
  3892. if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
  3893. }
  3894. if (!valid) {
  3895. stbi_rewind( s );
  3896. return 0;
  3897. }
  3898. token = hdr_gettoken(s,buffer);
  3899. if (strncmp(token, "-Y ", 3)) {
  3900. stbi_rewind( s );
  3901. return 0;
  3902. }
  3903. token += 3;
  3904. *y = strtol(token, &token, 10);
  3905. while (*token == ' ') ++token;
  3906. if (strncmp(token, "+X ", 3)) {
  3907. stbi_rewind( s );
  3908. return 0;
  3909. }
  3910. token += 3;
  3911. *x = strtol(token, NULL, 10);
  3912. *comp = 3;
  3913. return 1;
  3914. }
  3915. #endif // STBI_NO_HDR
  3916. static int stbi_bmp_info(stbi *s, int *x, int *y, int *comp)
  3917. {
  3918. int hsz;
  3919. if (get8(s) != 'B' || get8(s) != 'M') {
  3920. stbi_rewind( s );
  3921. return 0;
  3922. }
  3923. skip(s,12);
  3924. hsz = get32le(s);
  3925. if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {
  3926. stbi_rewind( s );
  3927. return 0;
  3928. }
  3929. if (hsz == 12) {
  3930. *x = get16le(s);
  3931. *y = get16le(s);
  3932. } else {
  3933. *x = get32le(s);
  3934. *y = get32le(s);
  3935. }
  3936. if (get16le(s) != 1) {
  3937. stbi_rewind( s );
  3938. return 0;
  3939. }
  3940. *comp = get16le(s) / 8;
  3941. return 1;
  3942. }
  3943. static int stbi_psd_info(stbi *s, int *x, int *y, int *comp)
  3944. {
  3945. int channelCount;
  3946. if (get32(s) != 0x38425053) {
  3947. stbi_rewind( s );
  3948. return 0;
  3949. }
  3950. if (get16(s) != 1) {
  3951. stbi_rewind( s );
  3952. return 0;
  3953. }
  3954. skip(s, 6);
  3955. channelCount = get16(s);
  3956. if (channelCount < 0 || channelCount > 16) {
  3957. stbi_rewind( s );
  3958. return 0;
  3959. }
  3960. *y = get32(s);
  3961. *x = get32(s);
  3962. if (get16(s) != 8) {
  3963. stbi_rewind( s );
  3964. return 0;
  3965. }
  3966. if (get16(s) != 3) {
  3967. stbi_rewind( s );
  3968. return 0;
  3969. }
  3970. *comp = 4;
  3971. return 1;
  3972. }
  3973. static int stbi_pic_info(stbi *s, int *x, int *y, int *comp)
  3974. {
  3975. int act_comp=0,num_packets=0,chained;
  3976. pic_packet_t packets[10];
  3977. skip(s, 92);
  3978. *x = get16(s);
  3979. *y = get16(s);
  3980. if (at_eof(s)) return 0;
  3981. if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
  3982. stbi_rewind( s );
  3983. return 0;
  3984. }
  3985. skip(s, 8);
  3986. do {
  3987. pic_packet_t *packet;
  3988. if (num_packets==sizeof(packets)/sizeof(packets[0]))
  3989. return 0;
  3990. packet = &packets[num_packets++];
  3991. chained = get8(s);
  3992. packet->size = get8u(s);
  3993. packet->type = get8u(s);
  3994. packet->channel = get8u(s);
  3995. act_comp |= packet->channel;
  3996. if (at_eof(s)) {
  3997. stbi_rewind( s );
  3998. return 0;
  3999. }
  4000. if (packet->size != 8) {
  4001. stbi_rewind( s );
  4002. return 0;
  4003. }
  4004. } while (chained);
  4005. *comp = (act_comp & 0x10 ? 4 : 3);
  4006. return 1;
  4007. }
  4008. static int stbi_info_main(stbi *s, int *x, int *y, int *comp)
  4009. {
  4010. if (stbi_jpeg_info(s, x, y, comp))
  4011. return 1;
  4012. if (stbi_png_info(s, x, y, comp))
  4013. return 1;
  4014. if (stbi_gif_info(s, x, y, comp))
  4015. return 1;
  4016. if (stbi_bmp_info(s, x, y, comp))
  4017. return 1;
  4018. if (stbi_psd_info(s, x, y, comp))
  4019. return 1;
  4020. if (stbi_pic_info(s, x, y, comp))
  4021. return 1;
  4022. #ifndef STBI_NO_HDR
  4023. if (stbi_hdr_info(s, x, y, comp))
  4024. return 1;
  4025. #endif
  4026. // test tga last because it's a crappy test!
  4027. if (stbi_tga_info(s, x, y, comp))
  4028. return 1;
  4029. return e("unknown image type", "Image not of any known type, or corrupt");
  4030. }
  4031. #ifndef STBI_NO_STDIO
  4032. int stbi_info(char const *filename, int *x, int *y, int *comp)
  4033. {
  4034. FILE *f = fopen(filename, "rb");
  4035. int result;
  4036. if (!f) return e("can't fopen", "Unable to open file");
  4037. result = stbi_info_from_file(f, x, y, comp);
  4038. fclose(f);
  4039. return result;
  4040. }
  4041. int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
  4042. {
  4043. int r;
  4044. stbi s;
  4045. long pos = ftell(f);
  4046. start_file(&s, f);
  4047. r = stbi_info_main(&s,x,y,comp);
  4048. fseek(f,pos,SEEK_SET);
  4049. return r;
  4050. }
  4051. #endif // !STBI_NO_STDIO
  4052. int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
  4053. {
  4054. stbi s;
  4055. start_mem(&s,buffer,len);
  4056. return stbi_info_main(&s,x,y,comp);
  4057. }
  4058. int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
  4059. {
  4060. stbi s;
  4061. start_callbacks(&s, (stbi_io_callbacks *) c, user);
  4062. return stbi_info_main(&s,x,y,comp);
  4063. }
  4064. #endif // STBI_HEADER_FILE_ONLY
  4065. /*
  4066. revision history:
  4067. 1.33 (2011-07-14)
  4068. make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
  4069. 1.32 (2011-07-13)
  4070. support for "info" function for all supported filetypes (SpartanJ)
  4071. 1.31 (2011-06-20)
  4072. a few more leak fixes, bug in PNG handling (SpartanJ)
  4073. 1.30 (2011-06-11)
  4074. added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
  4075. removed deprecated format-specific test/load functions
  4076. removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
  4077. error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
  4078. fix inefficiency in decoding 32-bit BMP (David Woo)
  4079. 1.29 (2010-08-16)
  4080. various warning fixes from Aurelien Pocheville
  4081. 1.28 (2010-08-01)
  4082. fix bug in GIF palette transparency (SpartanJ)
  4083. 1.27 (2010-08-01)
  4084. cast-to-uint8 to fix warnings
  4085. 1.26 (2010-07-24)
  4086. fix bug in file buffering for PNG reported by SpartanJ
  4087. 1.25 (2010-07-17)
  4088. refix trans_data warning (Won Chun)
  4089. 1.24 (2010-07-12)
  4090. perf improvements reading from files on platforms with lock-heavy fgetc()
  4091. minor perf improvements for jpeg
  4092. deprecated type-specific functions so we'll get feedback if they're needed
  4093. attempt to fix trans_data warning (Won Chun)
  4094. 1.23 fixed bug in iPhone support
  4095. 1.22 (2010-07-10)
  4096. removed image *writing* support
  4097. stbi_info support from Jetro Lauha
  4098. GIF support from Jean-Marc Lienher
  4099. iPhone PNG-extensions from James Brown
  4100. warning-fixes from Nicolas Schulz and Janez Zemva (i.e. Janez (U+017D)emva)
  4101. 1.21 fix use of 'uint8' in header (reported by jon blow)
  4102. 1.20 added support for Softimage PIC, by Tom Seddon
  4103. 1.19 bug in interlaced PNG corruption check (found by ryg)
  4104. 1.18 2008-08-02
  4105. fix a threading bug (local mutable static)
  4106. 1.17 support interlaced PNG
  4107. 1.16 major bugfix - convert_format converted one too many pixels
  4108. 1.15 initialize some fields for thread safety
  4109. 1.14 fix threadsafe conversion bug
  4110. header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
  4111. 1.13 threadsafe
  4112. 1.12 const qualifiers in the API
  4113. 1.11 Support installable IDCT, colorspace conversion routines
  4114. 1.10 Fixes for 64-bit (don't use "unsigned long")
  4115. optimized upsampling by Fabian "ryg" Giesen
  4116. 1.09 Fix format-conversion for PSD code (bad global variables!)
  4117. 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
  4118. 1.07 attempt to fix C++ warning/errors again
  4119. 1.06 attempt to fix C++ warning/errors again
  4120. 1.05 fix TGA loading to return correct *comp and use good luminance calc
  4121. 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
  4122. 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
  4123. 1.02 support for (subset of) HDR files, float interface for preferred access to them
  4124. 1.01 fix bug: possible bug in handling right-side up bmps... not sure
  4125. fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all
  4126. 1.00 interface to zlib that skips zlib header
  4127. 0.99 correct handling of alpha in palette
  4128. 0.98 TGA loader by lonesock; dynamically add loaders (untested)
  4129. 0.97 jpeg errors on too large a file; also catch another malloc failure
  4130. 0.96 fix detection of invalid v value - particleman@mollyrocket forum
  4131. 0.95 during header scan, seek to markers in case of padding
  4132. 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
  4133. 0.93 handle jpegtran output; verbose errors
  4134. 0.92 read 4,8,16,24,32-bit BMP files of several formats
  4135. 0.91 output 24-bit Windows 3.0 BMP files
  4136. 0.90 fix a few more warnings; bump version number to approach 1.0
  4137. 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
  4138. 0.60 fix compiling as c++
  4139. 0.59 fix warnings: merge Dave Moore's -Wall fixes
  4140. 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
  4141. 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
  4142. 0.56 fix bug: zlib uncompressed mode len vs. nlen
  4143. 0.55 fix bug: restart_interval not initialized to 0
  4144. 0.54 allow NULL for 'int *comp'
  4145. 0.53 fix bug in png 3->4; speedup png decoding
  4146. 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
  4147. 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
  4148. on 'test' only check type, not whether we support this variant
  4149. 0.50 first released version
  4150. */