🛠️🐜 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.

7462 lines
254 KiB

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