Counter Strike : Global Offensive Source Code
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.

5099 lines
161 KiB

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