🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
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.

6755 lines
227 KiB

  1. /* stb_image - v2.12 - public domain image loader - http://nothings.org/stb_image.h
  2. no warranty implied; use at your own risk
  3. Do this:
  4. #define STB_IMAGE_IMPLEMENTATION
  5. before you include this file in *one* C or C++ file to create the implementation.
  6. // i.e. it should look like this:
  7. #include ...
  8. #include ...
  9. #include ...
  10. #define STB_IMAGE_IMPLEMENTATION
  11. #include "stb_image.h"
  12. You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
  13. And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
  14. QUICK NOTES:
  15. Primarily of interest to game developers and other people who can
  16. avoid problematic images and only need the trivial interface
  17. JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
  18. PNG 1/2/4/8-bit-per-channel (16 bpc not supported)
  19. TGA (not sure what subset, if a subset)
  20. BMP non-1bpp, non-RLE
  21. PSD (composited view only, no extra channels, 8/16 bit-per-channel)
  22. GIF (*comp always reports as 4-channel)
  23. HDR (radiance rgbE format)
  24. PIC (Softimage PIC)
  25. PNM (PPM and PGM binary only)
  26. Animated GIF still needs a proper API, but here's one way to do it:
  27. http://gist.github.com/urraka/685d9a6340b26b830d49
  28. - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
  29. - decode from arbitrary I/O callbacks
  30. - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)
  31. Full documentation under "DOCUMENTATION" below.
  32. Revision 2.00 release notes:
  33. - Progressive JPEG is now supported.
  34. - PPM and PGM binary formats are now supported, thanks to Ken Miller.
  35. - x86 platforms now make use of SSE2 SIMD instructions for
  36. JPEG decoding, and ARM platforms can use NEON SIMD if requested.
  37. This work was done by Fabian "ryg" Giesen. SSE2 is used by
  38. default, but NEON must be enabled explicitly; see docs.
  39. With other JPEG optimizations included in this version, we see
  40. 2x speedup on a JPEG on an x86 machine, and a 1.5x speedup
  41. on a JPEG on an ARM machine, relative to previous versions of this
  42. library. The same results will not obtain for all JPGs and for all
  43. x86/ARM machines. (Note that progressive JPEGs are significantly
  44. slower to decode than regular JPEGs.) This doesn't mean that this
  45. is the fastest JPEG decoder in the land; rather, it brings it
  46. closer to parity with standard libraries. If you want the fastest
  47. decode, look elsewhere. (See "Philosophy" section of docs below.)
  48. See final bullet items below for more info on SIMD.
  49. - Added STBI_MALLOC, STBI_REALLOC, and STBI_FREE macros for replacing
  50. the memory allocator. Unlike other STBI libraries, these macros don't
  51. support a context parameter, so if you need to pass a context in to
  52. the allocator, you'll have to store it in a global or a thread-local
  53. variable.
  54. - Split existing STBI_NO_HDR flag into two flags, STBI_NO_HDR and
  55. STBI_NO_LINEAR.
  56. STBI_NO_HDR: suppress implementation of .hdr reader format
  57. STBI_NO_LINEAR: suppress high-dynamic-range light-linear float API
  58. - You can suppress implementation of any of the decoders to reduce
  59. your code footprint by #defining one or more of the following
  60. symbols before creating the implementation.
  61. STBI_NO_JPEG
  62. STBI_NO_PNG
  63. STBI_NO_BMP
  64. STBI_NO_PSD
  65. STBI_NO_TGA
  66. STBI_NO_GIF
  67. STBI_NO_HDR
  68. STBI_NO_PIC
  69. STBI_NO_PNM (.ppm and .pgm)
  70. - You can request *only* certain decoders and suppress all other ones
  71. (this will be more forward-compatible, as addition of new decoders
  72. doesn't require you to disable them explicitly):
  73. STBI_ONLY_JPEG
  74. STBI_ONLY_PNG
  75. STBI_ONLY_BMP
  76. STBI_ONLY_PSD
  77. STBI_ONLY_TGA
  78. STBI_ONLY_GIF
  79. STBI_ONLY_HDR
  80. STBI_ONLY_PIC
  81. STBI_ONLY_PNM (.ppm and .pgm)
  82. Note that you can define multiples of these, and you will get all
  83. of them ("only x" and "only y" is interpreted to mean "only x&y").
  84. - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
  85. want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
  86. - Compilation of all SIMD code can be suppressed with
  87. #define STBI_NO_SIMD
  88. It should not be necessary to disable SIMD unless you have issues
  89. compiling (e.g. using an x86 compiler which doesn't support SSE
  90. intrinsics or that doesn't support the method used to detect
  91. SSE2 support at run-time), and even those can be reported as
  92. bugs so I can refine the built-in compile-time checking to be
  93. smarter.
  94. - The old STBI_SIMD system which allowed installing a user-defined
  95. IDCT etc. has been removed. If you need this, don't upgrade. My
  96. assumption is that almost nobody was doing this, and those who
  97. were will find the built-in SIMD more satisfactory anyway.
  98. - RGB values computed for JPEG images are slightly different from
  99. previous versions of stb_image. (This is due to using less
  100. integer precision in SIMD.) The C code has been adjusted so
  101. that the same RGB values will be computed regardless of whether
  102. SIMD support is available, so your app should always produce
  103. consistent results. But these results are slightly different from
  104. previous versions. (Specifically, about 3% of available YCbCr values
  105. will compute different RGB results from pre-1.49 versions by +-1;
  106. most of the deviating values are one smaller in the G channel.)
  107. - If you must produce consistent results with previous versions of
  108. stb_image, #define STBI_JPEG_OLD and you will get the same results
  109. you used to; however, you will not get the SIMD speedups for
  110. the YCbCr-to-RGB conversion step (although you should still see
  111. significant JPEG speedup from the other changes).
  112. Please note that STBI_JPEG_OLD is a temporary feature; it will be
  113. removed in future versions of the library. It is only intended for
  114. near-term back-compatibility use.
  115. Latest revision history:
  116. 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
  117. 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64
  118. RGB-format JPEG; remove white matting in PSD;
  119. allocate large structures on the stack;
  120. correct channel count for PNG & BMP
  121. 2.10 (2016-01-22) avoid warning introduced in 2.09
  122. 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED
  123. 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA
  124. 2.07 (2015-09-13) partial animated GIF support
  125. limited 16-bit PSD support
  126. minor bugs, code cleanup, and compiler warnings
  127. 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value
  128. 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning
  129. 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit
  130. 2.03 (2015-04-12) additional corruption checking
  131. stbi_set_flip_vertically_on_load
  132. fix NEON support; fix mingw support
  133. 2.02 (2015-01-19) fix incorrect assert, fix warning
  134. 2.01 (2015-01-17) fix various warnings
  135. 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG
  136. 2.00 (2014-12-25) optimize JPEG, including x86 SSE2 & ARM NEON SIMD
  137. progressive JPEG
  138. PGM/PPM support
  139. STBI_MALLOC,STBI_REALLOC,STBI_FREE
  140. STBI_NO_*, STBI_ONLY_*
  141. GIF bugfix
  142. See end of file for full revision history.
  143. ============================ Contributors =========================
  144. Image formats Extensions, features
  145. Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info)
  146. Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info)
  147. Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG)
  148. Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks)
  149. Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG)
  150. Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip)
  151. Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD)
  152. urraka@github (animated gif) Junggon Kim (PNM comments)
  153. Daniel Gibson (16-bit TGA)
  154. Optimizations & bugfixes
  155. Fabian "ryg" Giesen
  156. Arseny Kapoulkine
  157. Bug & warning fixes
  158. Marc LeBlanc David Woo Guillaume George Martins Mozeiko
  159. Christpher Lloyd Martin Golini Jerry Jansson Joseph Thomson
  160. Dave Moore Roy Eltham Hayaki Saito Phil Jordan
  161. Won Chun Luke Graham Johan Duparc Nathan Reed
  162. the Horde3D community Thomas Ruf Ronny Chevalier Nick Verigakis
  163. Janez Zemva John Bartholomew Michal Cichon svdijk@github
  164. Jonathan Blow Ken Hamada Tero Hanninen Baldur Karlsson
  165. Laurent Gomila Cort Stratton Sergio Gonzalez romigrou@github
  166. Aruelien Pocheville Thibault Reuille Cass Everitt Matthew Gregan
  167. Ryamond Barbiero Paul Du Bois Engin Manap snagar@github
  168. Michaelangel007@github Oriol Ferrer Mesia socks-the-fox
  169. Blazej Dariusz Roszkowski
  170. LICENSE
  171. This software is dual-licensed to the public domain and under the following
  172. license: you are granted a perpetual, irrevocable license to copy, modify,
  173. publish, and distribute this file as you see fit.
  174. */
  175. #ifndef STBI_INCLUDE_STB_IMAGE_H
  176. #define STBI_INCLUDE_STB_IMAGE_H
  177. // DOCUMENTATION
  178. //
  179. // Limitations:
  180. // - no 16-bit-per-channel PNG
  181. // - no 12-bit-per-channel JPEG
  182. // - no JPEGs with arithmetic coding
  183. // - no 1-bit BMP
  184. // - GIF always returns *comp=4
  185. //
  186. // Basic usage (see HDR discussion below for HDR usage):
  187. // int x,y,n;
  188. // unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
  189. // // ... process data if not NULL ...
  190. // // ... x = width, y = height, n = # 8-bit components per pixel ...
  191. // // ... replace '0' with '1'..'4' to force that many components per pixel
  192. // // ... but 'n' will always be the number that it would have been if you said 0
  193. // stbi_image_free(data)
  194. //
  195. // Standard parameters:
  196. // int *x -- outputs image width in pixels
  197. // int *y -- outputs image height in pixels
  198. // int *comp -- outputs # of image components in image file
  199. // int req_comp -- if non-zero, # of image components requested in result
  200. //
  201. // The return value from an image loader is an 'unsigned char *' which points
  202. // to the pixel data, or NULL on an allocation failure or if the image is
  203. // corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
  204. // with each pixel consisting of N interleaved 8-bit components; the first
  205. // pixel pointed to is top-left-most in the image. There is no padding between
  206. // image scanlines or between pixels, regardless of format. The number of
  207. // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
  208. // If req_comp is non-zero, *comp has the number of components that _would_
  209. // have been output otherwise. E.g. if you set req_comp to 4, you will always
  210. // get RGBA output, but you can check *comp to see if it's trivially opaque
  211. // because e.g. there were only 3 channels in the source image.
  212. //
  213. // An output image with N components has the following components interleaved
  214. // in this order in each pixel:
  215. //
  216. // N=#comp components
  217. // 1 grey
  218. // 2 grey, alpha
  219. // 3 red, green, blue
  220. // 4 red, green, blue, alpha
  221. //
  222. // If image loading fails for any reason, the return value will be NULL,
  223. // and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
  224. // can be queried for an extremely brief, end-user unfriendly explanation
  225. // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
  226. // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
  227. // more user-friendly ones.
  228. //
  229. // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
  230. //
  231. // ===========================================================================
  232. //
  233. // Philosophy
  234. //
  235. // stb libraries are designed with the following priorities:
  236. //
  237. // 1. easy to use
  238. // 2. easy to maintain
  239. // 3. good performance
  240. //
  241. // Sometimes I let "good performance" creep up in priority over "easy to maintain",
  242. // and for best performance I may provide less-easy-to-use APIs that give higher
  243. // performance, in addition to the easy to use ones. Nevertheless, it's important
  244. // to keep in mind that from the standpoint of you, a client of this library,
  245. // all you care about is #1 and #3, and stb libraries do not emphasize #3 above all.
  246. //
  247. // Some secondary priorities arise directly from the first two, some of which
  248. // make more explicit reasons why performance can't be emphasized.
  249. //
  250. // - Portable ("ease of use")
  251. // - Small footprint ("easy to maintain")
  252. // - No dependencies ("ease of use")
  253. //
  254. // ===========================================================================
  255. //
  256. // I/O callbacks
  257. //
  258. // I/O callbacks allow you to read from arbitrary sources, like packaged
  259. // files or some other source. Data read from callbacks are processed
  260. // through a small internal buffer (currently 128 bytes) to try to reduce
  261. // overhead.
  262. //
  263. // The three functions you must define are "read" (reads some bytes of data),
  264. // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
  265. //
  266. // ===========================================================================
  267. //
  268. // SIMD support
  269. //
  270. // The JPEG decoder will try to automatically use SIMD kernels on x86 when
  271. // supported by the compiler. For ARM Neon support, you must explicitly
  272. // request it.
  273. //
  274. // (The old do-it-yourself SIMD API is no longer supported in the current
  275. // code.)
  276. //
  277. // On x86, SSE2 will automatically be used when available based on a run-time
  278. // test; if not, the generic C versions are used as a fall-back. On ARM targets,
  279. // the typical path is to have separate builds for NEON and non-NEON devices
  280. // (at least this is true for iOS and Android). Therefore, the NEON support is
  281. // toggled by a build flag: define STBI_NEON to get NEON loops.
  282. //
  283. // The output of the JPEG decoder is slightly different from versions where
  284. // SIMD support was introduced (that is, for versions before 1.49). The
  285. // difference is only +-1 in the 8-bit RGB channels, and only on a small
  286. // fraction of pixels. You can force the pre-1.49 behavior by defining
  287. // STBI_JPEG_OLD, but this will disable some of the SIMD decoding path
  288. // and hence cost some performance.
  289. //
  290. // If for some reason you do not want to use any of SIMD code, or if
  291. // you have issues compiling it, you can disable it entirely by
  292. // defining STBI_NO_SIMD.
  293. //
  294. // ===========================================================================
  295. //
  296. // HDR image support (disable by defining STBI_NO_HDR)
  297. //
  298. // stb_image now supports loading HDR images in general, and currently
  299. // the Radiance .HDR file format, although the support is provided
  300. // generically. You can still load any file through the existing interface;
  301. // if you attempt to load an HDR file, it will be automatically remapped to
  302. // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
  303. // both of these constants can be reconfigured through this interface:
  304. //
  305. // stbi_hdr_to_ldr_gamma(2.2f);
  306. // stbi_hdr_to_ldr_scale(1.0f);
  307. //
  308. // (note, do not use _inverse_ constants; stbi_image will invert them
  309. // appropriately).
  310. //
  311. // Additionally, there is a new, parallel interface for loading files as
  312. // (linear) floats to preserve the full dynamic range:
  313. //
  314. // float *data = stbi_loadf(filename, &x, &y, &n, 0);
  315. //
  316. // If you load LDR images through this interface, those images will
  317. // be promoted to floating point values, run through the inverse of
  318. // constants corresponding to the above:
  319. //
  320. // stbi_ldr_to_hdr_scale(1.0f);
  321. // stbi_ldr_to_hdr_gamma(2.2f);
  322. //
  323. // Finally, given a filename (or an open file or memory block--see header
  324. // file for details) containing image data, you can query for the "most
  325. // appropriate" interface to use (that is, whether the image is HDR or
  326. // not), using:
  327. //
  328. // stbi_is_hdr(char *filename);
  329. //
  330. // ===========================================================================
  331. //
  332. // iPhone PNG support:
  333. //
  334. // By default we convert iphone-formatted PNGs back to RGB, even though
  335. // they are internally encoded differently. You can disable this conversion
  336. // by by calling stbi_convert_iphone_png_to_rgb(0), in which case
  337. // you will always just get the native iphone "format" through (which
  338. // is BGR stored in RGB).
  339. //
  340. // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
  341. // pixel to remove any premultiplied alpha *only* if the image file explicitly
  342. // says there's premultiplied data (currently only happens in iPhone images,
  343. // and only if iPhone convert-to-rgb processing is on).
  344. //
  345. #ifndef STBI_NO_STDIO
  346. #include <stdio.h>
  347. #endif // STBI_NO_STDIO
  348. #define STBI_VERSION 1
  349. enum
  350. {
  351. STBI_default = 0, // only used for req_comp
  352. STBI_grey = 1,
  353. STBI_grey_alpha = 2,
  354. STBI_rgb = 3,
  355. STBI_rgb_alpha = 4
  356. };
  357. typedef unsigned char stbi_uc;
  358. #ifdef __cplusplus
  359. extern "C" {
  360. #endif
  361. #ifdef STB_IMAGE_STATIC
  362. #define STBIDEF static
  363. #else
  364. #define STBIDEF extern
  365. #endif
  366. //////////////////////////////////////////////////////////////////////////////
  367. //
  368. // PRIMARY API - works on images of any type
  369. //
  370. //
  371. // load image by filename, open file, or memory buffer
  372. //
  373. typedef struct
  374. {
  375. int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
  376. void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
  377. int (*eof) (void *user); // returns nonzero if we are at end of file/data
  378. } stbi_io_callbacks;
  379. STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
  380. STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *comp, int req_comp);
  381. STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *comp, int req_comp);
  382. #ifndef STBI_NO_STDIO
  383. STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
  384. // for stbi_load_from_file, file pointer is left pointing immediately after image
  385. #endif
  386. #ifndef STBI_NO_LINEAR
  387. STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
  388. STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
  389. STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
  390. #ifndef STBI_NO_STDIO
  391. STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
  392. #endif
  393. #endif
  394. #ifndef STBI_NO_HDR
  395. STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
  396. STBIDEF void stbi_hdr_to_ldr_scale(float scale);
  397. #endif // STBI_NO_HDR
  398. #ifndef STBI_NO_LINEAR
  399. STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
  400. STBIDEF void stbi_ldr_to_hdr_scale(float scale);
  401. #endif // STBI_NO_LINEAR
  402. // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR
  403. STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
  404. STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
  405. #ifndef STBI_NO_STDIO
  406. STBIDEF int stbi_is_hdr (char const *filename);
  407. STBIDEF int stbi_is_hdr_from_file(FILE *f);
  408. #endif // STBI_NO_STDIO
  409. // get a VERY brief reason for failure
  410. // NOT THREADSAFE
  411. STBIDEF const char *stbi_failure_reason (void);
  412. // free the loaded image -- this is just free()
  413. STBIDEF void stbi_image_free (void *retval_from_stbi_load);
  414. // get image dimensions & components without fully decoding
  415. STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
  416. STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
  417. #ifndef STBI_NO_STDIO
  418. STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
  419. STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
  420. #endif
  421. // for image formats that explicitly notate that they have premultiplied alpha,
  422. // we just return the colors as stored in the file. set this flag to force
  423. // unpremultiplication. results are undefined if the unpremultiply overflow.
  424. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
  425. // indicate whether we should process iphone images back to canonical format,
  426. // or just pass them through "as-is"
  427. STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
  428. // flip the image vertically, so the first pixel in the output array is the bottom left
  429. STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
  430. // ZLIB client - used by PNG, available for other purposes
  431. STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
  432. STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
  433. STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
  434. STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  435. STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
  436. STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  437. #ifdef __cplusplus
  438. }
  439. #endif
  440. //
  441. //
  442. //// end header file /////////////////////////////////////////////////////
  443. #endif // STBI_INCLUDE_STB_IMAGE_H
  444. #ifdef STB_IMAGE_IMPLEMENTATION
  445. #if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \
  446. || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \
  447. || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \
  448. || defined(STBI_ONLY_ZLIB)
  449. #ifndef STBI_ONLY_JPEG
  450. #define STBI_NO_JPEG
  451. #endif
  452. #ifndef STBI_ONLY_PNG
  453. #define STBI_NO_PNG
  454. #endif
  455. #ifndef STBI_ONLY_BMP
  456. #define STBI_NO_BMP
  457. #endif
  458. #ifndef STBI_ONLY_PSD
  459. #define STBI_NO_PSD
  460. #endif
  461. #ifndef STBI_ONLY_TGA
  462. #define STBI_NO_TGA
  463. #endif
  464. #ifndef STBI_ONLY_GIF
  465. #define STBI_NO_GIF
  466. #endif
  467. #ifndef STBI_ONLY_HDR
  468. #define STBI_NO_HDR
  469. #endif
  470. #ifndef STBI_ONLY_PIC
  471. #define STBI_NO_PIC
  472. #endif
  473. #ifndef STBI_ONLY_PNM
  474. #define STBI_NO_PNM
  475. #endif
  476. #endif
  477. #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)
  478. #define STBI_NO_ZLIB
  479. #endif
  480. #include <stdarg.h>
  481. #include <stddef.h> // ptrdiff_t on osx
  482. #include <stdlib.h>
  483. #include <string.h>
  484. #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
  485. #include <math.h> // ldexp
  486. #endif
  487. #ifndef STBI_NO_STDIO
  488. #include <stdio.h>
  489. #endif
  490. #ifndef STBI_ASSERT
  491. #include <assert.h>
  492. #define STBI_ASSERT(x) assert(x)
  493. #endif
  494. #ifndef _MSC_VER
  495. #ifdef __cplusplus
  496. #define stbi_inline inline
  497. #else
  498. #define stbi_inline
  499. #endif
  500. #else
  501. #define stbi_inline __forceinline
  502. #endif
  503. #ifdef _MSC_VER
  504. typedef unsigned short stbi__uint16;
  505. typedef signed short stbi__int16;
  506. typedef unsigned int stbi__uint32;
  507. typedef signed int stbi__int32;
  508. #else
  509. #include <stdint.h>
  510. typedef uint16_t stbi__uint16;
  511. typedef int16_t stbi__int16;
  512. typedef uint32_t stbi__uint32;
  513. typedef int32_t stbi__int32;
  514. #endif
  515. // should produce compiler error if size is wrong
  516. typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
  517. #ifdef _MSC_VER
  518. #define STBI_NOTUSED(v) (void)(v)
  519. #else
  520. #define STBI_NOTUSED(v) (void)sizeof(v)
  521. #endif
  522. #ifdef _MSC_VER
  523. #define STBI_HAS_LROTL
  524. #endif
  525. #ifdef STBI_HAS_LROTL
  526. #define stbi_lrot(x,y) _lrotl(x,y)
  527. #else
  528. #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))
  529. #endif
  530. #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))
  531. // ok
  532. #elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED)
  533. // ok
  534. #else
  535. #error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)."
  536. #endif
  537. #ifndef STBI_MALLOC
  538. #define STBI_MALLOC(sz) malloc(sz)
  539. #define STBI_REALLOC(p,newsz) realloc(p,newsz)
  540. #define STBI_FREE(p) free(p)
  541. #endif
  542. #ifndef STBI_REALLOC_SIZED
  543. #define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz)
  544. #endif
  545. // x86/x64 detection
  546. #if defined(__x86_64__) || defined(_M_X64)
  547. #define STBI__X64_TARGET
  548. #elif defined(__i386) || defined(_M_IX86)
  549. #define STBI__X86_TARGET
  550. #endif
  551. #if defined(__GNUC__) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) && !defined(__SSE2__) && !defined(STBI_NO_SIMD)
  552. // NOTE: not clear do we actually need this for the 64-bit path?
  553. // gcc doesn't support sse2 intrinsics unless you compile with -msse2,
  554. // (but compiling with -msse2 allows the compiler to use SSE2 everywhere;
  555. // this is just broken and gcc are jerks for not fixing it properly
  556. // http://www.virtualdub.org/blog/pivot/entry.php?id=363 )
  557. #define STBI_NO_SIMD
  558. #endif
  559. #if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)
  560. // Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET
  561. //
  562. // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the
  563. // Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant.
  564. // As a result, enabling SSE2 on 32-bit MinGW is dangerous when not
  565. // simultaneously enabling "-mstackrealign".
  566. //
  567. // See https://github.com/nothings/stb/issues/81 for more information.
  568. //
  569. // So default to no SSE2 on 32-bit MinGW. If you've read this far and added
  570. // -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2.
  571. #define STBI_NO_SIMD
  572. #endif
  573. #if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))
  574. #define STBI_SSE2
  575. #include <emmintrin.h>
  576. #ifdef _MSC_VER
  577. #if _MSC_VER >= 1400 // not VC6
  578. #include <intrin.h> // __cpuid
  579. static int stbi__cpuid3(void)
  580. {
  581. int info[4];
  582. __cpuid(info,1);
  583. return info[3];
  584. }
  585. #else
  586. static int stbi__cpuid3(void)
  587. {
  588. int res;
  589. __asm {
  590. mov eax,1
  591. cpuid
  592. mov res,edx
  593. }
  594. return res;
  595. }
  596. #endif
  597. #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
  598. static int stbi__sse2_available()
  599. {
  600. int info3 = stbi__cpuid3();
  601. return ((info3 >> 26) & 1) != 0;
  602. }
  603. #else // assume GCC-style if not VC++
  604. #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
  605. static int stbi__sse2_available()
  606. {
  607. #if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 408 // GCC 4.8 or later
  608. // GCC 4.8+ has a nice way to do this
  609. return __builtin_cpu_supports("sse2");
  610. #else
  611. // portable way to do this, preferably without using GCC inline ASM?
  612. // just bail for now.
  613. return 0;
  614. #endif
  615. }
  616. #endif
  617. #endif
  618. // ARM NEON
  619. #if defined(STBI_NO_SIMD) && defined(STBI_NEON)
  620. #undef STBI_NEON
  621. #endif
  622. #ifdef STBI_NEON
  623. #include <arm_neon.h>
  624. // assume GCC or Clang on ARM targets
  625. #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
  626. #endif
  627. #ifndef STBI_SIMD_ALIGN
  628. #define STBI_SIMD_ALIGN(type, name) type name
  629. #endif
  630. ///////////////////////////////////////////////
  631. //
  632. // stbi__context struct and start_xxx functions
  633. // stbi__context structure is our basic context used by all images, so it
  634. // contains all the IO context, plus some basic image information
  635. typedef struct
  636. {
  637. stbi__uint32 img_x, img_y;
  638. int img_n, img_out_n;
  639. stbi_io_callbacks io;
  640. void *io_user_data;
  641. int read_from_callbacks;
  642. int buflen;
  643. stbi_uc buffer_start[128];
  644. stbi_uc *img_buffer, *img_buffer_end;
  645. stbi_uc *img_buffer_original, *img_buffer_original_end;
  646. } stbi__context;
  647. static void stbi__refill_buffer(stbi__context *s);
  648. // initialize a memory-decode context
  649. static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
  650. {
  651. s->io.read = NULL;
  652. s->read_from_callbacks = 0;
  653. s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
  654. s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len;
  655. }
  656. // initialize a callback-based context
  657. static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)
  658. {
  659. s->io = *c;
  660. s->io_user_data = user;
  661. s->buflen = sizeof(s->buffer_start);
  662. s->read_from_callbacks = 1;
  663. s->img_buffer_original = s->buffer_start;
  664. stbi__refill_buffer(s);
  665. s->img_buffer_original_end = s->img_buffer_end;
  666. }
  667. #ifndef STBI_NO_STDIO
  668. static int stbi__stdio_read(void *user, char *data, int size)
  669. {
  670. return (int) fread(data,1,size,(FILE*) user);
  671. }
  672. static void stbi__stdio_skip(void *user, int n)
  673. {
  674. fseek((FILE*) user, n, SEEK_CUR);
  675. }
  676. static int stbi__stdio_eof(void *user)
  677. {
  678. return feof((FILE*) user);
  679. }
  680. static stbi_io_callbacks stbi__stdio_callbacks =
  681. {
  682. stbi__stdio_read,
  683. stbi__stdio_skip,
  684. stbi__stdio_eof,
  685. };
  686. static void stbi__start_file(stbi__context *s, FILE *f)
  687. {
  688. stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);
  689. }
  690. //static void stop_file(stbi__context *s) { }
  691. #endif // !STBI_NO_STDIO
  692. static void stbi__rewind(stbi__context *s)
  693. {
  694. // conceptually rewind SHOULD rewind to the beginning of the stream,
  695. // but we just rewind to the beginning of the initial buffer, because
  696. // we only use it after doing 'test', which only ever looks at at most 92 bytes
  697. s->img_buffer = s->img_buffer_original;
  698. s->img_buffer_end = s->img_buffer_original_end;
  699. }
  700. #ifndef STBI_NO_JPEG
  701. static int stbi__jpeg_test(stbi__context *s);
  702. static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  703. static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);
  704. #endif
  705. #ifndef STBI_NO_PNG
  706. static int stbi__png_test(stbi__context *s);
  707. static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  708. static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);
  709. #endif
  710. #ifndef STBI_NO_BMP
  711. static int stbi__bmp_test(stbi__context *s);
  712. static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  713. static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp);
  714. #endif
  715. #ifndef STBI_NO_TGA
  716. static int stbi__tga_test(stbi__context *s);
  717. static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  718. static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);
  719. #endif
  720. #ifndef STBI_NO_PSD
  721. static int stbi__psd_test(stbi__context *s);
  722. static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  723. static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp);
  724. #endif
  725. #ifndef STBI_NO_HDR
  726. static int stbi__hdr_test(stbi__context *s);
  727. static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  728. static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp);
  729. #endif
  730. #ifndef STBI_NO_PIC
  731. static int stbi__pic_test(stbi__context *s);
  732. static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  733. static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp);
  734. #endif
  735. #ifndef STBI_NO_GIF
  736. static int stbi__gif_test(stbi__context *s);
  737. static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  738. static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);
  739. #endif
  740. #ifndef STBI_NO_PNM
  741. static int stbi__pnm_test(stbi__context *s);
  742. static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  743. static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);
  744. #endif
  745. // this is not threadsafe
  746. static const char *stbi__g_failure_reason;
  747. STBIDEF const char *stbi_failure_reason(void)
  748. {
  749. return stbi__g_failure_reason;
  750. }
  751. static int stbi__err(const char *str)
  752. {
  753. stbi__g_failure_reason = str;
  754. return 0;
  755. }
  756. static void *stbi__malloc(size_t size)
  757. {
  758. return STBI_MALLOC(size);
  759. }
  760. // stbi__err - error
  761. // stbi__errpf - error returning pointer to float
  762. // stbi__errpuc - error returning pointer to unsigned char
  763. #ifdef STBI_NO_FAILURE_STRINGS
  764. #define stbi__err(x,y) 0
  765. #elif defined(STBI_FAILURE_USERMSG)
  766. #define stbi__err(x,y) stbi__err(y)
  767. #else
  768. #define stbi__err(x,y) stbi__err(x)
  769. #endif
  770. #define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL))
  771. #define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL))
  772. STBIDEF void stbi_image_free(void *retval_from_stbi_load)
  773. {
  774. STBI_FREE(retval_from_stbi_load);
  775. }
  776. #ifndef STBI_NO_LINEAR
  777. static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
  778. #endif
  779. #ifndef STBI_NO_HDR
  780. static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp);
  781. #endif
  782. static int stbi__vertically_flip_on_load = 0;
  783. STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)
  784. {
  785. stbi__vertically_flip_on_load = flag_true_if_should_flip;
  786. }
  787. static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  788. {
  789. #ifndef STBI_NO_JPEG
  790. if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp);
  791. #endif
  792. #ifndef STBI_NO_PNG
  793. if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp);
  794. #endif
  795. #ifndef STBI_NO_BMP
  796. if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp);
  797. #endif
  798. #ifndef STBI_NO_GIF
  799. if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp);
  800. #endif
  801. #ifndef STBI_NO_PSD
  802. if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp);
  803. #endif
  804. #ifndef STBI_NO_PIC
  805. if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp);
  806. #endif
  807. #ifndef STBI_NO_PNM
  808. if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp);
  809. #endif
  810. #ifndef STBI_NO_HDR
  811. if (stbi__hdr_test(s)) {
  812. float *hdr = stbi__hdr_load(s, x,y,comp,req_comp);
  813. return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
  814. }
  815. #endif
  816. #ifndef STBI_NO_TGA
  817. // test tga last because it's a crappy test!
  818. if (stbi__tga_test(s))
  819. return stbi__tga_load(s,x,y,comp,req_comp);
  820. #endif
  821. return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
  822. }
  823. static unsigned char *stbi__load_flip(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  824. {
  825. unsigned char *result = stbi__load_main(s, x, y, comp, req_comp);
  826. if (stbi__vertically_flip_on_load && result != NULL) {
  827. int w = *x, h = *y;
  828. int depth = req_comp ? req_comp : *comp;
  829. int row,col,z;
  830. stbi_uc temp;
  831. // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once
  832. for (row = 0; row < (h>>1); row++) {
  833. for (col = 0; col < w; col++) {
  834. for (z = 0; z < depth; z++) {
  835. temp = result[(row * w + col) * depth + z];
  836. result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z];
  837. result[((h - row - 1) * w + col) * depth + z] = temp;
  838. }
  839. }
  840. }
  841. }
  842. return result;
  843. }
  844. #ifndef STBI_NO_HDR
  845. static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp)
  846. {
  847. if (stbi__vertically_flip_on_load && result != NULL) {
  848. int w = *x, h = *y;
  849. int depth = req_comp ? req_comp : *comp;
  850. int row,col,z;
  851. float temp;
  852. // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once
  853. for (row = 0; row < (h>>1); row++) {
  854. for (col = 0; col < w; col++) {
  855. for (z = 0; z < depth; z++) {
  856. temp = result[(row * w + col) * depth + z];
  857. result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z];
  858. result[((h - row - 1) * w + col) * depth + z] = temp;
  859. }
  860. }
  861. }
  862. }
  863. }
  864. #endif
  865. #ifndef STBI_NO_STDIO
  866. static FILE *stbi__fopen(char const *filename, char const *mode)
  867. {
  868. FILE *f;
  869. #if defined(_MSC_VER) && _MSC_VER >= 1400
  870. if (0 != fopen_s(&f, filename, mode))
  871. f=0;
  872. #else
  873. f = fopen(filename, mode);
  874. #endif
  875. return f;
  876. }
  877. STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
  878. {
  879. FILE *f = stbi__fopen(filename, "rb");
  880. unsigned char *result;
  881. if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
  882. result = stbi_load_from_file(f,x,y,comp,req_comp);
  883. fclose(f);
  884. return result;
  885. }
  886. STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
  887. {
  888. unsigned char *result;
  889. stbi__context s;
  890. stbi__start_file(&s,f);
  891. result = stbi__load_flip(&s,x,y,comp,req_comp);
  892. if (result) {
  893. // need to 'unget' all the characters in the IO buffer
  894. fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
  895. }
  896. return result;
  897. }
  898. #endif //!STBI_NO_STDIO
  899. STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  900. {
  901. stbi__context s;
  902. stbi__start_mem(&s,buffer,len);
  903. return stbi__load_flip(&s,x,y,comp,req_comp);
  904. }
  905. STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  906. {
  907. stbi__context s;
  908. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  909. return stbi__load_flip(&s,x,y,comp,req_comp);
  910. }
  911. #ifndef STBI_NO_LINEAR
  912. static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  913. {
  914. unsigned char *data;
  915. #ifndef STBI_NO_HDR
  916. if (stbi__hdr_test(s)) {
  917. float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp);
  918. if (hdr_data)
  919. stbi__float_postprocess(hdr_data,x,y,comp,req_comp);
  920. return hdr_data;
  921. }
  922. #endif
  923. data = stbi__load_flip(s, x, y, comp, req_comp);
  924. if (data)
  925. return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
  926. return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
  927. }
  928. STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  929. {
  930. stbi__context s;
  931. stbi__start_mem(&s,buffer,len);
  932. return stbi__loadf_main(&s,x,y,comp,req_comp);
  933. }
  934. STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  935. {
  936. stbi__context s;
  937. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  938. return stbi__loadf_main(&s,x,y,comp,req_comp);
  939. }
  940. #ifndef STBI_NO_STDIO
  941. STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
  942. {
  943. float *result;
  944. FILE *f = stbi__fopen(filename, "rb");
  945. if (!f) return stbi__errpf("can't fopen", "Unable to open file");
  946. result = stbi_loadf_from_file(f,x,y,comp,req_comp);
  947. fclose(f);
  948. return result;
  949. }
  950. STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
  951. {
  952. stbi__context s;
  953. stbi__start_file(&s,f);
  954. return stbi__loadf_main(&s,x,y,comp,req_comp);
  955. }
  956. #endif // !STBI_NO_STDIO
  957. #endif // !STBI_NO_LINEAR
  958. // these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is
  959. // defined, for API simplicity; if STBI_NO_LINEAR is defined, it always
  960. // reports false!
  961. STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
  962. {
  963. #ifndef STBI_NO_HDR
  964. stbi__context s;
  965. stbi__start_mem(&s,buffer,len);
  966. return stbi__hdr_test(&s);
  967. #else
  968. STBI_NOTUSED(buffer);
  969. STBI_NOTUSED(len);
  970. return 0;
  971. #endif
  972. }
  973. #ifndef STBI_NO_STDIO
  974. STBIDEF int stbi_is_hdr (char const *filename)
  975. {
  976. FILE *f = stbi__fopen(filename, "rb");
  977. int result=0;
  978. if (f) {
  979. result = stbi_is_hdr_from_file(f);
  980. fclose(f);
  981. }
  982. return result;
  983. }
  984. STBIDEF int stbi_is_hdr_from_file(FILE *f)
  985. {
  986. #ifndef STBI_NO_HDR
  987. stbi__context s;
  988. stbi__start_file(&s,f);
  989. return stbi__hdr_test(&s);
  990. #else
  991. STBI_NOTUSED(f);
  992. return 0;
  993. #endif
  994. }
  995. #endif // !STBI_NO_STDIO
  996. STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
  997. {
  998. #ifndef STBI_NO_HDR
  999. stbi__context s;
  1000. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  1001. return stbi__hdr_test(&s);
  1002. #else
  1003. STBI_NOTUSED(clbk);
  1004. STBI_NOTUSED(user);
  1005. return 0;
  1006. #endif
  1007. }
  1008. #ifndef STBI_NO_LINEAR
  1009. static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;
  1010. STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
  1011. STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
  1012. #endif
  1013. static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
  1014. STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
  1015. STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
  1016. //////////////////////////////////////////////////////////////////////////////
  1017. //
  1018. // Common code used by all image loaders
  1019. //
  1020. enum
  1021. {
  1022. STBI__SCAN_load=0,
  1023. STBI__SCAN_type,
  1024. STBI__SCAN_header
  1025. };
  1026. static void stbi__refill_buffer(stbi__context *s)
  1027. {
  1028. int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
  1029. if (n == 0) {
  1030. // at end of file, treat same as if from memory, but need to handle case
  1031. // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
  1032. s->read_from_callbacks = 0;
  1033. s->img_buffer = s->buffer_start;
  1034. s->img_buffer_end = s->buffer_start+1;
  1035. *s->img_buffer = 0;
  1036. } else {
  1037. s->img_buffer = s->buffer_start;
  1038. s->img_buffer_end = s->buffer_start + n;
  1039. }
  1040. }
  1041. stbi_inline static stbi_uc stbi__get8(stbi__context *s)
  1042. {
  1043. if (s->img_buffer < s->img_buffer_end)
  1044. return *s->img_buffer++;
  1045. if (s->read_from_callbacks) {
  1046. stbi__refill_buffer(s);
  1047. return *s->img_buffer++;
  1048. }
  1049. return 0;
  1050. }
  1051. stbi_inline static int stbi__at_eof(stbi__context *s)
  1052. {
  1053. if (s->io.read) {
  1054. if (!(s->io.eof)(s->io_user_data)) return 0;
  1055. // if feof() is true, check if buffer = end
  1056. // special case: we've only got the special 0 character at the end
  1057. if (s->read_from_callbacks == 0) return 1;
  1058. }
  1059. return s->img_buffer >= s->img_buffer_end;
  1060. }
  1061. static void stbi__skip(stbi__context *s, int n)
  1062. {
  1063. if (n < 0) {
  1064. s->img_buffer = s->img_buffer_end;
  1065. return;
  1066. }
  1067. if (s->io.read) {
  1068. int blen = (int) (s->img_buffer_end - s->img_buffer);
  1069. if (blen < n) {
  1070. s->img_buffer = s->img_buffer_end;
  1071. (s->io.skip)(s->io_user_data, n - blen);
  1072. return;
  1073. }
  1074. }
  1075. s->img_buffer += n;
  1076. }
  1077. static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
  1078. {
  1079. if (s->io.read) {
  1080. int blen = (int) (s->img_buffer_end - s->img_buffer);
  1081. if (blen < n) {
  1082. int res, count;
  1083. memcpy(buffer, s->img_buffer, blen);
  1084. count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
  1085. res = (count == (n-blen));
  1086. s->img_buffer = s->img_buffer_end;
  1087. return res;
  1088. }
  1089. }
  1090. if (s->img_buffer+n <= s->img_buffer_end) {
  1091. memcpy(buffer, s->img_buffer, n);
  1092. s->img_buffer += n;
  1093. return 1;
  1094. } else
  1095. return 0;
  1096. }
  1097. static int stbi__get16be(stbi__context *s)
  1098. {
  1099. int z = stbi__get8(s);
  1100. return (z << 8) + stbi__get8(s);
  1101. }
  1102. static stbi__uint32 stbi__get32be(stbi__context *s)
  1103. {
  1104. stbi__uint32 z = stbi__get16be(s);
  1105. return (z << 16) + stbi__get16be(s);
  1106. }
  1107. #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF)
  1108. // nothing
  1109. #else
  1110. static int stbi__get16le(stbi__context *s)
  1111. {
  1112. int z = stbi__get8(s);
  1113. return z + (stbi__get8(s) << 8);
  1114. }
  1115. #endif
  1116. #ifndef STBI_NO_BMP
  1117. static stbi__uint32 stbi__get32le(stbi__context *s)
  1118. {
  1119. stbi__uint32 z = stbi__get16le(s);
  1120. return z + (stbi__get16le(s) << 16);
  1121. }
  1122. #endif
  1123. #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings
  1124. //////////////////////////////////////////////////////////////////////////////
  1125. //
  1126. // generic converter from built-in img_n to req_comp
  1127. // individual types do this automatically as much as possible (e.g. jpeg
  1128. // does all cases internally since it needs to colorspace convert anyway,
  1129. // and it never has alpha, so very few cases ). png can automatically
  1130. // interleave an alpha=255 channel, but falls back to this for other cases
  1131. //
  1132. // assume data buffer is malloced, so malloc a new one and free that one
  1133. // only failure mode is malloc failing
  1134. static stbi_uc stbi__compute_y(int r, int g, int b)
  1135. {
  1136. return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);
  1137. }
  1138. static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)
  1139. {
  1140. int i,j;
  1141. unsigned char *good;
  1142. if (req_comp == img_n) return data;
  1143. STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
  1144. good = (unsigned char *) stbi__malloc(req_comp * x * y);
  1145. if (good == NULL) {
  1146. STBI_FREE(data);
  1147. return stbi__errpuc("outofmem", "Out of memory");
  1148. }
  1149. for (j=0; j < (int) y; ++j) {
  1150. unsigned char *src = data + j * x * img_n ;
  1151. unsigned char *dest = good + j * x * req_comp;
  1152. #define COMBO(a,b) ((a)*8+(b))
  1153. #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
  1154. // convert source image with img_n components to one with req_comp components;
  1155. // avoid switch per pixel, so use switch per scanline and massive macros
  1156. switch (COMBO(img_n, req_comp)) {
  1157. CASE(1,2) dest[0]=src[0], dest[1]=255; break;
  1158. CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
  1159. CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
  1160. CASE(2,1) dest[0]=src[0]; break;
  1161. CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
  1162. CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
  1163. CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
  1164. CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;
  1165. CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
  1166. CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;
  1167. CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
  1168. CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
  1169. default: STBI_ASSERT(0);
  1170. }
  1171. #undef CASE
  1172. }
  1173. STBI_FREE(data);
  1174. return good;
  1175. }
  1176. #ifndef STBI_NO_LINEAR
  1177. static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
  1178. {
  1179. int i,k,n;
  1180. float *output = (float *) stbi__malloc(x * y * comp * sizeof(float));
  1181. if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); }
  1182. // compute number of non-alpha components
  1183. if (comp & 1) n = comp; else n = comp-1;
  1184. for (i=0; i < x*y; ++i) {
  1185. for (k=0; k < n; ++k) {
  1186. output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale);
  1187. }
  1188. if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
  1189. }
  1190. STBI_FREE(data);
  1191. return output;
  1192. }
  1193. #endif
  1194. #ifndef STBI_NO_HDR
  1195. #define stbi__float2int(x) ((int) (x))
  1196. static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)
  1197. {
  1198. int i,k,n;
  1199. stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp);
  1200. if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); }
  1201. // compute number of non-alpha components
  1202. if (comp & 1) n = comp; else n = comp-1;
  1203. for (i=0; i < x*y; ++i) {
  1204. for (k=0; k < n; ++k) {
  1205. float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;
  1206. if (z < 0) z = 0;
  1207. if (z > 255) z = 255;
  1208. output[i*comp + k] = (stbi_uc) stbi__float2int(z);
  1209. }
  1210. if (k < comp) {
  1211. float z = data[i*comp+k] * 255 + 0.5f;
  1212. if (z < 0) z = 0;
  1213. if (z > 255) z = 255;
  1214. output[i*comp + k] = (stbi_uc) stbi__float2int(z);
  1215. }
  1216. }
  1217. STBI_FREE(data);
  1218. return output;
  1219. }
  1220. #endif
  1221. //////////////////////////////////////////////////////////////////////////////
  1222. //
  1223. // "baseline" JPEG/JFIF decoder
  1224. //
  1225. // simple implementation
  1226. // - doesn't support delayed output of y-dimension
  1227. // - simple interface (only one output format: 8-bit interleaved RGB)
  1228. // - doesn't try to recover corrupt jpegs
  1229. // - doesn't allow partial loading, loading multiple at once
  1230. // - still fast on x86 (copying globals into locals doesn't help x86)
  1231. // - allocates lots of intermediate memory (full size of all components)
  1232. // - non-interleaved case requires this anyway
  1233. // - allows good upsampling (see next)
  1234. // high-quality
  1235. // - upsampled channels are bilinearly interpolated, even across blocks
  1236. // - quality integer IDCT derived from IJG's 'slow'
  1237. // performance
  1238. // - fast huffman; reasonable integer IDCT
  1239. // - some SIMD kernels for common paths on targets with SSE2/NEON
  1240. // - uses a lot of intermediate memory, could cache poorly
  1241. #ifndef STBI_NO_JPEG
  1242. // huffman decoding acceleration
  1243. #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
  1244. typedef struct
  1245. {
  1246. stbi_uc fast[1 << FAST_BITS];
  1247. // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
  1248. stbi__uint16 code[256];
  1249. stbi_uc values[256];
  1250. stbi_uc size[257];
  1251. unsigned int maxcode[18];
  1252. int delta[17]; // old 'firstsymbol' - old 'firstcode'
  1253. } stbi__huffman;
  1254. typedef struct
  1255. {
  1256. stbi__context *s;
  1257. stbi__huffman huff_dc[4];
  1258. stbi__huffman huff_ac[4];
  1259. stbi_uc dequant[4][64];
  1260. stbi__int16 fast_ac[4][1 << FAST_BITS];
  1261. // sizes for components, interleaved MCUs
  1262. int img_h_max, img_v_max;
  1263. int img_mcu_x, img_mcu_y;
  1264. int img_mcu_w, img_mcu_h;
  1265. // definition of jpeg image component
  1266. struct
  1267. {
  1268. int id;
  1269. int h,v;
  1270. int tq;
  1271. int hd,ha;
  1272. int dc_pred;
  1273. int x,y,w2,h2;
  1274. stbi_uc *data;
  1275. void *raw_data, *raw_coeff;
  1276. stbi_uc *linebuf;
  1277. short *coeff; // progressive only
  1278. int coeff_w, coeff_h; // number of 8x8 coefficient blocks
  1279. } img_comp[4];
  1280. stbi__uint32 code_buffer; // jpeg entropy-coded buffer
  1281. int code_bits; // number of valid bits
  1282. unsigned char marker; // marker seen while filling entropy buffer
  1283. int nomore; // flag if we saw a marker so must stop
  1284. int progressive;
  1285. int spec_start;
  1286. int spec_end;
  1287. int succ_high;
  1288. int succ_low;
  1289. int eob_run;
  1290. int rgb;
  1291. int scan_n, order[4];
  1292. int restart_interval, todo;
  1293. // kernels
  1294. void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]);
  1295. void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step);
  1296. stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs);
  1297. } stbi__jpeg;
  1298. static int stbi__build_huffman(stbi__huffman *h, int *count)
  1299. {
  1300. int i,j,k=0,code;
  1301. // build size list for each symbol (from JPEG spec)
  1302. for (i=0; i < 16; ++i)
  1303. for (j=0; j < count[i]; ++j)
  1304. h->size[k++] = (stbi_uc) (i+1);
  1305. h->size[k] = 0;
  1306. // compute actual symbols (from jpeg spec)
  1307. code = 0;
  1308. k = 0;
  1309. for(j=1; j <= 16; ++j) {
  1310. // compute delta to add to code to compute symbol id
  1311. h->delta[j] = k - code;
  1312. if (h->size[k] == j) {
  1313. while (h->size[k] == j)
  1314. h->code[k++] = (stbi__uint16) (code++);
  1315. if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG");
  1316. }
  1317. // compute largest code + 1 for this size, preshifted as needed later
  1318. h->maxcode[j] = code << (16-j);
  1319. code <<= 1;
  1320. }
  1321. h->maxcode[j] = 0xffffffff;
  1322. // build non-spec acceleration table; 255 is flag for not-accelerated
  1323. memset(h->fast, 255, 1 << FAST_BITS);
  1324. for (i=0; i < k; ++i) {
  1325. int s = h->size[i];
  1326. if (s <= FAST_BITS) {
  1327. int c = h->code[i] << (FAST_BITS-s);
  1328. int m = 1 << (FAST_BITS-s);
  1329. for (j=0; j < m; ++j) {
  1330. h->fast[c+j] = (stbi_uc) i;
  1331. }
  1332. }
  1333. }
  1334. return 1;
  1335. }
  1336. // build a table that decodes both magnitude and value of small ACs in
  1337. // one go.
  1338. static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h)
  1339. {
  1340. int i;
  1341. for (i=0; i < (1 << FAST_BITS); ++i) {
  1342. stbi_uc fast = h->fast[i];
  1343. fast_ac[i] = 0;
  1344. if (fast < 255) {
  1345. int rs = h->values[fast];
  1346. int run = (rs >> 4) & 15;
  1347. int magbits = rs & 15;
  1348. int len = h->size[fast];
  1349. if (magbits && len + magbits <= FAST_BITS) {
  1350. // magnitude code followed by receive_extend code
  1351. int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);
  1352. int m = 1 << (magbits - 1);
  1353. if (k < m) k += (-1 << magbits) + 1;
  1354. // if the result is small enough, we can fit it in fast_ac table
  1355. if (k >= -128 && k <= 127)
  1356. fast_ac[i] = (stbi__int16) ((k << 8) + (run << 4) + (len + magbits));
  1357. }
  1358. }
  1359. }
  1360. }
  1361. static void stbi__grow_buffer_unsafe(stbi__jpeg *j)
  1362. {
  1363. do {
  1364. int b = j->nomore ? 0 : stbi__get8(j->s);
  1365. if (b == 0xff) {
  1366. int c = stbi__get8(j->s);
  1367. if (c != 0) {
  1368. j->marker = (unsigned char) c;
  1369. j->nomore = 1;
  1370. return;
  1371. }
  1372. }
  1373. j->code_buffer |= b << (24 - j->code_bits);
  1374. j->code_bits += 8;
  1375. } while (j->code_bits <= 24);
  1376. }
  1377. // (1 << n) - 1
  1378. static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
  1379. // decode a jpeg huffman value from the bitstream
  1380. stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)
  1381. {
  1382. unsigned int temp;
  1383. int c,k;
  1384. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1385. // look at the top FAST_BITS and determine what symbol ID it is,
  1386. // if the code is <= FAST_BITS
  1387. c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
  1388. k = h->fast[c];
  1389. if (k < 255) {
  1390. int s = h->size[k];
  1391. if (s > j->code_bits)
  1392. return -1;
  1393. j->code_buffer <<= s;
  1394. j->code_bits -= s;
  1395. return h->values[k];
  1396. }
  1397. // naive test is to shift the code_buffer down so k bits are
  1398. // valid, then test against maxcode. To speed this up, we've
  1399. // preshifted maxcode left so that it has (16-k) 0s at the
  1400. // end; in other words, regardless of the number of bits, it
  1401. // wants to be compared against something shifted to have 16;
  1402. // that way we don't need to shift inside the loop.
  1403. temp = j->code_buffer >> 16;
  1404. for (k=FAST_BITS+1 ; ; ++k)
  1405. if (temp < h->maxcode[k])
  1406. break;
  1407. if (k == 17) {
  1408. // error! code not found
  1409. j->code_bits -= 16;
  1410. return -1;
  1411. }
  1412. if (k > j->code_bits)
  1413. return -1;
  1414. // convert the huffman code to the symbol id
  1415. c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
  1416. STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);
  1417. // convert the id to a symbol
  1418. j->code_bits -= k;
  1419. j->code_buffer <<= k;
  1420. return h->values[c];
  1421. }
  1422. // bias[n] = (-1<<n) + 1
  1423. static int const stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767};
  1424. // combined JPEG 'receive' and JPEG 'extend', since baseline
  1425. // always extends everything it receives.
  1426. stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
  1427. {
  1428. unsigned int k;
  1429. int sgn;
  1430. if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
  1431. sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB
  1432. k = stbi_lrot(j->code_buffer, n);
  1433. STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask)));
  1434. j->code_buffer = k & ~stbi__bmask[n];
  1435. k &= stbi__bmask[n];
  1436. j->code_bits -= n;
  1437. return k + (stbi__jbias[n] & ~sgn);
  1438. }
  1439. // get some unsigned bits
  1440. stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)
  1441. {
  1442. unsigned int k;
  1443. if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
  1444. k = stbi_lrot(j->code_buffer, n);
  1445. j->code_buffer = k & ~stbi__bmask[n];
  1446. k &= stbi__bmask[n];
  1447. j->code_bits -= n;
  1448. return k;
  1449. }
  1450. stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j)
  1451. {
  1452. unsigned int k;
  1453. if (j->code_bits < 1) stbi__grow_buffer_unsafe(j);
  1454. k = j->code_buffer;
  1455. j->code_buffer <<= 1;
  1456. --j->code_bits;
  1457. return k & 0x80000000;
  1458. }
  1459. // given a value that's at position X in the zigzag stream,
  1460. // where does it appear in the 8x8 matrix coded as row-major?
  1461. static stbi_uc stbi__jpeg_dezigzag[64+15] =
  1462. {
  1463. 0, 1, 8, 16, 9, 2, 3, 10,
  1464. 17, 24, 32, 25, 18, 11, 4, 5,
  1465. 12, 19, 26, 33, 40, 48, 41, 34,
  1466. 27, 20, 13, 6, 7, 14, 21, 28,
  1467. 35, 42, 49, 56, 57, 50, 43, 36,
  1468. 29, 22, 15, 23, 30, 37, 44, 51,
  1469. 58, 59, 52, 45, 38, 31, 39, 46,
  1470. 53, 60, 61, 54, 47, 55, 62, 63,
  1471. // let corrupt input sample past end
  1472. 63, 63, 63, 63, 63, 63, 63, 63,
  1473. 63, 63, 63, 63, 63, 63, 63
  1474. };
  1475. // decode one 64-entry block--
  1476. static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi_uc *dequant)
  1477. {
  1478. int diff,dc,k;
  1479. int t;
  1480. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1481. t = stbi__jpeg_huff_decode(j, hdc);
  1482. if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1483. // 0 all the ac values now so we can do it 32-bits at a time
  1484. memset(data,0,64*sizeof(data[0]));
  1485. diff = t ? stbi__extend_receive(j, t) : 0;
  1486. dc = j->img_comp[b].dc_pred + diff;
  1487. j->img_comp[b].dc_pred = dc;
  1488. data[0] = (short) (dc * dequant[0]);
  1489. // decode AC components, see JPEG spec
  1490. k = 1;
  1491. do {
  1492. unsigned int zig;
  1493. int c,r,s;
  1494. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1495. c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
  1496. r = fac[c];
  1497. if (r) { // fast-AC path
  1498. k += (r >> 4) & 15; // run
  1499. s = r & 15; // combined length
  1500. j->code_buffer <<= s;
  1501. j->code_bits -= s;
  1502. // decode into unzigzag'd location
  1503. zig = stbi__jpeg_dezigzag[k++];
  1504. data[zig] = (short) ((r >> 8) * dequant[zig]);
  1505. } else {
  1506. int rs = stbi__jpeg_huff_decode(j, hac);
  1507. if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1508. s = rs & 15;
  1509. r = rs >> 4;
  1510. if (s == 0) {
  1511. if (rs != 0xf0) break; // end block
  1512. k += 16;
  1513. } else {
  1514. k += r;
  1515. // decode into unzigzag'd location
  1516. zig = stbi__jpeg_dezigzag[k++];
  1517. data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]);
  1518. }
  1519. }
  1520. } while (k < 64);
  1521. return 1;
  1522. }
  1523. static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b)
  1524. {
  1525. int diff,dc;
  1526. int t;
  1527. if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
  1528. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1529. if (j->succ_high == 0) {
  1530. // first scan for DC coefficient, must be first
  1531. memset(data,0,64*sizeof(data[0])); // 0 all the ac values now
  1532. t = stbi__jpeg_huff_decode(j, hdc);
  1533. diff = t ? stbi__extend_receive(j, t) : 0;
  1534. dc = j->img_comp[b].dc_pred + diff;
  1535. j->img_comp[b].dc_pred = dc;
  1536. data[0] = (short) (dc << j->succ_low);
  1537. } else {
  1538. // refinement scan for DC coefficient
  1539. if (stbi__jpeg_get_bit(j))
  1540. data[0] += (short) (1 << j->succ_low);
  1541. }
  1542. return 1;
  1543. }
  1544. // @OPTIMIZE: store non-zigzagged during the decode passes,
  1545. // and only de-zigzag when dequantizing
  1546. static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac)
  1547. {
  1548. int k;
  1549. if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
  1550. if (j->succ_high == 0) {
  1551. int shift = j->succ_low;
  1552. if (j->eob_run) {
  1553. --j->eob_run;
  1554. return 1;
  1555. }
  1556. k = j->spec_start;
  1557. do {
  1558. unsigned int zig;
  1559. int c,r,s;
  1560. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1561. c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
  1562. r = fac[c];
  1563. if (r) { // fast-AC path
  1564. k += (r >> 4) & 15; // run
  1565. s = r & 15; // combined length
  1566. j->code_buffer <<= s;
  1567. j->code_bits -= s;
  1568. zig = stbi__jpeg_dezigzag[k++];
  1569. data[zig] = (short) ((r >> 8) << shift);
  1570. } else {
  1571. int rs = stbi__jpeg_huff_decode(j, hac);
  1572. if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1573. s = rs & 15;
  1574. r = rs >> 4;
  1575. if (s == 0) {
  1576. if (r < 15) {
  1577. j->eob_run = (1 << r);
  1578. if (r)
  1579. j->eob_run += stbi__jpeg_get_bits(j, r);
  1580. --j->eob_run;
  1581. break;
  1582. }
  1583. k += 16;
  1584. } else {
  1585. k += r;
  1586. zig = stbi__jpeg_dezigzag[k++];
  1587. data[zig] = (short) (stbi__extend_receive(j,s) << shift);
  1588. }
  1589. }
  1590. } while (k <= j->spec_end);
  1591. } else {
  1592. // refinement scan for these AC coefficients
  1593. short bit = (short) (1 << j->succ_low);
  1594. if (j->eob_run) {
  1595. --j->eob_run;
  1596. for (k = j->spec_start; k <= j->spec_end; ++k) {
  1597. short *p = &data[stbi__jpeg_dezigzag[k]];
  1598. if (*p != 0)
  1599. if (stbi__jpeg_get_bit(j))
  1600. if ((*p & bit)==0) {
  1601. if (*p > 0)
  1602. *p += bit;
  1603. else
  1604. *p -= bit;
  1605. }
  1606. }
  1607. } else {
  1608. k = j->spec_start;
  1609. do {
  1610. int r,s;
  1611. int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh
  1612. if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1613. s = rs & 15;
  1614. r = rs >> 4;
  1615. if (s == 0) {
  1616. if (r < 15) {
  1617. j->eob_run = (1 << r) - 1;
  1618. if (r)
  1619. j->eob_run += stbi__jpeg_get_bits(j, r);
  1620. r = 64; // force end of block
  1621. } else {
  1622. // r=15 s=0 should write 16 0s, so we just do
  1623. // a run of 15 0s and then write s (which is 0),
  1624. // so we don't have to do anything special here
  1625. }
  1626. } else {
  1627. if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG");
  1628. // sign bit
  1629. if (stbi__jpeg_get_bit(j))
  1630. s = bit;
  1631. else
  1632. s = -bit;
  1633. }
  1634. // advance by r
  1635. while (k <= j->spec_end) {
  1636. short *p = &data[stbi__jpeg_dezigzag[k++]];
  1637. if (*p != 0) {
  1638. if (stbi__jpeg_get_bit(j))
  1639. if ((*p & bit)==0) {
  1640. if (*p > 0)
  1641. *p += bit;
  1642. else
  1643. *p -= bit;
  1644. }
  1645. } else {
  1646. if (r == 0) {
  1647. *p = (short) s;
  1648. break;
  1649. }
  1650. --r;
  1651. }
  1652. }
  1653. } while (k <= j->spec_end);
  1654. }
  1655. }
  1656. return 1;
  1657. }
  1658. // take a -128..127 value and stbi__clamp it and convert to 0..255
  1659. stbi_inline static stbi_uc stbi__clamp(int x)
  1660. {
  1661. // trick to use a single test to catch both cases
  1662. if ((unsigned int) x > 255) {
  1663. if (x < 0) return 0;
  1664. if (x > 255) return 255;
  1665. }
  1666. return (stbi_uc) x;
  1667. }
  1668. #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5)))
  1669. #define stbi__fsh(x) ((x) << 12)
  1670. // derived from jidctint -- DCT_ISLOW
  1671. #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
  1672. int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
  1673. p2 = s2; \
  1674. p3 = s6; \
  1675. p1 = (p2+p3) * stbi__f2f(0.5411961f); \
  1676. t2 = p1 + p3*stbi__f2f(-1.847759065f); \
  1677. t3 = p1 + p2*stbi__f2f( 0.765366865f); \
  1678. p2 = s0; \
  1679. p3 = s4; \
  1680. t0 = stbi__fsh(p2+p3); \
  1681. t1 = stbi__fsh(p2-p3); \
  1682. x0 = t0+t3; \
  1683. x3 = t0-t3; \
  1684. x1 = t1+t2; \
  1685. x2 = t1-t2; \
  1686. t0 = s7; \
  1687. t1 = s5; \
  1688. t2 = s3; \
  1689. t3 = s1; \
  1690. p3 = t0+t2; \
  1691. p4 = t1+t3; \
  1692. p1 = t0+t3; \
  1693. p2 = t1+t2; \
  1694. p5 = (p3+p4)*stbi__f2f( 1.175875602f); \
  1695. t0 = t0*stbi__f2f( 0.298631336f); \
  1696. t1 = t1*stbi__f2f( 2.053119869f); \
  1697. t2 = t2*stbi__f2f( 3.072711026f); \
  1698. t3 = t3*stbi__f2f( 1.501321110f); \
  1699. p1 = p5 + p1*stbi__f2f(-0.899976223f); \
  1700. p2 = p5 + p2*stbi__f2f(-2.562915447f); \
  1701. p3 = p3*stbi__f2f(-1.961570560f); \
  1702. p4 = p4*stbi__f2f(-0.390180644f); \
  1703. t3 += p1+p4; \
  1704. t2 += p2+p3; \
  1705. t1 += p2+p4; \
  1706. t0 += p1+p3;
  1707. static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64])
  1708. {
  1709. int i,val[64],*v=val;
  1710. stbi_uc *o;
  1711. short *d = data;
  1712. // columns
  1713. for (i=0; i < 8; ++i,++d, ++v) {
  1714. // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
  1715. if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
  1716. && d[40]==0 && d[48]==0 && d[56]==0) {
  1717. // no shortcut 0 seconds
  1718. // (1|2|3|4|5|6|7)==0 0 seconds
  1719. // all separate -0.047 seconds
  1720. // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
  1721. int dcterm = d[0] << 2;
  1722. v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
  1723. } else {
  1724. STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56])
  1725. // constants scaled things up by 1<<12; let's bring them back
  1726. // down, but keep 2 extra bits of precision
  1727. x0 += 512; x1 += 512; x2 += 512; x3 += 512;
  1728. v[ 0] = (x0+t3) >> 10;
  1729. v[56] = (x0-t3) >> 10;
  1730. v[ 8] = (x1+t2) >> 10;
  1731. v[48] = (x1-t2) >> 10;
  1732. v[16] = (x2+t1) >> 10;
  1733. v[40] = (x2-t1) >> 10;
  1734. v[24] = (x3+t0) >> 10;
  1735. v[32] = (x3-t0) >> 10;
  1736. }
  1737. }
  1738. for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
  1739. // no fast case since the first 1D IDCT spread components out
  1740. STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
  1741. // constants scaled things up by 1<<12, plus we had 1<<2 from first
  1742. // loop, plus horizontal and vertical each scale by sqrt(8) so together
  1743. // we've got an extra 1<<3, so 1<<17 total we need to remove.
  1744. // so we want to round that, which means adding 0.5 * 1<<17,
  1745. // aka 65536. Also, we'll end up with -128 to 127 that we want
  1746. // to encode as 0..255 by adding 128, so we'll add that before the shift
  1747. x0 += 65536 + (128<<17);
  1748. x1 += 65536 + (128<<17);
  1749. x2 += 65536 + (128<<17);
  1750. x3 += 65536 + (128<<17);
  1751. // tried computing the shifts into temps, or'ing the temps to see
  1752. // if any were out of range, but that was slower
  1753. o[0] = stbi__clamp((x0+t3) >> 17);
  1754. o[7] = stbi__clamp((x0-t3) >> 17);
  1755. o[1] = stbi__clamp((x1+t2) >> 17);
  1756. o[6] = stbi__clamp((x1-t2) >> 17);
  1757. o[2] = stbi__clamp((x2+t1) >> 17);
  1758. o[5] = stbi__clamp((x2-t1) >> 17);
  1759. o[3] = stbi__clamp((x3+t0) >> 17);
  1760. o[4] = stbi__clamp((x3-t0) >> 17);
  1761. }
  1762. }
  1763. #ifdef STBI_SSE2
  1764. // sse2 integer IDCT. not the fastest possible implementation but it
  1765. // produces bit-identical results to the generic C version so it's
  1766. // fully "transparent".
  1767. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
  1768. {
  1769. // This is constructed to match our regular (generic) integer IDCT exactly.
  1770. __m128i row0, row1, row2, row3, row4, row5, row6, row7;
  1771. __m128i tmp;
  1772. // dot product constant: even elems=x, odd elems=y
  1773. #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y))
  1774. // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit)
  1775. // out(1) = c1[even]*x + c1[odd]*y
  1776. #define dct_rot(out0,out1, x,y,c0,c1) \
  1777. __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \
  1778. __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \
  1779. __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \
  1780. __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \
  1781. __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \
  1782. __m128i out1##_h = _mm_madd_epi16(c0##hi, c1)
  1783. // out = in << 12 (in 16-bit, out 32-bit)
  1784. #define dct_widen(out, in) \
  1785. __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
  1786. __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
  1787. // wide add
  1788. #define dct_wadd(out, a, b) \
  1789. __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \
  1790. __m128i out##_h = _mm_add_epi32(a##_h, b##_h)
  1791. // wide sub
  1792. #define dct_wsub(out, a, b) \
  1793. __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \
  1794. __m128i out##_h = _mm_sub_epi32(a##_h, b##_h)
  1795. // butterfly a/b, add bias, then shift by "s" and pack
  1796. #define dct_bfly32o(out0, out1, a,b,bias,s) \
  1797. { \
  1798. __m128i abiased_l = _mm_add_epi32(a##_l, bias); \
  1799. __m128i abiased_h = _mm_add_epi32(a##_h, bias); \
  1800. dct_wadd(sum, abiased, b); \
  1801. dct_wsub(dif, abiased, b); \
  1802. out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \
  1803. out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \
  1804. }
  1805. // 8-bit interleave step (for transposes)
  1806. #define dct_interleave8(a, b) \
  1807. tmp = a; \
  1808. a = _mm_unpacklo_epi8(a, b); \
  1809. b = _mm_unpackhi_epi8(tmp, b)
  1810. // 16-bit interleave step (for transposes)
  1811. #define dct_interleave16(a, b) \
  1812. tmp = a; \
  1813. a = _mm_unpacklo_epi16(a, b); \
  1814. b = _mm_unpackhi_epi16(tmp, b)
  1815. #define dct_pass(bias,shift) \
  1816. { \
  1817. /* even part */ \
  1818. dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \
  1819. __m128i sum04 = _mm_add_epi16(row0, row4); \
  1820. __m128i dif04 = _mm_sub_epi16(row0, row4); \
  1821. dct_widen(t0e, sum04); \
  1822. dct_widen(t1e, dif04); \
  1823. dct_wadd(x0, t0e, t3e); \
  1824. dct_wsub(x3, t0e, t3e); \
  1825. dct_wadd(x1, t1e, t2e); \
  1826. dct_wsub(x2, t1e, t2e); \
  1827. /* odd part */ \
  1828. dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \
  1829. dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \
  1830. __m128i sum17 = _mm_add_epi16(row1, row7); \
  1831. __m128i sum35 = _mm_add_epi16(row3, row5); \
  1832. dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \
  1833. dct_wadd(x4, y0o, y4o); \
  1834. dct_wadd(x5, y1o, y5o); \
  1835. dct_wadd(x6, y2o, y5o); \
  1836. dct_wadd(x7, y3o, y4o); \
  1837. dct_bfly32o(row0,row7, x0,x7,bias,shift); \
  1838. dct_bfly32o(row1,row6, x1,x6,bias,shift); \
  1839. dct_bfly32o(row2,row5, x2,x5,bias,shift); \
  1840. dct_bfly32o(row3,row4, x3,x4,bias,shift); \
  1841. }
  1842. __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
  1843. __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f));
  1844. __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f));
  1845. __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
  1846. __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f));
  1847. __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f));
  1848. __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f));
  1849. __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f));
  1850. // rounding biases in column/row passes, see stbi__idct_block for explanation.
  1851. __m128i bias_0 = _mm_set1_epi32(512);
  1852. __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17));
  1853. // load
  1854. row0 = _mm_load_si128((const __m128i *) (data + 0*8));
  1855. row1 = _mm_load_si128((const __m128i *) (data + 1*8));
  1856. row2 = _mm_load_si128((const __m128i *) (data + 2*8));
  1857. row3 = _mm_load_si128((const __m128i *) (data + 3*8));
  1858. row4 = _mm_load_si128((const __m128i *) (data + 4*8));
  1859. row5 = _mm_load_si128((const __m128i *) (data + 5*8));
  1860. row6 = _mm_load_si128((const __m128i *) (data + 6*8));
  1861. row7 = _mm_load_si128((const __m128i *) (data + 7*8));
  1862. // column pass
  1863. dct_pass(bias_0, 10);
  1864. {
  1865. // 16bit 8x8 transpose pass 1
  1866. dct_interleave16(row0, row4);
  1867. dct_interleave16(row1, row5);
  1868. dct_interleave16(row2, row6);
  1869. dct_interleave16(row3, row7);
  1870. // transpose pass 2
  1871. dct_interleave16(row0, row2);
  1872. dct_interleave16(row1, row3);
  1873. dct_interleave16(row4, row6);
  1874. dct_interleave16(row5, row7);
  1875. // transpose pass 3
  1876. dct_interleave16(row0, row1);
  1877. dct_interleave16(row2, row3);
  1878. dct_interleave16(row4, row5);
  1879. dct_interleave16(row6, row7);
  1880. }
  1881. // row pass
  1882. dct_pass(bias_1, 17);
  1883. {
  1884. // pack
  1885. __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7
  1886. __m128i p1 = _mm_packus_epi16(row2, row3);
  1887. __m128i p2 = _mm_packus_epi16(row4, row5);
  1888. __m128i p3 = _mm_packus_epi16(row6, row7);
  1889. // 8bit 8x8 transpose pass 1
  1890. dct_interleave8(p0, p2); // a0e0a1e1...
  1891. dct_interleave8(p1, p3); // c0g0c1g1...
  1892. // transpose pass 2
  1893. dct_interleave8(p0, p1); // a0c0e0g0...
  1894. dct_interleave8(p2, p3); // b0d0f0h0...
  1895. // transpose pass 3
  1896. dct_interleave8(p0, p2); // a0b0c0d0...
  1897. dct_interleave8(p1, p3); // a4b4c4d4...
  1898. // store
  1899. _mm_storel_epi64((__m128i *) out, p0); out += out_stride;
  1900. _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride;
  1901. _mm_storel_epi64((__m128i *) out, p2); out += out_stride;
  1902. _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride;
  1903. _mm_storel_epi64((__m128i *) out, p1); out += out_stride;
  1904. _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride;
  1905. _mm_storel_epi64((__m128i *) out, p3); out += out_stride;
  1906. _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e));
  1907. }
  1908. #undef dct_const
  1909. #undef dct_rot
  1910. #undef dct_widen
  1911. #undef dct_wadd
  1912. #undef dct_wsub
  1913. #undef dct_bfly32o
  1914. #undef dct_interleave8
  1915. #undef dct_interleave16
  1916. #undef dct_pass
  1917. }
  1918. #endif // STBI_SSE2
  1919. #ifdef STBI_NEON
  1920. // NEON integer IDCT. should produce bit-identical
  1921. // results to the generic C version.
  1922. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
  1923. {
  1924. int16x8_t row0, row1, row2, row3, row4, row5, row6, row7;
  1925. int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f));
  1926. int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f));
  1927. int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f));
  1928. int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f));
  1929. int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f));
  1930. int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f));
  1931. int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f));
  1932. int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f));
  1933. int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f));
  1934. int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f));
  1935. int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f));
  1936. int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f));
  1937. #define dct_long_mul(out, inq, coeff) \
  1938. int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \
  1939. int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff)
  1940. #define dct_long_mac(out, acc, inq, coeff) \
  1941. int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \
  1942. int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff)
  1943. #define dct_widen(out, inq) \
  1944. int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \
  1945. int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12)
  1946. // wide add
  1947. #define dct_wadd(out, a, b) \
  1948. int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \
  1949. int32x4_t out##_h = vaddq_s32(a##_h, b##_h)
  1950. // wide sub
  1951. #define dct_wsub(out, a, b) \
  1952. int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \
  1953. int32x4_t out##_h = vsubq_s32(a##_h, b##_h)
  1954. // butterfly a/b, then shift using "shiftop" by "s" and pack
  1955. #define dct_bfly32o(out0,out1, a,b,shiftop,s) \
  1956. { \
  1957. dct_wadd(sum, a, b); \
  1958. dct_wsub(dif, a, b); \
  1959. out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \
  1960. out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \
  1961. }
  1962. #define dct_pass(shiftop, shift) \
  1963. { \
  1964. /* even part */ \
  1965. int16x8_t sum26 = vaddq_s16(row2, row6); \
  1966. dct_long_mul(p1e, sum26, rot0_0); \
  1967. dct_long_mac(t2e, p1e, row6, rot0_1); \
  1968. dct_long_mac(t3e, p1e, row2, rot0_2); \
  1969. int16x8_t sum04 = vaddq_s16(row0, row4); \
  1970. int16x8_t dif04 = vsubq_s16(row0, row4); \
  1971. dct_widen(t0e, sum04); \
  1972. dct_widen(t1e, dif04); \
  1973. dct_wadd(x0, t0e, t3e); \
  1974. dct_wsub(x3, t0e, t3e); \
  1975. dct_wadd(x1, t1e, t2e); \
  1976. dct_wsub(x2, t1e, t2e); \
  1977. /* odd part */ \
  1978. int16x8_t sum15 = vaddq_s16(row1, row5); \
  1979. int16x8_t sum17 = vaddq_s16(row1, row7); \
  1980. int16x8_t sum35 = vaddq_s16(row3, row5); \
  1981. int16x8_t sum37 = vaddq_s16(row3, row7); \
  1982. int16x8_t sumodd = vaddq_s16(sum17, sum35); \
  1983. dct_long_mul(p5o, sumodd, rot1_0); \
  1984. dct_long_mac(p1o, p5o, sum17, rot1_1); \
  1985. dct_long_mac(p2o, p5o, sum35, rot1_2); \
  1986. dct_long_mul(p3o, sum37, rot2_0); \
  1987. dct_long_mul(p4o, sum15, rot2_1); \
  1988. dct_wadd(sump13o, p1o, p3o); \
  1989. dct_wadd(sump24o, p2o, p4o); \
  1990. dct_wadd(sump23o, p2o, p3o); \
  1991. dct_wadd(sump14o, p1o, p4o); \
  1992. dct_long_mac(x4, sump13o, row7, rot3_0); \
  1993. dct_long_mac(x5, sump24o, row5, rot3_1); \
  1994. dct_long_mac(x6, sump23o, row3, rot3_2); \
  1995. dct_long_mac(x7, sump14o, row1, rot3_3); \
  1996. dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \
  1997. dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \
  1998. dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \
  1999. dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \
  2000. }
  2001. // load
  2002. row0 = vld1q_s16(data + 0*8);
  2003. row1 = vld1q_s16(data + 1*8);
  2004. row2 = vld1q_s16(data + 2*8);
  2005. row3 = vld1q_s16(data + 3*8);
  2006. row4 = vld1q_s16(data + 4*8);
  2007. row5 = vld1q_s16(data + 5*8);
  2008. row6 = vld1q_s16(data + 6*8);
  2009. row7 = vld1q_s16(data + 7*8);
  2010. // add DC bias
  2011. row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0));
  2012. // column pass
  2013. dct_pass(vrshrn_n_s32, 10);
  2014. // 16bit 8x8 transpose
  2015. {
  2016. // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively.
  2017. // whether compilers actually get this is another story, sadly.
  2018. #define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; }
  2019. #define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); }
  2020. #define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); }
  2021. // pass 1
  2022. dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6
  2023. dct_trn16(row2, row3);
  2024. dct_trn16(row4, row5);
  2025. dct_trn16(row6, row7);
  2026. // pass 2
  2027. dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4
  2028. dct_trn32(row1, row3);
  2029. dct_trn32(row4, row6);
  2030. dct_trn32(row5, row7);
  2031. // pass 3
  2032. dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0
  2033. dct_trn64(row1, row5);
  2034. dct_trn64(row2, row6);
  2035. dct_trn64(row3, row7);
  2036. #undef dct_trn16
  2037. #undef dct_trn32
  2038. #undef dct_trn64
  2039. }
  2040. // row pass
  2041. // vrshrn_n_s32 only supports shifts up to 16, we need
  2042. // 17. so do a non-rounding shift of 16 first then follow
  2043. // up with a rounding shift by 1.
  2044. dct_pass(vshrn_n_s32, 16);
  2045. {
  2046. // pack and round
  2047. uint8x8_t p0 = vqrshrun_n_s16(row0, 1);
  2048. uint8x8_t p1 = vqrshrun_n_s16(row1, 1);
  2049. uint8x8_t p2 = vqrshrun_n_s16(row2, 1);
  2050. uint8x8_t p3 = vqrshrun_n_s16(row3, 1);
  2051. uint8x8_t p4 = vqrshrun_n_s16(row4, 1);
  2052. uint8x8_t p5 = vqrshrun_n_s16(row5, 1);
  2053. uint8x8_t p6 = vqrshrun_n_s16(row6, 1);
  2054. uint8x8_t p7 = vqrshrun_n_s16(row7, 1);
  2055. // again, these can translate into one instruction, but often don't.
  2056. #define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; }
  2057. #define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); }
  2058. #define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); }
  2059. // sadly can't use interleaved stores here since we only write
  2060. // 8 bytes to each scan line!
  2061. // 8x8 8-bit transpose pass 1
  2062. dct_trn8_8(p0, p1);
  2063. dct_trn8_8(p2, p3);
  2064. dct_trn8_8(p4, p5);
  2065. dct_trn8_8(p6, p7);
  2066. // pass 2
  2067. dct_trn8_16(p0, p2);
  2068. dct_trn8_16(p1, p3);
  2069. dct_trn8_16(p4, p6);
  2070. dct_trn8_16(p5, p7);
  2071. // pass 3
  2072. dct_trn8_32(p0, p4);
  2073. dct_trn8_32(p1, p5);
  2074. dct_trn8_32(p2, p6);
  2075. dct_trn8_32(p3, p7);
  2076. // store
  2077. vst1_u8(out, p0); out += out_stride;
  2078. vst1_u8(out, p1); out += out_stride;
  2079. vst1_u8(out, p2); out += out_stride;
  2080. vst1_u8(out, p3); out += out_stride;
  2081. vst1_u8(out, p4); out += out_stride;
  2082. vst1_u8(out, p5); out += out_stride;
  2083. vst1_u8(out, p6); out += out_stride;
  2084. vst1_u8(out, p7);
  2085. #undef dct_trn8_8
  2086. #undef dct_trn8_16
  2087. #undef dct_trn8_32
  2088. }
  2089. #undef dct_long_mul
  2090. #undef dct_long_mac
  2091. #undef dct_widen
  2092. #undef dct_wadd
  2093. #undef dct_wsub
  2094. #undef dct_bfly32o
  2095. #undef dct_pass
  2096. }
  2097. #endif // STBI_NEON
  2098. #define STBI__MARKER_none 0xff
  2099. // if there's a pending marker from the entropy stream, return that
  2100. // otherwise, fetch from the stream and get a marker. if there's no
  2101. // marker, return 0xff, which is never a valid marker value
  2102. static stbi_uc stbi__get_marker(stbi__jpeg *j)
  2103. {
  2104. stbi_uc x;
  2105. if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }
  2106. x = stbi__get8(j->s);
  2107. if (x != 0xff) return STBI__MARKER_none;
  2108. while (x == 0xff)
  2109. x = stbi__get8(j->s);
  2110. return x;
  2111. }
  2112. // in each scan, we'll have scan_n components, and the order
  2113. // of the components is specified by order[]
  2114. #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
  2115. // after a restart interval, stbi__jpeg_reset the entropy decoder and
  2116. // the dc prediction
  2117. static void stbi__jpeg_reset(stbi__jpeg *j)
  2118. {
  2119. j->code_bits = 0;
  2120. j->code_buffer = 0;
  2121. j->nomore = 0;
  2122. j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
  2123. j->marker = STBI__MARKER_none;
  2124. j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
  2125. j->eob_run = 0;
  2126. // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
  2127. // since we don't even allow 1<<30 pixels
  2128. }
  2129. static int stbi__parse_entropy_coded_data(stbi__jpeg *z)
  2130. {
  2131. stbi__jpeg_reset(z);
  2132. if (!z->progressive) {
  2133. if (z->scan_n == 1) {
  2134. int i,j;
  2135. STBI_SIMD_ALIGN(short, data[64]);
  2136. int n = z->order[0];
  2137. // non-interleaved data, we just need to process one block at a time,
  2138. // in trivial scanline order
  2139. // number of blocks to do just depends on how many actual "pixels" this
  2140. // component has, independent of interleaved MCU blocking and such
  2141. int w = (z->img_comp[n].x+7) >> 3;
  2142. int h = (z->img_comp[n].y+7) >> 3;
  2143. for (j=0; j < h; ++j) {
  2144. for (i=0; i < w; ++i) {
  2145. int ha = z->img_comp[n].ha;
  2146. if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
  2147. z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
  2148. // every data block is an MCU, so countdown the restart interval
  2149. if (--z->todo <= 0) {
  2150. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  2151. // if it's NOT a restart, then just bail, so we get corrupt data
  2152. // rather than no data
  2153. if (!STBI__RESTART(z->marker)) return 1;
  2154. stbi__jpeg_reset(z);
  2155. }
  2156. }
  2157. }
  2158. return 1;
  2159. } else { // interleaved
  2160. int i,j,k,x,y;
  2161. STBI_SIMD_ALIGN(short, data[64]);
  2162. for (j=0; j < z->img_mcu_y; ++j) {
  2163. for (i=0; i < z->img_mcu_x; ++i) {
  2164. // scan an interleaved mcu... process scan_n components in order
  2165. for (k=0; k < z->scan_n; ++k) {
  2166. int n = z->order[k];
  2167. // scan out an mcu's worth of this component; that's just determined
  2168. // by the basic H and V specified for the component
  2169. for (y=0; y < z->img_comp[n].v; ++y) {
  2170. for (x=0; x < z->img_comp[n].h; ++x) {
  2171. int x2 = (i*z->img_comp[n].h + x)*8;
  2172. int y2 = (j*z->img_comp[n].v + y)*8;
  2173. int ha = z->img_comp[n].ha;
  2174. if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
  2175. z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data);
  2176. }
  2177. }
  2178. }
  2179. // after all interleaved components, that's an interleaved MCU,
  2180. // so now count down the restart interval
  2181. if (--z->todo <= 0) {
  2182. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  2183. if (!STBI__RESTART(z->marker)) return 1;
  2184. stbi__jpeg_reset(z);
  2185. }
  2186. }
  2187. }
  2188. return 1;
  2189. }
  2190. } else {
  2191. if (z->scan_n == 1) {
  2192. int i,j;
  2193. int n = z->order[0];
  2194. // non-interleaved data, we just need to process one block at a time,
  2195. // in trivial scanline order
  2196. // number of blocks to do just depends on how many actual "pixels" this
  2197. // component has, independent of interleaved MCU blocking and such
  2198. int w = (z->img_comp[n].x+7) >> 3;
  2199. int h = (z->img_comp[n].y+7) >> 3;
  2200. for (j=0; j < h; ++j) {
  2201. for (i=0; i < w; ++i) {
  2202. short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
  2203. if (z->spec_start == 0) {
  2204. if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
  2205. return 0;
  2206. } else {
  2207. int ha = z->img_comp[n].ha;
  2208. if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha]))
  2209. return 0;
  2210. }
  2211. // every data block is an MCU, so countdown the restart interval
  2212. if (--z->todo <= 0) {
  2213. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  2214. if (!STBI__RESTART(z->marker)) return 1;
  2215. stbi__jpeg_reset(z);
  2216. }
  2217. }
  2218. }
  2219. return 1;
  2220. } else { // interleaved
  2221. int i,j,k,x,y;
  2222. for (j=0; j < z->img_mcu_y; ++j) {
  2223. for (i=0; i < z->img_mcu_x; ++i) {
  2224. // scan an interleaved mcu... process scan_n components in order
  2225. for (k=0; k < z->scan_n; ++k) {
  2226. int n = z->order[k];
  2227. // scan out an mcu's worth of this component; that's just determined
  2228. // by the basic H and V specified for the component
  2229. for (y=0; y < z->img_comp[n].v; ++y) {
  2230. for (x=0; x < z->img_comp[n].h; ++x) {
  2231. int x2 = (i*z->img_comp[n].h + x);
  2232. int y2 = (j*z->img_comp[n].v + y);
  2233. short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w);
  2234. if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
  2235. return 0;
  2236. }
  2237. }
  2238. }
  2239. // after all interleaved components, that's an interleaved MCU,
  2240. // so now count down the restart interval
  2241. if (--z->todo <= 0) {
  2242. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  2243. if (!STBI__RESTART(z->marker)) return 1;
  2244. stbi__jpeg_reset(z);
  2245. }
  2246. }
  2247. }
  2248. return 1;
  2249. }
  2250. }
  2251. }
  2252. static void stbi__jpeg_dequantize(short *data, stbi_uc *dequant)
  2253. {
  2254. int i;
  2255. for (i=0; i < 64; ++i)
  2256. data[i] *= dequant[i];
  2257. }
  2258. static void stbi__jpeg_finish(stbi__jpeg *z)
  2259. {
  2260. if (z->progressive) {
  2261. // dequantize and idct the data
  2262. int i,j,n;
  2263. for (n=0; n < z->s->img_n; ++n) {
  2264. int w = (z->img_comp[n].x+7) >> 3;
  2265. int h = (z->img_comp[n].y+7) >> 3;
  2266. for (j=0; j < h; ++j) {
  2267. for (i=0; i < w; ++i) {
  2268. short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
  2269. stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);
  2270. z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
  2271. }
  2272. }
  2273. }
  2274. }
  2275. }
  2276. static int stbi__process_marker(stbi__jpeg *z, int m)
  2277. {
  2278. int L;
  2279. switch (m) {
  2280. case STBI__MARKER_none: // no marker found
  2281. return stbi__err("expected marker","Corrupt JPEG");
  2282. case 0xDD: // DRI - specify restart interval
  2283. if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG");
  2284. z->restart_interval = stbi__get16be(z->s);
  2285. return 1;
  2286. case 0xDB: // DQT - define quantization table
  2287. L = stbi__get16be(z->s)-2;
  2288. while (L > 0) {
  2289. int q = stbi__get8(z->s);
  2290. int p = q >> 4;
  2291. int t = q & 15,i;
  2292. if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG");
  2293. if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG");
  2294. for (i=0; i < 64; ++i)
  2295. z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s);
  2296. L -= 65;
  2297. }
  2298. return L==0;
  2299. case 0xC4: // DHT - define huffman table
  2300. L = stbi__get16be(z->s)-2;
  2301. while (L > 0) {
  2302. stbi_uc *v;
  2303. int sizes[16],i,n=0;
  2304. int q = stbi__get8(z->s);
  2305. int tc = q >> 4;
  2306. int th = q & 15;
  2307. if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG");
  2308. for (i=0; i < 16; ++i) {
  2309. sizes[i] = stbi__get8(z->s);
  2310. n += sizes[i];
  2311. }
  2312. L -= 17;
  2313. if (tc == 0) {
  2314. if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;
  2315. v = z->huff_dc[th].values;
  2316. } else {
  2317. if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;
  2318. v = z->huff_ac[th].values;
  2319. }
  2320. for (i=0; i < n; ++i)
  2321. v[i] = stbi__get8(z->s);
  2322. if (tc != 0)
  2323. stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
  2324. L -= n;
  2325. }
  2326. return L==0;
  2327. }
  2328. // check for comment block or APP blocks
  2329. if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
  2330. stbi__skip(z->s, stbi__get16be(z->s)-2);
  2331. return 1;
  2332. }
  2333. return 0;
  2334. }
  2335. // after we see SOS
  2336. static int stbi__process_scan_header(stbi__jpeg *z)
  2337. {
  2338. int i;
  2339. int Ls = stbi__get16be(z->s);
  2340. z->scan_n = stbi__get8(z->s);
  2341. if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG");
  2342. if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG");
  2343. for (i=0; i < z->scan_n; ++i) {
  2344. int id = stbi__get8(z->s), which;
  2345. int q = stbi__get8(z->s);
  2346. for (which = 0; which < z->s->img_n; ++which)
  2347. if (z->img_comp[which].id == id)
  2348. break;
  2349. if (which == z->s->img_n) return 0; // no match
  2350. z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG");
  2351. z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG");
  2352. z->order[i] = which;
  2353. }
  2354. {
  2355. int aa;
  2356. z->spec_start = stbi__get8(z->s);
  2357. z->spec_end = stbi__get8(z->s); // should be 63, but might be 0
  2358. aa = stbi__get8(z->s);
  2359. z->succ_high = (aa >> 4);
  2360. z->succ_low = (aa & 15);
  2361. if (z->progressive) {
  2362. if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13)
  2363. return stbi__err("bad SOS", "Corrupt JPEG");
  2364. } else {
  2365. if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG");
  2366. if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG");
  2367. z->spec_end = 63;
  2368. }
  2369. }
  2370. return 1;
  2371. }
  2372. static int stbi__process_frame_header(stbi__jpeg *z, int scan)
  2373. {
  2374. stbi__context *s = z->s;
  2375. int Lf,p,i,q, h_max=1,v_max=1,c;
  2376. Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG
  2377. p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
  2378. s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
  2379. s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
  2380. c = stbi__get8(s);
  2381. if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires
  2382. s->img_n = c;
  2383. for (i=0; i < c; ++i) {
  2384. z->img_comp[i].data = NULL;
  2385. z->img_comp[i].linebuf = NULL;
  2386. }
  2387. if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG");
  2388. z->rgb = 0;
  2389. for (i=0; i < s->img_n; ++i) {
  2390. static unsigned char rgb[3] = { 'R', 'G', 'B' };
  2391. z->img_comp[i].id = stbi__get8(s);
  2392. if (z->img_comp[i].id != i+1) // JFIF requires
  2393. if (z->img_comp[i].id != i) { // some version of jpegtran outputs non-JFIF-compliant files!
  2394. // somethings output this (see http://fileformats.archiveteam.org/wiki/JPEG#Color_format)
  2395. if (z->img_comp[i].id != rgb[i])
  2396. return stbi__err("bad component ID","Corrupt JPEG");
  2397. ++z->rgb;
  2398. }
  2399. q = stbi__get8(s);
  2400. z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG");
  2401. z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG");
  2402. z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");
  2403. }
  2404. if (scan != STBI__SCAN_load) return 1;
  2405. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
  2406. for (i=0; i < s->img_n; ++i) {
  2407. if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
  2408. if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
  2409. }
  2410. // compute interleaved mcu info
  2411. z->img_h_max = h_max;
  2412. z->img_v_max = v_max;
  2413. z->img_mcu_w = h_max * 8;
  2414. z->img_mcu_h = v_max * 8;
  2415. z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
  2416. z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
  2417. for (i=0; i < s->img_n; ++i) {
  2418. // number of effective pixels (e.g. for non-interleaved MCU)
  2419. z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
  2420. z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
  2421. // to simplify generation, we'll allocate enough memory to decode
  2422. // the bogus oversized data from using interleaved MCUs and their
  2423. // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
  2424. // discard the extra data until colorspace conversion
  2425. z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
  2426. z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
  2427. z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
  2428. if (z->img_comp[i].raw_data == NULL) {
  2429. for(--i; i >= 0; --i) {
  2430. STBI_FREE(z->img_comp[i].raw_data);
  2431. z->img_comp[i].raw_data = NULL;
  2432. }
  2433. return stbi__err("outofmem", "Out of memory");
  2434. }
  2435. // align blocks for idct using mmx/sse
  2436. z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
  2437. z->img_comp[i].linebuf = NULL;
  2438. if (z->progressive) {
  2439. z->img_comp[i].coeff_w = (z->img_comp[i].w2 + 7) >> 3;
  2440. z->img_comp[i].coeff_h = (z->img_comp[i].h2 + 7) >> 3;
  2441. z->img_comp[i].raw_coeff = STBI_MALLOC(z->img_comp[i].coeff_w * z->img_comp[i].coeff_h * 64 * sizeof(short) + 15);
  2442. z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);
  2443. } else {
  2444. z->img_comp[i].coeff = 0;
  2445. z->img_comp[i].raw_coeff = 0;
  2446. }
  2447. }
  2448. return 1;
  2449. }
  2450. // use comparisons since in some cases we handle more than one case (e.g. SOF)
  2451. #define stbi__DNL(x) ((x) == 0xdc)
  2452. #define stbi__SOI(x) ((x) == 0xd8)
  2453. #define stbi__EOI(x) ((x) == 0xd9)
  2454. #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2)
  2455. #define stbi__SOS(x) ((x) == 0xda)
  2456. #define stbi__SOF_progressive(x) ((x) == 0xc2)
  2457. static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan)
  2458. {
  2459. int m;
  2460. z->marker = STBI__MARKER_none; // initialize cached marker to empty
  2461. m = stbi__get_marker(z);
  2462. if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG");
  2463. if (scan == STBI__SCAN_type) return 1;
  2464. m = stbi__get_marker(z);
  2465. while (!stbi__SOF(m)) {
  2466. if (!stbi__process_marker(z,m)) return 0;
  2467. m = stbi__get_marker(z);
  2468. while (m == STBI__MARKER_none) {
  2469. // some files have extra padding after their blocks, so ok, we'll scan
  2470. if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG");
  2471. m = stbi__get_marker(z);
  2472. }
  2473. }
  2474. z->progressive = stbi__SOF_progressive(m);
  2475. if (!stbi__process_frame_header(z, scan)) return 0;
  2476. return 1;
  2477. }
  2478. // decode image to YCbCr format
  2479. static int stbi__decode_jpeg_image(stbi__jpeg *j)
  2480. {
  2481. int m;
  2482. for (m = 0; m < 4; m++) {
  2483. j->img_comp[m].raw_data = NULL;
  2484. j->img_comp[m].raw_coeff = NULL;
  2485. }
  2486. j->restart_interval = 0;
  2487. if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0;
  2488. m = stbi__get_marker(j);
  2489. while (!stbi__EOI(m)) {
  2490. if (stbi__SOS(m)) {
  2491. if (!stbi__process_scan_header(j)) return 0;
  2492. if (!stbi__parse_entropy_coded_data(j)) return 0;
  2493. if (j->marker == STBI__MARKER_none ) {
  2494. // handle 0s at the end of image data from IP Kamera 9060
  2495. while (!stbi__at_eof(j->s)) {
  2496. int x = stbi__get8(j->s);
  2497. if (x == 255) {
  2498. j->marker = stbi__get8(j->s);
  2499. break;
  2500. } else if (x != 0) {
  2501. return stbi__err("junk before marker", "Corrupt JPEG");
  2502. }
  2503. }
  2504. // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0
  2505. }
  2506. } else {
  2507. if (!stbi__process_marker(j, m)) return 0;
  2508. }
  2509. m = stbi__get_marker(j);
  2510. }
  2511. if (j->progressive)
  2512. stbi__jpeg_finish(j);
  2513. return 1;
  2514. }
  2515. // static jfif-centered resampling (across block boundaries)
  2516. typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,
  2517. int w, int hs);
  2518. #define stbi__div4(x) ((stbi_uc) ((x) >> 2))
  2519. static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2520. {
  2521. STBI_NOTUSED(out);
  2522. STBI_NOTUSED(in_far);
  2523. STBI_NOTUSED(w);
  2524. STBI_NOTUSED(hs);
  2525. return in_near;
  2526. }
  2527. static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2528. {
  2529. // need to generate two samples vertically for every one in input
  2530. int i;
  2531. STBI_NOTUSED(hs);
  2532. for (i=0; i < w; ++i)
  2533. out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);
  2534. return out;
  2535. }
  2536. static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2537. {
  2538. // need to generate two samples horizontally for every one in input
  2539. int i;
  2540. stbi_uc *input = in_near;
  2541. if (w == 1) {
  2542. // if only one sample, can't do any interpolation
  2543. out[0] = out[1] = input[0];
  2544. return out;
  2545. }
  2546. out[0] = input[0];
  2547. out[1] = stbi__div4(input[0]*3 + input[1] + 2);
  2548. for (i=1; i < w-1; ++i) {
  2549. int n = 3*input[i]+2;
  2550. out[i*2+0] = stbi__div4(n+input[i-1]);
  2551. out[i*2+1] = stbi__div4(n+input[i+1]);
  2552. }
  2553. out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);
  2554. out[i*2+1] = input[w-1];
  2555. STBI_NOTUSED(in_far);
  2556. STBI_NOTUSED(hs);
  2557. return out;
  2558. }
  2559. #define stbi__div16(x) ((stbi_uc) ((x) >> 4))
  2560. static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2561. {
  2562. // need to generate 2x2 samples for every one in input
  2563. int i,t0,t1;
  2564. if (w == 1) {
  2565. out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
  2566. return out;
  2567. }
  2568. t1 = 3*in_near[0] + in_far[0];
  2569. out[0] = stbi__div4(t1+2);
  2570. for (i=1; i < w; ++i) {
  2571. t0 = t1;
  2572. t1 = 3*in_near[i]+in_far[i];
  2573. out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
  2574. out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
  2575. }
  2576. out[w*2-1] = stbi__div4(t1+2);
  2577. STBI_NOTUSED(hs);
  2578. return out;
  2579. }
  2580. #if defined(STBI_SSE2) || defined(STBI_NEON)
  2581. static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2582. {
  2583. // need to generate 2x2 samples for every one in input
  2584. int i=0,t0,t1;
  2585. if (w == 1) {
  2586. out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
  2587. return out;
  2588. }
  2589. t1 = 3*in_near[0] + in_far[0];
  2590. // process groups of 8 pixels for as long as we can.
  2591. // note we can't handle the last pixel in a row in this loop
  2592. // because we need to handle the filter boundary conditions.
  2593. for (; i < ((w-1) & ~7); i += 8) {
  2594. #if defined(STBI_SSE2)
  2595. // load and perform the vertical filtering pass
  2596. // this uses 3*x + y = 4*x + (y - x)
  2597. __m128i zero = _mm_setzero_si128();
  2598. __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i));
  2599. __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i));
  2600. __m128i farw = _mm_unpacklo_epi8(farb, zero);
  2601. __m128i nearw = _mm_unpacklo_epi8(nearb, zero);
  2602. __m128i diff = _mm_sub_epi16(farw, nearw);
  2603. __m128i nears = _mm_slli_epi16(nearw, 2);
  2604. __m128i curr = _mm_add_epi16(nears, diff); // current row
  2605. // horizontal filter works the same based on shifted vers of current
  2606. // row. "prev" is current row shifted right by 1 pixel; we need to
  2607. // insert the previous pixel value (from t1).
  2608. // "next" is current row shifted left by 1 pixel, with first pixel
  2609. // of next block of 8 pixels added in.
  2610. __m128i prv0 = _mm_slli_si128(curr, 2);
  2611. __m128i nxt0 = _mm_srli_si128(curr, 2);
  2612. __m128i prev = _mm_insert_epi16(prv0, t1, 0);
  2613. __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7);
  2614. // horizontal filter, polyphase implementation since it's convenient:
  2615. // even pixels = 3*cur + prev = cur*4 + (prev - cur)
  2616. // odd pixels = 3*cur + next = cur*4 + (next - cur)
  2617. // note the shared term.
  2618. __m128i bias = _mm_set1_epi16(8);
  2619. __m128i curs = _mm_slli_epi16(curr, 2);
  2620. __m128i prvd = _mm_sub_epi16(prev, curr);
  2621. __m128i nxtd = _mm_sub_epi16(next, curr);
  2622. __m128i curb = _mm_add_epi16(curs, bias);
  2623. __m128i even = _mm_add_epi16(prvd, curb);
  2624. __m128i odd = _mm_add_epi16(nxtd, curb);
  2625. // interleave even and odd pixels, then undo scaling.
  2626. __m128i int0 = _mm_unpacklo_epi16(even, odd);
  2627. __m128i int1 = _mm_unpackhi_epi16(even, odd);
  2628. __m128i de0 = _mm_srli_epi16(int0, 4);
  2629. __m128i de1 = _mm_srli_epi16(int1, 4);
  2630. // pack and write output
  2631. __m128i outv = _mm_packus_epi16(de0, de1);
  2632. _mm_storeu_si128((__m128i *) (out + i*2), outv);
  2633. #elif defined(STBI_NEON)
  2634. // load and perform the vertical filtering pass
  2635. // this uses 3*x + y = 4*x + (y - x)
  2636. uint8x8_t farb = vld1_u8(in_far + i);
  2637. uint8x8_t nearb = vld1_u8(in_near + i);
  2638. int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb));
  2639. int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2));
  2640. int16x8_t curr = vaddq_s16(nears, diff); // current row
  2641. // horizontal filter works the same based on shifted vers of current
  2642. // row. "prev" is current row shifted right by 1 pixel; we need to
  2643. // insert the previous pixel value (from t1).
  2644. // "next" is current row shifted left by 1 pixel, with first pixel
  2645. // of next block of 8 pixels added in.
  2646. int16x8_t prv0 = vextq_s16(curr, curr, 7);
  2647. int16x8_t nxt0 = vextq_s16(curr, curr, 1);
  2648. int16x8_t prev = vsetq_lane_s16(t1, prv0, 0);
  2649. int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7);
  2650. // horizontal filter, polyphase implementation since it's convenient:
  2651. // even pixels = 3*cur + prev = cur*4 + (prev - cur)
  2652. // odd pixels = 3*cur + next = cur*4 + (next - cur)
  2653. // note the shared term.
  2654. int16x8_t curs = vshlq_n_s16(curr, 2);
  2655. int16x8_t prvd = vsubq_s16(prev, curr);
  2656. int16x8_t nxtd = vsubq_s16(next, curr);
  2657. int16x8_t even = vaddq_s16(curs, prvd);
  2658. int16x8_t odd = vaddq_s16(curs, nxtd);
  2659. // undo scaling and round, then store with even/odd phases interleaved
  2660. uint8x8x2_t o;
  2661. o.val[0] = vqrshrun_n_s16(even, 4);
  2662. o.val[1] = vqrshrun_n_s16(odd, 4);
  2663. vst2_u8(out + i*2, o);
  2664. #endif
  2665. // "previous" value for next iter
  2666. t1 = 3*in_near[i+7] + in_far[i+7];
  2667. }
  2668. t0 = t1;
  2669. t1 = 3*in_near[i] + in_far[i];
  2670. out[i*2] = stbi__div16(3*t1 + t0 + 8);
  2671. for (++i; i < w; ++i) {
  2672. t0 = t1;
  2673. t1 = 3*in_near[i]+in_far[i];
  2674. out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
  2675. out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
  2676. }
  2677. out[w*2-1] = stbi__div4(t1+2);
  2678. STBI_NOTUSED(hs);
  2679. return out;
  2680. }
  2681. #endif
  2682. static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2683. {
  2684. // resample with nearest-neighbor
  2685. int i,j;
  2686. STBI_NOTUSED(in_far);
  2687. for (i=0; i < w; ++i)
  2688. for (j=0; j < hs; ++j)
  2689. out[i*hs+j] = in_near[i];
  2690. return out;
  2691. }
  2692. #ifdef STBI_JPEG_OLD
  2693. // this is the same YCbCr-to-RGB calculation that stb_image has used
  2694. // historically before the algorithm changes in 1.49
  2695. #define float2fixed(x) ((int) ((x) * 65536 + 0.5))
  2696. static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)
  2697. {
  2698. int i;
  2699. for (i=0; i < count; ++i) {
  2700. int y_fixed = (y[i] << 16) + 32768; // rounding
  2701. int r,g,b;
  2702. int cr = pcr[i] - 128;
  2703. int cb = pcb[i] - 128;
  2704. r = y_fixed + cr*float2fixed(1.40200f);
  2705. g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
  2706. b = y_fixed + cb*float2fixed(1.77200f);
  2707. r >>= 16;
  2708. g >>= 16;
  2709. b >>= 16;
  2710. if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
  2711. if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
  2712. if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
  2713. out[0] = (stbi_uc)r;
  2714. out[1] = (stbi_uc)g;
  2715. out[2] = (stbi_uc)b;
  2716. out[3] = 255;
  2717. out += step;
  2718. }
  2719. }
  2720. #else
  2721. // this is a reduced-precision calculation of YCbCr-to-RGB introduced
  2722. // to make sure the code produces the same results in both SIMD and scalar
  2723. #define float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8)
  2724. static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)
  2725. {
  2726. int i;
  2727. for (i=0; i < count; ++i) {
  2728. int y_fixed = (y[i] << 20) + (1<<19); // rounding
  2729. int r,g,b;
  2730. int cr = pcr[i] - 128;
  2731. int cb = pcb[i] - 128;
  2732. r = y_fixed + cr* float2fixed(1.40200f);
  2733. g = y_fixed + (cr*-float2fixed(0.71414f)) + ((cb*-float2fixed(0.34414f)) & 0xffff0000);
  2734. b = y_fixed + cb* float2fixed(1.77200f);
  2735. r >>= 20;
  2736. g >>= 20;
  2737. b >>= 20;
  2738. if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
  2739. if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
  2740. if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
  2741. out[0] = (stbi_uc)r;
  2742. out[1] = (stbi_uc)g;
  2743. out[2] = (stbi_uc)b;
  2744. out[3] = 255;
  2745. out += step;
  2746. }
  2747. }
  2748. #endif
  2749. #if defined(STBI_SSE2) || defined(STBI_NEON)
  2750. static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step)
  2751. {
  2752. int i = 0;
  2753. #ifdef STBI_SSE2
  2754. // step == 3 is pretty ugly on the final interleave, and i'm not convinced
  2755. // it's useful in practice (you wouldn't use it for textures, for example).
  2756. // so just accelerate step == 4 case.
  2757. if (step == 4) {
  2758. // this is a fairly straightforward implementation and not super-optimized.
  2759. __m128i signflip = _mm_set1_epi8(-0x80);
  2760. __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f));
  2761. __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f));
  2762. __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f));
  2763. __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f));
  2764. __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128);
  2765. __m128i xw = _mm_set1_epi16(255); // alpha channel
  2766. for (; i+7 < count; i += 8) {
  2767. // load
  2768. __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i));
  2769. __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i));
  2770. __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i));
  2771. __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128
  2772. __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128
  2773. // unpack to short (and left-shift cr, cb by 8)
  2774. __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes);
  2775. __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased);
  2776. __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased);
  2777. // color transform
  2778. __m128i yws = _mm_srli_epi16(yw, 4);
  2779. __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw);
  2780. __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw);
  2781. __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1);
  2782. __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1);
  2783. __m128i rws = _mm_add_epi16(cr0, yws);
  2784. __m128i gwt = _mm_add_epi16(cb0, yws);
  2785. __m128i bws = _mm_add_epi16(yws, cb1);
  2786. __m128i gws = _mm_add_epi16(gwt, cr1);
  2787. // descale
  2788. __m128i rw = _mm_srai_epi16(rws, 4);
  2789. __m128i bw = _mm_srai_epi16(bws, 4);
  2790. __m128i gw = _mm_srai_epi16(gws, 4);
  2791. // back to byte, set up for transpose
  2792. __m128i brb = _mm_packus_epi16(rw, bw);
  2793. __m128i gxb = _mm_packus_epi16(gw, xw);
  2794. // transpose to interleave channels
  2795. __m128i t0 = _mm_unpacklo_epi8(brb, gxb);
  2796. __m128i t1 = _mm_unpackhi_epi8(brb, gxb);
  2797. __m128i o0 = _mm_unpacklo_epi16(t0, t1);
  2798. __m128i o1 = _mm_unpackhi_epi16(t0, t1);
  2799. // store
  2800. _mm_storeu_si128((__m128i *) (out + 0), o0);
  2801. _mm_storeu_si128((__m128i *) (out + 16), o1);
  2802. out += 32;
  2803. }
  2804. }
  2805. #endif
  2806. #ifdef STBI_NEON
  2807. // in this version, step=3 support would be easy to add. but is there demand?
  2808. if (step == 4) {
  2809. // this is a fairly straightforward implementation and not super-optimized.
  2810. uint8x8_t signflip = vdup_n_u8(0x80);
  2811. int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f));
  2812. int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f));
  2813. int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f));
  2814. int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f));
  2815. for (; i+7 < count; i += 8) {
  2816. // load
  2817. uint8x8_t y_bytes = vld1_u8(y + i);
  2818. uint8x8_t cr_bytes = vld1_u8(pcr + i);
  2819. uint8x8_t cb_bytes = vld1_u8(pcb + i);
  2820. int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
  2821. int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
  2822. // expand to s16
  2823. int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));
  2824. int16x8_t crw = vshll_n_s8(cr_biased, 7);
  2825. int16x8_t cbw = vshll_n_s8(cb_biased, 7);
  2826. // color transform
  2827. int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0);
  2828. int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0);
  2829. int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1);
  2830. int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1);
  2831. int16x8_t rws = vaddq_s16(yws, cr0);
  2832. int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1);
  2833. int16x8_t bws = vaddq_s16(yws, cb1);
  2834. // undo scaling, round, convert to byte
  2835. uint8x8x4_t o;
  2836. o.val[0] = vqrshrun_n_s16(rws, 4);
  2837. o.val[1] = vqrshrun_n_s16(gws, 4);
  2838. o.val[2] = vqrshrun_n_s16(bws, 4);
  2839. o.val[3] = vdup_n_u8(255);
  2840. // store, interleaving r/g/b/a
  2841. vst4_u8(out, o);
  2842. out += 8*4;
  2843. }
  2844. }
  2845. #endif
  2846. for (; i < count; ++i) {
  2847. int y_fixed = (y[i] << 20) + (1<<19); // rounding
  2848. int r,g,b;
  2849. int cr = pcr[i] - 128;
  2850. int cb = pcb[i] - 128;
  2851. r = y_fixed + cr* float2fixed(1.40200f);
  2852. g = y_fixed + cr*-float2fixed(0.71414f) + ((cb*-float2fixed(0.34414f)) & 0xffff0000);
  2853. b = y_fixed + cb* float2fixed(1.77200f);
  2854. r >>= 20;
  2855. g >>= 20;
  2856. b >>= 20;
  2857. if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
  2858. if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
  2859. if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
  2860. out[0] = (stbi_uc)r;
  2861. out[1] = (stbi_uc)g;
  2862. out[2] = (stbi_uc)b;
  2863. out[3] = 255;
  2864. out += step;
  2865. }
  2866. }
  2867. #endif
  2868. // set up the kernels
  2869. static void stbi__setup_jpeg(stbi__jpeg *j)
  2870. {
  2871. j->idct_block_kernel = stbi__idct_block;
  2872. j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row;
  2873. j->resample_row_hv_2_kernel = stbi__resample_row_hv_2;
  2874. #ifdef STBI_SSE2
  2875. if (stbi__sse2_available()) {
  2876. j->idct_block_kernel = stbi__idct_simd;
  2877. #ifndef STBI_JPEG_OLD
  2878. j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
  2879. #endif
  2880. j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
  2881. }
  2882. #endif
  2883. #ifdef STBI_NEON
  2884. j->idct_block_kernel = stbi__idct_simd;
  2885. #ifndef STBI_JPEG_OLD
  2886. j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
  2887. #endif
  2888. j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
  2889. #endif
  2890. }
  2891. // clean up the temporary component buffers
  2892. static void stbi__cleanup_jpeg(stbi__jpeg *j)
  2893. {
  2894. int i;
  2895. for (i=0; i < j->s->img_n; ++i) {
  2896. if (j->img_comp[i].raw_data) {
  2897. STBI_FREE(j->img_comp[i].raw_data);
  2898. j->img_comp[i].raw_data = NULL;
  2899. j->img_comp[i].data = NULL;
  2900. }
  2901. if (j->img_comp[i].raw_coeff) {
  2902. STBI_FREE(j->img_comp[i].raw_coeff);
  2903. j->img_comp[i].raw_coeff = 0;
  2904. j->img_comp[i].coeff = 0;
  2905. }
  2906. if (j->img_comp[i].linebuf) {
  2907. STBI_FREE(j->img_comp[i].linebuf);
  2908. j->img_comp[i].linebuf = NULL;
  2909. }
  2910. }
  2911. }
  2912. typedef struct
  2913. {
  2914. resample_row_func resample;
  2915. stbi_uc *line0,*line1;
  2916. int hs,vs; // expansion factor in each axis
  2917. int w_lores; // horizontal pixels pre-expansion
  2918. int ystep; // how far through vertical expansion we are
  2919. int ypos; // which pre-expansion row we're on
  2920. } stbi__resample;
  2921. static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
  2922. {
  2923. int n, decode_n;
  2924. z->s->img_n = 0; // make stbi__cleanup_jpeg safe
  2925. // validate req_comp
  2926. if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
  2927. // load a jpeg image from whichever source, but leave in YCbCr format
  2928. if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }
  2929. // determine actual number of components to generate
  2930. n = req_comp ? req_comp : z->s->img_n;
  2931. if (z->s->img_n == 3 && n < 3)
  2932. decode_n = 1;
  2933. else
  2934. decode_n = z->s->img_n;
  2935. // resample and color-convert
  2936. {
  2937. int k;
  2938. unsigned int i,j;
  2939. stbi_uc *output;
  2940. stbi_uc *coutput[4];
  2941. stbi__resample res_comp[4];
  2942. for (k=0; k < decode_n; ++k) {
  2943. stbi__resample *r = &res_comp[k];
  2944. // allocate line buffer big enough for upsampling off the edges
  2945. // with upsample factor of 4
  2946. z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3);
  2947. if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
  2948. r->hs = z->img_h_max / z->img_comp[k].h;
  2949. r->vs = z->img_v_max / z->img_comp[k].v;
  2950. r->ystep = r->vs >> 1;
  2951. r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
  2952. r->ypos = 0;
  2953. r->line0 = r->line1 = z->img_comp[k].data;
  2954. if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
  2955. else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;
  2956. else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;
  2957. else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel;
  2958. else r->resample = stbi__resample_row_generic;
  2959. }
  2960. // can't error after this so, this is safe
  2961. output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1);
  2962. if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
  2963. // now go ahead and resample
  2964. for (j=0; j < z->s->img_y; ++j) {
  2965. stbi_uc *out = output + n * z->s->img_x * j;
  2966. for (k=0; k < decode_n; ++k) {
  2967. stbi__resample *r = &res_comp[k];
  2968. int y_bot = r->ystep >= (r->vs >> 1);
  2969. coutput[k] = r->resample(z->img_comp[k].linebuf,
  2970. y_bot ? r->line1 : r->line0,
  2971. y_bot ? r->line0 : r->line1,
  2972. r->w_lores, r->hs);
  2973. if (++r->ystep >= r->vs) {
  2974. r->ystep = 0;
  2975. r->line0 = r->line1;
  2976. if (++r->ypos < z->img_comp[k].y)
  2977. r->line1 += z->img_comp[k].w2;
  2978. }
  2979. }
  2980. if (n >= 3) {
  2981. stbi_uc *y = coutput[0];
  2982. if (z->s->img_n == 3) {
  2983. if (z->rgb == 3) {
  2984. for (i=0; i < z->s->img_x; ++i) {
  2985. out[0] = y[i];
  2986. out[1] = coutput[1][i];
  2987. out[2] = coutput[2][i];
  2988. out[3] = 255;
  2989. out += n;
  2990. }
  2991. } else {
  2992. z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
  2993. }
  2994. } else
  2995. for (i=0; i < z->s->img_x; ++i) {
  2996. out[0] = out[1] = out[2] = y[i];
  2997. out[3] = 255; // not used if n==3
  2998. out += n;
  2999. }
  3000. } else {
  3001. stbi_uc *y = coutput[0];
  3002. if (n == 1)
  3003. for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
  3004. else
  3005. for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;
  3006. }
  3007. }
  3008. stbi__cleanup_jpeg(z);
  3009. *out_x = z->s->img_x;
  3010. *out_y = z->s->img_y;
  3011. if (comp) *comp = z->s->img_n; // report original components, not output
  3012. return output;
  3013. }
  3014. }
  3015. static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  3016. {
  3017. unsigned char* result;
  3018. stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));
  3019. j->s = s;
  3020. stbi__setup_jpeg(j);
  3021. result = load_jpeg_image(j, x,y,comp,req_comp);
  3022. STBI_FREE(j);
  3023. return result;
  3024. }
  3025. static int stbi__jpeg_test(stbi__context *s)
  3026. {
  3027. int r;
  3028. stbi__jpeg j;
  3029. j.s = s;
  3030. stbi__setup_jpeg(&j);
  3031. r = stbi__decode_jpeg_header(&j, STBI__SCAN_type);
  3032. stbi__rewind(s);
  3033. return r;
  3034. }
  3035. static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)
  3036. {
  3037. if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) {
  3038. stbi__rewind( j->s );
  3039. return 0;
  3040. }
  3041. if (x) *x = j->s->img_x;
  3042. if (y) *y = j->s->img_y;
  3043. if (comp) *comp = j->s->img_n;
  3044. return 1;
  3045. }
  3046. static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
  3047. {
  3048. int result;
  3049. stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg)));
  3050. j->s = s;
  3051. result = stbi__jpeg_info_raw(j, x, y, comp);
  3052. STBI_FREE(j);
  3053. return result;
  3054. }
  3055. #endif
  3056. // public domain zlib decode v0.2 Sean Barrett 2006-11-18
  3057. // simple implementation
  3058. // - all input must be provided in an upfront buffer
  3059. // - all output is written to a single output buffer (can malloc/realloc)
  3060. // performance
  3061. // - fast huffman
  3062. #ifndef STBI_NO_ZLIB
  3063. // fast-way is faster to check than jpeg huffman, but slow way is slower
  3064. #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
  3065. #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
  3066. // zlib-style huffman encoding
  3067. // (jpegs packs from left, zlib from right, so can't share code)
  3068. typedef struct
  3069. {
  3070. stbi__uint16 fast[1 << STBI__ZFAST_BITS];
  3071. stbi__uint16 firstcode[16];
  3072. int maxcode[17];
  3073. stbi__uint16 firstsymbol[16];
  3074. stbi_uc size[288];
  3075. stbi__uint16 value[288];
  3076. } stbi__zhuffman;
  3077. stbi_inline static int stbi__bitreverse16(int n)
  3078. {
  3079. n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
  3080. n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
  3081. n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
  3082. n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
  3083. return n;
  3084. }
  3085. stbi_inline static int stbi__bit_reverse(int v, int bits)
  3086. {
  3087. STBI_ASSERT(bits <= 16);
  3088. // to bit reverse n bits, reverse 16 and shift
  3089. // e.g. 11 bits, bit reverse and shift away 5
  3090. return stbi__bitreverse16(v) >> (16-bits);
  3091. }
  3092. static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num)
  3093. {
  3094. int i,k=0;
  3095. int code, next_code[16], sizes[17];
  3096. // DEFLATE spec for generating codes
  3097. memset(sizes, 0, sizeof(sizes));
  3098. memset(z->fast, 0, sizeof(z->fast));
  3099. for (i=0; i < num; ++i)
  3100. ++sizes[sizelist[i]];
  3101. sizes[0] = 0;
  3102. for (i=1; i < 16; ++i)
  3103. if (sizes[i] > (1 << i))
  3104. return stbi__err("bad sizes", "Corrupt PNG");
  3105. code = 0;
  3106. for (i=1; i < 16; ++i) {
  3107. next_code[i] = code;
  3108. z->firstcode[i] = (stbi__uint16) code;
  3109. z->firstsymbol[i] = (stbi__uint16) k;
  3110. code = (code + sizes[i]);
  3111. if (sizes[i])
  3112. if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG");
  3113. z->maxcode[i] = code << (16-i); // preshift for inner loop
  3114. code <<= 1;
  3115. k += sizes[i];
  3116. }
  3117. z->maxcode[16] = 0x10000; // sentinel
  3118. for (i=0; i < num; ++i) {
  3119. int s = sizelist[i];
  3120. if (s) {
  3121. int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
  3122. stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i);
  3123. z->size [c] = (stbi_uc ) s;
  3124. z->value[c] = (stbi__uint16) i;
  3125. if (s <= STBI__ZFAST_BITS) {
  3126. int j = stbi__bit_reverse(next_code[s],s);
  3127. while (j < (1 << STBI__ZFAST_BITS)) {
  3128. z->fast[j] = fastv;
  3129. j += (1 << s);
  3130. }
  3131. }
  3132. ++next_code[s];
  3133. }
  3134. }
  3135. return 1;
  3136. }
  3137. // zlib-from-memory implementation for PNG reading
  3138. // because PNG allows splitting the zlib stream arbitrarily,
  3139. // and it's annoying structurally to have PNG call ZLIB call PNG,
  3140. // we require PNG read all the IDATs and combine them into a single
  3141. // memory buffer
  3142. typedef struct
  3143. {
  3144. stbi_uc *zbuffer, *zbuffer_end;
  3145. int num_bits;
  3146. stbi__uint32 code_buffer;
  3147. char *zout;
  3148. char *zout_start;
  3149. char *zout_end;
  3150. int z_expandable;
  3151. stbi__zhuffman z_length, z_distance;
  3152. } stbi__zbuf;
  3153. stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
  3154. {
  3155. if (z->zbuffer >= z->zbuffer_end) return 0;
  3156. return *z->zbuffer++;
  3157. }
  3158. static void stbi__fill_bits(stbi__zbuf *z)
  3159. {
  3160. do {
  3161. STBI_ASSERT(z->code_buffer < (1U << z->num_bits));
  3162. z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits;
  3163. z->num_bits += 8;
  3164. } while (z->num_bits <= 24);
  3165. }
  3166. stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)
  3167. {
  3168. unsigned int k;
  3169. if (z->num_bits < n) stbi__fill_bits(z);
  3170. k = z->code_buffer & ((1 << n) - 1);
  3171. z->code_buffer >>= n;
  3172. z->num_bits -= n;
  3173. return k;
  3174. }
  3175. static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
  3176. {
  3177. int b,s,k;
  3178. // not resolved by fast table, so compute it the slow way
  3179. // use jpeg approach, which requires MSbits at top
  3180. k = stbi__bit_reverse(a->code_buffer, 16);
  3181. for (s=STBI__ZFAST_BITS+1; ; ++s)
  3182. if (k < z->maxcode[s])
  3183. break;
  3184. if (s == 16) return -1; // invalid code!
  3185. // code size is s, so:
  3186. b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
  3187. STBI_ASSERT(z->size[b] == s);
  3188. a->code_buffer >>= s;
  3189. a->num_bits -= s;
  3190. return z->value[b];
  3191. }
  3192. stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
  3193. {
  3194. int b,s;
  3195. if (a->num_bits < 16) stbi__fill_bits(a);
  3196. b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
  3197. if (b) {
  3198. s = b >> 9;
  3199. a->code_buffer >>= s;
  3200. a->num_bits -= s;
  3201. return b & 511;
  3202. }
  3203. return stbi__zhuffman_decode_slowpath(a, z);
  3204. }
  3205. static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes
  3206. {
  3207. char *q;
  3208. int cur, limit, old_limit;
  3209. z->zout = zout;
  3210. if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
  3211. cur = (int) (z->zout - z->zout_start);
  3212. limit = old_limit = (int) (z->zout_end - z->zout_start);
  3213. while (cur + n > limit)
  3214. limit *= 2;
  3215. q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);
  3216. STBI_NOTUSED(old_limit);
  3217. if (q == NULL) return stbi__err("outofmem", "Out of memory");
  3218. z->zout_start = q;
  3219. z->zout = q + cur;
  3220. z->zout_end = q + limit;
  3221. return 1;
  3222. }
  3223. static int stbi__zlength_base[31] = {
  3224. 3,4,5,6,7,8,9,10,11,13,
  3225. 15,17,19,23,27,31,35,43,51,59,
  3226. 67,83,99,115,131,163,195,227,258,0,0 };
  3227. static int stbi__zlength_extra[31]=
  3228. { 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 };
  3229. static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
  3230. 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
  3231. static int stbi__zdist_extra[32] =
  3232. { 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};
  3233. static int stbi__parse_huffman_block(stbi__zbuf *a)
  3234. {
  3235. char *zout = a->zout;
  3236. for(;;) {
  3237. int z = stbi__zhuffman_decode(a, &a->z_length);
  3238. if (z < 256) {
  3239. if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes
  3240. if (zout >= a->zout_end) {
  3241. if (!stbi__zexpand(a, zout, 1)) return 0;
  3242. zout = a->zout;
  3243. }
  3244. *zout++ = (char) z;
  3245. } else {
  3246. stbi_uc *p;
  3247. int len,dist;
  3248. if (z == 256) {
  3249. a->zout = zout;
  3250. return 1;
  3251. }
  3252. z -= 257;
  3253. len = stbi__zlength_base[z];
  3254. if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
  3255. z = stbi__zhuffman_decode(a, &a->z_distance);
  3256. if (z < 0) return stbi__err("bad huffman code","Corrupt PNG");
  3257. dist = stbi__zdist_base[z];
  3258. if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
  3259. if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");
  3260. if (zout + len > a->zout_end) {
  3261. if (!stbi__zexpand(a, zout, len)) return 0;
  3262. zout = a->zout;
  3263. }
  3264. p = (stbi_uc *) (zout - dist);
  3265. if (dist == 1) { // run of one byte; common in images.
  3266. stbi_uc v = *p;
  3267. if (len) { do *zout++ = v; while (--len); }
  3268. } else {
  3269. if (len) { do *zout++ = *p++; while (--len); }
  3270. }
  3271. }
  3272. }
  3273. }
  3274. static int stbi__compute_huffman_codes(stbi__zbuf *a)
  3275. {
  3276. static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
  3277. stbi__zhuffman z_codelength;
  3278. stbi_uc lencodes[286+32+137];//padding for maximum single op
  3279. stbi_uc codelength_sizes[19];
  3280. int i,n;
  3281. int hlit = stbi__zreceive(a,5) + 257;
  3282. int hdist = stbi__zreceive(a,5) + 1;
  3283. int hclen = stbi__zreceive(a,4) + 4;
  3284. memset(codelength_sizes, 0, sizeof(codelength_sizes));
  3285. for (i=0; i < hclen; ++i) {
  3286. int s = stbi__zreceive(a,3);
  3287. codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;
  3288. }
  3289. if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
  3290. n = 0;
  3291. while (n < hlit + hdist) {
  3292. int c = stbi__zhuffman_decode(a, &z_codelength);
  3293. if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");
  3294. if (c < 16)
  3295. lencodes[n++] = (stbi_uc) c;
  3296. else if (c == 16) {
  3297. c = stbi__zreceive(a,2)+3;
  3298. memset(lencodes+n, lencodes[n-1], c);
  3299. n += c;
  3300. } else if (c == 17) {
  3301. c = stbi__zreceive(a,3)+3;
  3302. memset(lencodes+n, 0, c);
  3303. n += c;
  3304. } else {
  3305. STBI_ASSERT(c == 18);
  3306. c = stbi__zreceive(a,7)+11;
  3307. memset(lencodes+n, 0, c);
  3308. n += c;
  3309. }
  3310. }
  3311. if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG");
  3312. if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
  3313. if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
  3314. return 1;
  3315. }
  3316. static int stbi__parse_uncompressed_block(stbi__zbuf *a)
  3317. {
  3318. stbi_uc header[4];
  3319. int len,nlen,k;
  3320. if (a->num_bits & 7)
  3321. stbi__zreceive(a, a->num_bits & 7); // discard
  3322. // drain the bit-packed data into header
  3323. k = 0;
  3324. while (a->num_bits > 0) {
  3325. header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check
  3326. a->code_buffer >>= 8;
  3327. a->num_bits -= 8;
  3328. }
  3329. STBI_ASSERT(a->num_bits == 0);
  3330. // now fill header the normal way
  3331. while (k < 4)
  3332. header[k++] = stbi__zget8(a);
  3333. len = header[1] * 256 + header[0];
  3334. nlen = header[3] * 256 + header[2];
  3335. if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");
  3336. if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");
  3337. if (a->zout + len > a->zout_end)
  3338. if (!stbi__zexpand(a, a->zout, len)) return 0;
  3339. memcpy(a->zout, a->zbuffer, len);
  3340. a->zbuffer += len;
  3341. a->zout += len;
  3342. return 1;
  3343. }
  3344. static int stbi__parse_zlib_header(stbi__zbuf *a)
  3345. {
  3346. int cmf = stbi__zget8(a);
  3347. int cm = cmf & 15;
  3348. /* int cinfo = cmf >> 4; */
  3349. int flg = stbi__zget8(a);
  3350. if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
  3351. if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
  3352. if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png
  3353. // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
  3354. return 1;
  3355. }
  3356. // @TODO: should statically initialize these for optimal thread safety
  3357. static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32];
  3358. static void stbi__init_zdefaults(void)
  3359. {
  3360. int i; // use <= to match clearly with spec
  3361. for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
  3362. for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
  3363. for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
  3364. for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
  3365. for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
  3366. }
  3367. static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
  3368. {
  3369. int final, type;
  3370. if (parse_header)
  3371. if (!stbi__parse_zlib_header(a)) return 0;
  3372. a->num_bits = 0;
  3373. a->code_buffer = 0;
  3374. do {
  3375. final = stbi__zreceive(a,1);
  3376. type = stbi__zreceive(a,2);
  3377. if (type == 0) {
  3378. if (!stbi__parse_uncompressed_block(a)) return 0;
  3379. } else if (type == 3) {
  3380. return 0;
  3381. } else {
  3382. if (type == 1) {
  3383. // use fixed code lengths
  3384. if (!stbi__zdefault_distance[31]) stbi__init_zdefaults();
  3385. if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0;
  3386. if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;
  3387. } else {
  3388. if (!stbi__compute_huffman_codes(a)) return 0;
  3389. }
  3390. if (!stbi__parse_huffman_block(a)) return 0;
  3391. }
  3392. } while (!final);
  3393. return 1;
  3394. }
  3395. static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)
  3396. {
  3397. a->zout_start = obuf;
  3398. a->zout = obuf;
  3399. a->zout_end = obuf + olen;
  3400. a->z_expandable = exp;
  3401. return stbi__parse_zlib(a, parse_header);
  3402. }
  3403. STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
  3404. {
  3405. stbi__zbuf a;
  3406. char *p = (char *) stbi__malloc(initial_size);
  3407. if (p == NULL) return NULL;
  3408. a.zbuffer = (stbi_uc *) buffer;
  3409. a.zbuffer_end = (stbi_uc *) buffer + len;
  3410. if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {
  3411. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  3412. return a.zout_start;
  3413. } else {
  3414. STBI_FREE(a.zout_start);
  3415. return NULL;
  3416. }
  3417. }
  3418. STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
  3419. {
  3420. return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
  3421. }
  3422. STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
  3423. {
  3424. stbi__zbuf a;
  3425. char *p = (char *) stbi__malloc(initial_size);
  3426. if (p == NULL) return NULL;
  3427. a.zbuffer = (stbi_uc *) buffer;
  3428. a.zbuffer_end = (stbi_uc *) buffer + len;
  3429. if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {
  3430. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  3431. return a.zout_start;
  3432. } else {
  3433. STBI_FREE(a.zout_start);
  3434. return NULL;
  3435. }
  3436. }
  3437. STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
  3438. {
  3439. stbi__zbuf a;
  3440. a.zbuffer = (stbi_uc *) ibuffer;
  3441. a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
  3442. if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
  3443. return (int) (a.zout - a.zout_start);
  3444. else
  3445. return -1;
  3446. }
  3447. STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
  3448. {
  3449. stbi__zbuf a;
  3450. char *p = (char *) stbi__malloc(16384);
  3451. if (p == NULL) return NULL;
  3452. a.zbuffer = (stbi_uc *) buffer;
  3453. a.zbuffer_end = (stbi_uc *) buffer+len;
  3454. if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
  3455. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  3456. return a.zout_start;
  3457. } else {
  3458. STBI_FREE(a.zout_start);
  3459. return NULL;
  3460. }
  3461. }
  3462. STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
  3463. {
  3464. stbi__zbuf a;
  3465. a.zbuffer = (stbi_uc *) ibuffer;
  3466. a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
  3467. if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
  3468. return (int) (a.zout - a.zout_start);
  3469. else
  3470. return -1;
  3471. }
  3472. #endif
  3473. // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
  3474. // simple implementation
  3475. // - only 8-bit samples
  3476. // - no CRC checking
  3477. // - allocates lots of intermediate memory
  3478. // - avoids problem of streaming data between subsystems
  3479. // - avoids explicit window management
  3480. // performance
  3481. // - uses stb_zlib, a PD zlib implementation with fast huffman decoding
  3482. #ifndef STBI_NO_PNG
  3483. typedef struct
  3484. {
  3485. stbi__uint32 length;
  3486. stbi__uint32 type;
  3487. } stbi__pngchunk;
  3488. static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
  3489. {
  3490. stbi__pngchunk c;
  3491. c.length = stbi__get32be(s);
  3492. c.type = stbi__get32be(s);
  3493. return c;
  3494. }
  3495. static int stbi__check_png_header(stbi__context *s)
  3496. {
  3497. static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };
  3498. int i;
  3499. for (i=0; i < 8; ++i)
  3500. if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");
  3501. return 1;
  3502. }
  3503. typedef struct
  3504. {
  3505. stbi__context *s;
  3506. stbi_uc *idata, *expanded, *out;
  3507. int depth;
  3508. } stbi__png;
  3509. enum {
  3510. STBI__F_none=0,
  3511. STBI__F_sub=1,
  3512. STBI__F_up=2,
  3513. STBI__F_avg=3,
  3514. STBI__F_paeth=4,
  3515. // synthetic filters used for first scanline to avoid needing a dummy row of 0s
  3516. STBI__F_avg_first,
  3517. STBI__F_paeth_first
  3518. };
  3519. static stbi_uc first_row_filter[5] =
  3520. {
  3521. STBI__F_none,
  3522. STBI__F_sub,
  3523. STBI__F_none,
  3524. STBI__F_avg_first,
  3525. STBI__F_paeth_first
  3526. };
  3527. static int stbi__paeth(int a, int b, int c)
  3528. {
  3529. int p = a + b - c;
  3530. int pa = abs(p-a);
  3531. int pb = abs(p-b);
  3532. int pc = abs(p-c);
  3533. if (pa <= pb && pa <= pc) return a;
  3534. if (pb <= pc) return b;
  3535. return c;
  3536. }
  3537. static stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 };
  3538. // create the png data from post-deflated data
  3539. static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)
  3540. {
  3541. int bytes = (depth == 16? 2 : 1);
  3542. stbi__context *s = a->s;
  3543. stbi__uint32 i,j,stride = x*out_n*bytes;
  3544. stbi__uint32 img_len, img_width_bytes;
  3545. int k;
  3546. int img_n = s->img_n; // copy it into a local for later
  3547. int output_bytes = out_n*bytes;
  3548. int filter_bytes = img_n*bytes;
  3549. int width = x;
  3550. STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);
  3551. a->out = (stbi_uc *) stbi__malloc(x * y * output_bytes); // extra bytes to write off the end into
  3552. if (!a->out) return stbi__err("outofmem", "Out of memory");
  3553. img_width_bytes = (((img_n * x * depth) + 7) >> 3);
  3554. img_len = (img_width_bytes + 1) * y;
  3555. if (s->img_x == x && s->img_y == y) {
  3556. if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG");
  3557. } else { // interlaced:
  3558. if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG");
  3559. }
  3560. for (j=0; j < y; ++j) {
  3561. stbi_uc *cur = a->out + stride*j;
  3562. stbi_uc *prior = cur - stride;
  3563. int filter = *raw++;
  3564. if (filter > 4)
  3565. return stbi__err("invalid filter","Corrupt PNG");
  3566. if (depth < 8) {
  3567. STBI_ASSERT(img_width_bytes <= x);
  3568. cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place
  3569. filter_bytes = 1;
  3570. width = img_width_bytes;
  3571. }
  3572. // if first row, use special filter that doesn't sample previous row
  3573. if (j == 0) filter = first_row_filter[filter];
  3574. // handle first byte explicitly
  3575. for (k=0; k < filter_bytes; ++k) {
  3576. switch (filter) {
  3577. case STBI__F_none : cur[k] = raw[k]; break;
  3578. case STBI__F_sub : cur[k] = raw[k]; break;
  3579. case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;
  3580. case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break;
  3581. case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break;
  3582. case STBI__F_avg_first : cur[k] = raw[k]; break;
  3583. case STBI__F_paeth_first: cur[k] = raw[k]; break;
  3584. }
  3585. }
  3586. if (depth == 8) {
  3587. if (img_n != out_n)
  3588. cur[img_n] = 255; // first pixel
  3589. raw += img_n;
  3590. cur += out_n;
  3591. prior += out_n;
  3592. } else if (depth == 16) {
  3593. if (img_n != out_n) {
  3594. cur[filter_bytes] = 255; // first pixel top byte
  3595. cur[filter_bytes+1] = 255; // first pixel bottom byte
  3596. }
  3597. raw += filter_bytes;
  3598. cur += output_bytes;
  3599. prior += output_bytes;
  3600. } else {
  3601. raw += 1;
  3602. cur += 1;
  3603. prior += 1;
  3604. }
  3605. // this is a little gross, so that we don't switch per-pixel or per-component
  3606. if (depth < 8 || img_n == out_n) {
  3607. int nk = (width - 1)*filter_bytes;
  3608. #define CASE(f) \
  3609. case f: \
  3610. for (k=0; k < nk; ++k)
  3611. switch (filter) {
  3612. // "none" filter turns into a memcpy here; make that explicit.
  3613. case STBI__F_none: memcpy(cur, raw, nk); break;
  3614. CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); break;
  3615. CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;
  3616. CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); break;
  3617. CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); break;
  3618. CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); break;
  3619. CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); break;
  3620. }
  3621. #undef CASE
  3622. raw += nk;
  3623. } else {
  3624. STBI_ASSERT(img_n+1 == out_n);
  3625. #define CASE(f) \
  3626. case f: \
  3627. for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \
  3628. for (k=0; k < filter_bytes; ++k)
  3629. switch (filter) {
  3630. CASE(STBI__F_none) cur[k] = raw[k]; break;
  3631. CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); break;
  3632. CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;
  3633. CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); break;
  3634. CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); break;
  3635. CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); break;
  3636. CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); break;
  3637. }
  3638. #undef CASE
  3639. // the loop above sets the high byte of the pixels' alpha, but for
  3640. // 16 bit png files we also need the low byte set. we'll do that here.
  3641. if (depth == 16) {
  3642. cur = a->out + stride*j; // start at the beginning of the row again
  3643. for (i=0; i < x; ++i,cur+=output_bytes) {
  3644. cur[filter_bytes+1] = 255;
  3645. }
  3646. }
  3647. }
  3648. }
  3649. // we make a separate pass to expand bits to pixels; for performance,
  3650. // this could run two scanlines behind the above code, so it won't
  3651. // intefere with filtering but will still be in the cache.
  3652. if (depth < 8) {
  3653. for (j=0; j < y; ++j) {
  3654. stbi_uc *cur = a->out + stride*j;
  3655. stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes;
  3656. // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit
  3657. // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop
  3658. stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range
  3659. // note that the final byte might overshoot and write more data than desired.
  3660. // we can allocate enough data that this never writes out of memory, but it
  3661. // could also overwrite the next scanline. can it overwrite non-empty data
  3662. // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel.
  3663. // so we need to explicitly clamp the final ones
  3664. if (depth == 4) {
  3665. for (k=x*img_n; k >= 2; k-=2, ++in) {
  3666. *cur++ = scale * ((*in >> 4) );
  3667. *cur++ = scale * ((*in ) & 0x0f);
  3668. }
  3669. if (k > 0) *cur++ = scale * ((*in >> 4) );
  3670. } else if (depth == 2) {
  3671. for (k=x*img_n; k >= 4; k-=4, ++in) {
  3672. *cur++ = scale * ((*in >> 6) );
  3673. *cur++ = scale * ((*in >> 4) & 0x03);
  3674. *cur++ = scale * ((*in >> 2) & 0x03);
  3675. *cur++ = scale * ((*in ) & 0x03);
  3676. }
  3677. if (k > 0) *cur++ = scale * ((*in >> 6) );
  3678. if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03);
  3679. if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03);
  3680. } else if (depth == 1) {
  3681. for (k=x*img_n; k >= 8; k-=8, ++in) {
  3682. *cur++ = scale * ((*in >> 7) );
  3683. *cur++ = scale * ((*in >> 6) & 0x01);
  3684. *cur++ = scale * ((*in >> 5) & 0x01);
  3685. *cur++ = scale * ((*in >> 4) & 0x01);
  3686. *cur++ = scale * ((*in >> 3) & 0x01);
  3687. *cur++ = scale * ((*in >> 2) & 0x01);
  3688. *cur++ = scale * ((*in >> 1) & 0x01);
  3689. *cur++ = scale * ((*in ) & 0x01);
  3690. }
  3691. if (k > 0) *cur++ = scale * ((*in >> 7) );
  3692. if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01);
  3693. if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01);
  3694. if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01);
  3695. if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01);
  3696. if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01);
  3697. if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01);
  3698. }
  3699. if (img_n != out_n) {
  3700. int q;
  3701. // insert alpha = 255
  3702. cur = a->out + stride*j;
  3703. if (img_n == 1) {
  3704. for (q=x-1; q >= 0; --q) {
  3705. cur[q*2+1] = 255;
  3706. cur[q*2+0] = cur[q];
  3707. }
  3708. } else {
  3709. STBI_ASSERT(img_n == 3);
  3710. for (q=x-1; q >= 0; --q) {
  3711. cur[q*4+3] = 255;
  3712. cur[q*4+2] = cur[q*3+2];
  3713. cur[q*4+1] = cur[q*3+1];
  3714. cur[q*4+0] = cur[q*3+0];
  3715. }
  3716. }
  3717. }
  3718. }
  3719. } else if (depth == 16) {
  3720. // force the image data from big-endian to platform-native.
  3721. // this is done in a separate pass due to the decoding relying
  3722. // on the data being untouched, but could probably be done
  3723. // per-line during decode if care is taken.
  3724. stbi_uc *cur = a->out;
  3725. stbi__uint16 *cur16 = (stbi__uint16*)cur;
  3726. for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) {
  3727. *cur16 = (cur[0] << 8) | cur[1];
  3728. }
  3729. }
  3730. return 1;
  3731. }
  3732. static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)
  3733. {
  3734. stbi_uc *final;
  3735. int p;
  3736. if (!interlaced)
  3737. return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);
  3738. // de-interlacing
  3739. final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n);
  3740. for (p=0; p < 7; ++p) {
  3741. int xorig[] = { 0,4,0,2,0,1,0 };
  3742. int yorig[] = { 0,0,4,0,2,0,1 };
  3743. int xspc[] = { 8,8,4,4,2,2,1 };
  3744. int yspc[] = { 8,8,8,4,4,2,2 };
  3745. int i,j,x,y;
  3746. // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
  3747. x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
  3748. y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
  3749. if (x && y) {
  3750. stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
  3751. if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) {
  3752. STBI_FREE(final);
  3753. return 0;
  3754. }
  3755. for (j=0; j < y; ++j) {
  3756. for (i=0; i < x; ++i) {
  3757. int out_y = j*yspc[p]+yorig[p];
  3758. int out_x = i*xspc[p]+xorig[p];
  3759. memcpy(final + out_y*a->s->img_x*out_n + out_x*out_n,
  3760. a->out + (j*x+i)*out_n, out_n);
  3761. }
  3762. }
  3763. STBI_FREE(a->out);
  3764. image_data += img_len;
  3765. image_data_len -= img_len;
  3766. }
  3767. }
  3768. a->out = final;
  3769. return 1;
  3770. }
  3771. static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)
  3772. {
  3773. stbi__context *s = z->s;
  3774. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  3775. stbi_uc *p = z->out;
  3776. // compute color-based transparency, assuming we've
  3777. // already got 255 as the alpha value in the output
  3778. STBI_ASSERT(out_n == 2 || out_n == 4);
  3779. if (out_n == 2) {
  3780. for (i=0; i < pixel_count; ++i) {
  3781. p[1] = (p[0] == tc[0] ? 0 : 255);
  3782. p += 2;
  3783. }
  3784. } else {
  3785. for (i=0; i < pixel_count; ++i) {
  3786. if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
  3787. p[3] = 0;
  3788. p += 4;
  3789. }
  3790. }
  3791. return 1;
  3792. }
  3793. static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n)
  3794. {
  3795. stbi__context *s = z->s;
  3796. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  3797. stbi__uint16 *p = (stbi__uint16*) z->out;
  3798. // compute color-based transparency, assuming we've
  3799. // already got 65535 as the alpha value in the output
  3800. STBI_ASSERT(out_n == 2 || out_n == 4);
  3801. if (out_n == 2) {
  3802. for (i = 0; i < pixel_count; ++i) {
  3803. p[1] = (p[0] == tc[0] ? 0 : 65535);
  3804. p += 2;
  3805. }
  3806. } else {
  3807. for (i = 0; i < pixel_count; ++i) {
  3808. if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
  3809. p[3] = 0;
  3810. p += 4;
  3811. }
  3812. }
  3813. return 1;
  3814. }
  3815. static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)
  3816. {
  3817. stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
  3818. stbi_uc *p, *temp_out, *orig = a->out;
  3819. p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n);
  3820. if (p == NULL) return stbi__err("outofmem", "Out of memory");
  3821. // between here and free(out) below, exitting would leak
  3822. temp_out = p;
  3823. if (pal_img_n == 3) {
  3824. for (i=0; i < pixel_count; ++i) {
  3825. int n = orig[i]*4;
  3826. p[0] = palette[n ];
  3827. p[1] = palette[n+1];
  3828. p[2] = palette[n+2];
  3829. p += 3;
  3830. }
  3831. } else {
  3832. for (i=0; i < pixel_count; ++i) {
  3833. int n = orig[i]*4;
  3834. p[0] = palette[n ];
  3835. p[1] = palette[n+1];
  3836. p[2] = palette[n+2];
  3837. p[3] = palette[n+3];
  3838. p += 4;
  3839. }
  3840. }
  3841. STBI_FREE(a->out);
  3842. a->out = temp_out;
  3843. STBI_NOTUSED(len);
  3844. return 1;
  3845. }
  3846. static int stbi__reduce_png(stbi__png *p)
  3847. {
  3848. int i;
  3849. int img_len = p->s->img_x * p->s->img_y * p->s->img_out_n;
  3850. stbi_uc *reduced;
  3851. stbi__uint16 *orig = (stbi__uint16*)p->out;
  3852. if (p->depth != 16) return 1; // don't need to do anything if not 16-bit data
  3853. reduced = (stbi_uc *)stbi__malloc(img_len);
  3854. if (p == NULL) return stbi__err("outofmem", "Out of memory");
  3855. for (i = 0; i < img_len; ++i) reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is a decent approx of 16->8 bit scaling
  3856. p->out = reduced;
  3857. STBI_FREE(orig);
  3858. return 1;
  3859. }
  3860. static int stbi__unpremultiply_on_load = 0;
  3861. static int stbi__de_iphone_flag = 0;
  3862. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
  3863. {
  3864. stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply;
  3865. }
  3866. STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
  3867. {
  3868. stbi__de_iphone_flag = flag_true_if_should_convert;
  3869. }
  3870. static void stbi__de_iphone(stbi__png *z)
  3871. {
  3872. stbi__context *s = z->s;
  3873. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  3874. stbi_uc *p = z->out;
  3875. if (s->img_out_n == 3) { // convert bgr to rgb
  3876. for (i=0; i < pixel_count; ++i) {
  3877. stbi_uc t = p[0];
  3878. p[0] = p[2];
  3879. p[2] = t;
  3880. p += 3;
  3881. }
  3882. } else {
  3883. STBI_ASSERT(s->img_out_n == 4);
  3884. if (stbi__unpremultiply_on_load) {
  3885. // convert bgr to rgb and unpremultiply
  3886. for (i=0; i < pixel_count; ++i) {
  3887. stbi_uc a = p[3];
  3888. stbi_uc t = p[0];
  3889. if (a) {
  3890. p[0] = p[2] * 255 / a;
  3891. p[1] = p[1] * 255 / a;
  3892. p[2] = t * 255 / a;
  3893. } else {
  3894. p[0] = p[2];
  3895. p[2] = t;
  3896. }
  3897. p += 4;
  3898. }
  3899. } else {
  3900. // convert bgr to rgb
  3901. for (i=0; i < pixel_count; ++i) {
  3902. stbi_uc t = p[0];
  3903. p[0] = p[2];
  3904. p[2] = t;
  3905. p += 4;
  3906. }
  3907. }
  3908. }
  3909. }
  3910. #define STBI__PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
  3911. static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
  3912. {
  3913. stbi_uc palette[1024], pal_img_n=0;
  3914. stbi_uc has_trans=0, tc[3];
  3915. stbi__uint16 tc16[3];
  3916. stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;
  3917. int first=1,k,interlace=0, color=0, is_iphone=0;
  3918. stbi__context *s = z->s;
  3919. z->expanded = NULL;
  3920. z->idata = NULL;
  3921. z->out = NULL;
  3922. if (!stbi__check_png_header(s)) return 0;
  3923. if (scan == STBI__SCAN_type) return 1;
  3924. for (;;) {
  3925. stbi__pngchunk c = stbi__get_chunk_header(s);
  3926. switch (c.type) {
  3927. case STBI__PNG_TYPE('C','g','B','I'):
  3928. is_iphone = 1;
  3929. stbi__skip(s, c.length);
  3930. break;
  3931. case STBI__PNG_TYPE('I','H','D','R'): {
  3932. int comp,filter;
  3933. if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
  3934. first = 0;
  3935. if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
  3936. s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
  3937. s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
  3938. z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only");
  3939. color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");
  3940. if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG");
  3941. if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");
  3942. comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");
  3943. filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");
  3944. interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");
  3945. if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");
  3946. if (!pal_img_n) {
  3947. s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
  3948. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
  3949. if (scan == STBI__SCAN_header) return 1;
  3950. } else {
  3951. // if paletted, then pal_n is our final components, and
  3952. // img_n is # components to decompress/filter.
  3953. s->img_n = 1;
  3954. if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");
  3955. // if SCAN_header, have to scan to see if we have a tRNS
  3956. }
  3957. break;
  3958. }
  3959. case STBI__PNG_TYPE('P','L','T','E'): {
  3960. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  3961. if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");
  3962. pal_len = c.length / 3;
  3963. if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");
  3964. for (i=0; i < pal_len; ++i) {
  3965. palette[i*4+0] = stbi__get8(s);
  3966. palette[i*4+1] = stbi__get8(s);
  3967. palette[i*4+2] = stbi__get8(s);
  3968. palette[i*4+3] = 255;
  3969. }
  3970. break;
  3971. }
  3972. case STBI__PNG_TYPE('t','R','N','S'): {
  3973. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  3974. if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");
  3975. if (pal_img_n) {
  3976. if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; }
  3977. if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");
  3978. if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");
  3979. pal_img_n = 4;
  3980. for (i=0; i < c.length; ++i)
  3981. palette[i*4+3] = stbi__get8(s);
  3982. } else {
  3983. if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");
  3984. if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");
  3985. has_trans = 1;
  3986. if (z->depth == 16) {
  3987. for (k = 0; k < s->img_n; ++k) tc16[k] = stbi__get16be(s); // copy the values as-is
  3988. } else {
  3989. for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger
  3990. }
  3991. }
  3992. break;
  3993. }
  3994. case STBI__PNG_TYPE('I','D','A','T'): {
  3995. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  3996. if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");
  3997. if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; }
  3998. if ((int)(ioff + c.length) < (int)ioff) return 0;
  3999. if (ioff + c.length > idata_limit) {
  4000. stbi__uint32 idata_limit_old = idata_limit;
  4001. stbi_uc *p;
  4002. if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
  4003. while (ioff + c.length > idata_limit)
  4004. idata_limit *= 2;
  4005. STBI_NOTUSED(idata_limit_old);
  4006. p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
  4007. z->idata = p;
  4008. }
  4009. if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");
  4010. ioff += c.length;
  4011. break;
  4012. }
  4013. case STBI__PNG_TYPE('I','E','N','D'): {
  4014. stbi__uint32 raw_len, bpl;
  4015. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  4016. if (scan != STBI__SCAN_load) return 1;
  4017. if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");
  4018. // initial guess for decoded data size to avoid unnecessary reallocs
  4019. bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component
  4020. raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */;
  4021. z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone);
  4022. if (z->expanded == NULL) return 0; // zlib should set error
  4023. STBI_FREE(z->idata); z->idata = NULL;
  4024. if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
  4025. s->img_out_n = s->img_n+1;
  4026. else
  4027. s->img_out_n = s->img_n;
  4028. if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0;
  4029. if (has_trans) {
  4030. if (z->depth == 16) {
  4031. if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0;
  4032. } else {
  4033. if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
  4034. }
  4035. }
  4036. if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
  4037. stbi__de_iphone(z);
  4038. if (pal_img_n) {
  4039. // pal_img_n == 3 or 4
  4040. s->img_n = pal_img_n; // record the actual colors we had
  4041. s->img_out_n = pal_img_n;
  4042. if (req_comp >= 3) s->img_out_n = req_comp;
  4043. if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
  4044. return 0;
  4045. }
  4046. STBI_FREE(z->expanded); z->expanded = NULL;
  4047. return 1;
  4048. }
  4049. default:
  4050. // if critical, fail
  4051. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  4052. if ((c.type & (1 << 29)) == 0) {
  4053. #ifndef STBI_NO_FAILURE_STRINGS
  4054. // not threadsafe
  4055. static char invalid_chunk[] = "XXXX PNG chunk not known";
  4056. invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
  4057. invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
  4058. invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
  4059. invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
  4060. #endif
  4061. return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type");
  4062. }
  4063. stbi__skip(s, c.length);
  4064. break;
  4065. }
  4066. // end of PNG chunk, read and skip CRC
  4067. stbi__get32be(s);
  4068. }
  4069. }
  4070. static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp)
  4071. {
  4072. unsigned char *result=NULL;
  4073. if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
  4074. if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
  4075. if (p->depth == 16) {
  4076. if (!stbi__reduce_png(p)) {
  4077. return result;
  4078. }
  4079. }
  4080. result = p->out;
  4081. p->out = NULL;
  4082. if (req_comp && req_comp != p->s->img_out_n) {
  4083. result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
  4084. p->s->img_out_n = req_comp;
  4085. if (result == NULL) return result;
  4086. }
  4087. *x = p->s->img_x;
  4088. *y = p->s->img_y;
  4089. if (n) *n = p->s->img_n;
  4090. }
  4091. STBI_FREE(p->out); p->out = NULL;
  4092. STBI_FREE(p->expanded); p->expanded = NULL;
  4093. STBI_FREE(p->idata); p->idata = NULL;
  4094. return result;
  4095. }
  4096. static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  4097. {
  4098. stbi__png p;
  4099. p.s = s;
  4100. return stbi__do_png(&p, x,y,comp,req_comp);
  4101. }
  4102. static int stbi__png_test(stbi__context *s)
  4103. {
  4104. int r;
  4105. r = stbi__check_png_header(s);
  4106. stbi__rewind(s);
  4107. return r;
  4108. }
  4109. static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
  4110. {
  4111. if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) {
  4112. stbi__rewind( p->s );
  4113. return 0;
  4114. }
  4115. if (x) *x = p->s->img_x;
  4116. if (y) *y = p->s->img_y;
  4117. if (comp) *comp = p->s->img_n;
  4118. return 1;
  4119. }
  4120. static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
  4121. {
  4122. stbi__png p;
  4123. p.s = s;
  4124. return stbi__png_info_raw(&p, x, y, comp);
  4125. }
  4126. #endif
  4127. // Microsoft/Windows BMP image
  4128. #ifndef STBI_NO_BMP
  4129. static int stbi__bmp_test_raw(stbi__context *s)
  4130. {
  4131. int r;
  4132. int sz;
  4133. if (stbi__get8(s) != 'B') return 0;
  4134. if (stbi__get8(s) != 'M') return 0;
  4135. stbi__get32le(s); // discard filesize
  4136. stbi__get16le(s); // discard reserved
  4137. stbi__get16le(s); // discard reserved
  4138. stbi__get32le(s); // discard data offset
  4139. sz = stbi__get32le(s);
  4140. r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124);
  4141. return r;
  4142. }
  4143. static int stbi__bmp_test(stbi__context *s)
  4144. {
  4145. int r = stbi__bmp_test_raw(s);
  4146. stbi__rewind(s);
  4147. return r;
  4148. }
  4149. // returns 0..31 for the highest set bit
  4150. static int stbi__high_bit(unsigned int z)
  4151. {
  4152. int n=0;
  4153. if (z == 0) return -1;
  4154. if (z >= 0x10000) n += 16, z >>= 16;
  4155. if (z >= 0x00100) n += 8, z >>= 8;
  4156. if (z >= 0x00010) n += 4, z >>= 4;
  4157. if (z >= 0x00004) n += 2, z >>= 2;
  4158. if (z >= 0x00002) n += 1, z >>= 1;
  4159. return n;
  4160. }
  4161. static int stbi__bitcount(unsigned int a)
  4162. {
  4163. a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
  4164. a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
  4165. a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
  4166. a = (a + (a >> 8)); // max 16 per 8 bits
  4167. a = (a + (a >> 16)); // max 32 per 8 bits
  4168. return a & 0xff;
  4169. }
  4170. static int stbi__shiftsigned(int v, int shift, int bits)
  4171. {
  4172. int result;
  4173. int z=0;
  4174. if (shift < 0) v <<= -shift;
  4175. else v >>= shift;
  4176. result = v;
  4177. z = bits;
  4178. while (z < 8) {
  4179. result += v >> z;
  4180. z += bits;
  4181. }
  4182. return result;
  4183. }
  4184. typedef struct
  4185. {
  4186. int bpp, offset, hsz;
  4187. unsigned int mr,mg,mb,ma, all_a;
  4188. } stbi__bmp_data;
  4189. static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
  4190. {
  4191. int hsz;
  4192. if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");
  4193. stbi__get32le(s); // discard filesize
  4194. stbi__get16le(s); // discard reserved
  4195. stbi__get16le(s); // discard reserved
  4196. info->offset = stbi__get32le(s);
  4197. info->hsz = hsz = stbi__get32le(s);
  4198. info->mr = info->mg = info->mb = info->ma = 0;
  4199. if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
  4200. if (hsz == 12) {
  4201. s->img_x = stbi__get16le(s);
  4202. s->img_y = stbi__get16le(s);
  4203. } else {
  4204. s->img_x = stbi__get32le(s);
  4205. s->img_y = stbi__get32le(s);
  4206. }
  4207. if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP");
  4208. info->bpp = stbi__get16le(s);
  4209. if (info->bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit");
  4210. if (hsz != 12) {
  4211. int compress = stbi__get32le(s);
  4212. if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
  4213. stbi__get32le(s); // discard sizeof
  4214. stbi__get32le(s); // discard hres
  4215. stbi__get32le(s); // discard vres
  4216. stbi__get32le(s); // discard colorsused
  4217. stbi__get32le(s); // discard max important
  4218. if (hsz == 40 || hsz == 56) {
  4219. if (hsz == 56) {
  4220. stbi__get32le(s);
  4221. stbi__get32le(s);
  4222. stbi__get32le(s);
  4223. stbi__get32le(s);
  4224. }
  4225. if (info->bpp == 16 || info->bpp == 32) {
  4226. if (compress == 0) {
  4227. if (info->bpp == 32) {
  4228. info->mr = 0xffu << 16;
  4229. info->mg = 0xffu << 8;
  4230. info->mb = 0xffu << 0;
  4231. info->ma = 0xffu << 24;
  4232. info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0
  4233. } else {
  4234. info->mr = 31u << 10;
  4235. info->mg = 31u << 5;
  4236. info->mb = 31u << 0;
  4237. }
  4238. } else if (compress == 3) {
  4239. info->mr = stbi__get32le(s);
  4240. info->mg = stbi__get32le(s);
  4241. info->mb = stbi__get32le(s);
  4242. // not documented, but generated by photoshop and handled by mspaint
  4243. if (info->mr == info->mg && info->mg == info->mb) {
  4244. // ?!?!?
  4245. return stbi__errpuc("bad BMP", "bad BMP");
  4246. }
  4247. } else
  4248. return stbi__errpuc("bad BMP", "bad BMP");
  4249. }
  4250. } else {
  4251. int i;
  4252. if (hsz != 108 && hsz != 124)
  4253. return stbi__errpuc("bad BMP", "bad BMP");
  4254. info->mr = stbi__get32le(s);
  4255. info->mg = stbi__get32le(s);
  4256. info->mb = stbi__get32le(s);
  4257. info->ma = stbi__get32le(s);
  4258. stbi__get32le(s); // discard color space
  4259. for (i=0; i < 12; ++i)
  4260. stbi__get32le(s); // discard color space parameters
  4261. if (hsz == 124) {
  4262. stbi__get32le(s); // discard rendering intent
  4263. stbi__get32le(s); // discard offset of profile data
  4264. stbi__get32le(s); // discard size of profile data
  4265. stbi__get32le(s); // discard reserved
  4266. }
  4267. }
  4268. }
  4269. return (void *) 1;
  4270. }
  4271. static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  4272. {
  4273. stbi_uc *out;
  4274. unsigned int mr=0,mg=0,mb=0,ma=0, all_a;
  4275. stbi_uc pal[256][4];
  4276. int psize=0,i,j,width;
  4277. int flip_vertically, pad, target;
  4278. stbi__bmp_data info;
  4279. info.all_a = 255;
  4280. if (stbi__bmp_parse_header(s, &info) == NULL)
  4281. return NULL; // error code already set
  4282. flip_vertically = ((int) s->img_y) > 0;
  4283. s->img_y = abs((int) s->img_y);
  4284. mr = info.mr;
  4285. mg = info.mg;
  4286. mb = info.mb;
  4287. ma = info.ma;
  4288. all_a = info.all_a;
  4289. if (info.hsz == 12) {
  4290. if (info.bpp < 24)
  4291. psize = (info.offset - 14 - 24) / 3;
  4292. } else {
  4293. if (info.bpp < 16)
  4294. psize = (info.offset - 14 - info.hsz) >> 2;
  4295. }
  4296. s->img_n = ma ? 4 : 3;
  4297. if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
  4298. target = req_comp;
  4299. else
  4300. target = s->img_n; // if they want monochrome, we'll post-convert
  4301. out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y);
  4302. if (!out) return stbi__errpuc("outofmem", "Out of memory");
  4303. if (info.bpp < 16) {
  4304. int z=0;
  4305. if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); }
  4306. for (i=0; i < psize; ++i) {
  4307. pal[i][2] = stbi__get8(s);
  4308. pal[i][1] = stbi__get8(s);
  4309. pal[i][0] = stbi__get8(s);
  4310. if (info.hsz != 12) stbi__get8(s);
  4311. pal[i][3] = 255;
  4312. }
  4313. stbi__skip(s, info.offset - 14 - info.hsz - psize * (info.hsz == 12 ? 3 : 4));
  4314. if (info.bpp == 4) width = (s->img_x + 1) >> 1;
  4315. else if (info.bpp == 8) width = s->img_x;
  4316. else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); }
  4317. pad = (-width)&3;
  4318. for (j=0; j < (int) s->img_y; ++j) {
  4319. for (i=0; i < (int) s->img_x; i += 2) {
  4320. int v=stbi__get8(s),v2=0;
  4321. if (info.bpp == 4) {
  4322. v2 = v & 15;
  4323. v >>= 4;
  4324. }
  4325. out[z++] = pal[v][0];
  4326. out[z++] = pal[v][1];
  4327. out[z++] = pal[v][2];
  4328. if (target == 4) out[z++] = 255;
  4329. if (i+1 == (int) s->img_x) break;
  4330. v = (info.bpp == 8) ? stbi__get8(s) : v2;
  4331. out[z++] = pal[v][0];
  4332. out[z++] = pal[v][1];
  4333. out[z++] = pal[v][2];
  4334. if (target == 4) out[z++] = 255;
  4335. }
  4336. stbi__skip(s, pad);
  4337. }
  4338. } else {
  4339. int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
  4340. int z = 0;
  4341. int easy=0;
  4342. stbi__skip(s, info.offset - 14 - info.hsz);
  4343. if (info.bpp == 24) width = 3 * s->img_x;
  4344. else if (info.bpp == 16) width = 2*s->img_x;
  4345. else /* bpp = 32 and pad = 0 */ width=0;
  4346. pad = (-width) & 3;
  4347. if (info.bpp == 24) {
  4348. easy = 1;
  4349. } else if (info.bpp == 32) {
  4350. if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
  4351. easy = 2;
  4352. }
  4353. if (!easy) {
  4354. if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
  4355. // right shift amt to put high bit in position #7
  4356. rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);
  4357. gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);
  4358. bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);
  4359. ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);
  4360. }
  4361. for (j=0; j < (int) s->img_y; ++j) {
  4362. if (easy) {
  4363. for (i=0; i < (int) s->img_x; ++i) {
  4364. unsigned char a;
  4365. out[z+2] = stbi__get8(s);
  4366. out[z+1] = stbi__get8(s);
  4367. out[z+0] = stbi__get8(s);
  4368. z += 3;
  4369. a = (easy == 2 ? stbi__get8(s) : 255);
  4370. all_a |= a;
  4371. if (target == 4) out[z++] = a;
  4372. }
  4373. } else {
  4374. int bpp = info.bpp;
  4375. for (i=0; i < (int) s->img_x; ++i) {
  4376. stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s));
  4377. int a;
  4378. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));
  4379. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));
  4380. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));
  4381. a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
  4382. all_a |= a;
  4383. if (target == 4) out[z++] = STBI__BYTECAST(a);
  4384. }
  4385. }
  4386. stbi__skip(s, pad);
  4387. }
  4388. }
  4389. // if alpha channel is all 0s, replace with all 255s
  4390. if (target == 4 && all_a == 0)
  4391. for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4)
  4392. out[i] = 255;
  4393. if (flip_vertically) {
  4394. stbi_uc t;
  4395. for (j=0; j < (int) s->img_y>>1; ++j) {
  4396. stbi_uc *p1 = out + j *s->img_x*target;
  4397. stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
  4398. for (i=0; i < (int) s->img_x*target; ++i) {
  4399. t = p1[i], p1[i] = p2[i], p2[i] = t;
  4400. }
  4401. }
  4402. }
  4403. if (req_comp && req_comp != target) {
  4404. out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
  4405. if (out == NULL) return out; // stbi__convert_format frees input on failure
  4406. }
  4407. *x = s->img_x;
  4408. *y = s->img_y;
  4409. if (comp) *comp = s->img_n;
  4410. return out;
  4411. }
  4412. #endif
  4413. // Targa Truevision - TGA
  4414. // by Jonathan Dummer
  4415. #ifndef STBI_NO_TGA
  4416. // returns STBI_rgb or whatever, 0 on error
  4417. static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16)
  4418. {
  4419. // only RGB or RGBA (incl. 16bit) or grey allowed
  4420. if(is_rgb16) *is_rgb16 = 0;
  4421. switch(bits_per_pixel) {
  4422. case 8: return STBI_grey;
  4423. case 16: if(is_grey) return STBI_grey_alpha;
  4424. // else: fall-through
  4425. case 15: if(is_rgb16) *is_rgb16 = 1;
  4426. return STBI_rgb;
  4427. case 24: // fall-through
  4428. case 32: return bits_per_pixel/8;
  4429. default: return 0;
  4430. }
  4431. }
  4432. static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)
  4433. {
  4434. int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp;
  4435. int sz, tga_colormap_type;
  4436. stbi__get8(s); // discard Offset
  4437. tga_colormap_type = stbi__get8(s); // colormap type
  4438. if( tga_colormap_type > 1 ) {
  4439. stbi__rewind(s);
  4440. return 0; // only RGB or indexed allowed
  4441. }
  4442. tga_image_type = stbi__get8(s); // image type
  4443. if ( tga_colormap_type == 1 ) { // colormapped (paletted) image
  4444. if (tga_image_type != 1 && tga_image_type != 9) {
  4445. stbi__rewind(s);
  4446. return 0;
  4447. }
  4448. stbi__skip(s,4); // skip index of first colormap entry and number of entries
  4449. sz = stbi__get8(s); // check bits per palette color entry
  4450. if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) {
  4451. stbi__rewind(s);
  4452. return 0;
  4453. }
  4454. stbi__skip(s,4); // skip image x and y origin
  4455. tga_colormap_bpp = sz;
  4456. } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE
  4457. if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) {
  4458. stbi__rewind(s);
  4459. return 0; // only RGB or grey allowed, +/- RLE
  4460. }
  4461. stbi__skip(s,9); // skip colormap specification and image x/y origin
  4462. tga_colormap_bpp = 0;
  4463. }
  4464. tga_w = stbi__get16le(s);
  4465. if( tga_w < 1 ) {
  4466. stbi__rewind(s);
  4467. return 0; // test width
  4468. }
  4469. tga_h = stbi__get16le(s);
  4470. if( tga_h < 1 ) {
  4471. stbi__rewind(s);
  4472. return 0; // test height
  4473. }
  4474. tga_bits_per_pixel = stbi__get8(s); // bits per pixel
  4475. stbi__get8(s); // ignore alpha bits
  4476. if (tga_colormap_bpp != 0) {
  4477. if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) {
  4478. // when using a colormap, tga_bits_per_pixel is the size of the indexes
  4479. // I don't think anything but 8 or 16bit indexes makes sense
  4480. stbi__rewind(s);
  4481. return 0;
  4482. }
  4483. tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL);
  4484. } else {
  4485. tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL);
  4486. }
  4487. if(!tga_comp) {
  4488. stbi__rewind(s);
  4489. return 0;
  4490. }
  4491. if (x) *x = tga_w;
  4492. if (y) *y = tga_h;
  4493. if (comp) *comp = tga_comp;
  4494. return 1; // seems to have passed everything
  4495. }
  4496. static int stbi__tga_test(stbi__context *s)
  4497. {
  4498. int res = 0;
  4499. int sz, tga_color_type;
  4500. stbi__get8(s); // discard Offset
  4501. tga_color_type = stbi__get8(s); // color type
  4502. if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed
  4503. sz = stbi__get8(s); // image type
  4504. if ( tga_color_type == 1 ) { // colormapped (paletted) image
  4505. if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9
  4506. stbi__skip(s,4); // skip index of first colormap entry and number of entries
  4507. sz = stbi__get8(s); // check bits per palette color entry
  4508. if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;
  4509. stbi__skip(s,4); // skip image x and y origin
  4510. } else { // "normal" image w/o colormap
  4511. if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE
  4512. stbi__skip(s,9); // skip colormap specification and image x/y origin
  4513. }
  4514. if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width
  4515. if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height
  4516. sz = stbi__get8(s); // bits per pixel
  4517. if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index
  4518. if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;
  4519. res = 1; // if we got this far, everything's good and we can return 1 instead of 0
  4520. errorEnd:
  4521. stbi__rewind(s);
  4522. return res;
  4523. }
  4524. // read 16bit value and convert to 24bit RGB
  4525. void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out)
  4526. {
  4527. stbi__uint16 px = stbi__get16le(s);
  4528. stbi__uint16 fiveBitMask = 31;
  4529. // we have 3 channels with 5bits each
  4530. int r = (px >> 10) & fiveBitMask;
  4531. int g = (px >> 5) & fiveBitMask;
  4532. int b = px & fiveBitMask;
  4533. // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later
  4534. out[0] = (r * 255)/31;
  4535. out[1] = (g * 255)/31;
  4536. out[2] = (b * 255)/31;
  4537. // some people claim that the most significant bit might be used for alpha
  4538. // (possibly if an alpha-bit is set in the "image descriptor byte")
  4539. // but that only made 16bit test images completely translucent..
  4540. // so let's treat all 15 and 16bit TGAs as RGB with no alpha.
  4541. }
  4542. static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  4543. {
  4544. // read in the TGA header stuff
  4545. int tga_offset = stbi__get8(s);
  4546. int tga_indexed = stbi__get8(s);
  4547. int tga_image_type = stbi__get8(s);
  4548. int tga_is_RLE = 0;
  4549. int tga_palette_start = stbi__get16le(s);
  4550. int tga_palette_len = stbi__get16le(s);
  4551. int tga_palette_bits = stbi__get8(s);
  4552. int tga_x_origin = stbi__get16le(s);
  4553. int tga_y_origin = stbi__get16le(s);
  4554. int tga_width = stbi__get16le(s);
  4555. int tga_height = stbi__get16le(s);
  4556. int tga_bits_per_pixel = stbi__get8(s);
  4557. int tga_comp, tga_rgb16=0;
  4558. int tga_inverted = stbi__get8(s);
  4559. // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?)
  4560. // image data
  4561. unsigned char *tga_data;
  4562. unsigned char *tga_palette = NULL;
  4563. int i, j;
  4564. unsigned char raw_data[4];
  4565. int RLE_count = 0;
  4566. int RLE_repeating = 0;
  4567. int read_next_pixel = 1;
  4568. // do a tiny bit of precessing
  4569. if ( tga_image_type >= 8 )
  4570. {
  4571. tga_image_type -= 8;
  4572. tga_is_RLE = 1;
  4573. }
  4574. tga_inverted = 1 - ((tga_inverted >> 5) & 1);
  4575. // If I'm paletted, then I'll use the number of bits from the palette
  4576. if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16);
  4577. else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16);
  4578. if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency
  4579. return stbi__errpuc("bad format", "Can't find out TGA pixelformat");
  4580. // tga info
  4581. *x = tga_width;
  4582. *y = tga_height;
  4583. if (comp) *comp = tga_comp;
  4584. tga_data = (unsigned char*)stbi__malloc( (size_t)tga_width * tga_height * tga_comp );
  4585. if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");
  4586. // skip to the data's starting position (offset usually = 0)
  4587. stbi__skip(s, tga_offset );
  4588. if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) {
  4589. for (i=0; i < tga_height; ++i) {
  4590. int row = tga_inverted ? tga_height -i - 1 : i;
  4591. stbi_uc *tga_row = tga_data + row*tga_width*tga_comp;
  4592. stbi__getn(s, tga_row, tga_width * tga_comp);
  4593. }
  4594. } else {
  4595. // do I need to load a palette?
  4596. if ( tga_indexed)
  4597. {
  4598. // any data to skip? (offset usually = 0)
  4599. stbi__skip(s, tga_palette_start );
  4600. // load the palette
  4601. tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_comp );
  4602. if (!tga_palette) {
  4603. STBI_FREE(tga_data);
  4604. return stbi__errpuc("outofmem", "Out of memory");
  4605. }
  4606. if (tga_rgb16) {
  4607. stbi_uc *pal_entry = tga_palette;
  4608. STBI_ASSERT(tga_comp == STBI_rgb);
  4609. for (i=0; i < tga_palette_len; ++i) {
  4610. stbi__tga_read_rgb16(s, pal_entry);
  4611. pal_entry += tga_comp;
  4612. }
  4613. } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) {
  4614. STBI_FREE(tga_data);
  4615. STBI_FREE(tga_palette);
  4616. return stbi__errpuc("bad palette", "Corrupt TGA");
  4617. }
  4618. }
  4619. // load the data
  4620. for (i=0; i < tga_width * tga_height; ++i)
  4621. {
  4622. // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?
  4623. if ( tga_is_RLE )
  4624. {
  4625. if ( RLE_count == 0 )
  4626. {
  4627. // yep, get the next byte as a RLE command
  4628. int RLE_cmd = stbi__get8(s);
  4629. RLE_count = 1 + (RLE_cmd & 127);
  4630. RLE_repeating = RLE_cmd >> 7;
  4631. read_next_pixel = 1;
  4632. } else if ( !RLE_repeating )
  4633. {
  4634. read_next_pixel = 1;
  4635. }
  4636. } else
  4637. {
  4638. read_next_pixel = 1;
  4639. }
  4640. // OK, if I need to read a pixel, do it now
  4641. if ( read_next_pixel )
  4642. {
  4643. // load however much data we did have
  4644. if ( tga_indexed )
  4645. {
  4646. // read in index, then perform the lookup
  4647. int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s);
  4648. if ( pal_idx >= tga_palette_len ) {
  4649. // invalid index
  4650. pal_idx = 0;
  4651. }
  4652. pal_idx *= tga_comp;
  4653. for (j = 0; j < tga_comp; ++j) {
  4654. raw_data[j] = tga_palette[pal_idx+j];
  4655. }
  4656. } else if(tga_rgb16) {
  4657. STBI_ASSERT(tga_comp == STBI_rgb);
  4658. stbi__tga_read_rgb16(s, raw_data);
  4659. } else {
  4660. // read in the data raw
  4661. for (j = 0; j < tga_comp; ++j) {
  4662. raw_data[j] = stbi__get8(s);
  4663. }
  4664. }
  4665. // clear the reading flag for the next pixel
  4666. read_next_pixel = 0;
  4667. } // end of reading a pixel
  4668. // copy data
  4669. for (j = 0; j < tga_comp; ++j)
  4670. tga_data[i*tga_comp+j] = raw_data[j];
  4671. // in case we're in RLE mode, keep counting down
  4672. --RLE_count;
  4673. }
  4674. // do I need to invert the image?
  4675. if ( tga_inverted )
  4676. {
  4677. for (j = 0; j*2 < tga_height; ++j)
  4678. {
  4679. int index1 = j * tga_width * tga_comp;
  4680. int index2 = (tga_height - 1 - j) * tga_width * tga_comp;
  4681. for (i = tga_width * tga_comp; i > 0; --i)
  4682. {
  4683. unsigned char temp = tga_data[index1];
  4684. tga_data[index1] = tga_data[index2];
  4685. tga_data[index2] = temp;
  4686. ++index1;
  4687. ++index2;
  4688. }
  4689. }
  4690. }
  4691. // clear my palette, if I had one
  4692. if ( tga_palette != NULL )
  4693. {
  4694. STBI_FREE( tga_palette );
  4695. }
  4696. }
  4697. // swap RGB - if the source data was RGB16, it already is in the right order
  4698. if (tga_comp >= 3 && !tga_rgb16)
  4699. {
  4700. unsigned char* tga_pixel = tga_data;
  4701. for (i=0; i < tga_width * tga_height; ++i)
  4702. {
  4703. unsigned char temp = tga_pixel[0];
  4704. tga_pixel[0] = tga_pixel[2];
  4705. tga_pixel[2] = temp;
  4706. tga_pixel += tga_comp;
  4707. }
  4708. }
  4709. // convert to target component count
  4710. if (req_comp && req_comp != tga_comp)
  4711. tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
  4712. // the things I do to get rid of an error message, and yet keep
  4713. // Microsoft's C compilers happy... [8^(
  4714. tga_palette_start = tga_palette_len = tga_palette_bits =
  4715. tga_x_origin = tga_y_origin = 0;
  4716. // OK, done
  4717. return tga_data;
  4718. }
  4719. #endif
  4720. // *************************************************************************************************
  4721. // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
  4722. #ifndef STBI_NO_PSD
  4723. static int stbi__psd_test(stbi__context *s)
  4724. {
  4725. int r = (stbi__get32be(s) == 0x38425053);
  4726. stbi__rewind(s);
  4727. return r;
  4728. }
  4729. static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  4730. {
  4731. int pixelCount;
  4732. int channelCount, compression;
  4733. int channel, i, count, len;
  4734. int bitdepth;
  4735. int w,h;
  4736. stbi_uc *out;
  4737. // Check identifier
  4738. if (stbi__get32be(s) != 0x38425053) // "8BPS"
  4739. return stbi__errpuc("not PSD", "Corrupt PSD image");
  4740. // Check file type version.
  4741. if (stbi__get16be(s) != 1)
  4742. return stbi__errpuc("wrong version", "Unsupported version of PSD image");
  4743. // Skip 6 reserved bytes.
  4744. stbi__skip(s, 6 );
  4745. // Read the number of channels (R, G, B, A, etc).
  4746. channelCount = stbi__get16be(s);
  4747. if (channelCount < 0 || channelCount > 16)
  4748. return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");
  4749. // Read the rows and columns of the image.
  4750. h = stbi__get32be(s);
  4751. w = stbi__get32be(s);
  4752. // Make sure the depth is 8 bits.
  4753. bitdepth = stbi__get16be(s);
  4754. if (bitdepth != 8 && bitdepth != 16)
  4755. return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit");
  4756. // Make sure the color mode is RGB.
  4757. // Valid options are:
  4758. // 0: Bitmap
  4759. // 1: Grayscale
  4760. // 2: Indexed color
  4761. // 3: RGB color
  4762. // 4: CMYK color
  4763. // 7: Multichannel
  4764. // 8: Duotone
  4765. // 9: Lab color
  4766. if (stbi__get16be(s) != 3)
  4767. return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
  4768. // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
  4769. stbi__skip(s,stbi__get32be(s) );
  4770. // Skip the image resources. (resolution, pen tool paths, etc)
  4771. stbi__skip(s, stbi__get32be(s) );
  4772. // Skip the reserved data.
  4773. stbi__skip(s, stbi__get32be(s) );
  4774. // Find out if the data is compressed.
  4775. // Known values:
  4776. // 0: no compression
  4777. // 1: RLE compressed
  4778. compression = stbi__get16be(s);
  4779. if (compression > 1)
  4780. return stbi__errpuc("bad compression", "PSD has an unknown compression format");
  4781. // Create the destination image.
  4782. out = (stbi_uc *) stbi__malloc(4 * w*h);
  4783. if (!out) return stbi__errpuc("outofmem", "Out of memory");
  4784. pixelCount = w*h;
  4785. // Initialize the data to zero.
  4786. //memset( out, 0, pixelCount * 4 );
  4787. // Finally, the image data.
  4788. if (compression) {
  4789. // RLE as used by .PSD and .TIFF
  4790. // Loop until you get the number of unpacked bytes you are expecting:
  4791. // Read the next source byte into n.
  4792. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
  4793. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
  4794. // Else if n is 128, noop.
  4795. // Endloop
  4796. // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
  4797. // which we're going to just skip.
  4798. stbi__skip(s, h * channelCount * 2 );
  4799. // Read the RLE data by channel.
  4800. for (channel = 0; channel < 4; channel++) {
  4801. stbi_uc *p;
  4802. p = out+channel;
  4803. if (channel >= channelCount) {
  4804. // Fill this channel with default data.
  4805. for (i = 0; i < pixelCount; i++, p += 4)
  4806. *p = (channel == 3 ? 255 : 0);
  4807. } else {
  4808. // Read the RLE data.
  4809. count = 0;
  4810. while (count < pixelCount) {
  4811. len = stbi__get8(s);
  4812. if (len == 128) {
  4813. // No-op.
  4814. } else if (len < 128) {
  4815. // Copy next len+1 bytes literally.
  4816. len++;
  4817. count += len;
  4818. while (len) {
  4819. *p = stbi__get8(s);
  4820. p += 4;
  4821. len--;
  4822. }
  4823. } else if (len > 128) {
  4824. stbi_uc val;
  4825. // Next -len+1 bytes in the dest are replicated from next source byte.
  4826. // (Interpret len as a negative 8-bit int.)
  4827. len ^= 0x0FF;
  4828. len += 2;
  4829. val = stbi__get8(s);
  4830. count += len;
  4831. while (len) {
  4832. *p = val;
  4833. p += 4;
  4834. len--;
  4835. }
  4836. }
  4837. }
  4838. }
  4839. }
  4840. } else {
  4841. // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
  4842. // where each channel consists of an 8-bit value for each pixel in the image.
  4843. // Read the data by channel.
  4844. for (channel = 0; channel < 4; channel++) {
  4845. stbi_uc *p;
  4846. p = out + channel;
  4847. if (channel >= channelCount) {
  4848. // Fill this channel with default data.
  4849. stbi_uc val = channel == 3 ? 255 : 0;
  4850. for (i = 0; i < pixelCount; i++, p += 4)
  4851. *p = val;
  4852. } else {
  4853. // Read the data.
  4854. if (bitdepth == 16) {
  4855. for (i = 0; i < pixelCount; i++, p += 4)
  4856. *p = (stbi_uc) (stbi__get16be(s) >> 8);
  4857. } else {
  4858. for (i = 0; i < pixelCount; i++, p += 4)
  4859. *p = stbi__get8(s);
  4860. }
  4861. }
  4862. }
  4863. }
  4864. if (channelCount >= 4) {
  4865. for (i=0; i < w*h; ++i) {
  4866. unsigned char *pixel = out + 4*i;
  4867. if (pixel[3] != 0 && pixel[3] != 255) {
  4868. // remove weird white matte from PSD
  4869. float a = pixel[3] / 255.0f;
  4870. float ra = 1.0f / a;
  4871. float inv_a = 255.0f * (1 - ra);
  4872. pixel[0] = (unsigned char) (pixel[0]*ra + inv_a);
  4873. pixel[1] = (unsigned char) (pixel[1]*ra + inv_a);
  4874. pixel[2] = (unsigned char) (pixel[2]*ra + inv_a);
  4875. }
  4876. }
  4877. }
  4878. if (req_comp && req_comp != 4) {
  4879. out = stbi__convert_format(out, 4, req_comp, w, h);
  4880. if (out == NULL) return out; // stbi__convert_format frees input on failure
  4881. }
  4882. if (comp) *comp = 4;
  4883. *y = h;
  4884. *x = w;
  4885. return out;
  4886. }
  4887. #endif
  4888. // *************************************************************************************************
  4889. // Softimage PIC loader
  4890. // by Tom Seddon
  4891. //
  4892. // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
  4893. // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
  4894. #ifndef STBI_NO_PIC
  4895. static int stbi__pic_is4(stbi__context *s,const char *str)
  4896. {
  4897. int i;
  4898. for (i=0; i<4; ++i)
  4899. if (stbi__get8(s) != (stbi_uc)str[i])
  4900. return 0;
  4901. return 1;
  4902. }
  4903. static int stbi__pic_test_core(stbi__context *s)
  4904. {
  4905. int i;
  4906. if (!stbi__pic_is4(s,"\x53\x80\xF6\x34"))
  4907. return 0;
  4908. for(i=0;i<84;++i)
  4909. stbi__get8(s);
  4910. if (!stbi__pic_is4(s,"PICT"))
  4911. return 0;
  4912. return 1;
  4913. }
  4914. typedef struct
  4915. {
  4916. stbi_uc size,type,channel;
  4917. } stbi__pic_packet;
  4918. static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)
  4919. {
  4920. int mask=0x80, i;
  4921. for (i=0; i<4; ++i, mask>>=1) {
  4922. if (channel & mask) {
  4923. if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short");
  4924. dest[i]=stbi__get8(s);
  4925. }
  4926. }
  4927. return dest;
  4928. }
  4929. static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)
  4930. {
  4931. int mask=0x80,i;
  4932. for (i=0;i<4; ++i, mask>>=1)
  4933. if (channel&mask)
  4934. dest[i]=src[i];
  4935. }
  4936. static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)
  4937. {
  4938. int act_comp=0,num_packets=0,y,chained;
  4939. stbi__pic_packet packets[10];
  4940. // this will (should...) cater for even some bizarre stuff like having data
  4941. // for the same channel in multiple packets.
  4942. do {
  4943. stbi__pic_packet *packet;
  4944. if (num_packets==sizeof(packets)/sizeof(packets[0]))
  4945. return stbi__errpuc("bad format","too many packets");
  4946. packet = &packets[num_packets++];
  4947. chained = stbi__get8(s);
  4948. packet->size = stbi__get8(s);
  4949. packet->type = stbi__get8(s);
  4950. packet->channel = stbi__get8(s);
  4951. act_comp |= packet->channel;
  4952. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)");
  4953. if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp");
  4954. } while (chained);
  4955. *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
  4956. for(y=0; y<height; ++y) {
  4957. int packet_idx;
  4958. for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
  4959. stbi__pic_packet *packet = &packets[packet_idx];
  4960. stbi_uc *dest = result+y*width*4;
  4961. switch (packet->type) {
  4962. default:
  4963. return stbi__errpuc("bad format","packet has bad compression type");
  4964. case 0: {//uncompressed
  4965. int x;
  4966. for(x=0;x<width;++x, dest+=4)
  4967. if (!stbi__readval(s,packet->channel,dest))
  4968. return 0;
  4969. break;
  4970. }
  4971. case 1://Pure RLE
  4972. {
  4973. int left=width, i;
  4974. while (left>0) {
  4975. stbi_uc count,value[4];
  4976. count=stbi__get8(s);
  4977. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)");
  4978. if (count > left)
  4979. count = (stbi_uc) left;
  4980. if (!stbi__readval(s,packet->channel,value)) return 0;
  4981. for(i=0; i<count; ++i,dest+=4)
  4982. stbi__copyval(packet->channel,dest,value);
  4983. left -= count;
  4984. }
  4985. }
  4986. break;
  4987. case 2: {//Mixed RLE
  4988. int left=width;
  4989. while (left>0) {
  4990. int count = stbi__get8(s), i;
  4991. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)");
  4992. if (count >= 128) { // Repeated
  4993. stbi_uc value[4];
  4994. if (count==128)
  4995. count = stbi__get16be(s);
  4996. else
  4997. count -= 127;
  4998. if (count > left)
  4999. return stbi__errpuc("bad file","scanline overrun");
  5000. if (!stbi__readval(s,packet->channel,value))
  5001. return 0;
  5002. for(i=0;i<count;++i, dest += 4)
  5003. stbi__copyval(packet->channel,dest,value);
  5004. } else { // Raw
  5005. ++count;
  5006. if (count>left) return stbi__errpuc("bad file","scanline overrun");
  5007. for(i=0;i<count;++i, dest+=4)
  5008. if (!stbi__readval(s,packet->channel,dest))
  5009. return 0;
  5010. }
  5011. left-=count;
  5012. }
  5013. break;
  5014. }
  5015. }
  5016. }
  5017. }
  5018. return result;
  5019. }
  5020. static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp)
  5021. {
  5022. stbi_uc *result;
  5023. int i, x,y;
  5024. for (i=0; i<92; ++i)
  5025. stbi__get8(s);
  5026. x = stbi__get16be(s);
  5027. y = stbi__get16be(s);
  5028. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");
  5029. if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode");
  5030. stbi__get32be(s); //skip `ratio'
  5031. stbi__get16be(s); //skip `fields'
  5032. stbi__get16be(s); //skip `pad'
  5033. // intermediate buffer is RGBA
  5034. result = (stbi_uc *) stbi__malloc(x*y*4);
  5035. memset(result, 0xff, x*y*4);
  5036. if (!stbi__pic_load_core(s,x,y,comp, result)) {
  5037. STBI_FREE(result);
  5038. result=0;
  5039. }
  5040. *px = x;
  5041. *py = y;
  5042. if (req_comp == 0) req_comp = *comp;
  5043. result=stbi__convert_format(result,4,req_comp,x,y);
  5044. return result;
  5045. }
  5046. static int stbi__pic_test(stbi__context *s)
  5047. {
  5048. int r = stbi__pic_test_core(s);
  5049. stbi__rewind(s);
  5050. return r;
  5051. }
  5052. #endif
  5053. // *************************************************************************************************
  5054. // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
  5055. #ifndef STBI_NO_GIF
  5056. typedef struct
  5057. {
  5058. stbi__int16 prefix;
  5059. stbi_uc first;
  5060. stbi_uc suffix;
  5061. } stbi__gif_lzw;
  5062. typedef struct
  5063. {
  5064. int w,h;
  5065. stbi_uc *out, *old_out; // output buffer (always 4 components)
  5066. int flags, bgindex, ratio, transparent, eflags, delay;
  5067. stbi_uc pal[256][4];
  5068. stbi_uc lpal[256][4];
  5069. stbi__gif_lzw codes[4096];
  5070. stbi_uc *color_table;
  5071. int parse, step;
  5072. int lflags;
  5073. int start_x, start_y;
  5074. int max_x, max_y;
  5075. int cur_x, cur_y;
  5076. int line_size;
  5077. } stbi__gif;
  5078. static int stbi__gif_test_raw(stbi__context *s)
  5079. {
  5080. int sz;
  5081. if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;
  5082. sz = stbi__get8(s);
  5083. if (sz != '9' && sz != '7') return 0;
  5084. if (stbi__get8(s) != 'a') return 0;
  5085. return 1;
  5086. }
  5087. static int stbi__gif_test(stbi__context *s)
  5088. {
  5089. int r = stbi__gif_test_raw(s);
  5090. stbi__rewind(s);
  5091. return r;
  5092. }
  5093. static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)
  5094. {
  5095. int i;
  5096. for (i=0; i < num_entries; ++i) {
  5097. pal[i][2] = stbi__get8(s);
  5098. pal[i][1] = stbi__get8(s);
  5099. pal[i][0] = stbi__get8(s);
  5100. pal[i][3] = transp == i ? 0 : 255;
  5101. }
  5102. }
  5103. static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)
  5104. {
  5105. stbi_uc version;
  5106. if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
  5107. return stbi__err("not GIF", "Corrupt GIF");
  5108. version = stbi__get8(s);
  5109. if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");
  5110. if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
  5111. stbi__g_failure_reason = "";
  5112. g->w = stbi__get16le(s);
  5113. g->h = stbi__get16le(s);
  5114. g->flags = stbi__get8(s);
  5115. g->bgindex = stbi__get8(s);
  5116. g->ratio = stbi__get8(s);
  5117. g->transparent = -1;
  5118. if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
  5119. if (is_info) return 1;
  5120. if (g->flags & 0x80)
  5121. stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
  5122. return 1;
  5123. }
  5124. static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
  5125. {
  5126. stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));
  5127. if (!stbi__gif_header(s, g, comp, 1)) {
  5128. STBI_FREE(g);
  5129. stbi__rewind( s );
  5130. return 0;
  5131. }
  5132. if (x) *x = g->w;
  5133. if (y) *y = g->h;
  5134. STBI_FREE(g);
  5135. return 1;
  5136. }
  5137. static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)
  5138. {
  5139. stbi_uc *p, *c;
  5140. // recurse to decode the prefixes, since the linked-list is backwards,
  5141. // and working backwards through an interleaved image would be nasty
  5142. if (g->codes[code].prefix >= 0)
  5143. stbi__out_gif_code(g, g->codes[code].prefix);
  5144. if (g->cur_y >= g->max_y) return;
  5145. p = &g->out[g->cur_x + g->cur_y];
  5146. c = &g->color_table[g->codes[code].suffix * 4];
  5147. if (c[3] >= 128) {
  5148. p[0] = c[2];
  5149. p[1] = c[1];
  5150. p[2] = c[0];
  5151. p[3] = c[3];
  5152. }
  5153. g->cur_x += 4;
  5154. if (g->cur_x >= g->max_x) {
  5155. g->cur_x = g->start_x;
  5156. g->cur_y += g->step;
  5157. while (g->cur_y >= g->max_y && g->parse > 0) {
  5158. g->step = (1 << g->parse) * g->line_size;
  5159. g->cur_y = g->start_y + (g->step >> 1);
  5160. --g->parse;
  5161. }
  5162. }
  5163. }
  5164. static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)
  5165. {
  5166. stbi_uc lzw_cs;
  5167. stbi__int32 len, init_code;
  5168. stbi__uint32 first;
  5169. stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
  5170. stbi__gif_lzw *p;
  5171. lzw_cs = stbi__get8(s);
  5172. if (lzw_cs > 12) return NULL;
  5173. clear = 1 << lzw_cs;
  5174. first = 1;
  5175. codesize = lzw_cs + 1;
  5176. codemask = (1 << codesize) - 1;
  5177. bits = 0;
  5178. valid_bits = 0;
  5179. for (init_code = 0; init_code < clear; init_code++) {
  5180. g->codes[init_code].prefix = -1;
  5181. g->codes[init_code].first = (stbi_uc) init_code;
  5182. g->codes[init_code].suffix = (stbi_uc) init_code;
  5183. }
  5184. // support no starting clear code
  5185. avail = clear+2;
  5186. oldcode = -1;
  5187. len = 0;
  5188. for(;;) {
  5189. if (valid_bits < codesize) {
  5190. if (len == 0) {
  5191. len = stbi__get8(s); // start new block
  5192. if (len == 0)
  5193. return g->out;
  5194. }
  5195. --len;
  5196. bits |= (stbi__int32) stbi__get8(s) << valid_bits;
  5197. valid_bits += 8;
  5198. } else {
  5199. stbi__int32 code = bits & codemask;
  5200. bits >>= codesize;
  5201. valid_bits -= codesize;
  5202. // @OPTIMIZE: is there some way we can accelerate the non-clear path?
  5203. if (code == clear) { // clear code
  5204. codesize = lzw_cs + 1;
  5205. codemask = (1 << codesize) - 1;
  5206. avail = clear + 2;
  5207. oldcode = -1;
  5208. first = 0;
  5209. } else if (code == clear + 1) { // end of stream code
  5210. stbi__skip(s, len);
  5211. while ((len = stbi__get8(s)) > 0)
  5212. stbi__skip(s,len);
  5213. return g->out;
  5214. } else if (code <= avail) {
  5215. if (first) return stbi__errpuc("no clear code", "Corrupt GIF");
  5216. if (oldcode >= 0) {
  5217. p = &g->codes[avail++];
  5218. if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF");
  5219. p->prefix = (stbi__int16) oldcode;
  5220. p->first = g->codes[oldcode].first;
  5221. p->suffix = (code == avail) ? p->first : g->codes[code].first;
  5222. } else if (code == avail)
  5223. return stbi__errpuc("illegal code in raster", "Corrupt GIF");
  5224. stbi__out_gif_code(g, (stbi__uint16) code);
  5225. if ((avail & codemask) == 0 && avail <= 0x0FFF) {
  5226. codesize++;
  5227. codemask = (1 << codesize) - 1;
  5228. }
  5229. oldcode = code;
  5230. } else {
  5231. return stbi__errpuc("illegal code in raster", "Corrupt GIF");
  5232. }
  5233. }
  5234. }
  5235. }
  5236. static void stbi__fill_gif_background(stbi__gif *g, int x0, int y0, int x1, int y1)
  5237. {
  5238. int x, y;
  5239. stbi_uc *c = g->pal[g->bgindex];
  5240. for (y = y0; y < y1; y += 4 * g->w) {
  5241. for (x = x0; x < x1; x += 4) {
  5242. stbi_uc *p = &g->out[y + x];
  5243. p[0] = c[2];
  5244. p[1] = c[1];
  5245. p[2] = c[0];
  5246. p[3] = 0;
  5247. }
  5248. }
  5249. }
  5250. // this function is designed to support animated gifs, although stb_image doesn't support it
  5251. static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp)
  5252. {
  5253. int i;
  5254. stbi_uc *prev_out = 0;
  5255. if (g->out == 0 && !stbi__gif_header(s, g, comp,0))
  5256. return 0; // stbi__g_failure_reason set by stbi__gif_header
  5257. prev_out = g->out;
  5258. g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h);
  5259. if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");
  5260. switch ((g->eflags & 0x1C) >> 2) {
  5261. case 0: // unspecified (also always used on 1st frame)
  5262. stbi__fill_gif_background(g, 0, 0, 4 * g->w, 4 * g->w * g->h);
  5263. break;
  5264. case 1: // do not dispose
  5265. if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h);
  5266. g->old_out = prev_out;
  5267. break;
  5268. case 2: // dispose to background
  5269. if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h);
  5270. stbi__fill_gif_background(g, g->start_x, g->start_y, g->max_x, g->max_y);
  5271. break;
  5272. case 3: // dispose to previous
  5273. if (g->old_out) {
  5274. for (i = g->start_y; i < g->max_y; i += 4 * g->w)
  5275. memcpy(&g->out[i + g->start_x], &g->old_out[i + g->start_x], g->max_x - g->start_x);
  5276. }
  5277. break;
  5278. }
  5279. for (;;) {
  5280. switch (stbi__get8(s)) {
  5281. case 0x2C: /* Image Descriptor */
  5282. {
  5283. int prev_trans = -1;
  5284. stbi__int32 x, y, w, h;
  5285. stbi_uc *o;
  5286. x = stbi__get16le(s);
  5287. y = stbi__get16le(s);
  5288. w = stbi__get16le(s);
  5289. h = stbi__get16le(s);
  5290. if (((x + w) > (g->w)) || ((y + h) > (g->h)))
  5291. return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
  5292. g->line_size = g->w * 4;
  5293. g->start_x = x * 4;
  5294. g->start_y = y * g->line_size;
  5295. g->max_x = g->start_x + w * 4;
  5296. g->max_y = g->start_y + h * g->line_size;
  5297. g->cur_x = g->start_x;
  5298. g->cur_y = g->start_y;
  5299. g->lflags = stbi__get8(s);
  5300. if (g->lflags & 0x40) {
  5301. g->step = 8 * g->line_size; // first interlaced spacing
  5302. g->parse = 3;
  5303. } else {
  5304. g->step = g->line_size;
  5305. g->parse = 0;
  5306. }
  5307. if (g->lflags & 0x80) {
  5308. stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
  5309. g->color_table = (stbi_uc *) g->lpal;
  5310. } else if (g->flags & 0x80) {
  5311. if (g->transparent >= 0 && (g->eflags & 0x01)) {
  5312. prev_trans = g->pal[g->transparent][3];
  5313. g->pal[g->transparent][3] = 0;
  5314. }
  5315. g->color_table = (stbi_uc *) g->pal;
  5316. } else
  5317. return stbi__errpuc("missing color table", "Corrupt GIF");
  5318. o = stbi__process_gif_raster(s, g);
  5319. if (o == NULL) return NULL;
  5320. if (prev_trans != -1)
  5321. g->pal[g->transparent][3] = (stbi_uc) prev_trans;
  5322. return o;
  5323. }
  5324. case 0x21: // Comment Extension.
  5325. {
  5326. int len;
  5327. if (stbi__get8(s) == 0xF9) { // Graphic Control Extension.
  5328. len = stbi__get8(s);
  5329. if (len == 4) {
  5330. g->eflags = stbi__get8(s);
  5331. g->delay = stbi__get16le(s);
  5332. g->transparent = stbi__get8(s);
  5333. } else {
  5334. stbi__skip(s, len);
  5335. break;
  5336. }
  5337. }
  5338. while ((len = stbi__get8(s)) != 0)
  5339. stbi__skip(s, len);
  5340. break;
  5341. }
  5342. case 0x3B: // gif stream termination code
  5343. return (stbi_uc *) s; // using '1' causes warning on some compilers
  5344. default:
  5345. return stbi__errpuc("unknown code", "Corrupt GIF");
  5346. }
  5347. }
  5348. STBI_NOTUSED(req_comp);
  5349. }
  5350. static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  5351. {
  5352. stbi_uc *u = 0;
  5353. stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));
  5354. memset(g, 0, sizeof(*g));
  5355. u = stbi__gif_load_next(s, g, comp, req_comp);
  5356. if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
  5357. if (u) {
  5358. *x = g->w;
  5359. *y = g->h;
  5360. if (req_comp && req_comp != 4)
  5361. u = stbi__convert_format(u, 4, req_comp, g->w, g->h);
  5362. }
  5363. else if (g->out)
  5364. STBI_FREE(g->out);
  5365. STBI_FREE(g);
  5366. return u;
  5367. }
  5368. static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)
  5369. {
  5370. return stbi__gif_info_raw(s,x,y,comp);
  5371. }
  5372. #endif
  5373. // *************************************************************************************************
  5374. // Radiance RGBE HDR loader
  5375. // originally by Nicolas Schulz
  5376. #ifndef STBI_NO_HDR
  5377. static int stbi__hdr_test_core(stbi__context *s)
  5378. {
  5379. const char *signature = "#?RADIANCE\n";
  5380. int i;
  5381. for (i=0; signature[i]; ++i)
  5382. if (stbi__get8(s) != signature[i])
  5383. return 0;
  5384. return 1;
  5385. }
  5386. static int stbi__hdr_test(stbi__context* s)
  5387. {
  5388. int r = stbi__hdr_test_core(s);
  5389. stbi__rewind(s);
  5390. return r;
  5391. }
  5392. #define STBI__HDR_BUFLEN 1024
  5393. static char *stbi__hdr_gettoken(stbi__context *z, char *buffer)
  5394. {
  5395. int len=0;
  5396. char c = '\0';
  5397. c = (char) stbi__get8(z);
  5398. while (!stbi__at_eof(z) && c != '\n') {
  5399. buffer[len++] = c;
  5400. if (len == STBI__HDR_BUFLEN-1) {
  5401. // flush to end of line
  5402. while (!stbi__at_eof(z) && stbi__get8(z) != '\n')
  5403. ;
  5404. break;
  5405. }
  5406. c = (char) stbi__get8(z);
  5407. }
  5408. buffer[len] = 0;
  5409. return buffer;
  5410. }
  5411. static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)
  5412. {
  5413. if ( input[3] != 0 ) {
  5414. float f1;
  5415. // Exponent
  5416. f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
  5417. if (req_comp <= 2)
  5418. output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
  5419. else {
  5420. output[0] = input[0] * f1;
  5421. output[1] = input[1] * f1;
  5422. output[2] = input[2] * f1;
  5423. }
  5424. if (req_comp == 2) output[1] = 1;
  5425. if (req_comp == 4) output[3] = 1;
  5426. } else {
  5427. switch (req_comp) {
  5428. case 4: output[3] = 1; /* fallthrough */
  5429. case 3: output[0] = output[1] = output[2] = 0;
  5430. break;
  5431. case 2: output[1] = 1; /* fallthrough */
  5432. case 1: output[0] = 0;
  5433. break;
  5434. }
  5435. }
  5436. }
  5437. static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  5438. {
  5439. char buffer[STBI__HDR_BUFLEN];
  5440. char *token;
  5441. int valid = 0;
  5442. int width, height;
  5443. stbi_uc *scanline;
  5444. float *hdr_data;
  5445. int len;
  5446. unsigned char count, value;
  5447. int i, j, k, c1,c2, z;
  5448. // Check identifier
  5449. if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
  5450. return stbi__errpf("not HDR", "Corrupt HDR image");
  5451. // Parse header
  5452. for(;;) {
  5453. token = stbi__hdr_gettoken(s,buffer);
  5454. if (token[0] == 0) break;
  5455. if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
  5456. }
  5457. if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");
  5458. // Parse width and height
  5459. // can't use sscanf() if we're not using stdio!
  5460. token = stbi__hdr_gettoken(s,buffer);
  5461. if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
  5462. token += 3;
  5463. height = (int) strtol(token, &token, 10);
  5464. while (*token == ' ') ++token;
  5465. if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
  5466. token += 3;
  5467. width = (int) strtol(token, NULL, 10);
  5468. *x = width;
  5469. *y = height;
  5470. if (comp) *comp = 3;
  5471. if (req_comp == 0) req_comp = 3;
  5472. // Read data
  5473. hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float));
  5474. // Load image data
  5475. // image data is stored as some number of sca
  5476. if ( width < 8 || width >= 32768) {
  5477. // Read flat data
  5478. for (j=0; j < height; ++j) {
  5479. for (i=0; i < width; ++i) {
  5480. stbi_uc rgbe[4];
  5481. main_decode_loop:
  5482. stbi__getn(s, rgbe, 4);
  5483. stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
  5484. }
  5485. }
  5486. } else {
  5487. // Read RLE-encoded data
  5488. scanline = NULL;
  5489. for (j = 0; j < height; ++j) {
  5490. c1 = stbi__get8(s);
  5491. c2 = stbi__get8(s);
  5492. len = stbi__get8(s);
  5493. if (c1 != 2 || c2 != 2 || (len & 0x80)) {
  5494. // not run-length encoded, so we have to actually use THIS data as a decoded
  5495. // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
  5496. stbi_uc rgbe[4];
  5497. rgbe[0] = (stbi_uc) c1;
  5498. rgbe[1] = (stbi_uc) c2;
  5499. rgbe[2] = (stbi_uc) len;
  5500. rgbe[3] = (stbi_uc) stbi__get8(s);
  5501. stbi__hdr_convert(hdr_data, rgbe, req_comp);
  5502. i = 1;
  5503. j = 0;
  5504. STBI_FREE(scanline);
  5505. goto main_decode_loop; // yes, this makes no sense
  5506. }
  5507. len <<= 8;
  5508. len |= stbi__get8(s);
  5509. if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }
  5510. if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4);
  5511. for (k = 0; k < 4; ++k) {
  5512. i = 0;
  5513. while (i < width) {
  5514. count = stbi__get8(s);
  5515. if (count > 128) {
  5516. // Run
  5517. value = stbi__get8(s);
  5518. count -= 128;
  5519. for (z = 0; z < count; ++z)
  5520. scanline[i++ * 4 + k] = value;
  5521. } else {
  5522. // Dump
  5523. for (z = 0; z < count; ++z)
  5524. scanline[i++ * 4 + k] = stbi__get8(s);
  5525. }
  5526. }
  5527. }
  5528. for (i=0; i < width; ++i)
  5529. stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
  5530. }
  5531. STBI_FREE(scanline);
  5532. }
  5533. return hdr_data;
  5534. }
  5535. static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)
  5536. {
  5537. char buffer[STBI__HDR_BUFLEN];
  5538. char *token;
  5539. int valid = 0;
  5540. if (stbi__hdr_test(s) == 0) {
  5541. stbi__rewind( s );
  5542. return 0;
  5543. }
  5544. for(;;) {
  5545. token = stbi__hdr_gettoken(s,buffer);
  5546. if (token[0] == 0) break;
  5547. if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
  5548. }
  5549. if (!valid) {
  5550. stbi__rewind( s );
  5551. return 0;
  5552. }
  5553. token = stbi__hdr_gettoken(s,buffer);
  5554. if (strncmp(token, "-Y ", 3)) {
  5555. stbi__rewind( s );
  5556. return 0;
  5557. }
  5558. token += 3;
  5559. *y = (int) strtol(token, &token, 10);
  5560. while (*token == ' ') ++token;
  5561. if (strncmp(token, "+X ", 3)) {
  5562. stbi__rewind( s );
  5563. return 0;
  5564. }
  5565. token += 3;
  5566. *x = (int) strtol(token, NULL, 10);
  5567. *comp = 3;
  5568. return 1;
  5569. }
  5570. #endif // STBI_NO_HDR
  5571. #ifndef STBI_NO_BMP
  5572. static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
  5573. {
  5574. void *p;
  5575. stbi__bmp_data info;
  5576. info.all_a = 255;
  5577. p = stbi__bmp_parse_header(s, &info);
  5578. stbi__rewind( s );
  5579. if (p == NULL)
  5580. return 0;
  5581. *x = s->img_x;
  5582. *y = s->img_y;
  5583. *comp = info.ma ? 4 : 3;
  5584. return 1;
  5585. }
  5586. #endif
  5587. #ifndef STBI_NO_PSD
  5588. static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)
  5589. {
  5590. int channelCount;
  5591. if (stbi__get32be(s) != 0x38425053) {
  5592. stbi__rewind( s );
  5593. return 0;
  5594. }
  5595. if (stbi__get16be(s) != 1) {
  5596. stbi__rewind( s );
  5597. return 0;
  5598. }
  5599. stbi__skip(s, 6);
  5600. channelCount = stbi__get16be(s);
  5601. if (channelCount < 0 || channelCount > 16) {
  5602. stbi__rewind( s );
  5603. return 0;
  5604. }
  5605. *y = stbi__get32be(s);
  5606. *x = stbi__get32be(s);
  5607. if (stbi__get16be(s) != 8) {
  5608. stbi__rewind( s );
  5609. return 0;
  5610. }
  5611. if (stbi__get16be(s) != 3) {
  5612. stbi__rewind( s );
  5613. return 0;
  5614. }
  5615. *comp = 4;
  5616. return 1;
  5617. }
  5618. #endif
  5619. #ifndef STBI_NO_PIC
  5620. static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
  5621. {
  5622. int act_comp=0,num_packets=0,chained;
  5623. stbi__pic_packet packets[10];
  5624. if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) {
  5625. stbi__rewind(s);
  5626. return 0;
  5627. }
  5628. stbi__skip(s, 88);
  5629. *x = stbi__get16be(s);
  5630. *y = stbi__get16be(s);
  5631. if (stbi__at_eof(s)) {
  5632. stbi__rewind( s);
  5633. return 0;
  5634. }
  5635. if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
  5636. stbi__rewind( s );
  5637. return 0;
  5638. }
  5639. stbi__skip(s, 8);
  5640. do {
  5641. stbi__pic_packet *packet;
  5642. if (num_packets==sizeof(packets)/sizeof(packets[0]))
  5643. return 0;
  5644. packet = &packets[num_packets++];
  5645. chained = stbi__get8(s);
  5646. packet->size = stbi__get8(s);
  5647. packet->type = stbi__get8(s);
  5648. packet->channel = stbi__get8(s);
  5649. act_comp |= packet->channel;
  5650. if (stbi__at_eof(s)) {
  5651. stbi__rewind( s );
  5652. return 0;
  5653. }
  5654. if (packet->size != 8) {
  5655. stbi__rewind( s );
  5656. return 0;
  5657. }
  5658. } while (chained);
  5659. *comp = (act_comp & 0x10 ? 4 : 3);
  5660. return 1;
  5661. }
  5662. #endif
  5663. // *************************************************************************************************
  5664. // Portable Gray Map and Portable Pixel Map loader
  5665. // by Ken Miller
  5666. //
  5667. // PGM: http://netpbm.sourceforge.net/doc/pgm.html
  5668. // PPM: http://netpbm.sourceforge.net/doc/ppm.html
  5669. //
  5670. // Known limitations:
  5671. // Does not support comments in the header section
  5672. // Does not support ASCII image data (formats P2 and P3)
  5673. // Does not support 16-bit-per-channel
  5674. #ifndef STBI_NO_PNM
  5675. static int stbi__pnm_test(stbi__context *s)
  5676. {
  5677. char p, t;
  5678. p = (char) stbi__get8(s);
  5679. t = (char) stbi__get8(s);
  5680. if (p != 'P' || (t != '5' && t != '6')) {
  5681. stbi__rewind( s );
  5682. return 0;
  5683. }
  5684. return 1;
  5685. }
  5686. static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  5687. {
  5688. stbi_uc *out;
  5689. if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n))
  5690. return 0;
  5691. *x = s->img_x;
  5692. *y = s->img_y;
  5693. *comp = s->img_n;
  5694. out = (stbi_uc *) stbi__malloc(s->img_n * s->img_x * s->img_y);
  5695. if (!out) return stbi__errpuc("outofmem", "Out of memory");
  5696. stbi__getn(s, out, s->img_n * s->img_x * s->img_y);
  5697. if (req_comp && req_comp != s->img_n) {
  5698. out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
  5699. if (out == NULL) return out; // stbi__convert_format frees input on failure
  5700. }
  5701. return out;
  5702. }
  5703. static int stbi__pnm_isspace(char c)
  5704. {
  5705. return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
  5706. }
  5707. static void stbi__pnm_skip_whitespace(stbi__context *s, char *c)
  5708. {
  5709. for (;;) {
  5710. while (!stbi__at_eof(s) && stbi__pnm_isspace(*c))
  5711. *c = (char) stbi__get8(s);
  5712. if (stbi__at_eof(s) || *c != '#')
  5713. break;
  5714. while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' )
  5715. *c = (char) stbi__get8(s);
  5716. }
  5717. }
  5718. static int stbi__pnm_isdigit(char c)
  5719. {
  5720. return c >= '0' && c <= '9';
  5721. }
  5722. static int stbi__pnm_getinteger(stbi__context *s, char *c)
  5723. {
  5724. int value = 0;
  5725. while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) {
  5726. value = value*10 + (*c - '0');
  5727. *c = (char) stbi__get8(s);
  5728. }
  5729. return value;
  5730. }
  5731. static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp)
  5732. {
  5733. int maxv;
  5734. char c, p, t;
  5735. stbi__rewind( s );
  5736. // Get identifier
  5737. p = (char) stbi__get8(s);
  5738. t = (char) stbi__get8(s);
  5739. if (p != 'P' || (t != '5' && t != '6')) {
  5740. stbi__rewind( s );
  5741. return 0;
  5742. }
  5743. *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
  5744. c = (char) stbi__get8(s);
  5745. stbi__pnm_skip_whitespace(s, &c);
  5746. *x = stbi__pnm_getinteger(s, &c); // read width
  5747. stbi__pnm_skip_whitespace(s, &c);
  5748. *y = stbi__pnm_getinteger(s, &c); // read height
  5749. stbi__pnm_skip_whitespace(s, &c);
  5750. maxv = stbi__pnm_getinteger(s, &c); // read max value
  5751. if (maxv > 255)
  5752. return stbi__err("max value > 255", "PPM image not 8-bit");
  5753. else
  5754. return 1;
  5755. }
  5756. #endif
  5757. static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
  5758. {
  5759. #ifndef STBI_NO_JPEG
  5760. if (stbi__jpeg_info(s, x, y, comp)) return 1;
  5761. #endif
  5762. #ifndef STBI_NO_PNG
  5763. if (stbi__png_info(s, x, y, comp)) return 1;
  5764. #endif
  5765. #ifndef STBI_NO_GIF
  5766. if (stbi__gif_info(s, x, y, comp)) return 1;
  5767. #endif
  5768. #ifndef STBI_NO_BMP
  5769. if (stbi__bmp_info(s, x, y, comp)) return 1;
  5770. #endif
  5771. #ifndef STBI_NO_PSD
  5772. if (stbi__psd_info(s, x, y, comp)) return 1;
  5773. #endif
  5774. #ifndef STBI_NO_PIC
  5775. if (stbi__pic_info(s, x, y, comp)) return 1;
  5776. #endif
  5777. #ifndef STBI_NO_PNM
  5778. if (stbi__pnm_info(s, x, y, comp)) return 1;
  5779. #endif
  5780. #ifndef STBI_NO_HDR
  5781. if (stbi__hdr_info(s, x, y, comp)) return 1;
  5782. #endif
  5783. // test tga last because it's a crappy test!
  5784. #ifndef STBI_NO_TGA
  5785. if (stbi__tga_info(s, x, y, comp))
  5786. return 1;
  5787. #endif
  5788. return stbi__err("unknown image type", "Image not of any known type, or corrupt");
  5789. }
  5790. #ifndef STBI_NO_STDIO
  5791. STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)
  5792. {
  5793. FILE *f = stbi__fopen(filename, "rb");
  5794. int result;
  5795. if (!f) return stbi__err("can't fopen", "Unable to open file");
  5796. result = stbi_info_from_file(f, x, y, comp);
  5797. fclose(f);
  5798. return result;
  5799. }
  5800. STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
  5801. {
  5802. int r;
  5803. stbi__context s;
  5804. long pos = ftell(f);
  5805. stbi__start_file(&s, f);
  5806. r = stbi__info_main(&s,x,y,comp);
  5807. fseek(f,pos,SEEK_SET);
  5808. return r;
  5809. }
  5810. #endif // !STBI_NO_STDIO
  5811. STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
  5812. {
  5813. stbi__context s;
  5814. stbi__start_mem(&s,buffer,len);
  5815. return stbi__info_main(&s,x,y,comp);
  5816. }
  5817. STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
  5818. {
  5819. stbi__context s;
  5820. stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
  5821. return stbi__info_main(&s,x,y,comp);
  5822. }
  5823. #endif // STB_IMAGE_IMPLEMENTATION
  5824. /*
  5825. revision history:
  5826. 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
  5827. 2.11 (2016-04-02) allocate large structures on the stack
  5828. remove white matting for transparent PSD
  5829. fix reported channel count for PNG & BMP
  5830. re-enable SSE2 in non-gcc 64-bit
  5831. support RGB-formatted JPEG
  5832. read 16-bit PNGs (only as 8-bit)
  5833. 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED
  5834. 2.09 (2016-01-16) allow comments in PNM files
  5835. 16-bit-per-pixel TGA (not bit-per-component)
  5836. info() for TGA could break due to .hdr handling
  5837. info() for BMP to shares code instead of sloppy parse
  5838. can use STBI_REALLOC_SIZED if allocator doesn't support realloc
  5839. code cleanup
  5840. 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA
  5841. 2.07 (2015-09-13) fix compiler warnings
  5842. partial animated GIF support
  5843. limited 16-bpc PSD support
  5844. #ifdef unused functions
  5845. bug with < 92 byte PIC,PNM,HDR,TGA
  5846. 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value
  5847. 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning
  5848. 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit
  5849. 2.03 (2015-04-12) extra corruption checking (mmozeiko)
  5850. stbi_set_flip_vertically_on_load (nguillemot)
  5851. fix NEON support; fix mingw support
  5852. 2.02 (2015-01-19) fix incorrect assert, fix warning
  5853. 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2
  5854. 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG
  5855. 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg)
  5856. progressive JPEG (stb)
  5857. PGM/PPM support (Ken Miller)
  5858. STBI_MALLOC,STBI_REALLOC,STBI_FREE
  5859. GIF bugfix -- seemingly never worked
  5860. STBI_NO_*, STBI_ONLY_*
  5861. 1.48 (2014-12-14) fix incorrectly-named assert()
  5862. 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb)
  5863. optimize PNG (ryg)
  5864. fix bug in interlaced PNG with user-specified channel count (stb)
  5865. 1.46 (2014-08-26)
  5866. fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG
  5867. 1.45 (2014-08-16)
  5868. fix MSVC-ARM internal compiler error by wrapping malloc
  5869. 1.44 (2014-08-07)
  5870. various warning fixes from Ronny Chevalier
  5871. 1.43 (2014-07-15)
  5872. fix MSVC-only compiler problem in code changed in 1.42
  5873. 1.42 (2014-07-09)
  5874. don't define _CRT_SECURE_NO_WARNINGS (affects user code)
  5875. fixes to stbi__cleanup_jpeg path
  5876. added STBI_ASSERT to avoid requiring assert.h
  5877. 1.41 (2014-06-25)
  5878. fix search&replace from 1.36 that messed up comments/error messages
  5879. 1.40 (2014-06-22)
  5880. fix gcc struct-initialization warning
  5881. 1.39 (2014-06-15)
  5882. fix to TGA optimization when req_comp != number of components in TGA;
  5883. fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite)
  5884. add support for BMP version 5 (more ignored fields)
  5885. 1.38 (2014-06-06)
  5886. suppress MSVC warnings on integer casts truncating values
  5887. fix accidental rename of 'skip' field of I/O
  5888. 1.37 (2014-06-04)
  5889. remove duplicate typedef
  5890. 1.36 (2014-06-03)
  5891. convert to header file single-file library
  5892. if de-iphone isn't set, load iphone images color-swapped instead of returning NULL
  5893. 1.35 (2014-05-27)
  5894. various warnings
  5895. fix broken STBI_SIMD path
  5896. fix bug where stbi_load_from_file no longer left file pointer in correct place
  5897. fix broken non-easy path for 32-bit BMP (possibly never used)
  5898. TGA optimization by Arseny Kapoulkine
  5899. 1.34 (unknown)
  5900. use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case
  5901. 1.33 (2011-07-14)
  5902. make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
  5903. 1.32 (2011-07-13)
  5904. support for "info" function for all supported filetypes (SpartanJ)
  5905. 1.31 (2011-06-20)
  5906. a few more leak fixes, bug in PNG handling (SpartanJ)
  5907. 1.30 (2011-06-11)
  5908. added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
  5909. removed deprecated format-specific test/load functions
  5910. removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
  5911. error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
  5912. fix inefficiency in decoding 32-bit BMP (David Woo)
  5913. 1.29 (2010-08-16)
  5914. various warning fixes from Aurelien Pocheville
  5915. 1.28 (2010-08-01)
  5916. fix bug in GIF palette transparency (SpartanJ)
  5917. 1.27 (2010-08-01)
  5918. cast-to-stbi_uc to fix warnings
  5919. 1.26 (2010-07-24)
  5920. fix bug in file buffering for PNG reported by SpartanJ
  5921. 1.25 (2010-07-17)
  5922. refix trans_data warning (Won Chun)
  5923. 1.24 (2010-07-12)
  5924. perf improvements reading from files on platforms with lock-heavy fgetc()
  5925. minor perf improvements for jpeg
  5926. deprecated type-specific functions so we'll get feedback if they're needed
  5927. attempt to fix trans_data warning (Won Chun)
  5928. 1.23 fixed bug in iPhone support
  5929. 1.22 (2010-07-10)
  5930. removed image *writing* support
  5931. stbi_info support from Jetro Lauha
  5932. GIF support from Jean-Marc Lienher
  5933. iPhone PNG-extensions from James Brown
  5934. warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)
  5935. 1.21 fix use of 'stbi_uc' in header (reported by jon blow)
  5936. 1.20 added support for Softimage PIC, by Tom Seddon
  5937. 1.19 bug in interlaced PNG corruption check (found by ryg)
  5938. 1.18 (2008-08-02)
  5939. fix a threading bug (local mutable static)
  5940. 1.17 support interlaced PNG
  5941. 1.16 major bugfix - stbi__convert_format converted one too many pixels
  5942. 1.15 initialize some fields for thread safety
  5943. 1.14 fix threadsafe conversion bug
  5944. header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
  5945. 1.13 threadsafe
  5946. 1.12 const qualifiers in the API
  5947. 1.11 Support installable IDCT, colorspace conversion routines
  5948. 1.10 Fixes for 64-bit (don't use "unsigned long")
  5949. optimized upsampling by Fabian "ryg" Giesen
  5950. 1.09 Fix format-conversion for PSD code (bad global variables!)
  5951. 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
  5952. 1.07 attempt to fix C++ warning/errors again
  5953. 1.06 attempt to fix C++ warning/errors again
  5954. 1.05 fix TGA loading to return correct *comp and use good luminance calc
  5955. 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
  5956. 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
  5957. 1.02 support for (subset of) HDR files, float interface for preferred access to them
  5958. 1.01 fix bug: possible bug in handling right-side up bmps... not sure
  5959. fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all
  5960. 1.00 interface to zlib that skips zlib header
  5961. 0.99 correct handling of alpha in palette
  5962. 0.98 TGA loader by lonesock; dynamically add loaders (untested)
  5963. 0.97 jpeg errors on too large a file; also catch another malloc failure
  5964. 0.96 fix detection of invalid v value - particleman@mollyrocket forum
  5965. 0.95 during header scan, seek to markers in case of padding
  5966. 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
  5967. 0.93 handle jpegtran output; verbose errors
  5968. 0.92 read 4,8,16,24,32-bit BMP files of several formats
  5969. 0.91 output 24-bit Windows 3.0 BMP files
  5970. 0.90 fix a few more warnings; bump version number to approach 1.0
  5971. 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
  5972. 0.60 fix compiling as c++
  5973. 0.59 fix warnings: merge Dave Moore's -Wall fixes
  5974. 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
  5975. 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
  5976. 0.56 fix bug: zlib uncompressed mode len vs. nlen
  5977. 0.55 fix bug: restart_interval not initialized to 0
  5978. 0.54 allow NULL for 'int *comp'
  5979. 0.53 fix bug in png 3->4; speedup png decoding
  5980. 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
  5981. 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
  5982. on 'test' only check type, not whether we support this variant
  5983. 0.50 (2006-11-19)
  5984. first released version
  5985. */