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