1 /* stb_image - v1.37 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
2 when you control the images you're loading
3 no warranty implied; use at your own risk
4
5 Do this:
6 #define STB_IMAGE_IMPLEMENTATION
7 before you include this file in *one* C or C++ file to create the implementation.
8
9 QUICK NOTES:
10 Primarily of interest to game developers and other people who can
11 avoid problematic images and only need the trivial interface
12
13 JPEG baseline (no JPEG progressive)
14 PNG 8-bit-per-channel only
15
16 TGA (not sure what subset, if a subset)
17 BMP non-1bpp, non-RLE
18 PSD (composited view only, no extra channels)
19
20 GIF (*comp always reports as 4-channel)
21 HDR (radiance rgbE format)
22 PIC (Softimage PIC)
23
24 - stbi__jpeg_huff_decode from memory or through FILE (define STBI_NO_STDIO to remove code)
25 - stbi__jpeg_huff_decode from arbitrary I/O callbacks
26 - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
27
28 Latest revisions:
29 1.37 (2014-06-04) remove duplicate typedef
30 1.36 (2014-06-03) converted to header file, allow reading incorrect iphoned-images without iphone flag
31 1.35 (2014-05-27) warnings, bugfixes, TGA optimization, etc
32 1.34 (unknown ) warning fix
33 1.33 (2011-07-14) minor fixes suggested by Dave Moore
34 1.32 (2011-07-13) info support for all filetypes (SpartanJ)
35 1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ)
36 1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger)
37 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville
38 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)
39
40 See end of file for full revision history.
41
42 TODO:
43 stbi_info support for BMP,PSD,HDR,PIC
44
45
46 ============================ Contributors =========================
47
48 Image formats Bug fixes & warning fixes
49 Sean Barrett (jpeg, png, bmp) Marc LeBlanc
50 Nicolas Schulz (hdr, psd) Christpher Lloyd
51 Jonathan Dummer (tga) Dave Moore
52 Jean-Marc Lienher (gif) Won Chun
53 Tom Seddon (pic) the Horde3D community
54 Thatcher Ulrich (psd) Janez Zemva
55 Jonathan Blow
56 Laurent Gomila
57 Extensions, features Aruelien Pocheville
58 Jetro Lauha (stbi_info) Ryamond Barbiero
59 James "moose2000" Brown (iPhone PNG) David Woo
60 Ben "Disch" Wenger (io callbacks) Roy Eltham
61 Martin "SpartanJ" Golini Luke Graham
62 Thomas Ruf
63 John Bartholomew
64 Optimizations & bugfixes Ken Hamada
65 Fabian "ryg" Giesen Cort Stratton
66 Arseny Kapoulkine Blazej Dariusz Roszkowski
67 Thibault Reuille
68 If your name should be here but Paul Du Bois
69 isn't let Sean know. Guillaume George
70
71 */
72
73 #ifndef STBI_INCLUDE_STB_IMAGE_H
74 #define STBI_INCLUDE_STB_IMAGE_H
75
76 // Limitations:
77 // - no jpeg progressive support
78 // - non-HDR formats support 8-bit samples only (jpeg, png)
79 // - no delayed line count (jpeg) -- IJG doesn't support either
80 // - no 1-bit BMP
81 // - GIF always returns *comp=4
82 //
83 // Basic usage (see HDR discussion below):
84 // int x,y,n;
85 // unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
86 // // ... process data if not NULL ...
87 // // ... x = width, y = height, n = # 8-bit components per pixel ...
88 // // ... replace '0' with '1'..'4' to force that many components per pixel
89 // // ... but 'n' will always be the number that it would have been if you said 0
90 // stbi_image_free(data)
91 //
92 // Standard parameters:
93 // int *x -- outputs image width in pixels
94 // int *y -- outputs image height in pixels
95 // int *comp -- outputs # of image components in image file
96 // int req_comp -- if non-zero, # of image components requested in result
97 //
98 // The return value from an image loader is an 'unsigned char *' which points
99 // to the pixel data. The pixel data consists of *y scanlines of *x pixels,
100 // with each pixel consisting of N interleaved 8-bit components; the first
101 // pixel pointed to is top-left-most in the image. There is no padding between
102 // image scanlines or between pixels, regardless of format. The number of
103 // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
104 // If req_comp is non-zero, *comp has the number of components that _would_
105 // have been output otherwise. E.g. if you set req_comp to 4, you will always
106 // get RGBA output, but you can check *comp to easily see if it's opaque.
107 //
108 // An output image with N components has the following components interleaved
109 // in this order in each pixel:
110 //
111 // N=#comp components
112 // 1 grey
113 // 2 grey, alpha
114 // 3 red, green, blue
115 // 4 red, green, blue, alpha
116 //
117 // If image loading fails for any reason, the return value will be NULL,
118 // and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
119 // can be queried for an extremely brief, end-user unfriendly explanation
120 // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
121 // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
122 // more user-friendly ones.
123 //
124 // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
125 //
126 // ===========================================================================
127 //
128 // iPhone PNG support:
129 //
130 // By default we convert iphone-formatted PNGs back to RGB; nominally they
131 // would silently load as BGR, except the existing code should have just
132 // failed on such iPhone PNGs. But you can disable this conversion by
133 // by calling stbi_convert_iphone_png_to_rgb(0), in which case
134 // you will always just get the native iphone "format" through.
135 //
136 // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
137 // pixel to remove any premultiplied alpha *only* if the image file explicitly
138 // says there's premultiplied data (currently only happens in iPhone images,
139 // and only if iPhone convert-to-rgb processing is on).
140 //
141 // ===========================================================================
142 //
143 // HDR image support (disable by defining STBI_NO_HDR)
144 //
145 // stb_image now supports loading HDR images in general, and currently
146 // the Radiance .HDR file format, although the support is provided
147 // generically. You can still load any file through the existing interface;
148 // if you attempt to load an HDR file, it will be automatically remapped to
149 // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
150 // both of these constants can be reconfigured through this interface:
151 //
152 // stbi_hdr_to_ldr_gamma(2.2f);
153 // stbi_hdr_to_ldr_scale(1.0f);
154 //
155 // (note, do not use _inverse_ constants; stbi_image will invert them
156 // appropriately).
157 //
158 // Additionally, there is a new, parallel interface for loading files as
159 // (linear) floats to preserve the full dynamic range:
160 //
161 // float *data = stbi_loadf(filename, &x, &y, &n, 0);
162 //
163 // If you load LDR images through this interface, those images will
164 // be promoted to floating point values, run through the inverse of
165 // constants corresponding to the above:
166 //
167 // stbi_ldr_to_hdr_scale(1.0f);
168 // stbi_ldr_to_hdr_gamma(2.2f);
169 //
170 // Finally, given a filename (or an open file or memory block--see header
171 // file for details) containing image data, you can query for the "most
172 // appropriate" interface to use (that is, whether the image is HDR or
173 // not), using:
174 //
175 // stbi_is_hdr(char *filename);
176 //
177 // ===========================================================================
178 //
179 // I/O callbacks
180 //
181 // I/O callbacks allow you to read from arbitrary sources, like packaged
182 // files or some other source. Data read from callbacks are processed
183 // through a small internal buffer (currently 128 bytes) to try to reduce
184 // overhead.
185 //
186 // The three functions you must define are "read" (reads some bytes of data),
187 // "stbi__skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
188
189
190 #ifndef STBI_NO_STDIO
191
192 #if defined(_MSC_VER) && _MSC_VER >= 1400
193 #define _CRT_SECURE_NO_WARNINGS // suppress warnings about fopen()
194 #pragma warning(push)
195 #pragma warning(disable:4996) // suppress even more warnings about fopen()
196 #endif
197 #include <stdio.h>
198 #endif // STBI_NO_STDIO
199
200 #define STBI_VERSION 1
201
202 enum
203 {
204 STBI_default = 0, // only used for req_comp
205
206 STBI_grey = 1,
207 STBI_grey_alpha = 2,
208 STBI_rgb = 3,
209 STBI_rgb_alpha = 4
210 };
211
212 typedef unsigned char stbi_uc;
213
214 #ifdef __cplusplus
215 extern "C" {
216 #endif
217
218 #ifdef STB_IMAGE_STATIC
219 #define STBIDEF static
220 #else
221 #define STBIDEF extern
222 #endif
223
224 //////////////////////////////////////////////////////////////////////////////
225 //
226 // PRIMARY API - works on images of any type
227 //
228
229 //
230 // load image by filename, open file, or memory buffer
231 //
232
233 STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
234
235 #ifndef STBI_NO_STDIO
236 STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
237 STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
238 // for stbi_load_from_file, file pointer is left pointing immediately after image
239 #endif
240
241 typedef struct
242 {
243 int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
244 void (*stbi__skip) (void *user,int n); // stbi__skip the next 'n' bytes, or 'unget' the last -n bytes if negative
245 int (*eof) (void *user); // returns nonzero if we are at end of file/data
246 } stbi_io_callbacks;
247
248 STBIDEF stbi_uc *stbi_load_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
249
250 #ifndef STBI_NO_HDR
251 STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
252
253 #ifndef STBI_NO_STDIO
254 STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
255 STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
256 #endif
257
258 STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
259
260 STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
261 STBIDEF void stbi_hdr_to_ldr_scale(float scale);
262
263 STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
264 STBIDEF void stbi_ldr_to_hdr_scale(float scale);
265 #endif // STBI_NO_HDR
266
267 // stbi_is_hdr is always defined
268 STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
269 STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
270 #ifndef STBI_NO_STDIO
271 STBIDEF int stbi_is_hdr (char const *filename);
272 STBIDEF int stbi_is_hdr_from_file(FILE *f);
273 #endif // STBI_NO_STDIO
274
275
276 // get a VERY brief reason for failure
277 // NOT THREADSAFE
278 STBIDEF const char *stbi_failure_reason (void);
279
280 // free the loaded image -- this is just free()
281 STBIDEF void stbi_image_free (void *retval_from_stbi_load);
282
283 // get image dimensions & components without fully decoding
284 STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
285 STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
286
287 #ifndef STBI_NO_STDIO
288 STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
289 STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
290
291 #endif
292
293
294
295 // for image formats that explicitly notate that they have premultiplied alpha,
296 // we just return the colors as stored in the file. set this flag to force
297 // unpremultiplication. results are undefined if the unpremultiply overflow.
298 STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
299
300 // indicate whether we should process iphone images back to canonical format,
301 // or just pass them through "as-is"
302 STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
303
304
305 // ZLIB client - used by PNG, available for other purposes
306
307 STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
308 STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
309 STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
310 STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
311
312 STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
313 STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
314
315
316 // define faster low-level operations (typically SIMD support)
317 #ifdef STBI_SIMD
318 typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);
319 // compute an integer IDCT on "input"
320 // input[x] = data[x] * dequantize[x]
321 // write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
322 // CLAMP results to 0..255
323 typedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step);
324 // compute a conversion from YCbCr to RGB
325 // 'count' pixels
326 // write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
327 // y: Y input channel
328 // cb: Cb input channel; scale/biased to be 0..255
329 // cr: Cr input channel; scale/biased to be 0..255
330
331 STBIDEF void stbi_install_idct(stbi_idct_8x8 func);
332 STBIDEF void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
333 #endif // STBI_SIMD
334
335
336 #ifdef __cplusplus
337 }
338 #endif
339
340 //
341 //
342 //// end header file /////////////////////////////////////////////////////
343 #endif // STBI_INCLUDE_STB_IMAGE_H
344
345 #ifdef STB_IMAGE_IMPLEMENTATION
346
347 #ifndef STBI_NO_HDR
348 #include <math.h> // ldexp
349 #include <string.h> // strcmp, strtok
350 #endif
351
352 #ifndef STBI_NO_STDIO
353 #include <stdio.h>
354 #endif
355 #include <stdlib.h>
356 #include <memory.h>
357 #include <assert.h>
358 #include <stdarg.h>
359 #include <stddef.h> // ptrdiff_t on osx
360
361 #ifndef _MSC_VER
362 #ifdef __cplusplus
363 #define stbi_inline inline
364 #else
365 #define stbi_inline
366 #endif
367 #else
368 #define stbi_inline __forceinline
369 #endif
370
371
372 #ifdef _MSC_VER
373 typedef unsigned short stbi__uint16;
374 typedef signed short stbi__int16;
375 typedef unsigned int stbi__uint32;
376 typedef signed int stbi__int32;
377 #else
378 #include <stdint.h>
379 typedef uint16_t stbi__uint16;
380 typedef int16_t stbi__int16;
381 typedef uint32_t stbi__uint32;
382 typedef int32_t stbi__int32;
383 #endif
384
385 // should produce compiler error if size is wrong
386 typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
387
388 #ifdef _MSC_VER
389 #define STBI_NOTUSED(v) (void)(v)
390 #else
391 #define STBI_NOTUSED(v) (void)sizeof(v)
392 #endif
393
394 #ifdef _MSC_VER
395 #define STBI_HAS_LROTL
396 #endif
397
398 #ifdef STBI_HAS_LROTL
399 #define stbi_lrot(x,y) _lrotl(x,y)
400 #else
401 #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))
402 #endif
403
404 ///////////////////////////////////////////////
405 //
406 // stbi__context struct and start_xxx functions
407
408 // stbi__context structure is our basic context used by all images, so it
409 // contains all the IO context, plus some basic image information
410 typedef struct
411 {
412 stbi__uint32 img_x, img_y;
413 int img_n, img_out_n;
414
415 stbi_io_callbacks io;
416 void *io_user_data;
417
418 int read_from_callbacks;
419 int buflen;
420 stbi_uc buffer_start[128];
421
422 stbi_uc *img_buffer, *img_buffer_end;
423 stbi_uc *img_buffer_original;
424 } stbi__context;
425
426
427 static void stbi__refill_buffer(stbi__context *s);
428
429 // initialize a memory-stbi__jpeg_huff_decode context
stbi__start_mem(stbi__context * s,stbi_uc const * buffer,int len)430 static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
431 {
432 s->io.read = NULL;
433 s->read_from_callbacks = 0;
434 s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
435 s->img_buffer_end = (stbi_uc *) buffer+len;
436 }
437
438 // initialize a callback-based context
stbi__start_callbacks(stbi__context * s,stbi_io_callbacks * c,void * user)439 static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)
440 {
441 s->io = *c;
442 s->io_user_data = user;
443 s->buflen = sizeof(s->buffer_start);
444 s->read_from_callbacks = 1;
445 s->img_buffer_original = s->buffer_start;
446 stbi__refill_buffer(s);
447 }
448
449 #ifndef STBI_NO_STDIO
450
stbi__stdio_read(void * user,char * data,int size)451 static int stbi__stdio_read(void *user, char *data, int size)
452 {
453 return (int) fread(data,1,size,(FILE*) user);
454 }
455
stbi__stdio_skip(void * user,int n)456 static void stbi__stdio_skip(void *user, int n)
457 {
458 fseek((FILE*) user, n, SEEK_CUR);
459 }
460
stbi__stdio_eof(void * user)461 static int stbi__stdio_eof(void *user)
462 {
463 return feof((FILE*) user);
464 }
465
466 static stbi_io_callbacks stbi__stdio_callbacks =
467 {
468 stbi__stdio_read,
469 stbi__stdio_skip,
470 stbi__stdio_eof,
471 };
472
stbi__start_file(stbi__context * s,FILE * f)473 static void stbi__start_file(stbi__context *s, FILE *f)
474 {
475 stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);
476 }
477
478 //static void stop_file(stbi__context *s) { }
479
480 #endif // !STBI_NO_STDIO
481
stbi__rewind(stbi__context * s)482 static void stbi__rewind(stbi__context *s)
483 {
484 // conceptually rewind SHOULD rewind to the beginning of the stream,
485 // but we just rewind to the beginning of the initial buffer, because
486 // we only use it after doing 'test', which only ever looks at at most 92 bytes
487 s->img_buffer = s->img_buffer_original;
488 }
489
490 static int stbi__jpeg_test(stbi__context *s);
491 static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
492 static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);
493 static int stbi__png_test(stbi__context *s);
494 static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
495 static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);
496 static int stbi__bmp_test(stbi__context *s);
497 static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
498 static int stbi__tga_test(stbi__context *s);
499 static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
500 static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);
501 static int stbi__psd_test(stbi__context *s);
502 static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
503 #ifndef STBI_NO_HDR
504 static int stbi__hdr_test(stbi__context *s);
505 static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
506 #endif
507 static int stbi__pic_test(stbi__context *s);
508 static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
509 static int stbi__gif_test(stbi__context *s);
510 static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
511 static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);
512
513
514 // this is not threadsafe
515 static const char *stbi__g_failure_reason;
516
stbi_failure_reason(void)517 STBIDEF const char *stbi_failure_reason(void)
518 {
519 return stbi__g_failure_reason;
520 }
521
stbi__err(const char * str)522 static int stbi__err(const char *str)
523 {
524 stbi__g_failure_reason = str;
525 return 0;
526 }
527
528 // stbi__err - error
529 // stbi__errpf - error returning pointer to float
530 // stbi__errpuc - error returning pointer to unsigned char
531
532 #ifdef STBI_NO_FAILURE_STRINGS
533 #define stbi__err(x,y) 0
534 #elif defined(STBI_FAILURE_USERMSG)
535 #define stbi__err(x,y) stbi__err(y)
536 #else
537 #define stbi__err(x,y) stbi__err(x)
538 #endif
539
540 #define stbi__errpf(x,y) ((float *) (stbi__err(x,y)?NULL:NULL))
541 #define stbi__errpuc(x,y) ((unsigned char *) (stbi__err(x,y)?NULL:NULL))
542
stbi_image_free(void * retval_from_stbi_load)543 STBIDEF void stbi_image_free(void *retval_from_stbi_load)
544 {
545 free(retval_from_stbi_load);
546 }
547
548 #ifndef STBI_NO_HDR
549 static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
550 static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp);
551 #endif
552
stbi_load_main(stbi__context * s,int * x,int * y,int * comp,int req_comp)553 static unsigned char *stbi_load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
554 {
555 if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp);
556 if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp);
557 if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp);
558 if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp);
559 if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp);
560 if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp);
561
562 #ifndef STBI_NO_HDR
563 if (stbi__hdr_test(s)) {
564 float *hdr = stbi__hdr_load(s, x,y,comp,req_comp);
565 return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
566 }
567 #endif
568
569 // test tga last because it's a crappy test!
570 if (stbi__tga_test(s))
571 return stbi__tga_load(s,x,y,comp,req_comp);
572 return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
573 }
574
575 #ifndef STBI_NO_STDIO
stbi_load(char const * filename,int * x,int * y,int * comp,int req_comp)576 STBIDEF unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
577 {
578 FILE *f = fopen(filename, "rb");
579 unsigned char *result;
580 if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
581 result = stbi_load_from_file(f,x,y,comp,req_comp);
582 fclose(f);
583 return result;
584 }
585
stbi_load_from_file(FILE * f,int * x,int * y,int * comp,int req_comp)586 STBIDEF unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
587 {
588 unsigned char *result;
589 stbi__context s;
590 stbi__start_file(&s,f);
591 result = stbi_load_main(&s,x,y,comp,req_comp);
592 if (result) {
593 // need to 'unget' all the characters in the IO buffer
594 fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
595 }
596 return result;
597 }
598 #endif //!STBI_NO_STDIO
599
stbi_load_from_memory(stbi_uc const * buffer,int len,int * x,int * y,int * comp,int req_comp)600 STBIDEF unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
601 {
602 stbi__context s;
603 stbi__start_mem(&s,buffer,len);
604 return stbi_load_main(&s,x,y,comp,req_comp);
605 }
606
stbi_load_from_callbacks(stbi_io_callbacks const * clbk,void * user,int * x,int * y,int * comp,int req_comp)607 unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
608 {
609 stbi__context s;
610 stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
611 return stbi_load_main(&s,x,y,comp,req_comp);
612 }
613
614 #ifndef STBI_NO_HDR
615
stbi_loadf_main(stbi__context * s,int * x,int * y,int * comp,int req_comp)616 float *stbi_loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
617 {
618 unsigned char *data;
619 #ifndef STBI_NO_HDR
620 if (stbi__hdr_test(s))
621 return stbi__hdr_load(s,x,y,comp,req_comp);
622 #endif
623 data = stbi_load_main(s, x, y, comp, req_comp);
624 if (data)
625 return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
626 return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
627 }
628
stbi_loadf_from_memory(stbi_uc const * buffer,int len,int * x,int * y,int * comp,int req_comp)629 float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
630 {
631 stbi__context s;
632 stbi__start_mem(&s,buffer,len);
633 return stbi_loadf_main(&s,x,y,comp,req_comp);
634 }
635
stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk,void * user,int * x,int * y,int * comp,int req_comp)636 float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
637 {
638 stbi__context s;
639 stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
640 return stbi_loadf_main(&s,x,y,comp,req_comp);
641 }
642
643 #ifndef STBI_NO_STDIO
stbi_loadf(char const * filename,int * x,int * y,int * comp,int req_comp)644 float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
645 {
646 FILE *f = fopen(filename, "rb");
647 float *result;
648 if (!f) return stbi__errpf("can't fopen", "Unable to open file");
649 result = stbi_loadf_from_file(f,x,y,comp,req_comp);
650 fclose(f);
651 return result;
652 }
653
stbi_loadf_from_file(FILE * f,int * x,int * y,int * comp,int req_comp)654 float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
655 {
656 stbi__context s;
657 stbi__start_file(&s,f);
658 return stbi_loadf_main(&s,x,y,comp,req_comp);
659 }
660 #endif // !STBI_NO_STDIO
661
662 #endif // !STBI_NO_HDR
663
664 // these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
665 // defined, for API simplicity; if STBI_NO_HDR is defined, it always
666 // reports false!
667
stbi_is_hdr_from_memory(stbi_uc const * buffer,int len)668 int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
669 {
670 #ifndef STBI_NO_HDR
671 stbi__context s;
672 stbi__start_mem(&s,buffer,len);
673 return stbi__hdr_test(&s);
674 #else
675 STBI_NOTUSED(buffer);
676 STBI_NOTUSED(len);
677 return 0;
678 #endif
679 }
680
681 #ifndef STBI_NO_STDIO
stbi_is_hdr(char const * filename)682 STBIDEF int stbi_is_hdr (char const *filename)
683 {
684 FILE *f = fopen(filename, "rb");
685 int result=0;
686 if (f) {
687 result = stbi_is_hdr_from_file(f);
688 fclose(f);
689 }
690 return result;
691 }
692
stbi_is_hdr_from_file(FILE * f)693 STBIDEF int stbi_is_hdr_from_file(FILE *f)
694 {
695 #ifndef STBI_NO_HDR
696 stbi__context s;
697 stbi__start_file(&s,f);
698 return stbi__hdr_test(&s);
699 #else
700 (void) f;
701 return 0;
702 #endif
703 }
704 #endif // !STBI_NO_STDIO
705
stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk,void * user)706 STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
707 {
708 #ifndef STBI_NO_HDR
709 stbi__context s;
710 stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
711 return stbi__hdr_test(&s);
712 #else
713 (void) clbk;
714 (void) user;
715 return 0;
716 #endif
717 }
718
719 #ifndef STBI_NO_HDR
720 static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
721 static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;
722
stbi_hdr_to_ldr_gamma(float gamma)723 void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
stbi_hdr_to_ldr_scale(float scale)724 void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
725
stbi_ldr_to_hdr_gamma(float gamma)726 void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
stbi_ldr_to_hdr_scale(float scale)727 void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
728 #endif
729
730
731 //////////////////////////////////////////////////////////////////////////////
732 //
733 // Common code used by all image loaders
734 //
735
736 enum
737 {
738 SCAN_load=0,
739 SCAN_type,
740 SCAN_header
741 };
742
stbi__refill_buffer(stbi__context * s)743 static void stbi__refill_buffer(stbi__context *s)
744 {
745 int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
746 if (n == 0) {
747 // at end of file, treat same as if from memory, but need to handle case
748 // where s->img_buffer isn't pointing to safe memory, stbi__err.g. 0-byte file
749 s->read_from_callbacks = 0;
750 s->img_buffer = s->buffer_start;
751 s->img_buffer_end = s->buffer_start+1;
752 *s->img_buffer = 0;
753 } else {
754 s->img_buffer = s->buffer_start;
755 s->img_buffer_end = s->buffer_start + n;
756 }
757 }
758
stbi__get8(stbi__context * s)759 stbi_inline static int stbi__get8(stbi__context *s)
760 {
761 if (s->img_buffer < s->img_buffer_end)
762 return *s->img_buffer++;
763 if (s->read_from_callbacks) {
764 stbi__refill_buffer(s);
765 return *s->img_buffer++;
766 }
767 return 0;
768 }
769
stbi__at_eof(stbi__context * s)770 stbi_inline static int stbi__at_eof(stbi__context *s)
771 {
772 if (s->io.read) {
773 if (!(s->io.eof)(s->io_user_data)) return 0;
774 // if feof() is true, check if buffer = end
775 // special case: we've only got the special 0 character at the end
776 if (s->read_from_callbacks == 0) return 1;
777 }
778
779 return s->img_buffer >= s->img_buffer_end;
780 }
781
stbi__get8u(stbi__context * s)782 stbi_inline static stbi_uc stbi__get8u(stbi__context *s)
783 {
784 return (stbi_uc) stbi__get8(s);
785 }
786
stbi__skip(stbi__context * s,int n)787 static void stbi__skip(stbi__context *s, int n)
788 {
789 if (s->io.read) {
790 int blen = (int) (s->img_buffer_end - s->img_buffer);
791 if (blen < n) {
792 s->img_buffer = s->img_buffer_end;
793 (s->io.stbi__skip)(s->io_user_data, n - blen);
794 return;
795 }
796 }
797 s->img_buffer += n;
798 }
799
stbi__getn(stbi__context * s,stbi_uc * buffer,int n)800 static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
801 {
802 if (s->io.read) {
803 int blen = (int) (s->img_buffer_end - s->img_buffer);
804 if (blen < n) {
805 int res, count;
806
807 memcpy(buffer, s->img_buffer, blen);
808
809 count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
810 res = (count == (n-blen));
811 s->img_buffer = s->img_buffer_end;
812 return res;
813 }
814 }
815
816 if (s->img_buffer+n <= s->img_buffer_end) {
817 memcpy(buffer, s->img_buffer, n);
818 s->img_buffer += n;
819 return 1;
820 } else
821 return 0;
822 }
823
stbi__get16be(stbi__context * s)824 static stbi__uint16 stbi__get16be(stbi__context *s)
825 {
826 int z = stbi__get8(s);
827 return (z << 8) + stbi__get8(s);
828 }
829
stbi__get32be(stbi__context * s)830 static stbi__uint32 stbi__get32be(stbi__context *s)
831 {
832 stbi__uint32 z = stbi__get16be(s);
833 return (z << 16) + stbi__get16be(s);
834 }
835
stbi__get16le(stbi__context * s)836 static stbi__uint16 stbi__get16le(stbi__context *s)
837 {
838 int z = stbi__get8(s);
839 return z + (stbi__get8(s) << 8);
840 }
841
stbi__get32le(stbi__context * s)842 static stbi__uint32 stbi__get32le(stbi__context *s)
843 {
844 stbi__uint32 z = stbi__get16le(s);
845 return z + (stbi__get16le(s) << 16);
846 }
847
848 //////////////////////////////////////////////////////////////////////////////
849 //
850 // generic converter from built-in img_n to req_comp
851 // individual types do this automatically as much as possible (stbi__err.g. jpeg
852 // does all cases internally since it needs to colorspace convert anyway,
853 // and it never has alpha, so very few cases ). png can automatically
854 // interleave an alpha=255 channel, but falls back to this for other cases
855 //
856 // assume data buffer is malloced, so malloc a new one and free that one
857 // only failure mode is malloc failing
858
stbi__compute_y(int r,int g,int b)859 static stbi_uc stbi__compute_y(int r, int g, int b)
860 {
861 return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);
862 }
863
stbi__convert_format(unsigned char * data,int img_n,int req_comp,unsigned int x,unsigned int y)864 static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)
865 {
866 int i,j;
867 unsigned char *good;
868
869 if (req_comp == img_n) return data;
870 assert(req_comp >= 1 && req_comp <= 4);
871
872 good = (unsigned char *) malloc(req_comp * x * y);
873 if (good == NULL) {
874 free(data);
875 return stbi__errpuc("outofmem", "Out of memory");
876 }
877
878 for (j=0; j < (int) y; ++j) {
879 unsigned char *src = data + j * x * img_n ;
880 unsigned char *dest = good + j * x * req_comp;
881
882 #define COMBO(a,b) ((a)*8+(b))
883 #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
884 // convert source image with img_n components to one with req_comp components;
885 // avoid switch per pixel, so use switch per scanline and massive macros
886 switch (COMBO(img_n, req_comp)) {
887 CASE(1,2) dest[0]=src[0], dest[1]=255; break;
888 CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
889 CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
890 CASE(2,1) dest[0]=src[0]; break;
891 CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
892 CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
893 CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
894 CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;
895 CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
896 CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;
897 CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
898 CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
899 default: assert(0);
900 }
901 #undef CASE
902 }
903
904 free(data);
905 return good;
906 }
907
908 #ifndef STBI_NO_HDR
stbi__ldr_to_hdr(stbi_uc * data,int x,int y,int comp)909 static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
910 {
911 int i,k,n;
912 float *output = (float *) malloc(x * y * comp * sizeof(float));
913 if (output == NULL) { free(data); return stbi__errpf("outofmem", "Out of memory"); }
914 // compute number of non-alpha components
915 if (comp & 1) n = comp; else n = comp-1;
916 for (i=0; i < x*y; ++i) {
917 for (k=0; k < n; ++k) {
918 output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale;
919 }
920 if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
921 }
922 free(data);
923 return output;
924 }
925
926 #define stbi__float2int(x) ((int) (x))
stbi__hdr_to_ldr(float * data,int x,int y,int comp)927 static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)
928 {
929 int i,k,n;
930 stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
931 if (output == NULL) { free(data); return stbi__errpuc("outofmem", "Out of memory"); }
932 // compute number of non-alpha components
933 if (comp & 1) n = comp; else n = comp-1;
934 for (i=0; i < x*y; ++i) {
935 for (k=0; k < n; ++k) {
936 float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;
937 if (z < 0) z = 0;
938 if (z > 255) z = 255;
939 output[i*comp + k] = (stbi_uc) stbi__float2int(z);
940 }
941 if (k < comp) {
942 float z = data[i*comp+k] * 255 + 0.5f;
943 if (z < 0) z = 0;
944 if (z > 255) z = 255;
945 output[i*comp + k] = (stbi_uc) stbi__float2int(z);
946 }
947 }
948 free(data);
949 return output;
950 }
951 #endif
952
953 //////////////////////////////////////////////////////////////////////////////
954 //
955 // "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
956 //
957 // simple implementation
958 // - channel subsampling of at most 2 in each dimension
959 // - doesn't support delayed output of y-dimension
960 // - simple interface (only one output format: 8-bit interleaved RGB)
961 // - doesn't try to recover corrupt jpegs
962 // - doesn't allow partial loading, loading multiple at once
963 // - still fast on x86 (copying globals into locals doesn't help x86)
964 // - allocates lots of intermediate memory (full size of all components)
965 // - non-interleaved case requires this anyway
966 // - allows good upsampling (see next)
967 // high-quality
968 // - upsampled channels are bilinearly interpolated, even across blocks
969 // - quality integer IDCT derived from IJG's 'slow'
970 // performance
971 // - fast huffman; reasonable integer IDCT
972 // - uses a lot of intermediate memory, could cache poorly
973 // - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
974 // stb_jpeg: 1.34 seconds (MSVC6, default release build)
975 // stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
976 // IJL11.dll: 1.08 seconds (compiled by intel)
977 // IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
978 // IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
979
980 // huffman decoding acceleration
981 #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
982
983 typedef struct
984 {
985 stbi_uc fast[1 << FAST_BITS];
986 // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
987 stbi__uint16 code[256];
988 stbi_uc values[256];
989 stbi_uc size[257];
990 unsigned int maxcode[18];
991 int delta[17]; // old 'firstsymbol' - old 'firstcode'
992 } stbi__huffman;
993
994 typedef struct
995 {
996 #ifdef STBI_SIMD
997 unsigned short dequant2[4][64];
998 #endif
999 stbi__context *s;
1000 stbi__huffman huff_dc[4];
1001 stbi__huffman huff_ac[4];
1002 stbi_uc dequant[4][64];
1003
1004 // sizes for components, interleaved MCUs
1005 int img_h_max, img_v_max;
1006 int img_mcu_x, img_mcu_y;
1007 int img_mcu_w, img_mcu_h;
1008
1009 // definition of jpeg image component
1010 struct
1011 {
1012 int id;
1013 int h,v;
1014 int tq;
1015 int hd,ha;
1016 int dc_pred;
1017
1018 int x,y,w2,h2;
1019 stbi_uc *data;
1020 void *raw_data;
1021 stbi_uc *linebuf;
1022 } img_comp[4];
1023
1024 stbi__uint32 code_buffer; // jpeg entropy-coded buffer
1025 int code_bits; // number of valid bits
1026 unsigned char marker; // marker seen while filling entropy buffer
1027 int nomore; // flag if we saw a marker so must stop
1028
1029 int scan_n, order[4];
1030 int restart_interval, todo;
1031 } stbi__jpeg;
1032
stbi__build_huffman(stbi__huffman * h,int * count)1033 static int stbi__build_huffman(stbi__huffman *h, int *count)
1034 {
1035 int i,j,k=0,code;
1036 // build size list for each symbol (from JPEG spec)
1037 for (i=0; i < 16; ++i)
1038 for (j=0; j < count[i]; ++j)
1039 h->size[k++] = (stbi_uc) (i+1);
1040 h->size[k] = 0;
1041
1042 // compute actual symbols (from jpeg spec)
1043 code = 0;
1044 k = 0;
1045 for(j=1; j <= 16; ++j) {
1046 // compute delta to add to code to compute symbol id
1047 h->delta[j] = k - code;
1048 if (h->size[k] == j) {
1049 while (h->size[k] == j)
1050 h->code[k++] = (stbi__uint16) (code++);
1051 if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG");
1052 }
1053 // compute largest code + 1 for this size, preshifted as needed later
1054 h->maxcode[j] = code << (16-j);
1055 code <<= 1;
1056 }
1057 h->maxcode[j] = 0xffffffff;
1058
1059 // build non-spec acceleration table; 255 is flag for not-accelerated
1060 memset(h->fast, 255, 1 << FAST_BITS);
1061 for (i=0; i < k; ++i) {
1062 int s = h->size[i];
1063 if (s <= FAST_BITS) {
1064 int c = h->code[i] << (FAST_BITS-s);
1065 int m = 1 << (FAST_BITS-s);
1066 for (j=0; j < m; ++j) {
1067 h->fast[c+j] = (stbi_uc) i;
1068 }
1069 }
1070 }
1071 return 1;
1072 }
1073
stbi__grow_buffer_unsafe(stbi__jpeg * j)1074 static void stbi__grow_buffer_unsafe(stbi__jpeg *j)
1075 {
1076 do {
1077 int b = j->nomore ? 0 : stbi__get8(j->s);
1078 if (b == 0xff) {
1079 int c = stbi__get8(j->s);
1080 if (c != 0) {
1081 j->marker = (unsigned char) c;
1082 j->nomore = 1;
1083 return;
1084 }
1085 }
1086 j->code_buffer |= b << (24 - j->code_bits);
1087 j->code_bits += 8;
1088 } while (j->code_bits <= 24);
1089 }
1090
1091 // (1 << n) - 1
1092 static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
1093
1094 // stbi__jpeg_huff_decode a jpeg huffman value from the bitstream
stbi__jpeg_huff_decode(stbi__jpeg * j,stbi__huffman * h)1095 stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)
1096 {
1097 unsigned int temp;
1098 int c,k;
1099
1100 if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
1101
1102 // look at the top FAST_BITS and determine what symbol ID it is,
1103 // if the code is <= FAST_BITS
1104 c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
1105 k = h->fast[c];
1106 if (k < 255) {
1107 int s = h->size[k];
1108 if (s > j->code_bits)
1109 return -1;
1110 j->code_buffer <<= s;
1111 j->code_bits -= s;
1112 return h->values[k];
1113 }
1114
1115 // naive test is to shift the code_buffer down so k bits are
1116 // valid, then test against maxcode. To speed this up, we've
1117 // preshifted maxcode left so that it has (16-k) 0s at the
1118 // end; in other words, regardless of the number of bits, it
1119 // wants to be compared against something shifted to have 16;
1120 // that way we don't need to shift inside the loop.
1121 temp = j->code_buffer >> 16;
1122 for (k=FAST_BITS+1 ; ; ++k)
1123 if (temp < h->maxcode[k])
1124 break;
1125 if (k == 17) {
1126 // error! code not found
1127 j->code_bits -= 16;
1128 return -1;
1129 }
1130
1131 if (k > j->code_bits)
1132 return -1;
1133
1134 // convert the huffman code to the symbol id
1135 c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
1136 assert((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);
1137
1138 // convert the id to a symbol
1139 j->code_bits -= k;
1140 j->code_buffer <<= k;
1141 return h->values[c];
1142 }
1143
1144 // combined JPEG 'receive' and JPEG 'extend', since baseline
1145 // always extends everything it receives.
stbi__extend_receive(stbi__jpeg * j,int n)1146 stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
1147 {
1148 unsigned int m = 1 << (n-1);
1149 unsigned int k;
1150 if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
1151
1152 #if 1
1153 k = stbi_lrot(j->code_buffer, n);
1154 j->code_buffer = k & ~stbi__bmask[n];
1155 k &= stbi__bmask[n];
1156 j->code_bits -= n;
1157 #else
1158 k = (j->code_buffer >> (32 - n)) & stbi__bmask[n];
1159 j->code_bits -= n;
1160 j->code_buffer <<= n;
1161 #endif
1162 // the following test is probably a random branch that won't
1163 // predict well. I tried to table accelerate it but failed.
1164 // maybe it's compiling as a conditional move?
1165 if (k < m)
1166 return (-1 << n) + k + 1;
1167 else
1168 return k;
1169 }
1170
1171 // given a value that's at position X in the zigzag stream,
1172 // where does it appear in the 8x8 matrix coded as row-major?
1173 static stbi_uc stbi__jpeg_dezigzag[64+15] =
1174 {
1175 0, 1, 8, 16, 9, 2, 3, 10,
1176 17, 24, 32, 25, 18, 11, 4, 5,
1177 12, 19, 26, 33, 40, 48, 41, 34,
1178 27, 20, 13, 6, 7, 14, 21, 28,
1179 35, 42, 49, 56, 57, 50, 43, 36,
1180 29, 22, 15, 23, 30, 37, 44, 51,
1181 58, 59, 52, 45, 38, 31, 39, 46,
1182 53, 60, 61, 54, 47, 55, 62, 63,
1183 // let corrupt input sample past end
1184 63, 63, 63, 63, 63, 63, 63, 63,
1185 63, 63, 63, 63, 63, 63, 63
1186 };
1187
1188 // stbi__jpeg_huff_decode one 64-entry block--
stbi__jpeg_decode_block(stbi__jpeg * j,short data[64],stbi__huffman * hdc,stbi__huffman * hac,int b)1189 static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, int b)
1190 {
1191 int diff,dc,k;
1192 int t = stbi__jpeg_huff_decode(j, hdc);
1193 if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG");
1194
1195 // 0 all the ac values now so we can do it 32-bits at a time
1196 memset(data,0,64*sizeof(data[0]));
1197
1198 diff = t ? stbi__extend_receive(j, t) : 0;
1199 dc = j->img_comp[b].dc_pred + diff;
1200 j->img_comp[b].dc_pred = dc;
1201 data[0] = (short) dc;
1202
1203 // stbi__jpeg_huff_decode AC components, see JPEG spec
1204 k = 1;
1205 do {
1206 int r,s;
1207 int rs = stbi__jpeg_huff_decode(j, hac);
1208 if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
1209 s = rs & 15;
1210 r = rs >> 4;
1211 if (s == 0) {
1212 if (rs != 0xf0) break; // end block
1213 k += 16;
1214 } else {
1215 k += r;
1216 // stbi__jpeg_huff_decode into unzigzag'd location
1217 data[stbi__jpeg_dezigzag[k++]] = (short) stbi__extend_receive(j,s);
1218 }
1219 } while (k < 64);
1220 return 1;
1221 }
1222
1223 // take a -128..127 value and stbi__clamp it and convert to 0..255
stbi__clamp(int x)1224 stbi_inline static stbi_uc stbi__clamp(int x)
1225 {
1226 // trick to use a single test to catch both cases
1227 if ((unsigned int) x > 255) {
1228 if (x < 0) return 0;
1229 if (x > 255) return 255;
1230 }
1231 return (stbi_uc) x;
1232 }
1233
1234 #define stbi__f2f(x) (int) (((x) * 4096 + 0.5))
1235 #define stbi__fsh(x) ((x) << 12)
1236
1237 // derived from jidctint -- DCT_ISLOW
1238 #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
1239 int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
1240 p2 = s2; \
1241 p3 = s6; \
1242 p1 = (p2+p3) * stbi__f2f(0.5411961f); \
1243 t2 = p1 + p3*stbi__f2f(-1.847759065f); \
1244 t3 = p1 + p2*stbi__f2f( 0.765366865f); \
1245 p2 = s0; \
1246 p3 = s4; \
1247 t0 = stbi__fsh(p2+p3); \
1248 t1 = stbi__fsh(p2-p3); \
1249 x0 = t0+t3; \
1250 x3 = t0-t3; \
1251 x1 = t1+t2; \
1252 x2 = t1-t2; \
1253 t0 = s7; \
1254 t1 = s5; \
1255 t2 = s3; \
1256 t3 = s1; \
1257 p3 = t0+t2; \
1258 p4 = t1+t3; \
1259 p1 = t0+t3; \
1260 p2 = t1+t2; \
1261 p5 = (p3+p4)*stbi__f2f( 1.175875602f); \
1262 t0 = t0*stbi__f2f( 0.298631336f); \
1263 t1 = t1*stbi__f2f( 2.053119869f); \
1264 t2 = t2*stbi__f2f( 3.072711026f); \
1265 t3 = t3*stbi__f2f( 1.501321110f); \
1266 p1 = p5 + p1*stbi__f2f(-0.899976223f); \
1267 p2 = p5 + p2*stbi__f2f(-2.562915447f); \
1268 p3 = p3*stbi__f2f(-1.961570560f); \
1269 p4 = p4*stbi__f2f(-0.390180644f); \
1270 t3 += p1+p4; \
1271 t2 += p2+p3; \
1272 t1 += p2+p4; \
1273 t0 += p1+p3;
1274
1275 #ifdef STBI_SIMD
1276 typedef unsigned short stbi_dequantize_t;
1277 #else
1278 typedef stbi_uc stbi_dequantize_t;
1279 #endif
1280
1281 // .344 seconds on 3*anemones.jpg
stbi__idct_block(stbi_uc * out,int out_stride,short data[64],stbi_dequantize_t * dequantize)1282 static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)
1283 {
1284 int i,val[64],*v=val;
1285 stbi_dequantize_t *dq = dequantize;
1286 stbi_uc *o;
1287 short *d = data;
1288
1289 // columns
1290 for (i=0; i < 8; ++i,++d,++dq, ++v) {
1291 // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
1292 if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
1293 && d[40]==0 && d[48]==0 && d[56]==0) {
1294 // no shortcut 0 seconds
1295 // (1|2|3|4|5|6|7)==0 0 seconds
1296 // all separate -0.047 seconds
1297 // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
1298 int dcterm = d[0] * dq[0] << 2;
1299 v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
1300 } else {
1301 STBI__IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
1302 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
1303 // constants scaled things up by 1<<12; let's bring them back
1304 // down, but keep 2 extra bits of precision
1305 x0 += 512; x1 += 512; x2 += 512; x3 += 512;
1306 v[ 0] = (x0+t3) >> 10;
1307 v[56] = (x0-t3) >> 10;
1308 v[ 8] = (x1+t2) >> 10;
1309 v[48] = (x1-t2) >> 10;
1310 v[16] = (x2+t1) >> 10;
1311 v[40] = (x2-t1) >> 10;
1312 v[24] = (x3+t0) >> 10;
1313 v[32] = (x3-t0) >> 10;
1314 }
1315 }
1316
1317 for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
1318 // no fast case since the first 1D IDCT spread components out
1319 STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
1320 // constants scaled things up by 1<<12, plus we had 1<<2 from first
1321 // loop, plus horizontal and vertical each scale by sqrt(8) so together
1322 // we've got an extra 1<<3, so 1<<17 total we need to remove.
1323 // so we want to round that, which means adding 0.5 * 1<<17,
1324 // aka 65536. Also, we'll end up with -128 to 127 that we want
1325 // to encode as 0..255 by adding 128, so we'll add that before the shift
1326 x0 += 65536 + (128<<17);
1327 x1 += 65536 + (128<<17);
1328 x2 += 65536 + (128<<17);
1329 x3 += 65536 + (128<<17);
1330 // tried computing the shifts into temps, or'ing the temps to see
1331 // if any were out of range, but that was slower
1332 o[0] = stbi__clamp((x0+t3) >> 17);
1333 o[7] = stbi__clamp((x0-t3) >> 17);
1334 o[1] = stbi__clamp((x1+t2) >> 17);
1335 o[6] = stbi__clamp((x1-t2) >> 17);
1336 o[2] = stbi__clamp((x2+t1) >> 17);
1337 o[5] = stbi__clamp((x2-t1) >> 17);
1338 o[3] = stbi__clamp((x3+t0) >> 17);
1339 o[4] = stbi__clamp((x3-t0) >> 17);
1340 }
1341 }
1342
1343 #ifdef STBI_SIMD
1344 static stbi_idct_8x8 stbi__idct_installed = stbi__idct_block;
1345
stbi_install_idct(stbi_idct_8x8 func)1346 STBIDEF void stbi_install_idct(stbi_idct_8x8 func)
1347 {
1348 stbi__idct_installed = func;
1349 }
1350 #endif
1351
1352 #define STBI__MARKER_none 0xff
1353 // if there's a pending marker from the entropy stream, return that
1354 // otherwise, fetch from the stream and get a marker. if there's no
1355 // marker, return 0xff, which is never a valid marker value
stbi__get_marker(stbi__jpeg * j)1356 static stbi_uc stbi__get_marker(stbi__jpeg *j)
1357 {
1358 stbi_uc x;
1359 if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }
1360 x = stbi__get8u(j->s);
1361 if (x != 0xff) return STBI__MARKER_none;
1362 while (x == 0xff)
1363 x = stbi__get8u(j->s);
1364 return x;
1365 }
1366
1367 // in each scan, we'll have scan_n components, and the order
1368 // of the components is specified by order[]
1369 #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
1370
1371 // after a restart interval, stbi__jpeg_reset the entropy decoder and
1372 // the dc prediction
stbi__jpeg_reset(stbi__jpeg * j)1373 static void stbi__jpeg_reset(stbi__jpeg *j)
1374 {
1375 j->code_bits = 0;
1376 j->code_buffer = 0;
1377 j->nomore = 0;
1378 j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
1379 j->marker = STBI__MARKER_none;
1380 j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
1381 // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
1382 // since we don't even allow 1<<30 pixels
1383 }
1384
stbi__parse_entropy_coded_data(stbi__jpeg * z)1385 static int stbi__parse_entropy_coded_data(stbi__jpeg *z)
1386 {
1387 stbi__jpeg_reset(z);
1388 if (z->scan_n == 1) {
1389 int i,j;
1390 #ifdef STBI_SIMD
1391 __declspec(align(16))
1392 #endif
1393 short data[64];
1394 int n = z->order[0];
1395 // non-interleaved data, we just need to process one block at a time,
1396 // in trivial scanline order
1397 // number of blocks to do just depends on how many actual "pixels" this
1398 // component has, independent of interleaved MCU blocking and such
1399 int w = (z->img_comp[n].x+7) >> 3;
1400 int h = (z->img_comp[n].y+7) >> 3;
1401 for (j=0; j < h; ++j) {
1402 for (i=0; i < w; ++i) {
1403 if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
1404 #ifdef STBI_SIMD
1405 stbi__idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
1406 #else
1407 stbi__idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
1408 #endif
1409 // every data block is an MCU, so countdown the restart interval
1410 if (--z->todo <= 0) {
1411 if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
1412 // if it's NOT a restart, then just bail, so we get corrupt data
1413 // rather than no data
1414 if (!STBI__RESTART(z->marker)) return 1;
1415 stbi__jpeg_reset(z);
1416 }
1417 }
1418 }
1419 } else { // interleaved!
1420 int i,j,k,x,y;
1421 short data[64];
1422 for (j=0; j < z->img_mcu_y; ++j) {
1423 for (i=0; i < z->img_mcu_x; ++i) {
1424 // scan an interleaved mcu... process scan_n components in order
1425 for (k=0; k < z->scan_n; ++k) {
1426 int n = z->order[k];
1427 // scan out an mcu's worth of this component; that's just determined
1428 // by the basic H and V specified for the component
1429 for (y=0; y < z->img_comp[n].v; ++y) {
1430 for (x=0; x < z->img_comp[n].h; ++x) {
1431 int x2 = (i*z->img_comp[n].h + x)*8;
1432 int y2 = (j*z->img_comp[n].v + y)*8;
1433 if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
1434 #ifdef STBI_SIMD
1435 stbi__idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
1436 #else
1437 stbi__idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
1438 #endif
1439 }
1440 }
1441 }
1442 // after all interleaved components, that's an interleaved MCU,
1443 // so now count down the restart interval
1444 if (--z->todo <= 0) {
1445 if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
1446 // if it's NOT a restart, then just bail, so we get corrupt data
1447 // rather than no data
1448 if (!STBI__RESTART(z->marker)) return 1;
1449 stbi__jpeg_reset(z);
1450 }
1451 }
1452 }
1453 }
1454 return 1;
1455 }
1456
stbi__process_marker(stbi__jpeg * z,int m)1457 static int stbi__process_marker(stbi__jpeg *z, int m)
1458 {
1459 int L;
1460 switch (m) {
1461 case STBI__MARKER_none: // no marker found
1462 return stbi__err("expected marker","Corrupt JPEG");
1463
1464 case 0xC2: // stbi__SOF - progressive
1465 return stbi__err("progressive jpeg","JPEG format not supported (progressive)");
1466
1467 case 0xDD: // DRI - specify restart interval
1468 if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG");
1469 z->restart_interval = stbi__get16be(z->s);
1470 return 1;
1471
1472 case 0xDB: // DQT - define quantization table
1473 L = stbi__get16be(z->s)-2;
1474 while (L > 0) {
1475 int q = stbi__get8(z->s);
1476 int p = q >> 4;
1477 int t = q & 15,i;
1478 if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG");
1479 if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG");
1480 for (i=0; i < 64; ++i)
1481 z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8u(z->s);
1482 #ifdef STBI_SIMD
1483 for (i=0; i < 64; ++i)
1484 z->dequant2[t][i] = z->dequant[t][i];
1485 #endif
1486 L -= 65;
1487 }
1488 return L==0;
1489
1490 case 0xC4: // DHT - define huffman table
1491 L = stbi__get16be(z->s)-2;
1492 while (L > 0) {
1493 stbi_uc *v;
1494 int sizes[16],i,n=0;
1495 int q = stbi__get8(z->s);
1496 int tc = q >> 4;
1497 int th = q & 15;
1498 if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG");
1499 for (i=0; i < 16; ++i) {
1500 sizes[i] = stbi__get8(z->s);
1501 n += sizes[i];
1502 }
1503 L -= 17;
1504 if (tc == 0) {
1505 if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;
1506 v = z->huff_dc[th].values;
1507 } else {
1508 if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;
1509 v = z->huff_ac[th].values;
1510 }
1511 for (i=0; i < n; ++i)
1512 v[i] = stbi__get8u(z->s);
1513 L -= n;
1514 }
1515 return L==0;
1516 }
1517 // check for comment block or APP blocks
1518 if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
1519 stbi__skip(z->s, stbi__get16be(z->s)-2);
1520 return 1;
1521 }
1522 return 0;
1523 }
1524
1525 // after we see stbi__SOS
stbi__process_scan_header(stbi__jpeg * z)1526 static int stbi__process_scan_header(stbi__jpeg *z)
1527 {
1528 int i;
1529 int Ls = stbi__get16be(z->s);
1530 z->scan_n = stbi__get8(z->s);
1531 if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad stbi__SOS component count","Corrupt JPEG");
1532 if (Ls != 6+2*z->scan_n) return stbi__err("bad stbi__SOS len","Corrupt JPEG");
1533 for (i=0; i < z->scan_n; ++i) {
1534 int id = stbi__get8(z->s), which;
1535 int q = stbi__get8(z->s);
1536 for (which = 0; which < z->s->img_n; ++which)
1537 if (z->img_comp[which].id == id)
1538 break;
1539 if (which == z->s->img_n) return 0;
1540 z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG");
1541 z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG");
1542 z->order[i] = which;
1543 }
1544 if (stbi__get8(z->s) != 0) return stbi__err("bad stbi__SOS","Corrupt JPEG");
1545 stbi__get8(z->s); // should be 63, but might be 0
1546 if (stbi__get8(z->s) != 0) return stbi__err("bad stbi__SOS","Corrupt JPEG");
1547
1548 return 1;
1549 }
1550
stbi__process_frame_header(stbi__jpeg * z,int scan)1551 static int stbi__process_frame_header(stbi__jpeg *z, int scan)
1552 {
1553 stbi__context *s = z->s;
1554 int Lf,p,i,q, h_max=1,v_max=1,c;
1555 Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad stbi__SOF len","Corrupt JPEG"); // JPEG
1556 p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
1557 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
1558 s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
1559 c = stbi__get8(s);
1560 if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires
1561 s->img_n = c;
1562 for (i=0; i < c; ++i) {
1563 z->img_comp[i].data = NULL;
1564 z->img_comp[i].linebuf = NULL;
1565 }
1566
1567 if (Lf != 8+3*s->img_n) return stbi__err("bad stbi__SOF len","Corrupt JPEG");
1568
1569 for (i=0; i < s->img_n; ++i) {
1570 z->img_comp[i].id = stbi__get8(s);
1571 if (z->img_comp[i].id != i+1) // JFIF requires
1572 if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!
1573 return stbi__err("bad component ID","Corrupt JPEG");
1574 q = stbi__get8(s);
1575 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");
1576 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");
1577 z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");
1578 }
1579
1580 if (scan != SCAN_load) return 1;
1581
1582 if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to stbi__jpeg_huff_decode");
1583
1584 for (i=0; i < s->img_n; ++i) {
1585 if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
1586 if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
1587 }
1588
1589 // compute interleaved mcu info
1590 z->img_h_max = h_max;
1591 z->img_v_max = v_max;
1592 z->img_mcu_w = h_max * 8;
1593 z->img_mcu_h = v_max * 8;
1594 z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
1595 z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
1596
1597 for (i=0; i < s->img_n; ++i) {
1598 // number of effective pixels (stbi__err.g. for non-interleaved MCU)
1599 z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
1600 z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
1601 // to simplify generation, we'll allocate enough memory to stbi__jpeg_huff_decode
1602 // the bogus oversized data from using interleaved MCUs and their
1603 // big blocks (stbi__err.g. a 16x16 iMCU on an image of width 33); we won't
1604 // discard the extra data until colorspace conversion
1605 z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
1606 z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
1607 z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
1608 if (z->img_comp[i].raw_data == NULL) {
1609 for(--i; i >= 0; --i) {
1610 free(z->img_comp[i].raw_data);
1611 z->img_comp[i].data = NULL;
1612 }
1613 return stbi__err("outofmem", "Out of memory");
1614 }
1615 // align blocks for installable-idct using mmx/sse
1616 z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
1617 z->img_comp[i].linebuf = NULL;
1618 }
1619
1620 return 1;
1621 }
1622
1623 // use comparisons since in some cases we handle more than one case (stbi__err.g. stbi__SOF)
1624 #define stbi__DNL(x) ((x) == 0xdc)
1625 #define stbi__SOI(x) ((x) == 0xd8)
1626 #define stbi__EOI(x) ((x) == 0xd9)
1627 #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1)
1628 #define stbi__SOS(x) ((x) == 0xda)
1629
decode_jpeg_header(stbi__jpeg * z,int scan)1630 static int decode_jpeg_header(stbi__jpeg *z, int scan)
1631 {
1632 int m;
1633 z->marker = STBI__MARKER_none; // initialize cached marker to empty
1634 m = stbi__get_marker(z);
1635 if (!stbi__SOI(m)) return stbi__err("no stbi__SOI","Corrupt JPEG");
1636 if (scan == SCAN_type) return 1;
1637 m = stbi__get_marker(z);
1638 while (!stbi__SOF(m)) {
1639 if (!stbi__process_marker(z,m)) return 0;
1640 m = stbi__get_marker(z);
1641 while (m == STBI__MARKER_none) {
1642 // some files have extra padding after their blocks, so ok, we'll scan
1643 if (stbi__at_eof(z->s)) return stbi__err("no stbi__SOF", "Corrupt JPEG");
1644 m = stbi__get_marker(z);
1645 }
1646 }
1647 if (!stbi__process_frame_header(z, scan)) return 0;
1648 return 1;
1649 }
1650
decode_jpeg_image(stbi__jpeg * j)1651 static int decode_jpeg_image(stbi__jpeg *j)
1652 {
1653 int m;
1654 j->restart_interval = 0;
1655 if (!decode_jpeg_header(j, SCAN_load)) return 0;
1656 m = stbi__get_marker(j);
1657 while (!stbi__EOI(m)) {
1658 if (stbi__SOS(m)) {
1659 if (!stbi__process_scan_header(j)) return 0;
1660 if (!stbi__parse_entropy_coded_data(j)) return 0;
1661 if (j->marker == STBI__MARKER_none ) {
1662 // handle 0s at the end of image data from IP Kamera 9060
1663 while (!stbi__at_eof(j->s)) {
1664 int x = stbi__get8(j->s);
1665 if (x == 255) {
1666 j->marker = stbi__get8u(j->s);
1667 break;
1668 } else if (x != 0) {
1669 return 0;
1670 }
1671 }
1672 // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0
1673 }
1674 } else {
1675 if (!stbi__process_marker(j, m)) return 0;
1676 }
1677 m = stbi__get_marker(j);
1678 }
1679 return 1;
1680 }
1681
1682 // static jfif-centered resampling (across block boundaries)
1683
1684 typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,
1685 int w, int hs);
1686
1687 #define stbi__div4(x) ((stbi_uc) ((x) >> 2))
1688
resample_row_1(stbi_uc * out,stbi_uc * in_near,stbi_uc * in_far,int w,int hs)1689 static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
1690 {
1691 STBI_NOTUSED(out);
1692 STBI_NOTUSED(in_far);
1693 STBI_NOTUSED(w);
1694 STBI_NOTUSED(hs);
1695 return in_near;
1696 }
1697
stbi__resample_row_v_2(stbi_uc * out,stbi_uc * in_near,stbi_uc * in_far,int w,int hs)1698 static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
1699 {
1700 // need to generate two samples vertically for every one in input
1701 int i;
1702 STBI_NOTUSED(hs);
1703 for (i=0; i < w; ++i)
1704 out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);
1705 return out;
1706 }
1707
stbi__resample_row_h_2(stbi_uc * out,stbi_uc * in_near,stbi_uc * in_far,int w,int hs)1708 static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
1709 {
1710 // need to generate two samples horizontally for every one in input
1711 int i;
1712 stbi_uc *input = in_near;
1713
1714 if (w == 1) {
1715 // if only one sample, can't do any interpolation
1716 out[0] = out[1] = input[0];
1717 return out;
1718 }
1719
1720 out[0] = input[0];
1721 out[1] = stbi__div4(input[0]*3 + input[1] + 2);
1722 for (i=1; i < w-1; ++i) {
1723 int n = 3*input[i]+2;
1724 out[i*2+0] = stbi__div4(n+input[i-1]);
1725 out[i*2+1] = stbi__div4(n+input[i+1]);
1726 }
1727 out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);
1728 out[i*2+1] = input[w-1];
1729
1730 STBI_NOTUSED(in_far);
1731 STBI_NOTUSED(hs);
1732
1733 return out;
1734 }
1735
1736 #define stbi__div16(x) ((stbi_uc) ((x) >> 4))
1737
stbi__resample_row_hv_2(stbi_uc * out,stbi_uc * in_near,stbi_uc * in_far,int w,int hs)1738 static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
1739 {
1740 // need to generate 2x2 samples for every one in input
1741 int i,t0,t1;
1742 if (w == 1) {
1743 out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
1744 return out;
1745 }
1746
1747 t1 = 3*in_near[0] + in_far[0];
1748 out[0] = stbi__div4(t1+2);
1749 for (i=1; i < w; ++i) {
1750 t0 = t1;
1751 t1 = 3*in_near[i]+in_far[i];
1752 out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
1753 out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
1754 }
1755 out[w*2-1] = stbi__div4(t1+2);
1756
1757 STBI_NOTUSED(hs);
1758
1759 return out;
1760 }
1761
stbi__resample_row_generic(stbi_uc * out,stbi_uc * in_near,stbi_uc * in_far,int w,int hs)1762 static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
1763 {
1764 // resample with nearest-neighbor
1765 int i,j;
1766 STBI_NOTUSED(in_far);
1767 for (i=0; i < w; ++i)
1768 for (j=0; j < hs; ++j)
1769 out[i*hs+j] = in_near[i];
1770 return out;
1771 }
1772
1773 #define float2fixed(x) ((int) ((x) * 65536 + 0.5))
1774
1775 // 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro)
1776 // VC6 without processor=Pro is generating multiple LEAs per multiply!
stbi__YCbCr_to_RGB_row(stbi_uc * out,const stbi_uc * y,const stbi_uc * pcb,const stbi_uc * pcr,int count,int step)1777 static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)
1778 {
1779 int i;
1780 for (i=0; i < count; ++i) {
1781 int y_fixed = (y[i] << 16) + 32768; // rounding
1782 int r,g,b;
1783 int cr = pcr[i] - 128;
1784 int cb = pcb[i] - 128;
1785 r = y_fixed + cr*float2fixed(1.40200f);
1786 g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
1787 b = y_fixed + cb*float2fixed(1.77200f);
1788 r >>= 16;
1789 g >>= 16;
1790 b >>= 16;
1791 if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
1792 if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
1793 if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
1794 out[0] = (stbi_uc)r;
1795 out[1] = (stbi_uc)g;
1796 out[2] = (stbi_uc)b;
1797 out[3] = 255;
1798 out += step;
1799 }
1800 }
1801
1802 #ifdef STBI_SIMD
1803 static stbi_YCbCr_to_RGB_run stbi__YCbCr_installed = stbi__YCbCr_to_RGB_row;
1804
stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)1805 STBIDEF void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
1806 {
1807 stbi__YCbCr_installed = func;
1808 }
1809 #endif
1810
1811
1812 // clean up the temporary component buffers
stbi__cleanup_jpeg(stbi__jpeg * j)1813 static void stbi__cleanup_jpeg(stbi__jpeg *j)
1814 {
1815 int i;
1816 for (i=0; i < j->s->img_n; ++i) {
1817 if (j->img_comp[i].data) {
1818 free(j->img_comp[i].raw_data);
1819 j->img_comp[i].data = NULL;
1820 }
1821 if (j->img_comp[i].linebuf) {
1822 free(j->img_comp[i].linebuf);
1823 j->img_comp[i].linebuf = NULL;
1824 }
1825 }
1826 }
1827
1828 typedef struct
1829 {
1830 resample_row_func resample;
1831 stbi_uc *line0,*line1;
1832 int hs,vs; // expansion factor in each axis
1833 int w_lores; // horizontal pixels pre-expansion
1834 int ystep; // how far through vertical expansion we are
1835 int ypos; // which pre-expansion row we're on
1836 } stbi__resample;
1837
load_jpeg_image(stbi__jpeg * z,int * out_x,int * out_y,int * comp,int req_comp)1838 static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
1839 {
1840 int n, decode_n;
1841 // validate req_comp
1842 if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
1843 z->s->img_n = 0;
1844
1845 // load a jpeg image from whichever source
1846 if (!decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }
1847
1848 // determine actual number of components to generate
1849 n = req_comp ? req_comp : z->s->img_n;
1850
1851 if (z->s->img_n == 3 && n < 3)
1852 decode_n = 1;
1853 else
1854 decode_n = z->s->img_n;
1855
1856 // resample and color-convert
1857 {
1858 int k;
1859 unsigned int i,j;
1860 stbi_uc *output;
1861 stbi_uc *coutput[4];
1862
1863 stbi__resample res_comp[4];
1864
1865 for (k=0; k < decode_n; ++k) {
1866 stbi__resample *r = &res_comp[k];
1867
1868 // allocate line buffer big enough for upsampling off the edges
1869 // with upsample factor of 4
1870 z->img_comp[k].linebuf = (stbi_uc *) malloc(z->s->img_x + 3);
1871 if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
1872
1873 r->hs = z->img_h_max / z->img_comp[k].h;
1874 r->vs = z->img_v_max / z->img_comp[k].v;
1875 r->ystep = r->vs >> 1;
1876 r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
1877 r->ypos = 0;
1878 r->line0 = r->line1 = z->img_comp[k].data;
1879
1880 if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
1881 else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;
1882 else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;
1883 else if (r->hs == 2 && r->vs == 2) r->resample = stbi__resample_row_hv_2;
1884 else r->resample = stbi__resample_row_generic;
1885 }
1886
1887 // can't error after this so, this is safe
1888 output = (stbi_uc *) malloc(n * z->s->img_x * z->s->img_y + 1);
1889 if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
1890
1891 // now go ahead and resample
1892 for (j=0; j < z->s->img_y; ++j) {
1893 stbi_uc *out = output + n * z->s->img_x * j;
1894 for (k=0; k < decode_n; ++k) {
1895 stbi__resample *r = &res_comp[k];
1896 int y_bot = r->ystep >= (r->vs >> 1);
1897 coutput[k] = r->resample(z->img_comp[k].linebuf,
1898 y_bot ? r->line1 : r->line0,
1899 y_bot ? r->line0 : r->line1,
1900 r->w_lores, r->hs);
1901 if (++r->ystep >= r->vs) {
1902 r->ystep = 0;
1903 r->line0 = r->line1;
1904 if (++r->ypos < z->img_comp[k].y)
1905 r->line1 += z->img_comp[k].w2;
1906 }
1907 }
1908 if (n >= 3) {
1909 stbi_uc *y = coutput[0];
1910 if (z->s->img_n == 3) {
1911 #ifdef STBI_SIMD
1912 stbi__YCbCr_installed(out, y, coutput[1], coutput[2], z->s->img_x, n);
1913 #else
1914 stbi__YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);
1915 #endif
1916 } else
1917 for (i=0; i < z->s->img_x; ++i) {
1918 out[0] = out[1] = out[2] = y[i];
1919 out[3] = 255; // not used if n==3
1920 out += n;
1921 }
1922 } else {
1923 stbi_uc *y = coutput[0];
1924 if (n == 1)
1925 for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
1926 else
1927 for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;
1928 }
1929 }
1930 stbi__cleanup_jpeg(z);
1931 *out_x = z->s->img_x;
1932 *out_y = z->s->img_y;
1933 if (comp) *comp = z->s->img_n; // report original components, not output
1934 return output;
1935 }
1936 }
1937
stbi__jpeg_load(stbi__context * s,int * x,int * y,int * comp,int req_comp)1938 static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
1939 {
1940 stbi__jpeg j;
1941 j.s = s;
1942 return load_jpeg_image(&j, x,y,comp,req_comp);
1943 }
1944
stbi__jpeg_test(stbi__context * s)1945 static int stbi__jpeg_test(stbi__context *s)
1946 {
1947 int r;
1948 stbi__jpeg j;
1949 j.s = s;
1950 r = decode_jpeg_header(&j, SCAN_type);
1951 stbi__rewind(s);
1952 return r;
1953 }
1954
stbi__jpeg_info_raw(stbi__jpeg * j,int * x,int * y,int * comp)1955 static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)
1956 {
1957 if (!decode_jpeg_header(j, SCAN_header)) {
1958 stbi__rewind( j->s );
1959 return 0;
1960 }
1961 if (x) *x = j->s->img_x;
1962 if (y) *y = j->s->img_y;
1963 if (comp) *comp = j->s->img_n;
1964 return 1;
1965 }
1966
stbi__jpeg_info(stbi__context * s,int * x,int * y,int * comp)1967 static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
1968 {
1969 stbi__jpeg j;
1970 j.s = s;
1971 return stbi__jpeg_info_raw(&j, x, y, comp);
1972 }
1973
1974 // public domain zlib stbi__jpeg_huff_decode v0.2 Sean Barrett 2006-11-18
1975 // simple implementation
1976 // - all input must be provided in an upfront buffer
1977 // - all output is written to a single output buffer (can malloc/realloc)
1978 // performance
1979 // - fast huffman
1980
1981 // fast-way is faster to check than jpeg huffman, but slow way is slower
1982 #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
1983 #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
1984
1985 // zlib-style huffman encoding
1986 // (jpegs packs from left, zlib from right, so can't share code)
1987 typedef struct
1988 {
1989 stbi__uint16 fast[1 << STBI__ZFAST_BITS];
1990 stbi__uint16 firstcode[16];
1991 int maxcode[17];
1992 stbi__uint16 firstsymbol[16];
1993 stbi_uc size[288];
1994 stbi__uint16 value[288];
1995 } stbi__zhuffman;
1996
stbi__bitreverse16(int n)1997 stbi_inline static int stbi__bitreverse16(int n)
1998 {
1999 n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
2000 n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
2001 n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
2002 n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
2003 return n;
2004 }
2005
stbi__bit_reverse(int v,int bits)2006 stbi_inline static int stbi__bit_reverse(int v, int bits)
2007 {
2008 assert(bits <= 16);
2009 // to bit reverse n bits, reverse 16 and shift
2010 // stbi__err.g. 11 bits, bit reverse and shift away 5
2011 return stbi__bitreverse16(v) >> (16-bits);
2012 }
2013
stbi__zbuild_huffman(stbi__zhuffman * z,stbi_uc * sizelist,int num)2014 static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num)
2015 {
2016 int i,k=0;
2017 int code, next_code[16], sizes[17];
2018
2019 // DEFLATE spec for generating codes
2020 memset(sizes, 0, sizeof(sizes));
2021 memset(z->fast, 255, sizeof(z->fast));
2022 for (i=0; i < num; ++i)
2023 ++sizes[sizelist[i]];
2024 sizes[0] = 0;
2025 for (i=1; i < 16; ++i)
2026 assert(sizes[i] <= (1 << i));
2027 code = 0;
2028 for (i=1; i < 16; ++i) {
2029 next_code[i] = code;
2030 z->firstcode[i] = (stbi__uint16) code;
2031 z->firstsymbol[i] = (stbi__uint16) k;
2032 code = (code + sizes[i]);
2033 if (sizes[i])
2034 if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt JPEG");
2035 z->maxcode[i] = code << (16-i); // preshift for inner loop
2036 code <<= 1;
2037 k += sizes[i];
2038 }
2039 z->maxcode[16] = 0x10000; // sentinel
2040 for (i=0; i < num; ++i) {
2041 int s = sizelist[i];
2042 if (s) {
2043 int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
2044 z->size[c] = (stbi_uc)s;
2045 z->value[c] = (stbi__uint16)i;
2046 if (s <= STBI__ZFAST_BITS) {
2047 int k = stbi__bit_reverse(next_code[s],s);
2048 while (k < (1 << STBI__ZFAST_BITS)) {
2049 z->fast[k] = (stbi__uint16) c;
2050 k += (1 << s);
2051 }
2052 }
2053 ++next_code[s];
2054 }
2055 }
2056 return 1;
2057 }
2058
2059 // zlib-from-memory implementation for PNG reading
2060 // because PNG allows splitting the zlib stream arbitrarily,
2061 // and it's annoying structurally to have PNG call ZLIB call PNG,
2062 // we require PNG read all the IDATs and combine them into a single
2063 // memory buffer
2064
2065 typedef struct
2066 {
2067 stbi_uc *zbuffer, *zbuffer_end;
2068 int num_bits;
2069 stbi__uint32 code_buffer;
2070
2071 char *zout;
2072 char *zout_start;
2073 char *zout_end;
2074 int z_expandable;
2075
2076 stbi__zhuffman z_length, z_distance;
2077 } stbi__zbuf;
2078
stbi__zget8(stbi__zbuf * z)2079 stbi_inline static int stbi__zget8(stbi__zbuf *z)
2080 {
2081 if (z->zbuffer >= z->zbuffer_end) return 0;
2082 return *z->zbuffer++;
2083 }
2084
stbi__fill_bits(stbi__zbuf * z)2085 static void stbi__fill_bits(stbi__zbuf *z)
2086 {
2087 do {
2088 assert(z->code_buffer < (1U << z->num_bits));
2089 z->code_buffer |= stbi__zget8(z) << z->num_bits;
2090 z->num_bits += 8;
2091 } while (z->num_bits <= 24);
2092 }
2093
stbi__zreceive(stbi__zbuf * z,int n)2094 stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)
2095 {
2096 unsigned int k;
2097 if (z->num_bits < n) stbi__fill_bits(z);
2098 k = z->code_buffer & ((1 << n) - 1);
2099 z->code_buffer >>= n;
2100 z->num_bits -= n;
2101 return k;
2102 }
2103
stbi__zhuffman_decode(stbi__zbuf * a,stbi__zhuffman * z)2104 stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
2105 {
2106 int b,s,k;
2107 if (a->num_bits < 16) stbi__fill_bits(a);
2108 b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
2109 if (b < 0xffff) {
2110 s = z->size[b];
2111 a->code_buffer >>= s;
2112 a->num_bits -= s;
2113 return z->value[b];
2114 }
2115
2116 // not resolved by fast table, so compute it the slow way
2117 // use jpeg approach, which requires MSbits at top
2118 k = stbi__bit_reverse(a->code_buffer, 16);
2119 for (s=STBI__ZFAST_BITS+1; ; ++s)
2120 if (k < z->maxcode[s])
2121 break;
2122 if (s == 16) return -1; // invalid code!
2123 // code size is s, so:
2124 b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
2125 assert(z->size[b] == s);
2126 a->code_buffer >>= s;
2127 a->num_bits -= s;
2128 return z->value[b];
2129 }
2130
stbi__zexpand(stbi__zbuf * z,int n)2131 static int stbi__zexpand(stbi__zbuf *z, int n) // need to make room for n bytes
2132 {
2133 char *q;
2134 int cur, limit;
2135 if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
2136 cur = (int) (z->zout - z->zout_start);
2137 limit = (int) (z->zout_end - z->zout_start);
2138 while (cur + n > limit)
2139 limit *= 2;
2140 q = (char *) realloc(z->zout_start, limit);
2141 if (q == NULL) return stbi__err("outofmem", "Out of memory");
2142 z->zout_start = q;
2143 z->zout = q + cur;
2144 z->zout_end = q + limit;
2145 return 1;
2146 }
2147
2148 static int stbi__zlength_base[31] = {
2149 3,4,5,6,7,8,9,10,11,13,
2150 15,17,19,23,27,31,35,43,51,59,
2151 67,83,99,115,131,163,195,227,258,0,0 };
2152
2153 static int stbi__zlength_extra[31]=
2154 { 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 };
2155
2156 static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
2157 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
2158
2159 static int stbi__zdist_extra[32] =
2160 { 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};
2161
stbi__parse_huffman_block(stbi__zbuf * a)2162 static int stbi__parse_huffman_block(stbi__zbuf *a)
2163 {
2164 for(;;) {
2165 int z = stbi__zhuffman_decode(a, &a->z_length);
2166 if (z < 256) {
2167 if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes
2168 if (a->zout >= a->zout_end) if (!stbi__zexpand(a, 1)) return 0;
2169 *a->zout++ = (char) z;
2170 } else {
2171 stbi_uc *p;
2172 int len,dist;
2173 if (z == 256) return 1;
2174 z -= 257;
2175 len = stbi__zlength_base[z];
2176 if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
2177 z = stbi__zhuffman_decode(a, &a->z_distance);
2178 if (z < 0) return stbi__err("bad huffman code","Corrupt PNG");
2179 dist = stbi__zdist_base[z];
2180 if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
2181 if (a->zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");
2182 if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, len)) return 0;
2183 p = (stbi_uc *) (a->zout - dist);
2184 while (len--)
2185 *a->zout++ = *p++;
2186 }
2187 }
2188 }
2189
stbi__compute_huffman_codes(stbi__zbuf * a)2190 static int stbi__compute_huffman_codes(stbi__zbuf *a)
2191 {
2192 static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
2193 stbi__zhuffman z_codelength;
2194 stbi_uc lencodes[286+32+137];//padding for maximum single op
2195 stbi_uc codelength_sizes[19];
2196 int i,n;
2197
2198 int hlit = stbi__zreceive(a,5) + 257;
2199 int hdist = stbi__zreceive(a,5) + 1;
2200 int hclen = stbi__zreceive(a,4) + 4;
2201
2202 memset(codelength_sizes, 0, sizeof(codelength_sizes));
2203 for (i=0; i < hclen; ++i) {
2204 int s = stbi__zreceive(a,3);
2205 codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;
2206 }
2207 if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
2208
2209 n = 0;
2210 while (n < hlit + hdist) {
2211 int c = stbi__zhuffman_decode(a, &z_codelength);
2212 assert(c >= 0 && c < 19);
2213 if (c < 16)
2214 lencodes[n++] = (stbi_uc) c;
2215 else if (c == 16) {
2216 c = stbi__zreceive(a,2)+3;
2217 memset(lencodes+n, lencodes[n-1], c);
2218 n += c;
2219 } else if (c == 17) {
2220 c = stbi__zreceive(a,3)+3;
2221 memset(lencodes+n, 0, c);
2222 n += c;
2223 } else {
2224 assert(c == 18);
2225 c = stbi__zreceive(a,7)+11;
2226 memset(lencodes+n, 0, c);
2227 n += c;
2228 }
2229 }
2230 if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG");
2231 if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
2232 if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
2233 return 1;
2234 }
2235
stbi__parse_uncomperssed_block(stbi__zbuf * a)2236 static int stbi__parse_uncomperssed_block(stbi__zbuf *a)
2237 {
2238 stbi_uc header[4];
2239 int len,nlen,k;
2240 if (a->num_bits & 7)
2241 stbi__zreceive(a, a->num_bits & 7); // discard
2242 // drain the bit-packed data into header
2243 k = 0;
2244 while (a->num_bits > 0) {
2245 header[k++] = (stbi_uc) (a->code_buffer & 255); // wtf this warns?
2246 a->code_buffer >>= 8;
2247 a->num_bits -= 8;
2248 }
2249 assert(a->num_bits == 0);
2250 // now fill header the normal way
2251 while (k < 4)
2252 header[k++] = (stbi_uc) stbi__zget8(a);
2253 len = header[1] * 256 + header[0];
2254 nlen = header[3] * 256 + header[2];
2255 if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");
2256 if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");
2257 if (a->zout + len > a->zout_end)
2258 if (!stbi__zexpand(a, len)) return 0;
2259 memcpy(a->zout, a->zbuffer, len);
2260 a->zbuffer += len;
2261 a->zout += len;
2262 return 1;
2263 }
2264
stbi__parse_zlib_header(stbi__zbuf * a)2265 static int stbi__parse_zlib_header(stbi__zbuf *a)
2266 {
2267 int cmf = stbi__zget8(a);
2268 int cm = cmf & 15;
2269 /* int cinfo = cmf >> 4; */
2270 int flg = stbi__zget8(a);
2271 if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
2272 if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
2273 if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png
2274 // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
2275 return 1;
2276 }
2277
2278 // @TODO: should statically initialize these for optimal thread safety
2279 static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32];
stbi__init_zdefaults(void)2280 static void stbi__init_zdefaults(void)
2281 {
2282 int i; // use <= to match clearly with spec
2283 for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
2284 for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
2285 for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
2286 for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
2287
2288 for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
2289 }
2290
stbi__parse_zlib(stbi__zbuf * a,int parse_header)2291 static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
2292 {
2293 int final, type;
2294 if (parse_header)
2295 if (!stbi__parse_zlib_header(a)) return 0;
2296 a->num_bits = 0;
2297 a->code_buffer = 0;
2298 do {
2299 final = stbi__zreceive(a,1);
2300 type = stbi__zreceive(a,2);
2301 if (type == 0) {
2302 if (!stbi__parse_uncomperssed_block(a)) return 0;
2303 } else if (type == 3) {
2304 return 0;
2305 } else {
2306 if (type == 1) {
2307 // use fixed code lengths
2308 if (!stbi__zdefault_distance[31]) stbi__init_zdefaults();
2309 if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0;
2310 if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;
2311 } else {
2312 if (!stbi__compute_huffman_codes(a)) return 0;
2313 }
2314 if (!stbi__parse_huffman_block(a)) return 0;
2315 }
2316 } while (!final);
2317 return 1;
2318 }
2319
stbi__do_zlib(stbi__zbuf * a,char * obuf,int olen,int exp,int parse_header)2320 static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)
2321 {
2322 a->zout_start = obuf;
2323 a->zout = obuf;
2324 a->zout_end = obuf + olen;
2325 a->z_expandable = exp;
2326
2327 return stbi__parse_zlib(a, parse_header);
2328 }
2329
stbi_zlib_decode_malloc_guesssize(const char * buffer,int len,int initial_size,int * outlen)2330 STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
2331 {
2332 stbi__zbuf a;
2333 char *p = (char *) malloc(initial_size);
2334 if (p == NULL) return NULL;
2335 a.zbuffer = (stbi_uc *) buffer;
2336 a.zbuffer_end = (stbi_uc *) buffer + len;
2337 if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {
2338 if (outlen) *outlen = (int) (a.zout - a.zout_start);
2339 return a.zout_start;
2340 } else {
2341 free(a.zout_start);
2342 return NULL;
2343 }
2344 }
2345
stbi_zlib_decode_malloc(char const * buffer,int len,int * outlen)2346 STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
2347 {
2348 return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
2349 }
2350
stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer,int len,int initial_size,int * outlen,int parse_header)2351 STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
2352 {
2353 stbi__zbuf a;
2354 char *p = (char *) malloc(initial_size);
2355 if (p == NULL) return NULL;
2356 a.zbuffer = (stbi_uc *) buffer;
2357 a.zbuffer_end = (stbi_uc *) buffer + len;
2358 if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {
2359 if (outlen) *outlen = (int) (a.zout - a.zout_start);
2360 return a.zout_start;
2361 } else {
2362 free(a.zout_start);
2363 return NULL;
2364 }
2365 }
2366
stbi_zlib_decode_buffer(char * obuffer,int olen,char const * ibuffer,int ilen)2367 STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
2368 {
2369 stbi__zbuf a;
2370 a.zbuffer = (stbi_uc *) ibuffer;
2371 a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
2372 if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
2373 return (int) (a.zout - a.zout_start);
2374 else
2375 return -1;
2376 }
2377
stbi_zlib_decode_noheader_malloc(char const * buffer,int len,int * outlen)2378 STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
2379 {
2380 stbi__zbuf a;
2381 char *p = (char *) malloc(16384);
2382 if (p == NULL) return NULL;
2383 a.zbuffer = (stbi_uc *) buffer;
2384 a.zbuffer_end = (stbi_uc *) buffer+len;
2385 if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
2386 if (outlen) *outlen = (int) (a.zout - a.zout_start);
2387 return a.zout_start;
2388 } else {
2389 free(a.zout_start);
2390 return NULL;
2391 }
2392 }
2393
stbi_zlib_decode_noheader_buffer(char * obuffer,int olen,const char * ibuffer,int ilen)2394 STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
2395 {
2396 stbi__zbuf a;
2397 a.zbuffer = (stbi_uc *) ibuffer;
2398 a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
2399 if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
2400 return (int) (a.zout - a.zout_start);
2401 else
2402 return -1;
2403 }
2404
2405 // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
2406 // simple implementation
2407 // - only 8-bit samples
2408 // - no CRC checking
2409 // - allocates lots of intermediate memory
2410 // - avoids problem of streaming data between subsystems
2411 // - avoids explicit window management
2412 // performance
2413 // - uses stb_zlib, a PD zlib implementation with fast huffman decoding
2414
2415
2416 typedef struct
2417 {
2418 stbi__uint32 length;
2419 stbi__uint32 type;
2420 } stbi__pngchunk;
2421
2422 #define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
2423
stbi__get_chunk_header(stbi__context * s)2424 static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
2425 {
2426 stbi__pngchunk c;
2427 c.length = stbi__get32be(s);
2428 c.type = stbi__get32be(s);
2429 return c;
2430 }
2431
stbi__check_png_header(stbi__context * s)2432 static int stbi__check_png_header(stbi__context *s)
2433 {
2434 static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };
2435 int i;
2436 for (i=0; i < 8; ++i)
2437 if (stbi__get8u(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");
2438 return 1;
2439 }
2440
2441 typedef struct
2442 {
2443 stbi__context *s;
2444 stbi_uc *idata, *expanded, *out;
2445 } stbi__png;
2446
2447
2448 enum {
2449 STBI__F_none=0, STBI__F_sub=1, STBI__F_up=2, STBI__F_avg=3, STBI__F_paeth=4,
2450 STBI__F_avg_first, STBI__F_paeth_first
2451 };
2452
2453 static stbi_uc first_row_filter[5] =
2454 {
2455 STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first
2456 };
2457
stbi__paeth(int a,int b,int c)2458 static int stbi__paeth(int a, int b, int c)
2459 {
2460 int p = a + b - c;
2461 int pa = abs(p-a);
2462 int pb = abs(p-b);
2463 int pc = abs(p-c);
2464 if (pa <= pb && pa <= pc) return a;
2465 if (pb <= pc) return b;
2466 return c;
2467 }
2468
2469 // create the png data from post-deflated data
stbi__create_png_image_raw(stbi__png * a,stbi_uc * raw,stbi__uint32 raw_len,int out_n,stbi__uint32 x,stbi__uint32 y)2470 static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y)
2471 {
2472 stbi__context *s = a->s;
2473 stbi__uint32 i,j,stride = x*out_n;
2474 int k;
2475 int img_n = s->img_n; // copy it into a local for later
2476 assert(out_n == s->img_n || out_n == s->img_n+1);
2477 a->out = (stbi_uc *) malloc(x * y * out_n);
2478 if (!a->out) return stbi__err("outofmem", "Out of memory");
2479 if (s->img_x == x && s->img_y == y) {
2480 if (raw_len != (img_n * x + 1) * y) return stbi__err("not enough pixels","Corrupt PNG");
2481 } else { // interlaced:
2482 if (raw_len < (img_n * x + 1) * y) return stbi__err("not enough pixels","Corrupt PNG");
2483 }
2484 for (j=0; j < y; ++j) {
2485 stbi_uc *cur = a->out + stride*j;
2486 stbi_uc *prior = cur - stride;
2487 int filter = *raw++;
2488 if (filter > 4) return stbi__err("invalid filter","Corrupt PNG");
2489 // if first row, use special filter that doesn't sample previous row
2490 if (j == 0) filter = first_row_filter[filter];
2491 // handle first pixel explicitly
2492 for (k=0; k < img_n; ++k) {
2493 switch (filter) {
2494 case STBI__F_none : cur[k] = raw[k]; break;
2495 case STBI__F_sub : cur[k] = raw[k]; break;
2496 case STBI__F_up : cur[k] = raw[k] + prior[k]; break;
2497 case STBI__F_avg : cur[k] = raw[k] + (prior[k]>>1); break;
2498 case STBI__F_paeth : cur[k] = (stbi_uc) (raw[k] + stbi__paeth(0,prior[k],0)); break;
2499 case STBI__F_avg_first : cur[k] = raw[k]; break;
2500 case STBI__F_paeth_first: cur[k] = raw[k]; break;
2501 }
2502 }
2503 if (img_n != out_n) cur[img_n] = 255;
2504 raw += img_n;
2505 cur += out_n;
2506 prior += out_n;
2507 // this is a little gross, so that we don't switch per-pixel or per-component
2508 if (img_n == out_n) {
2509 #define CASE(f) \
2510 case f: \
2511 for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \
2512 for (k=0; k < img_n; ++k)
2513 switch (filter) {
2514 CASE(STBI__F_none) cur[k] = raw[k]; break;
2515 CASE(STBI__F_sub) cur[k] = raw[k] + cur[k-img_n]; break;
2516 CASE(STBI__F_up) cur[k] = raw[k] + prior[k]; break;
2517 CASE(STBI__F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;
2518 CASE(STBI__F_paeth) cur[k] = (stbi_uc) (raw[k] + stbi__paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
2519 CASE(STBI__F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;
2520 CASE(STBI__F_paeth_first) cur[k] = (stbi_uc) (raw[k] + stbi__paeth(cur[k-img_n],0,0)); break;
2521 }
2522 #undef CASE
2523 } else {
2524 assert(img_n+1 == out_n);
2525 #define CASE(f) \
2526 case f: \
2527 for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
2528 for (k=0; k < img_n; ++k)
2529 switch (filter) {
2530 CASE(STBI__F_none) cur[k] = raw[k]; break;
2531 CASE(STBI__F_sub) cur[k] = raw[k] + cur[k-out_n]; break;
2532 CASE(STBI__F_up) cur[k] = raw[k] + prior[k]; break;
2533 CASE(STBI__F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;
2534 CASE(STBI__F_paeth) cur[k] = (stbi_uc) (raw[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
2535 CASE(STBI__F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;
2536 CASE(STBI__F_paeth_first) cur[k] = (stbi_uc) (raw[k] + stbi__paeth(cur[k-out_n],0,0)); break;
2537 }
2538 #undef CASE
2539 }
2540 }
2541 return 1;
2542 }
2543
stbi__create_png_image(stbi__png * a,stbi_uc * raw,stbi__uint32 raw_len,int out_n,int interlaced)2544 static int stbi__create_png_image(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, int interlaced)
2545 {
2546 stbi_uc *final;
2547 int p;
2548 if (!interlaced)
2549 return stbi__create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);
2550
2551 // de-interlacing
2552 final = (stbi_uc *) malloc(a->s->img_x * a->s->img_y * out_n);
2553 for (p=0; p < 7; ++p) {
2554 int xorig[] = { 0,4,0,2,0,1,0 };
2555 int yorig[] = { 0,0,4,0,2,0,1 };
2556 int xspc[] = { 8,8,4,4,2,2,1 };
2557 int yspc[] = { 8,8,8,4,4,2,2 };
2558 int i,j,x,y;
2559 // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
2560 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
2561 y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
2562 if (x && y) {
2563 if (!stbi__create_png_image_raw(a, raw, raw_len, out_n, x, y)) {
2564 free(final);
2565 return 0;
2566 }
2567 for (j=0; j < y; ++j)
2568 for (i=0; i < x; ++i)
2569 memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,
2570 a->out + (j*x+i)*out_n, out_n);
2571 free(a->out);
2572 raw += (x*out_n+1)*y;
2573 raw_len -= (x*out_n+1)*y;
2574 }
2575 }
2576 a->out = final;
2577
2578 return 1;
2579 }
2580
stbi__compute_transparency(stbi__png * z,stbi_uc tc[3],int out_n)2581 static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)
2582 {
2583 stbi__context *s = z->s;
2584 stbi__uint32 i, pixel_count = s->img_x * s->img_y;
2585 stbi_uc *p = z->out;
2586
2587 // compute color-based transparency, assuming we've
2588 // already got 255 as the alpha value in the output
2589 assert(out_n == 2 || out_n == 4);
2590
2591 if (out_n == 2) {
2592 for (i=0; i < pixel_count; ++i) {
2593 p[1] = (p[0] == tc[0] ? 0 : 255);
2594 p += 2;
2595 }
2596 } else {
2597 for (i=0; i < pixel_count; ++i) {
2598 if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
2599 p[3] = 0;
2600 p += 4;
2601 }
2602 }
2603 return 1;
2604 }
2605
stbi__expand_png_palette(stbi__png * a,stbi_uc * palette,int len,int pal_img_n)2606 static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)
2607 {
2608 stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
2609 stbi_uc *p, *temp_out, *orig = a->out;
2610
2611 p = (stbi_uc *) malloc(pixel_count * pal_img_n);
2612 if (p == NULL) return stbi__err("outofmem", "Out of memory");
2613
2614 // between here and free(out) below, exitting would leak
2615 temp_out = p;
2616
2617 if (pal_img_n == 3) {
2618 for (i=0; i < pixel_count; ++i) {
2619 int n = orig[i]*4;
2620 p[0] = palette[n ];
2621 p[1] = palette[n+1];
2622 p[2] = palette[n+2];
2623 p += 3;
2624 }
2625 } else {
2626 for (i=0; i < pixel_count; ++i) {
2627 int n = orig[i]*4;
2628 p[0] = palette[n ];
2629 p[1] = palette[n+1];
2630 p[2] = palette[n+2];
2631 p[3] = palette[n+3];
2632 p += 4;
2633 }
2634 }
2635 free(a->out);
2636 a->out = temp_out;
2637
2638 STBI_NOTUSED(len);
2639
2640 return 1;
2641 }
2642
2643 static int stbi__unpremultiply_on_load = 0;
2644 static int stbi__de_iphone_flag = 0;
2645
stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)2646 STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
2647 {
2648 stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply;
2649 }
2650
stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)2651 STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
2652 {
2653 stbi__de_iphone_flag = flag_true_if_should_convert;
2654 }
2655
stbi__de_iphone(stbi__png * z)2656 static void stbi__de_iphone(stbi__png *z)
2657 {
2658 stbi__context *s = z->s;
2659 stbi__uint32 i, pixel_count = s->img_x * s->img_y;
2660 stbi_uc *p = z->out;
2661
2662 if (s->img_out_n == 3) { // convert bgr to rgb
2663 for (i=0; i < pixel_count; ++i) {
2664 stbi_uc t = p[0];
2665 p[0] = p[2];
2666 p[2] = t;
2667 p += 3;
2668 }
2669 } else {
2670 assert(s->img_out_n == 4);
2671 if (stbi__unpremultiply_on_load) {
2672 // convert bgr to rgb and unpremultiply
2673 for (i=0; i < pixel_count; ++i) {
2674 stbi_uc a = p[3];
2675 stbi_uc t = p[0];
2676 if (a) {
2677 p[0] = p[2] * 255 / a;
2678 p[1] = p[1] * 255 / a;
2679 p[2] = t * 255 / a;
2680 } else {
2681 p[0] = p[2];
2682 p[2] = t;
2683 }
2684 p += 4;
2685 }
2686 } else {
2687 // convert bgr to rgb
2688 for (i=0; i < pixel_count; ++i) {
2689 stbi_uc t = p[0];
2690 p[0] = p[2];
2691 p[2] = t;
2692 p += 4;
2693 }
2694 }
2695 }
2696 }
2697
stbi__parse_png_file(stbi__png * z,int scan,int req_comp)2698 static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
2699 {
2700 stbi_uc palette[1024], pal_img_n=0;
2701 stbi_uc has_trans=0, tc[3];
2702 stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;
2703 int first=1,k,interlace=0, is_iphone=0;
2704 stbi__context *s = z->s;
2705
2706 z->expanded = NULL;
2707 z->idata = NULL;
2708 z->out = NULL;
2709
2710 if (!stbi__check_png_header(s)) return 0;
2711
2712 if (scan == SCAN_type) return 1;
2713
2714 for (;;) {
2715 stbi__pngchunk c = stbi__get_chunk_header(s);
2716 switch (c.type) {
2717 case PNG_TYPE('C','g','B','I'):
2718 is_iphone = 1;
2719 stbi__skip(s, c.length);
2720 break;
2721 case PNG_TYPE('I','H','D','R'): {
2722 int depth,color,comp,filter;
2723 if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
2724 first = 0;
2725 if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
2726 s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
2727 s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
2728 depth = stbi__get8(s); if (depth != 8) return stbi__err("8bit only","PNG not supported: 8-bit only");
2729 color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");
2730 if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");
2731 comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");
2732 filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");
2733 interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");
2734 if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");
2735 if (!pal_img_n) {
2736 s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
2737 if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to stbi__jpeg_huff_decode");
2738 if (scan == SCAN_header) return 1;
2739 } else {
2740 // if paletted, then pal_n is our final components, and
2741 // img_n is # components to decompress/filter.
2742 s->img_n = 1;
2743 if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");
2744 // if SCAN_header, have to scan to see if we have a tRNS
2745 }
2746 break;
2747 }
2748
2749 case PNG_TYPE('P','L','T','E'): {
2750 if (first) return stbi__err("first not IHDR", "Corrupt PNG");
2751 if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");
2752 pal_len = c.length / 3;
2753 if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");
2754 for (i=0; i < pal_len; ++i) {
2755 palette[i*4+0] = stbi__get8u(s);
2756 palette[i*4+1] = stbi__get8u(s);
2757 palette[i*4+2] = stbi__get8u(s);
2758 palette[i*4+3] = 255;
2759 }
2760 break;
2761 }
2762
2763 case PNG_TYPE('t','R','N','S'): {
2764 if (first) return stbi__err("first not IHDR", "Corrupt PNG");
2765 if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");
2766 if (pal_img_n) {
2767 if (scan == SCAN_header) { s->img_n = 4; return 1; }
2768 if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");
2769 if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");
2770 pal_img_n = 4;
2771 for (i=0; i < c.length; ++i)
2772 palette[i*4+3] = stbi__get8u(s);
2773 } else {
2774 if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");
2775 if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");
2776 has_trans = 1;
2777 for (k=0; k < s->img_n; ++k)
2778 tc[k] = (stbi_uc) stbi__get16be(s); // non 8-bit images will be larger
2779 }
2780 break;
2781 }
2782
2783 case PNG_TYPE('I','D','A','T'): {
2784 if (first) return stbi__err("first not IHDR", "Corrupt PNG");
2785 if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");
2786 if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }
2787 if (ioff + c.length > idata_limit) {
2788 stbi_uc *p;
2789 if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
2790 while (ioff + c.length > idata_limit)
2791 idata_limit *= 2;
2792 p = (stbi_uc *) realloc(z->idata, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
2793 z->idata = p;
2794 }
2795 if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");
2796 ioff += c.length;
2797 break;
2798 }
2799
2800 case PNG_TYPE('I','E','N','D'): {
2801 stbi__uint32 raw_len;
2802 if (first) return stbi__err("first not IHDR", "Corrupt PNG");
2803 if (scan != SCAN_load) return 1;
2804 if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");
2805 z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !is_iphone);
2806 if (z->expanded == NULL) return 0; // zlib should set error
2807 free(z->idata); z->idata = NULL;
2808 if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
2809 s->img_out_n = s->img_n+1;
2810 else
2811 s->img_out_n = s->img_n;
2812 if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;
2813 if (has_trans)
2814 if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
2815 if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
2816 stbi__de_iphone(z);
2817 if (pal_img_n) {
2818 // pal_img_n == 3 or 4
2819 s->img_n = pal_img_n; // record the actual colors we had
2820 s->img_out_n = pal_img_n;
2821 if (req_comp >= 3) s->img_out_n = req_comp;
2822 if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
2823 return 0;
2824 }
2825 free(z->expanded); z->expanded = NULL;
2826 return 1;
2827 }
2828
2829 default:
2830 // if critical, fail
2831 if (first) return stbi__err("first not IHDR", "Corrupt PNG");
2832 if ((c.type & (1 << 29)) == 0) {
2833 #ifndef STBI_NO_FAILURE_STRINGS
2834 // not threadsafe
2835 static char invalid_chunk[] = "XXXX stbi__pngchunk not known";
2836 invalid_chunk[0] = (stbi_uc) (c.type >> 24);
2837 invalid_chunk[1] = (stbi_uc) (c.type >> 16);
2838 invalid_chunk[2] = (stbi_uc) (c.type >> 8);
2839 invalid_chunk[3] = (stbi_uc) (c.type >> 0);
2840 #endif
2841 return stbi__err(invalid_chunk, "PNG not supported: unknown stbi__pngchunk type");
2842 }
2843 stbi__skip(s, c.length);
2844 break;
2845 }
2846 // end of stbi__pngchunk, read and stbi__skip CRC
2847 stbi__get32be(s);
2848 }
2849 }
2850
stbi__do_png(stbi__png * p,int * x,int * y,int * n,int req_comp)2851 static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp)
2852 {
2853 unsigned char *result=NULL;
2854 if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
2855 if (stbi__parse_png_file(p, SCAN_load, req_comp)) {
2856 result = p->out;
2857 p->out = NULL;
2858 if (req_comp && req_comp != p->s->img_out_n) {
2859 result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
2860 p->s->img_out_n = req_comp;
2861 if (result == NULL) return result;
2862 }
2863 *x = p->s->img_x;
2864 *y = p->s->img_y;
2865 if (n) *n = p->s->img_n;
2866 }
2867 free(p->out); p->out = NULL;
2868 free(p->expanded); p->expanded = NULL;
2869 free(p->idata); p->idata = NULL;
2870
2871 return result;
2872 }
2873
stbi__png_load(stbi__context * s,int * x,int * y,int * comp,int req_comp)2874 static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
2875 {
2876 stbi__png p;
2877 p.s = s;
2878 return stbi__do_png(&p, x,y,comp,req_comp);
2879 }
2880
stbi__png_test(stbi__context * s)2881 static int stbi__png_test(stbi__context *s)
2882 {
2883 int r;
2884 r = stbi__check_png_header(s);
2885 stbi__rewind(s);
2886 return r;
2887 }
2888
stbi__png_info_raw(stbi__png * p,int * x,int * y,int * comp)2889 static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
2890 {
2891 if (!stbi__parse_png_file(p, SCAN_header, 0)) {
2892 stbi__rewind( p->s );
2893 return 0;
2894 }
2895 if (x) *x = p->s->img_x;
2896 if (y) *y = p->s->img_y;
2897 if (comp) *comp = p->s->img_n;
2898 return 1;
2899 }
2900
stbi__png_info(stbi__context * s,int * x,int * y,int * comp)2901 static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
2902 {
2903 stbi__png p;
2904 p.s = s;
2905 return stbi__png_info_raw(&p, x, y, comp);
2906 }
2907
2908 // Microsoft/Windows BMP image
stbi__bmp_test(stbi__context * s)2909 static int stbi__bmp_test(stbi__context *s)
2910 {
2911 int r;
2912 int sz;
2913 if (stbi__get8(s) != 'B') return 0;
2914 if (stbi__get8(s) != 'M') return 0;
2915 stbi__get32le(s); // discard filesize
2916 stbi__get16le(s); // discard reserved
2917 stbi__get16le(s); // discard reserved
2918 stbi__get32le(s); // discard data offset
2919 sz = stbi__get32le(s);
2920 r = (sz == 12 || sz == 40 || sz == 56 || sz == 108);
2921 stbi__rewind(s);
2922 return r;
2923 }
2924
2925
2926 // returns 0..31 for the highest set bit
stbi__high_bit(unsigned int z)2927 static int stbi__high_bit(unsigned int z)
2928 {
2929 int n=0;
2930 if (z == 0) return -1;
2931 if (z >= 0x10000) n += 16, z >>= 16;
2932 if (z >= 0x00100) n += 8, z >>= 8;
2933 if (z >= 0x00010) n += 4, z >>= 4;
2934 if (z >= 0x00004) n += 2, z >>= 2;
2935 if (z >= 0x00002) n += 1, z >>= 1;
2936 return n;
2937 }
2938
stbi__bitcount(unsigned int a)2939 static int stbi__bitcount(unsigned int a)
2940 {
2941 a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
2942 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
2943 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
2944 a = (a + (a >> 8)); // max 16 per 8 bits
2945 a = (a + (a >> 16)); // max 32 per 8 bits
2946 return a & 0xff;
2947 }
2948
stbi__shiftsigned(int v,int shift,int bits)2949 static int stbi__shiftsigned(int v, int shift, int bits)
2950 {
2951 int result;
2952 int z=0;
2953
2954 if (shift < 0) v <<= -shift;
2955 else v >>= shift;
2956 result = v;
2957
2958 z = bits;
2959 while (z < 8) {
2960 result += v >> z;
2961 z += bits;
2962 }
2963 return result;
2964 }
2965
stbi__bmp_load(stbi__context * s,int * x,int * y,int * comp,int req_comp)2966 static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
2967 {
2968 stbi_uc *out;
2969 unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
2970 stbi_uc pal[256][4];
2971 int psize=0,i,j,compress=0,width;
2972 int bpp, flip_vertically, pad, target, offset, hsz;
2973 if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");
2974 stbi__get32le(s); // discard filesize
2975 stbi__get16le(s); // discard reserved
2976 stbi__get16le(s); // discard reserved
2977 offset = stbi__get32le(s);
2978 hsz = stbi__get32le(s);
2979 if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
2980 if (hsz == 12) {
2981 s->img_x = stbi__get16le(s);
2982 s->img_y = stbi__get16le(s);
2983 } else {
2984 s->img_x = stbi__get32le(s);
2985 s->img_y = stbi__get32le(s);
2986 }
2987 if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP");
2988 bpp = stbi__get16le(s);
2989 if (bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit");
2990 flip_vertically = ((int) s->img_y) > 0;
2991 s->img_y = abs((int) s->img_y);
2992 if (hsz == 12) {
2993 if (bpp < 24)
2994 psize = (offset - 14 - 24) / 3;
2995 } else {
2996 compress = stbi__get32le(s);
2997 if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
2998 stbi__get32le(s); // discard sizeof
2999 stbi__get32le(s); // discard hres
3000 stbi__get32le(s); // discard vres
3001 stbi__get32le(s); // discard colorsused
3002 stbi__get32le(s); // discard max important
3003 if (hsz == 40 || hsz == 56) {
3004 if (hsz == 56) {
3005 stbi__get32le(s);
3006 stbi__get32le(s);
3007 stbi__get32le(s);
3008 stbi__get32le(s);
3009 }
3010 if (bpp == 16 || bpp == 32) {
3011 mr = mg = mb = 0;
3012 if (compress == 0) {
3013 if (bpp == 32) {
3014 mr = 0xffu << 16;
3015 mg = 0xffu << 8;
3016 mb = 0xffu << 0;
3017 ma = 0xffu << 24;
3018 fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
3019 STBI_NOTUSED(fake_a);
3020 } else {
3021 mr = 31u << 10;
3022 mg = 31u << 5;
3023 mb = 31u << 0;
3024 }
3025 } else if (compress == 3) {
3026 mr = stbi__get32le(s);
3027 mg = stbi__get32le(s);
3028 mb = stbi__get32le(s);
3029 // not documented, but generated by photoshop and handled by mspaint
3030 if (mr == mg && mg == mb) {
3031 // ?!?!?
3032 return stbi__errpuc("bad BMP", "bad BMP");
3033 }
3034 } else
3035 return stbi__errpuc("bad BMP", "bad BMP");
3036 }
3037 } else {
3038 assert(hsz == 108);
3039 mr = stbi__get32le(s);
3040 mg = stbi__get32le(s);
3041 mb = stbi__get32le(s);
3042 ma = stbi__get32le(s);
3043 stbi__get32le(s); // discard color space
3044 for (i=0; i < 12; ++i)
3045 stbi__get32le(s); // discard color space parameters
3046 }
3047 if (bpp < 16)
3048 psize = (offset - 14 - hsz) >> 2;
3049 }
3050 s->img_n = ma ? 4 : 3;
3051 if (req_comp && req_comp >= 3) // we can directly stbi__jpeg_huff_decode 3 or 4
3052 target = req_comp;
3053 else
3054 target = s->img_n; // if they want monochrome, we'll post-convert
3055 out = (stbi_uc *) malloc(target * s->img_x * s->img_y);
3056 if (!out) return stbi__errpuc("outofmem", "Out of memory");
3057 if (bpp < 16) {
3058 int z=0;
3059 if (psize == 0 || psize > 256) { free(out); return stbi__errpuc("invalid", "Corrupt BMP"); }
3060 for (i=0; i < psize; ++i) {
3061 pal[i][2] = stbi__get8u(s);
3062 pal[i][1] = stbi__get8u(s);
3063 pal[i][0] = stbi__get8u(s);
3064 if (hsz != 12) stbi__get8(s);
3065 pal[i][3] = 255;
3066 }
3067 stbi__skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
3068 if (bpp == 4) width = (s->img_x + 1) >> 1;
3069 else if (bpp == 8) width = s->img_x;
3070 else { free(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); }
3071 pad = (-width)&3;
3072 for (j=0; j < (int) s->img_y; ++j) {
3073 for (i=0; i < (int) s->img_x; i += 2) {
3074 int v=stbi__get8(s),v2=0;
3075 if (bpp == 4) {
3076 v2 = v & 15;
3077 v >>= 4;
3078 }
3079 out[z++] = pal[v][0];
3080 out[z++] = pal[v][1];
3081 out[z++] = pal[v][2];
3082 if (target == 4) out[z++] = 255;
3083 if (i+1 == (int) s->img_x) break;
3084 v = (bpp == 8) ? stbi__get8(s) : v2;
3085 out[z++] = pal[v][0];
3086 out[z++] = pal[v][1];
3087 out[z++] = pal[v][2];
3088 if (target == 4) out[z++] = 255;
3089 }
3090 stbi__skip(s, pad);
3091 }
3092 } else {
3093 int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
3094 int z = 0;
3095 int easy=0;
3096 stbi__skip(s, offset - 14 - hsz);
3097 if (bpp == 24) width = 3 * s->img_x;
3098 else if (bpp == 16) width = 2*s->img_x;
3099 else /* bpp = 32 and pad = 0 */ width=0;
3100 pad = (-width) & 3;
3101 if (bpp == 24) {
3102 easy = 1;
3103 } else if (bpp == 32) {
3104 if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
3105 easy = 2;
3106 }
3107 if (!easy) {
3108 if (!mr || !mg || !mb) { free(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
3109 // right shift amt to put high bit in position #7
3110 rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);
3111 gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);
3112 bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);
3113 ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);
3114 }
3115 for (j=0; j < (int) s->img_y; ++j) {
3116 if (easy) {
3117 for (i=0; i < (int) s->img_x; ++i) {
3118 int a;
3119 out[z+2] = stbi__get8u(s);
3120 out[z+1] = stbi__get8u(s);
3121 out[z+0] = stbi__get8u(s);
3122 z += 3;
3123 a = (easy == 2 ? stbi__get8(s) : 255);
3124 if (target == 4) out[z++] = (stbi_uc) a;
3125 }
3126 } else {
3127 for (i=0; i < (int) s->img_x; ++i) {
3128 stbi__uint32 v = (stbi__uint32) (bpp == 16 ? stbi__get16le(s) : stbi__get32le(s));
3129 int a;
3130 out[z++] = (stbi_uc) stbi__shiftsigned(v & mr, rshift, rcount);
3131 out[z++] = (stbi_uc) stbi__shiftsigned(v & mg, gshift, gcount);
3132 out[z++] = (stbi_uc) stbi__shiftsigned(v & mb, bshift, bcount);
3133 a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
3134 if (target == 4) out[z++] = (stbi_uc) a;
3135 }
3136 }
3137 stbi__skip(s, pad);
3138 }
3139 }
3140 if (flip_vertically) {
3141 stbi_uc t;
3142 for (j=0; j < (int) s->img_y>>1; ++j) {
3143 stbi_uc *p1 = out + j *s->img_x*target;
3144 stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
3145 for (i=0; i < (int) s->img_x*target; ++i) {
3146 t = p1[i], p1[i] = p2[i], p2[i] = t;
3147 }
3148 }
3149 }
3150
3151 if (req_comp && req_comp != target) {
3152 out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
3153 if (out == NULL) return out; // stbi__convert_format frees input on failure
3154 }
3155
3156 *x = s->img_x;
3157 *y = s->img_y;
3158 if (comp) *comp = s->img_n;
3159 return out;
3160 }
3161
3162 // Targa Truevision - TGA
3163 // by Jonathan Dummer
3164
stbi__tga_info(stbi__context * s,int * x,int * y,int * comp)3165 static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)
3166 {
3167 int tga_w, tga_h, tga_comp;
3168 int sz;
3169 stbi__get8u(s); // discard Offset
3170 sz = stbi__get8u(s); // color type
3171 if( sz > 1 ) {
3172 stbi__rewind(s);
3173 return 0; // only RGB or indexed allowed
3174 }
3175 sz = stbi__get8u(s); // image type
3176 // only RGB or grey allowed, +/- RLE
3177 if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;
3178 stbi__skip(s,9);
3179 tga_w = stbi__get16le(s);
3180 if( tga_w < 1 ) {
3181 stbi__rewind(s);
3182 return 0; // test width
3183 }
3184 tga_h = stbi__get16le(s);
3185 if( tga_h < 1 ) {
3186 stbi__rewind(s);
3187 return 0; // test height
3188 }
3189 sz = stbi__get8(s); // bits per pixel
3190 // only RGB or RGBA or grey allowed
3191 if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {
3192 stbi__rewind(s);
3193 return 0;
3194 }
3195 tga_comp = sz;
3196 if (x) *x = tga_w;
3197 if (y) *y = tga_h;
3198 if (comp) *comp = tga_comp / 8;
3199 return 1; // seems to have passed everything
3200 }
3201
stbi__tga_test(stbi__context * s)3202 static int stbi__tga_test(stbi__context *s)
3203 {
3204 int res;
3205 int sz;
3206 stbi__get8u(s); // discard Offset
3207 sz = stbi__get8u(s); // color type
3208 if ( sz > 1 ) return 0; // only RGB or indexed allowed
3209 sz = stbi__get8u(s); // image type
3210 if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE
3211 stbi__get16be(s); // discard palette start
3212 stbi__get16be(s); // discard palette length
3213 stbi__get8(s); // discard bits per palette color entry
3214 stbi__get16be(s); // discard x origin
3215 stbi__get16be(s); // discard y origin
3216 if ( stbi__get16be(s) < 1 ) return 0; // test width
3217 if ( stbi__get16be(s) < 1 ) return 0; // test height
3218 sz = stbi__get8(s); // bits per pixel
3219 if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) )
3220 res = 0;
3221 else
3222 res = 1;
3223 stbi__rewind(s);
3224 return res;
3225 }
3226
stbi__tga_load(stbi__context * s,int * x,int * y,int * comp,int req_comp)3227 static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
3228 {
3229 // read in the TGA header stuff
3230 int tga_offset = stbi__get8u(s);
3231 int tga_indexed = stbi__get8u(s);
3232 int tga_image_type = stbi__get8u(s);
3233 int tga_is_RLE = 0;
3234 int tga_palette_start = stbi__get16le(s);
3235 int tga_palette_len = stbi__get16le(s);
3236 int tga_palette_bits = stbi__get8u(s);
3237 int tga_x_origin = stbi__get16le(s);
3238 int tga_y_origin = stbi__get16le(s);
3239 int tga_width = stbi__get16le(s);
3240 int tga_height = stbi__get16le(s);
3241 int tga_bits_per_pixel = stbi__get8u(s);
3242 int tga_comp = tga_bits_per_pixel / 8;
3243 int tga_inverted = stbi__get8u(s);
3244 // image data
3245 unsigned char *tga_data;
3246 unsigned char *tga_palette = NULL;
3247 int i, j;
3248 unsigned char raw_data[4];
3249 int RLE_count = 0;
3250 int RLE_repeating = 0;
3251 int read_next_pixel = 1;
3252
3253 // do a tiny bit of precessing
3254 if ( tga_image_type >= 8 )
3255 {
3256 tga_image_type -= 8;
3257 tga_is_RLE = 1;
3258 }
3259 /* int tga_alpha_bits = tga_inverted & 15; */
3260 tga_inverted = 1 - ((tga_inverted >> 5) & 1);
3261
3262 // error check
3263 if ( //(tga_indexed) ||
3264 (tga_width < 1) || (tga_height < 1) ||
3265 (tga_image_type < 1) || (tga_image_type > 3) ||
3266 ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
3267 (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
3268 )
3269 {
3270 return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA
3271 }
3272
3273 // If I'm paletted, then I'll use the number of bits from the palette
3274 if ( tga_indexed )
3275 {
3276 tga_comp = tga_palette_bits / 8;
3277 }
3278
3279 // tga info
3280 *x = tga_width;
3281 *y = tga_height;
3282 if (comp) *comp = tga_comp;
3283
3284 tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );
3285 if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");
3286
3287 // stbi__skip to the data's starting position (offset usually = 0)
3288 stbi__skip(s, tga_offset );
3289
3290 if ( !tga_indexed && !tga_is_RLE) {
3291 for (i=0; i < tga_height; ++i) {
3292 int y = tga_inverted ? tga_height -i - 1 : i;
3293 stbi_uc *tga_row = tga_data + y*tga_width*tga_comp;
3294 stbi__getn(s, tga_row, tga_width * tga_comp);
3295 }
3296 } else {
3297 // do I need to load a palette?
3298 if ( tga_indexed)
3299 {
3300 // any data to stbi__skip? (offset usually = 0)
3301 stbi__skip(s, tga_palette_start );
3302 // load the palette
3303 tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );
3304 if (!tga_palette) {
3305 free(tga_data);
3306 return stbi__errpuc("outofmem", "Out of memory");
3307 }
3308 if (!stbi__getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {
3309 free(tga_data);
3310 free(tga_palette);
3311 return stbi__errpuc("bad palette", "Corrupt TGA");
3312 }
3313 }
3314 // load the data
3315 for (i=0; i < tga_width * tga_height; ++i)
3316 {
3317 // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?
3318 if ( tga_is_RLE )
3319 {
3320 if ( RLE_count == 0 )
3321 {
3322 // yep, get the next byte as a RLE command
3323 int RLE_cmd = stbi__get8u(s);
3324 RLE_count = 1 + (RLE_cmd & 127);
3325 RLE_repeating = RLE_cmd >> 7;
3326 read_next_pixel = 1;
3327 } else if ( !RLE_repeating )
3328 {
3329 read_next_pixel = 1;
3330 }
3331 } else
3332 {
3333 read_next_pixel = 1;
3334 }
3335 // OK, if I need to read a pixel, do it now
3336 if ( read_next_pixel )
3337 {
3338 // load however much data we did have
3339 if ( tga_indexed )
3340 {
3341 // read in 1 byte, then perform the lookup
3342 int pal_idx = stbi__get8u(s);
3343 if ( pal_idx >= tga_palette_len )
3344 {
3345 // invalid index
3346 pal_idx = 0;
3347 }
3348 pal_idx *= tga_bits_per_pixel / 8;
3349 for (j = 0; j*8 < tga_bits_per_pixel; ++j)
3350 {
3351 raw_data[j] = tga_palette[pal_idx+j];
3352 }
3353 } else
3354 {
3355 // read in the data raw
3356 for (j = 0; j*8 < tga_bits_per_pixel; ++j)
3357 {
3358 raw_data[j] = stbi__get8u(s);
3359 }
3360 }
3361 // clear the reading flag for the next pixel
3362 read_next_pixel = 0;
3363 } // end of reading a pixel
3364
3365 // copy data
3366 for (j = 0; j < tga_comp; ++j)
3367 tga_data[i*tga_comp+j] = raw_data[j];
3368
3369 // in case we're in RLE mode, keep counting down
3370 --RLE_count;
3371 }
3372 // do I need to invert the image?
3373 if ( tga_inverted )
3374 {
3375 for (j = 0; j*2 < tga_height; ++j)
3376 {
3377 int index1 = j * tga_width * req_comp;
3378 int index2 = (tga_height - 1 - j) * tga_width * req_comp;
3379 for (i = tga_width * req_comp; i > 0; --i)
3380 {
3381 unsigned char temp = tga_data[index1];
3382 tga_data[index1] = tga_data[index2];
3383 tga_data[index2] = temp;
3384 ++index1;
3385 ++index2;
3386 }
3387 }
3388 }
3389 // clear my palette, if I had one
3390 if ( tga_palette != NULL )
3391 {
3392 free( tga_palette );
3393 }
3394 }
3395
3396 // swap RGB
3397 if (tga_comp >= 3)
3398 {
3399 unsigned char* tga_pixel = tga_data;
3400 for (i=0; i < tga_width * tga_height; ++i)
3401 {
3402 unsigned char temp = tga_pixel[0];
3403 tga_pixel[0] = tga_pixel[2];
3404 tga_pixel[2] = temp;
3405 tga_pixel += tga_comp;
3406 }
3407 }
3408
3409 // convert to target component count
3410 if (req_comp && req_comp != tga_comp)
3411 tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
3412
3413 // the things I do to get rid of an error message, and yet keep
3414 // Microsoft's C compilers happy... [8^(
3415 tga_palette_start = tga_palette_len = tga_palette_bits =
3416 tga_x_origin = tga_y_origin = 0;
3417 // OK, done
3418 return tga_data;
3419 }
3420
3421 // *************************************************************************************************
3422 // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
3423
stbi__psd_test(stbi__context * s)3424 static int stbi__psd_test(stbi__context *s)
3425 {
3426 int r = (stbi__get32be(s) == 0x38425053);
3427 stbi__rewind(s);
3428 return r;
3429 }
3430
stbi__psd_load(stbi__context * s,int * x,int * y,int * comp,int req_comp)3431 static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
3432 {
3433 int pixelCount;
3434 int channelCount, compression;
3435 int channel, i, count, len;
3436 int w,h;
3437 stbi_uc *out;
3438
3439 // Check identifier
3440 if (stbi__get32be(s) != 0x38425053) // "8BPS"
3441 return stbi__errpuc("not PSD", "Corrupt PSD image");
3442
3443 // Check file type version.
3444 if (stbi__get16be(s) != 1)
3445 return stbi__errpuc("wrong version", "Unsupported version of PSD image");
3446
3447 // Skip 6 reserved bytes.
3448 stbi__skip(s, 6 );
3449
3450 // Read the number of channels (R, G, B, A, etc).
3451 channelCount = stbi__get16be(s);
3452 if (channelCount < 0 || channelCount > 16)
3453 return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");
3454
3455 // Read the rows and columns of the image.
3456 h = stbi__get32be(s);
3457 w = stbi__get32be(s);
3458
3459 // Make sure the depth is 8 bits.
3460 if (stbi__get16be(s) != 8)
3461 return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 bit");
3462
3463 // Make sure the color mode is RGB.
3464 // Valid options are:
3465 // 0: Bitmap
3466 // 1: Grayscale
3467 // 2: Indexed color
3468 // 3: RGB color
3469 // 4: CMYK color
3470 // 7: Multichannel
3471 // 8: Duotone
3472 // 9: Lab color
3473 if (stbi__get16be(s) != 3)
3474 return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
3475
3476 // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
3477 stbi__skip(s,stbi__get32be(s) );
3478
3479 // Skip the image resources. (resolution, pen tool paths, etc)
3480 stbi__skip(s, stbi__get32be(s) );
3481
3482 // Skip the reserved data.
3483 stbi__skip(s, stbi__get32be(s) );
3484
3485 // Find out if the data is compressed.
3486 // Known values:
3487 // 0: no compression
3488 // 1: RLE compressed
3489 compression = stbi__get16be(s);
3490 if (compression > 1)
3491 return stbi__errpuc("bad compression", "PSD has an unknown compression format");
3492
3493 // Create the destination image.
3494 out = (stbi_uc *) malloc(4 * w*h);
3495 if (!out) return stbi__errpuc("outofmem", "Out of memory");
3496 pixelCount = w*h;
3497
3498 // Initialize the data to zero.
3499 //memset( out, 0, pixelCount * 4 );
3500
3501 // Finally, the image data.
3502 if (compression) {
3503 // RLE as used by .PSD and .TIFF
3504 // Loop until you get the number of unpacked bytes you are expecting:
3505 // Read the next source byte into n.
3506 // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
3507 // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
3508 // Else if n is 128, noop.
3509 // Endloop
3510
3511 // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
3512 // which we're going to just stbi__skip.
3513 stbi__skip(s, h * channelCount * 2 );
3514
3515 // Read the RLE data by channel.
3516 for (channel = 0; channel < 4; channel++) {
3517 stbi_uc *p;
3518
3519 p = out+channel;
3520 if (channel >= channelCount) {
3521 // Fill this channel with default data.
3522 for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
3523 } else {
3524 // Read the RLE data.
3525 count = 0;
3526 while (count < pixelCount) {
3527 len = stbi__get8(s);
3528 if (len == 128) {
3529 // No-op.
3530 } else if (len < 128) {
3531 // Copy next len+1 bytes literally.
3532 len++;
3533 count += len;
3534 while (len) {
3535 *p = stbi__get8u(s);
3536 p += 4;
3537 len--;
3538 }
3539 } else if (len > 128) {
3540 stbi_uc val;
3541 // Next -len+1 bytes in the dest are replicated from next source byte.
3542 // (Interpret len as a negative 8-bit int.)
3543 len ^= 0x0FF;
3544 len += 2;
3545 val = stbi__get8u(s);
3546 count += len;
3547 while (len) {
3548 *p = val;
3549 p += 4;
3550 len--;
3551 }
3552 }
3553 }
3554 }
3555 }
3556
3557 } else {
3558 // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
3559 // where each channel consists of an 8-bit value for each pixel in the image.
3560
3561 // Read the data by channel.
3562 for (channel = 0; channel < 4; channel++) {
3563 stbi_uc *p;
3564
3565 p = out + channel;
3566 if (channel > channelCount) {
3567 // Fill this channel with default data.
3568 for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
3569 } else {
3570 // Read the data.
3571 for (i = 0; i < pixelCount; i++)
3572 *p = stbi__get8u(s), p += 4;
3573 }
3574 }
3575 }
3576
3577 if (req_comp && req_comp != 4) {
3578 out = stbi__convert_format(out, 4, req_comp, w, h);
3579 if (out == NULL) return out; // stbi__convert_format frees input on failure
3580 }
3581
3582 if (comp) *comp = channelCount;
3583 *y = h;
3584 *x = w;
3585
3586 return out;
3587 }
3588
3589 // *************************************************************************************************
3590 // Softimage PIC loader
3591 // by Tom Seddon
3592 //
3593 // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
3594 // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
3595
stbi__pic_is4(stbi__context * s,const char * str)3596 static int stbi__pic_is4(stbi__context *s,const char *str)
3597 {
3598 int i;
3599 for (i=0; i<4; ++i)
3600 if (stbi__get8(s) != (stbi_uc)str[i])
3601 return 0;
3602
3603 return 1;
3604 }
3605
stbi__pic_test_core(stbi__context * s)3606 static int stbi__pic_test_core(stbi__context *s)
3607 {
3608 int i;
3609
3610 if (!stbi__pic_is4(s,"\x53\x80\xF6\x34"))
3611 return 0;
3612
3613 for(i=0;i<84;++i)
3614 stbi__get8(s);
3615
3616 if (!stbi__pic_is4(s,"PICT"))
3617 return 0;
3618
3619 return 1;
3620 }
3621
3622 typedef struct
3623 {
3624 stbi_uc size,type,channel;
3625 } stbi__pic_packet;
3626
stbi__readval(stbi__context * s,int channel,stbi_uc * dest)3627 static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)
3628 {
3629 int mask=0x80, i;
3630
3631 for (i=0; i<4; ++i, mask>>=1) {
3632 if (channel & mask) {
3633 if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short");
3634 dest[i]=stbi__get8u(s);
3635 }
3636 }
3637
3638 return dest;
3639 }
3640
stbi__copyval(int channel,stbi_uc * dest,const stbi_uc * src)3641 static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)
3642 {
3643 int mask=0x80,i;
3644
3645 for (i=0;i<4; ++i, mask>>=1)
3646 if (channel&mask)
3647 dest[i]=src[i];
3648 }
3649
stbi__pic_load_core(stbi__context * s,int width,int height,int * comp,stbi_uc * result)3650 static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)
3651 {
3652 int act_comp=0,num_packets=0,y,chained;
3653 stbi__pic_packet packets[10];
3654
3655 // this will (should...) cater for even some bizarre stuff like having data
3656 // for the same channel in multiple packets.
3657 do {
3658 stbi__pic_packet *packet;
3659
3660 if (num_packets==sizeof(packets)/sizeof(packets[0]))
3661 return stbi__errpuc("bad format","too many packets");
3662
3663 packet = &packets[num_packets++];
3664
3665 chained = stbi__get8(s);
3666 packet->size = stbi__get8u(s);
3667 packet->type = stbi__get8u(s);
3668 packet->channel = stbi__get8u(s);
3669
3670 act_comp |= packet->channel;
3671
3672 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)");
3673 if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp");
3674 } while (chained);
3675
3676 *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
3677
3678 for(y=0; y<height; ++y) {
3679 int packet_idx;
3680
3681 for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
3682 stbi__pic_packet *packet = &packets[packet_idx];
3683 stbi_uc *dest = result+y*width*4;
3684
3685 switch (packet->type) {
3686 default:
3687 return stbi__errpuc("bad format","packet has bad compression type");
3688
3689 case 0: {//uncompressed
3690 int x;
3691
3692 for(x=0;x<width;++x, dest+=4)
3693 if (!stbi__readval(s,packet->channel,dest))
3694 return 0;
3695 break;
3696 }
3697
3698 case 1://Pure RLE
3699 {
3700 int left=width, i;
3701
3702 while (left>0) {
3703 stbi_uc count,value[4];
3704
3705 count=stbi__get8u(s);
3706 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)");
3707
3708 if (count > left)
3709 count = (stbi_uc) left;
3710
3711 if (!stbi__readval(s,packet->channel,value)) return 0;
3712
3713 for(i=0; i<count; ++i,dest+=4)
3714 stbi__copyval(packet->channel,dest,value);
3715 left -= count;
3716 }
3717 }
3718 break;
3719
3720 case 2: {//Mixed RLE
3721 int left=width;
3722 while (left>0) {
3723 int count = stbi__get8(s), i;
3724 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)");
3725
3726 if (count >= 128) { // Repeated
3727 stbi_uc value[4];
3728 int i;
3729
3730 if (count==128)
3731 count = stbi__get16be(s);
3732 else
3733 count -= 127;
3734 if (count > left)
3735 return stbi__errpuc("bad file","scanline overrun");
3736
3737 if (!stbi__readval(s,packet->channel,value))
3738 return 0;
3739
3740 for(i=0;i<count;++i, dest += 4)
3741 stbi__copyval(packet->channel,dest,value);
3742 } else { // Raw
3743 ++count;
3744 if (count>left) return stbi__errpuc("bad file","scanline overrun");
3745
3746 for(i=0;i<count;++i, dest+=4)
3747 if (!stbi__readval(s,packet->channel,dest))
3748 return 0;
3749 }
3750 left-=count;
3751 }
3752 break;
3753 }
3754 }
3755 }
3756 }
3757
3758 return result;
3759 }
3760
stbi__pic_load(stbi__context * s,int * px,int * py,int * comp,int req_comp)3761 static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp)
3762 {
3763 stbi_uc *result;
3764 int i, x,y;
3765
3766 for (i=0; i<92; ++i)
3767 stbi__get8(s);
3768
3769 x = stbi__get16be(s);
3770 y = stbi__get16be(s);
3771 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");
3772 if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to stbi__jpeg_huff_decode");
3773
3774 stbi__get32be(s); //stbi__skip `ratio'
3775 stbi__get16be(s); //stbi__skip `fields'
3776 stbi__get16be(s); //stbi__skip `pad'
3777
3778 // intermediate buffer is RGBA
3779 result = (stbi_uc *) malloc(x*y*4);
3780 memset(result, 0xff, x*y*4);
3781
3782 if (!stbi__pic_load_core(s,x,y,comp, result)) {
3783 free(result);
3784 result=0;
3785 }
3786 *px = x;
3787 *py = y;
3788 if (req_comp == 0) req_comp = *comp;
3789 result=stbi__convert_format(result,4,req_comp,x,y);
3790
3791 return result;
3792 }
3793
stbi__pic_test(stbi__context * s)3794 static int stbi__pic_test(stbi__context *s)
3795 {
3796 int r = stbi__pic_test_core(s);
3797 stbi__rewind(s);
3798 return r;
3799 }
3800
3801 // *************************************************************************************************
3802 // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
3803 typedef struct
3804 {
3805 stbi__int16 prefix;
3806 stbi_uc first;
3807 stbi_uc suffix;
3808 } stbi__gif_lzw;
3809
3810 typedef struct
3811 {
3812 int w,h;
3813 stbi_uc *out; // output buffer (always 4 components)
3814 int flags, bgindex, ratio, transparent, eflags;
3815 stbi_uc pal[256][4];
3816 stbi_uc lpal[256][4];
3817 stbi__gif_lzw codes[4096];
3818 stbi_uc *color_table;
3819 int parse, step;
3820 int lflags;
3821 int start_x, start_y;
3822 int max_x, max_y;
3823 int cur_x, cur_y;
3824 int line_size;
3825 } stbi__gif;
3826
stbi__gif_test_raw(stbi__context * s)3827 static int stbi__gif_test_raw(stbi__context *s)
3828 {
3829 int sz;
3830 if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;
3831 sz = stbi__get8(s);
3832 if (sz != '9' && sz != '7') return 0;
3833 if (stbi__get8(s) != 'a') return 0;
3834 return 1;
3835 }
3836
stbi__gif_test(stbi__context * s)3837 static int stbi__gif_test(stbi__context *s)
3838 {
3839 int r = stbi__gif_test_raw(s);
3840 stbi__rewind(s);
3841 return r;
3842 }
3843
stbi__gif_parse_colortable(stbi__context * s,stbi_uc pal[256][4],int num_entries,int transp)3844 static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)
3845 {
3846 int i;
3847 for (i=0; i < num_entries; ++i) {
3848 pal[i][2] = stbi__get8u(s);
3849 pal[i][1] = stbi__get8u(s);
3850 pal[i][0] = stbi__get8u(s);
3851 pal[i][3] = transp ? 0 : 255;
3852 }
3853 }
3854
stbi__gif_header(stbi__context * s,stbi__gif * g,int * comp,int is_info)3855 static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)
3856 {
3857 stbi_uc version;
3858 if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
3859 return stbi__err("not GIF", "Corrupt GIF");
3860
3861 version = stbi__get8u(s);
3862 if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");
3863 if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
3864
3865 stbi__g_failure_reason = "";
3866 g->w = stbi__get16le(s);
3867 g->h = stbi__get16le(s);
3868 g->flags = stbi__get8(s);
3869 g->bgindex = stbi__get8(s);
3870 g->ratio = stbi__get8(s);
3871 g->transparent = -1;
3872
3873 if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
3874
3875 if (is_info) return 1;
3876
3877 if (g->flags & 0x80)
3878 stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
3879
3880 return 1;
3881 }
3882
stbi__gif_info_raw(stbi__context * s,int * x,int * y,int * comp)3883 static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
3884 {
3885 stbi__gif g;
3886 if (!stbi__gif_header(s, &g, comp, 1)) {
3887 stbi__rewind( s );
3888 return 0;
3889 }
3890 if (x) *x = g.w;
3891 if (y) *y = g.h;
3892 return 1;
3893 }
3894
stbi__out_gif_code(stbi__gif * g,stbi__uint16 code)3895 static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)
3896 {
3897 stbi_uc *p, *c;
3898
3899 // recurse to stbi__jpeg_huff_decode the prefixes, since the linked-list is backwards,
3900 // and working backwards through an interleaved image would be nasty
3901 if (g->codes[code].prefix >= 0)
3902 stbi__out_gif_code(g, g->codes[code].prefix);
3903
3904 if (g->cur_y >= g->max_y) return;
3905
3906 p = &g->out[g->cur_x + g->cur_y];
3907 c = &g->color_table[g->codes[code].suffix * 4];
3908
3909 if (c[3] >= 128) {
3910 p[0] = c[2];
3911 p[1] = c[1];
3912 p[2] = c[0];
3913 p[3] = c[3];
3914 }
3915 g->cur_x += 4;
3916
3917 if (g->cur_x >= g->max_x) {
3918 g->cur_x = g->start_x;
3919 g->cur_y += g->step;
3920
3921 while (g->cur_y >= g->max_y && g->parse > 0) {
3922 g->step = (1 << g->parse) * g->line_size;
3923 g->cur_y = g->start_y + (g->step >> 1);
3924 --g->parse;
3925 }
3926 }
3927 }
3928
stbi__process_gif_raster(stbi__context * s,stbi__gif * g)3929 static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)
3930 {
3931 stbi_uc lzw_cs;
3932 stbi__int32 len, code;
3933 stbi__uint32 first;
3934 stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
3935 stbi__gif_lzw *p;
3936
3937 lzw_cs = stbi__get8u(s);
3938 clear = 1 << lzw_cs;
3939 first = 1;
3940 codesize = lzw_cs + 1;
3941 codemask = (1 << codesize) - 1;
3942 bits = 0;
3943 valid_bits = 0;
3944 for (code = 0; code < clear; code++) {
3945 g->codes[code].prefix = -1;
3946 g->codes[code].first = (stbi_uc) code;
3947 g->codes[code].suffix = (stbi_uc) code;
3948 }
3949
3950 // support no starting clear code
3951 avail = clear+2;
3952 oldcode = -1;
3953
3954 len = 0;
3955 for(;;) {
3956 if (valid_bits < codesize) {
3957 if (len == 0) {
3958 len = stbi__get8(s); // start new block
3959 if (len == 0)
3960 return g->out;
3961 }
3962 --len;
3963 bits |= (stbi__int32) stbi__get8(s) << valid_bits;
3964 valid_bits += 8;
3965 } else {
3966 stbi__int32 code = bits & codemask;
3967 bits >>= codesize;
3968 valid_bits -= codesize;
3969 // @OPTIMIZE: is there some way we can accelerate the non-clear path?
3970 if (code == clear) { // clear code
3971 codesize = lzw_cs + 1;
3972 codemask = (1 << codesize) - 1;
3973 avail = clear + 2;
3974 oldcode = -1;
3975 first = 0;
3976 } else if (code == clear + 1) { // end of stream code
3977 stbi__skip(s, len);
3978 while ((len = stbi__get8(s)) > 0)
3979 stbi__skip(s,len);
3980 return g->out;
3981 } else if (code <= avail) {
3982 if (first) return stbi__errpuc("no clear code", "Corrupt GIF");
3983
3984 if (oldcode >= 0) {
3985 p = &g->codes[avail++];
3986 if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF");
3987 p->prefix = (stbi__int16) oldcode;
3988 p->first = g->codes[oldcode].first;
3989 p->suffix = (code == avail) ? p->first : g->codes[code].first;
3990 } else if (code == avail)
3991 return stbi__errpuc("illegal code in raster", "Corrupt GIF");
3992
3993 stbi__out_gif_code(g, (stbi__uint16) code);
3994
3995 if ((avail & codemask) == 0 && avail <= 0x0FFF) {
3996 codesize++;
3997 codemask = (1 << codesize) - 1;
3998 }
3999
4000 oldcode = code;
4001 } else {
4002 return stbi__errpuc("illegal code in raster", "Corrupt GIF");
4003 }
4004 }
4005 }
4006 }
4007
stbi__fill_gif_background(stbi__gif * g)4008 static void stbi__fill_gif_background(stbi__gif *g)
4009 {
4010 int i;
4011 stbi_uc *c = g->pal[g->bgindex];
4012 // @OPTIMIZE: write a dword at a time
4013 for (i = 0; i < g->w * g->h * 4; i += 4) {
4014 stbi_uc *p = &g->out[i];
4015 p[0] = c[2];
4016 p[1] = c[1];
4017 p[2] = c[0];
4018 p[3] = c[3];
4019 }
4020 }
4021
4022 // this function is designed to support animated gifs, although stb_image doesn't support it
stbi__gif_load_next(stbi__context * s,stbi__gif * g,int * comp,int req_comp)4023 static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp)
4024 {
4025 int i;
4026 stbi_uc *old_out = 0;
4027
4028 if (g->out == 0) {
4029 if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header
4030 g->out = (stbi_uc *) malloc(4 * g->w * g->h);
4031 if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");
4032 stbi__fill_gif_background(g);
4033 } else {
4034 // animated-gif-only path
4035 if (((g->eflags & 0x1C) >> 2) == 3) {
4036 old_out = g->out;
4037 g->out = (stbi_uc *) malloc(4 * g->w * g->h);
4038 if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");
4039 memcpy(g->out, old_out, g->w*g->h*4);
4040 }
4041 }
4042
4043 for (;;) {
4044 switch (stbi__get8(s)) {
4045 case 0x2C: /* Image Descriptor */
4046 {
4047 stbi__int32 x, y, w, h;
4048 stbi_uc *o;
4049
4050 x = stbi__get16le(s);
4051 y = stbi__get16le(s);
4052 w = stbi__get16le(s);
4053 h = stbi__get16le(s);
4054 if (((x + w) > (g->w)) || ((y + h) > (g->h)))
4055 return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
4056
4057 g->line_size = g->w * 4;
4058 g->start_x = x * 4;
4059 g->start_y = y * g->line_size;
4060 g->max_x = g->start_x + w * 4;
4061 g->max_y = g->start_y + h * g->line_size;
4062 g->cur_x = g->start_x;
4063 g->cur_y = g->start_y;
4064
4065 g->lflags = stbi__get8(s);
4066
4067 if (g->lflags & 0x40) {
4068 g->step = 8 * g->line_size; // first interlaced spacing
4069 g->parse = 3;
4070 } else {
4071 g->step = g->line_size;
4072 g->parse = 0;
4073 }
4074
4075 if (g->lflags & 0x80) {
4076 stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
4077 g->color_table = (stbi_uc *) g->lpal;
4078 } else if (g->flags & 0x80) {
4079 for (i=0; i < 256; ++i) // @OPTIMIZE: stbi__jpeg_reset only the previous transparent
4080 g->pal[i][3] = 255;
4081 if (g->transparent >= 0 && (g->eflags & 0x01))
4082 g->pal[g->transparent][3] = 0;
4083 g->color_table = (stbi_uc *) g->pal;
4084 } else
4085 return stbi__errpuc("missing color table", "Corrupt GIF");
4086
4087 o = stbi__process_gif_raster(s, g);
4088 if (o == NULL) return NULL;
4089
4090 if (req_comp && req_comp != 4)
4091 o = stbi__convert_format(o, 4, req_comp, g->w, g->h);
4092 return o;
4093 }
4094
4095 case 0x21: // Comment Extension.
4096 {
4097 int len;
4098 if (stbi__get8(s) == 0xF9) { // Graphic Control Extension.
4099 len = stbi__get8(s);
4100 if (len == 4) {
4101 g->eflags = stbi__get8(s);
4102 stbi__get16le(s); // delay
4103 g->transparent = stbi__get8(s);
4104 } else {
4105 stbi__skip(s, len);
4106 break;
4107 }
4108 }
4109 while ((len = stbi__get8(s)) != 0)
4110 stbi__skip(s, len);
4111 break;
4112 }
4113
4114 case 0x3B: // gif stream termination code
4115 return (stbi_uc *) 1;
4116
4117 default:
4118 return stbi__errpuc("unknown code", "Corrupt GIF");
4119 }
4120 }
4121 }
4122
stbi__gif_load(stbi__context * s,int * x,int * y,int * comp,int req_comp)4123 static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
4124 {
4125 stbi_uc *u = 0;
4126 stbi__gif g={0};
4127
4128 u = stbi__gif_load_next(s, &g, comp, req_comp);
4129 if (u == (void *) 1) u = 0; // end of animated gif marker
4130 if (u) {
4131 *x = g.w;
4132 *y = g.h;
4133 }
4134
4135 return u;
4136 }
4137
stbi__gif_info(stbi__context * s,int * x,int * y,int * comp)4138 static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)
4139 {
4140 return stbi__gif_info_raw(s,x,y,comp);
4141 }
4142
4143
4144 // *************************************************************************************************
4145 // Radiance RGBE HDR loader
4146 // originally by Nicolas Schulz
4147 #ifndef STBI_NO_HDR
stbi__hdr_test_core(stbi__context * s)4148 static int stbi__hdr_test_core(stbi__context *s)
4149 {
4150 const char *signature = "#?RADIANCE\n";
4151 int i;
4152 for (i=0; signature[i]; ++i)
4153 if (stbi__get8(s) != signature[i])
4154 return 0;
4155 return 1;
4156 }
4157
stbi__hdr_test(stbi__context * s)4158 static int stbi__hdr_test(stbi__context* s)
4159 {
4160 int r = stbi__hdr_test_core(s);
4161 stbi__rewind(s);
4162 return r;
4163 }
4164
4165 #define STBI__HDR_BUFLEN 1024
stbi__hdr_gettoken(stbi__context * z,char * buffer)4166 static char *stbi__hdr_gettoken(stbi__context *z, char *buffer)
4167 {
4168 int len=0;
4169 char c = '\0';
4170
4171 c = (char) stbi__get8(z);
4172
4173 while (!stbi__at_eof(z) && c != '\n') {
4174 buffer[len++] = c;
4175 if (len == STBI__HDR_BUFLEN-1) {
4176 // flush to end of line
4177 while (!stbi__at_eof(z) && stbi__get8(z) != '\n')
4178 ;
4179 break;
4180 }
4181 c = (char) stbi__get8(z);
4182 }
4183
4184 buffer[len] = 0;
4185 return buffer;
4186 }
4187
stbi__hdr_convert(float * output,stbi_uc * input,int req_comp)4188 static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)
4189 {
4190 if ( input[3] != 0 ) {
4191 float f1;
4192 // Exponent
4193 f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
4194 if (req_comp <= 2)
4195 output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
4196 else {
4197 output[0] = input[0] * f1;
4198 output[1] = input[1] * f1;
4199 output[2] = input[2] * f1;
4200 }
4201 if (req_comp == 2) output[1] = 1;
4202 if (req_comp == 4) output[3] = 1;
4203 } else {
4204 switch (req_comp) {
4205 case 4: output[3] = 1; /* fallthrough */
4206 case 3: output[0] = output[1] = output[2] = 0;
4207 break;
4208 case 2: output[1] = 1; /* fallthrough */
4209 case 1: output[0] = 0;
4210 break;
4211 }
4212 }
4213 }
4214
stbi__hdr_load(stbi__context * s,int * x,int * y,int * comp,int req_comp)4215 static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
4216 {
4217 char buffer[STBI__HDR_BUFLEN];
4218 char *token;
4219 int valid = 0;
4220 int width, height;
4221 stbi_uc *scanline;
4222 float *hdr_data;
4223 int len;
4224 unsigned char count, value;
4225 int i, j, k, c1,c2, z;
4226
4227
4228 // Check identifier
4229 if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
4230 return stbi__errpf("not HDR", "Corrupt HDR image");
4231
4232 // Parse header
4233 for(;;) {
4234 token = stbi__hdr_gettoken(s,buffer);
4235 if (token[0] == 0) break;
4236 if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
4237 }
4238
4239 if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");
4240
4241 // Parse width and height
4242 // can't use sscanf() if we're not using stdio!
4243 token = stbi__hdr_gettoken(s,buffer);
4244 if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
4245 token += 3;
4246 height = (int) strtol(token, &token, 10);
4247 while (*token == ' ') ++token;
4248 if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
4249 token += 3;
4250 width = (int) strtol(token, NULL, 10);
4251
4252 *x = width;
4253 *y = height;
4254
4255 if (comp) *comp = 3;
4256 if (req_comp == 0) req_comp = 3;
4257
4258 // Read data
4259 hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));
4260
4261 // Load image data
4262 // image data is stored as some number of sca
4263 if ( width < 8 || width >= 32768) {
4264 // Read flat data
4265 for (j=0; j < height; ++j) {
4266 for (i=0; i < width; ++i) {
4267 stbi_uc rgbe[4];
4268 main_decode_loop:
4269 stbi__getn(s, rgbe, 4);
4270 stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
4271 }
4272 }
4273 } else {
4274 // Read RLE-encoded data
4275 scanline = NULL;
4276
4277 for (j = 0; j < height; ++j) {
4278 c1 = stbi__get8(s);
4279 c2 = stbi__get8(s);
4280 len = stbi__get8(s);
4281 if (c1 != 2 || c2 != 2 || (len & 0x80)) {
4282 // not run-length encoded, so we have to actually use THIS data as a decoded
4283 // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
4284 stbi_uc rgbe[4];
4285 rgbe[0] = (stbi_uc) c1;
4286 rgbe[1] = (stbi_uc) c2;
4287 rgbe[2] = (stbi_uc) len;
4288 rgbe[3] = (stbi_uc) stbi__get8u(s);
4289 stbi__hdr_convert(hdr_data, rgbe, req_comp);
4290 i = 1;
4291 j = 0;
4292 free(scanline);
4293 goto main_decode_loop; // yes, this makes no sense
4294 }
4295 len <<= 8;
4296 len |= stbi__get8(s);
4297 if (len != width) { free(hdr_data); free(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }
4298 if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);
4299
4300 for (k = 0; k < 4; ++k) {
4301 i = 0;
4302 while (i < width) {
4303 count = stbi__get8u(s);
4304 if (count > 128) {
4305 // Run
4306 value = stbi__get8u(s);
4307 count -= 128;
4308 for (z = 0; z < count; ++z)
4309 scanline[i++ * 4 + k] = value;
4310 } else {
4311 // Dump
4312 for (z = 0; z < count; ++z)
4313 scanline[i++ * 4 + k] = stbi__get8u(s);
4314 }
4315 }
4316 }
4317 for (i=0; i < width; ++i)
4318 stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
4319 }
4320 free(scanline);
4321 }
4322
4323 return hdr_data;
4324 }
4325
stbi__hdr_info(stbi__context * s,int * x,int * y,int * comp)4326 static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)
4327 {
4328 char buffer[STBI__HDR_BUFLEN];
4329 char *token;
4330 int valid = 0;
4331
4332 if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {
4333 stbi__rewind( s );
4334 return 0;
4335 }
4336
4337 for(;;) {
4338 token = stbi__hdr_gettoken(s,buffer);
4339 if (token[0] == 0) break;
4340 if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
4341 }
4342
4343 if (!valid) {
4344 stbi__rewind( s );
4345 return 0;
4346 }
4347 token = stbi__hdr_gettoken(s,buffer);
4348 if (strncmp(token, "-Y ", 3)) {
4349 stbi__rewind( s );
4350 return 0;
4351 }
4352 token += 3;
4353 *y = (int) strtol(token, &token, 10);
4354 while (*token == ' ') ++token;
4355 if (strncmp(token, "+X ", 3)) {
4356 stbi__rewind( s );
4357 return 0;
4358 }
4359 token += 3;
4360 *x = (int) strtol(token, NULL, 10);
4361 *comp = 3;
4362 return 1;
4363 }
4364 #endif // STBI_NO_HDR
4365
stbi__bmp_info(stbi__context * s,int * x,int * y,int * comp)4366 static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
4367 {
4368 int hsz;
4369 if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') {
4370 stbi__rewind( s );
4371 return 0;
4372 }
4373 stbi__skip(s,12);
4374 hsz = stbi__get32le(s);
4375 if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {
4376 stbi__rewind( s );
4377 return 0;
4378 }
4379 if (hsz == 12) {
4380 *x = stbi__get16le(s);
4381 *y = stbi__get16le(s);
4382 } else {
4383 *x = stbi__get32le(s);
4384 *y = stbi__get32le(s);
4385 }
4386 if (stbi__get16le(s) != 1) {
4387 stbi__rewind( s );
4388 return 0;
4389 }
4390 *comp = stbi__get16le(s) / 8;
4391 return 1;
4392 }
4393
stbi__psd_info(stbi__context * s,int * x,int * y,int * comp)4394 static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)
4395 {
4396 int channelCount;
4397 if (stbi__get32be(s) != 0x38425053) {
4398 stbi__rewind( s );
4399 return 0;
4400 }
4401 if (stbi__get16be(s) != 1) {
4402 stbi__rewind( s );
4403 return 0;
4404 }
4405 stbi__skip(s, 6);
4406 channelCount = stbi__get16be(s);
4407 if (channelCount < 0 || channelCount > 16) {
4408 stbi__rewind( s );
4409 return 0;
4410 }
4411 *y = stbi__get32be(s);
4412 *x = stbi__get32be(s);
4413 if (stbi__get16be(s) != 8) {
4414 stbi__rewind( s );
4415 return 0;
4416 }
4417 if (stbi__get16be(s) != 3) {
4418 stbi__rewind( s );
4419 return 0;
4420 }
4421 *comp = 4;
4422 return 1;
4423 }
4424
stbi__pic_info(stbi__context * s,int * x,int * y,int * comp)4425 static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
4426 {
4427 int act_comp=0,num_packets=0,chained;
4428 stbi__pic_packet packets[10];
4429
4430 stbi__skip(s, 92);
4431
4432 *x = stbi__get16be(s);
4433 *y = stbi__get16be(s);
4434 if (stbi__at_eof(s)) return 0;
4435 if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
4436 stbi__rewind( s );
4437 return 0;
4438 }
4439
4440 stbi__skip(s, 8);
4441
4442 do {
4443 stbi__pic_packet *packet;
4444
4445 if (num_packets==sizeof(packets)/sizeof(packets[0]))
4446 return 0;
4447
4448 packet = &packets[num_packets++];
4449 chained = stbi__get8(s);
4450 packet->size = stbi__get8u(s);
4451 packet->type = stbi__get8u(s);
4452 packet->channel = stbi__get8u(s);
4453 act_comp |= packet->channel;
4454
4455 if (stbi__at_eof(s)) {
4456 stbi__rewind( s );
4457 return 0;
4458 }
4459 if (packet->size != 8) {
4460 stbi__rewind( s );
4461 return 0;
4462 }
4463 } while (chained);
4464
4465 *comp = (act_comp & 0x10 ? 4 : 3);
4466
4467 return 1;
4468 }
4469
stbi__info_main(stbi__context * s,int * x,int * y,int * comp)4470 static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
4471 {
4472 if (stbi__jpeg_info(s, x, y, comp))
4473 return 1;
4474 if (stbi__png_info(s, x, y, comp))
4475 return 1;
4476 if (stbi__gif_info(s, x, y, comp))
4477 return 1;
4478 if (stbi__bmp_info(s, x, y, comp))
4479 return 1;
4480 if (stbi__psd_info(s, x, y, comp))
4481 return 1;
4482 if (stbi__pic_info(s, x, y, comp))
4483 return 1;
4484 #ifndef STBI_NO_HDR
4485 if (stbi__hdr_info(s, x, y, comp))
4486 return 1;
4487 #endif
4488 // test tga last because it's a crappy test!
4489 if (stbi__tga_info(s, x, y, comp))
4490 return 1;
4491 return stbi__err("unknown image type", "Image not of any known type, or corrupt");
4492 }
4493
4494 #ifndef STBI_NO_STDIO
stbi_info(char const * filename,int * x,int * y,int * comp)4495 STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)
4496 {
4497 FILE *f = fopen(filename, "rb");
4498 int result;
4499 if (!f) return stbi__err("can't fopen", "Unable to open file");
4500 result = stbi_info_from_file(f, x, y, comp);
4501 fclose(f);
4502 return result;
4503 }
4504
stbi_info_from_file(FILE * f,int * x,int * y,int * comp)4505 STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
4506 {
4507 int r;
4508 stbi__context s;
4509 long pos = ftell(f);
4510 stbi__start_file(&s, f);
4511 r = stbi__info_main(&s,x,y,comp);
4512 fseek(f,pos,SEEK_SET);
4513 return r;
4514 }
4515 #endif // !STBI_NO_STDIO
4516
stbi_info_from_memory(stbi_uc const * buffer,int len,int * x,int * y,int * comp)4517 STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
4518 {
4519 stbi__context s;
4520 stbi__start_mem(&s,buffer,len);
4521 return stbi__info_main(&s,x,y,comp);
4522 }
4523
stbi_info_from_callbacks(stbi_io_callbacks const * c,void * user,int * x,int * y,int * comp)4524 STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
4525 {
4526 stbi__context s;
4527 stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
4528 return stbi__info_main(&s,x,y,comp);
4529 }
4530
4531 #endif // STB_IMAGE_IMPLEMENTATION
4532
4533 #if !defined(STBI_NO_STDIO) && defined(_MSC_VER) && _MSC_VER >= 1400
4534 #pragma warning(pop)
4535 #endif
4536
4537
4538 /*
4539 revision history:
4540 1.37 (2014-06-04)
4541 remove duplicate typedef
4542 1.36 (2014-06-03)
4543 convert to header file single-file library
4544 if de-iphone isn't set, load iphone images color-swapped instead of returning NULL
4545 1.35 (2014-05-27)
4546 various warnings
4547 fix broken STBI_SIMD path
4548 fix bug where stbi_load_from_file no longer left file pointer in correct place
4549 fix broken non-easy path for 32-bit BMP (possibly never used)
4550 TGA optimization by Arseny Kapoulkine
4551 1.34 (unknown)
4552 use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case
4553 1.33 (2011-07-14)
4554 make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
4555 1.32 (2011-07-13)
4556 support for "info" function for all supported filetypes (SpartanJ)
4557 1.31 (2011-06-20)
4558 a few more leak fixes, bug in PNG handling (SpartanJ)
4559 1.30 (2011-06-11)
4560 added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
4561 removed deprecated format-specific test/load functions
4562 removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
4563 error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
4564 fix inefficiency in decoding 32-bit BMP (David Woo)
4565 1.29 (2010-08-16)
4566 various warning fixes from Aurelien Pocheville
4567 1.28 (2010-08-01)
4568 fix bug in GIF palette transparency (SpartanJ)
4569 1.27 (2010-08-01)
4570 cast-to-stbi_uc to fix warnings
4571 1.26 (2010-07-24)
4572 fix bug in file buffering for PNG reported by SpartanJ
4573 1.25 (2010-07-17)
4574 refix trans_data warning (Won Chun)
4575 1.24 (2010-07-12)
4576 perf improvements reading from files on platforms with lock-heavy fgetc()
4577 minor perf improvements for jpeg
4578 deprecated type-specific functions so we'll get feedback if they're needed
4579 attempt to fix trans_data warning (Won Chun)
4580 1.23 fixed bug in iPhone support
4581 1.22 (2010-07-10)
4582 removed image *writing* support
4583 stbi_info support from Jetro Lauha
4584 GIF support from Jean-Marc Lienher
4585 iPhone PNG-extensions from James Brown
4586 warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)
4587 1.21 fix use of 'stbi_uc' in header (reported by jon blow)
4588 1.20 added support for Softimage PIC, by Tom Seddon
4589 1.19 bug in interlaced PNG corruption check (found by ryg)
4590 1.18 2008-08-02
4591 fix a threading bug (local mutable static)
4592 1.17 support interlaced PNG
4593 1.16 major bugfix - stbi__convert_format converted one too many pixels
4594 1.15 initialize some fields for thread safety
4595 1.14 fix threadsafe conversion bug
4596 header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
4597 1.13 threadsafe
4598 1.12 const qualifiers in the API
4599 1.11 Support installable IDCT, colorspace conversion routines
4600 1.10 Fixes for 64-bit (don't use "unsigned long")
4601 optimized upsampling by Fabian "ryg" Giesen
4602 1.09 Fix format-conversion for PSD code (bad global variables!)
4603 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
4604 1.07 attempt to fix C++ warning/errors again
4605 1.06 attempt to fix C++ warning/errors again
4606 1.05 fix TGA loading to return correct *comp and use good luminance calc
4607 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
4608 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
4609 1.02 support for (subset of) HDR files, float interface for preferred access to them
4610 1.01 fix bug: possible bug in handling right-side up bmps... not sure
4611 fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all
4612 1.00 interface to zlib that skips zlib header
4613 0.99 correct handling of alpha in palette
4614 0.98 TGA loader by lonesock; dynamically add loaders (untested)
4615 0.97 jpeg errors on too large a file; also catch another malloc failure
4616 0.96 fix detection of invalid v value - particleman@mollyrocket forum
4617 0.95 during header scan, seek to markers in case of padding
4618 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
4619 0.93 handle jpegtran output; verbose errors
4620 0.92 read 4,8,16,24,32-bit BMP files of several formats
4621 0.91 output 24-bit Windows 3.0 BMP files
4622 0.90 fix a few more warnings; bump version number to approach 1.0
4623 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
4624 0.60 fix compiling as c++
4625 0.59 fix warnings: merge Dave Moore's -Wall fixes
4626 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
4627 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
4628 0.56 fix bug: zlib uncompressed mode len vs. nlen
4629 0.55 fix bug: restart_interval not initialized to 0
4630 0.54 allow NULL for 'int *comp'
4631 0.53 fix bug in png 3->4; speedup png decoding
4632 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
4633 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
4634 on 'test' only check type, not whether we support this variant
4635 0.50 first released version
4636 */
4637