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

7897 lines
273 KiB

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