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

7987 lines
278 KiB

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