~oem-solutions-group/unity-2d/clutter-1.0

« back to all changes in this revision

Viewing changes to clutter/cogl/cogl/stb_image.c

  • Committer: Bazaar Package Importer
  • Author(s): Emilio Pozuelo Monfort
  • Date: 2010-03-21 13:27:56 UTC
  • mto: (2.1.3 experimental)
  • mto: This revision was merged to the branch mainline in revision 8.
  • Revision ID: james.westby@ubuntu.com-20100321132756-nf8yd30yxo3zzwcm
Tags: upstream-1.2.2
ImportĀ upstreamĀ versionĀ 1.2.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* stbi-1.18 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
 
2
                      when you control the images you're loading
 
3
 
 
4
   QUICK NOTES:
 
5
      Primarily of interest to game developers and other people who can
 
6
          avoid problematic images and only need the trivial interface
 
7
 
 
8
      JPEG baseline (no JPEG progressive, no oddball channel decimations)
 
9
      PNG 8-bit only
 
10
      BMP non-1bpp, non-RLE
 
11
      TGA (not sure what subset, if a subset)
 
12
      PSD (composited view only, no extra channels)
 
13
      HDR (radiance rgbE format)
 
14
      writes BMP,TGA (define STBI_NO_WRITE to remove code)
 
15
      decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)
 
16
      supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
 
17
        
 
18
   TODO:
 
19
      stbi_info_*
 
20
  
 
21
   history:
 
22
      1.18   fix a threading bug (local mutable static)
 
23
      1.17   support interlaced PNG
 
24
      1.16   major bugfix - convert_format converted one too many pixels
 
25
      1.15   initialize some fields for thread safety
 
26
      1.14   fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
 
27
      1.13   threadsafe
 
28
      1.12   const qualifiers in the API
 
29
      1.11   Support installable IDCT, colorspace conversion routines
 
30
      1.10   Fixes for 64-bit (don't use "unsigned long")
 
31
             optimized upsampling by Fabian "ryg" Giesen
 
32
      1.09   Fix format-conversion for PSD code (bad global variables!)
 
33
      1.08   Thatcher Ulrich's PSD code integrated by Nicolas Schulz
 
34
      1.07   attempt to fix C++ warning/errors again
 
35
      1.06   attempt to fix C++ warning/errors again
 
36
      1.05   fix TGA loading to return correct *comp and use good luminance calc
 
37
      1.04   default float alpha is 1, not 255; use 'void *' for stbi_image_free
 
38
      1.03   bugfixes to STBI_NO_STDIO, STBI_NO_HDR
 
39
      1.02   support for (subset of) HDR files, float interface for preferred access to them
 
40
      1.01   fix bug: possible bug in handling right-side up bmps... not sure
 
41
             fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all
 
42
      1.00   interface to zlib that skips zlib header
 
43
      0.99   correct handling of alpha in palette
 
44
      0.98   TGA loader by lonesock; dynamically add loaders (untested)
 
45
      0.97   jpeg errors on too large a file; also catch another malloc failure
 
46
      0.96   fix detection of invalid v value - particleman@mollyrocket forum
 
47
      0.95   during header scan, seek to markers in case of padding
 
48
      0.94   STBI_NO_STDIO to disable stdio usage; rename all #defines the same
 
49
      0.93   handle jpegtran output; verbose errors
 
50
      0.92   read 4,8,16,24,32-bit BMP files of several formats
 
51
      0.91   output 24-bit Windows 3.0 BMP files
 
52
      0.90   fix a few more warnings; bump version number to approach 1.0
 
53
      0.61   bugfixes due to Marc LeBlanc, Christopher Lloyd
 
54
      0.60   fix compiling as c++
 
55
      0.59   fix warnings: merge Dave Moore's -Wall fixes
 
56
      0.58   fix bug: zlib uncompressed mode len/nlen was wrong endian
 
57
      0.57   fix bug: jpg last huffman symbol before marker was >9 bits but less
 
58
                      than 16 available
 
59
      0.56   fix bug: zlib uncompressed mode len vs. nlen
 
60
      0.55   fix bug: restart_interval not initialized to 0
 
61
      0.54   allow NULL for 'int *comp'
 
62
      0.53   fix bug in png 3->4; speedup png decoding
 
63
      0.52   png handles req_comp=3,4 directly; minor cleanup; jpeg comments
 
64
      0.51   obey req_comp requests, 1-component jpegs return as 1-component,
 
65
             on 'test' only check type, not whether we support this variant
 
66
*/
 
67
 
 
68
 
 
69
#ifndef STBI_INCLUDE_STB_IMAGE_H
 
70
#define STBI_INCLUDE_STB_IMAGE_H
 
71
 
 
72
////   begin header file  ////////////////////////////////////////////////////
 
73
//
 
74
// Limitations:
 
75
//    - no progressive/interlaced support (jpeg, png)
 
76
//    - 8-bit samples only (jpeg, png)
 
77
//    - not threadsafe
 
78
//    - channel subsampling of at most 2 in each dimension (jpeg)
 
79
//    - no delayed line count (jpeg) -- IJG doesn't support either
 
80
//
 
81
// Basic usage (see HDR discussion below):
 
82
//    int x,y,n;
 
83
//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
 
84
//    // ... process data if not NULL ... 
 
85
//    // ... x = width, y = height, n = # 8-bit components per pixel ...
 
86
//    // ... replace '0' with '1'..'4' to force that many components per pixel
 
87
//    stbi_image_free(data)
 
88
//
 
89
// Standard parameters:
 
90
//    int *x       -- outputs image width in pixels
 
91
//    int *y       -- outputs image height in pixels
 
92
//    int *comp    -- outputs # of image components in image file
 
93
//    int req_comp -- if non-zero, # of image components requested in result
 
94
//
 
95
// The return value from an image loader is an 'unsigned char *' which points
 
96
// to the pixel data. The pixel data consists of *y scanlines of *x pixels,
 
97
// with each pixel consisting of N interleaved 8-bit components; the first
 
98
// pixel pointed to is top-left-most in the image. There is no padding between
 
99
// image scanlines or between pixels, regardless of format. The number of
 
100
// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
 
101
// If req_comp is non-zero, *comp has the number of components that _would_
 
102
// have been output otherwise. E.g. if you set req_comp to 4, you will always
 
103
// get RGBA output, but you can check *comp to easily see if it's opaque.
 
104
//
 
105
// An output image with N components has the following components interleaved
 
106
// in this order in each pixel:
 
107
//
 
108
//     N=#comp     components
 
109
//       1           grey
 
110
//       2           grey, alpha
 
111
//       3           red, green, blue
 
112
//       4           red, green, blue, alpha
 
113
//
 
114
// If image loading fails for any reason, the return value will be NULL,
 
115
// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
 
116
// can be queried for an extremely brief, end-user unfriendly explanation
 
117
// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
 
118
// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
 
119
// more user-friendly ones.
 
120
//
 
121
// Paletted PNG and BMP images are automatically depalettized.
 
122
//
 
123
//
 
124
// ===========================================================================
 
125
//
 
126
// HDR image support   (disable by defining STBI_NO_HDR)
 
127
//
 
128
// stb_image now supports loading HDR images in general, and currently
 
129
// the Radiance .HDR file format, although the support is provided
 
130
// generically. You can still load any file through the existing interface;
 
131
// if you attempt to load an HDR file, it will be automatically remapped to
 
132
// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
 
133
// both of these constants can be reconfigured through this interface:
 
134
//
 
135
//     stbi_hdr_to_ldr_gamma(2.2f);
 
136
//     stbi_hdr_to_ldr_scale(1.0f);
 
137
//
 
138
// (note, do not use _inverse_ constants; stbi_image will invert them
 
139
// appropriately).
 
140
//
 
141
// Additionally, there is a new, parallel interface for loading files as
 
142
// (linear) floats to preserve the full dynamic range:
 
143
//
 
144
//    float *data = stbi_loadf(filename, &x, &y, &n, 0);
 
145
// 
 
146
// If you load LDR images through this interface, those images will
 
147
// be promoted to floating point values, run through the inverse of
 
148
// constants corresponding to the above:
 
149
//
 
150
//     stbi_ldr_to_hdr_scale(1.0f);
 
151
//     stbi_ldr_to_hdr_gamma(2.2f);
 
152
//
 
153
// Finally, given a filename (or an open file or memory block--see header
 
154
// file for details) containing image data, you can query for the "most
 
155
// appropriate" interface to use (that is, whether the image is HDR or
 
156
// not), using:
 
157
//
 
158
//     stbi_is_hdr(char *filename);
 
159
 
 
160
#ifndef STBI_NO_STDIO
 
161
#include <stdio.h>
 
162
#endif
 
163
 
 
164
#define STBI_VERSION 1
 
165
 
 
166
enum
 
167
{
 
168
   STBI_default = 0, // only used for req_comp
 
169
 
 
170
   STBI_grey       = 1,
 
171
   STBI_grey_alpha = 2,
 
172
   STBI_rgb        = 3,
 
173
   STBI_rgb_alpha  = 4,
 
174
};
 
175
 
 
176
typedef unsigned char stbi_uc;
 
177
 
 
178
#ifdef __cplusplus
 
179
extern "C" {
 
180
#endif
 
181
 
 
182
// WRITING API
 
183
 
 
184
#if !defined(STBI_NO_WRITE) && !defined(STBI_NO_STDIO)
 
185
// write a BMP/TGA file given tightly packed 'comp' channels (no padding, nor bmp-stride-padding)
 
186
// (you must include the appropriate extension in the filename).
 
187
// returns TRUE on success, FALSE if couldn't open file, error writing file
 
188
extern int      stbi_write_bmp       (char const *filename,     int x, int y, int comp, void *data);
 
189
extern int      stbi_write_tga       (char const *filename,     int x, int y, int comp, void *data);
 
190
#endif
 
191
 
 
192
// PRIMARY API - works on images of any type
 
193
 
 
194
// load image by filename, open file, or memory buffer
 
195
#ifndef STBI_NO_STDIO
 
196
extern stbi_uc *stbi_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);
 
197
extern stbi_uc *stbi_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);
 
198
extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
 
199
#endif
 
200
extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
201
// for stbi_load_from_file, file pointer is left pointing immediately after image
 
202
 
 
203
#ifndef STBI_NO_HDR
 
204
#ifndef STBI_NO_STDIO
 
205
extern float *stbi_loadf            (char const *filename,     int *x, int *y, int *comp, int req_comp);
 
206
extern float *stbi_loadf_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);
 
207
#endif
 
208
extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
209
 
 
210
extern void   stbi_hdr_to_ldr_gamma(float gamma);
 
211
extern void   stbi_hdr_to_ldr_scale(float scale);
 
212
 
 
213
extern void   stbi_ldr_to_hdr_gamma(float gamma);
 
214
extern void   stbi_ldr_to_hdr_scale(float scale);
 
215
 
 
216
#endif // STBI_NO_HDR
 
217
 
 
218
// get a VERY brief reason for failure
 
219
// NOT THREADSAFE
 
220
extern char    *stbi_failure_reason  (void); 
 
221
 
 
222
// free the loaded image -- this is just free()
 
223
extern void     stbi_image_free      (void *retval_from_stbi_load);
 
224
 
 
225
// get image dimensions & components without fully decoding
 
226
extern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
 
227
extern int      stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
 
228
#ifndef STBI_NO_STDIO
 
229
extern int      stbi_info            (char const *filename,     int *x, int *y, int *comp);
 
230
extern int      stbi_is_hdr          (char const *filename);
 
231
extern int      stbi_is_hdr_from_file(FILE *f);
 
232
#endif
 
233
 
 
234
// ZLIB client - used by PNG, available for other purposes
 
235
 
 
236
extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
 
237
extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
 
238
extern int   stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
 
239
 
 
240
extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
 
241
extern int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
 
242
 
 
243
// TYPE-SPECIFIC ACCESS
 
244
 
 
245
// is it a jpeg?
 
246
extern int      stbi_jpeg_test_memory     (stbi_uc const *buffer, int len);
 
247
extern stbi_uc *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
248
extern int      stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
 
249
 
 
250
#ifndef STBI_NO_STDIO
 
251
extern stbi_uc *stbi_jpeg_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);
 
252
extern int      stbi_jpeg_test_file       (FILE *f);
 
253
extern stbi_uc *stbi_jpeg_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);
 
254
 
 
255
extern int      stbi_jpeg_info            (char const *filename,     int *x, int *y, int *comp);
 
256
extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
 
257
#endif
 
258
 
 
259
// is it a png?
 
260
extern int      stbi_png_test_memory      (stbi_uc const *buffer, int len);
 
261
extern stbi_uc *stbi_png_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
262
extern int      stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);
 
263
 
 
264
#ifndef STBI_NO_STDIO
 
265
extern stbi_uc *stbi_png_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);
 
266
extern int      stbi_png_info             (char const *filename,     int *x, int *y, int *comp);
 
267
extern int      stbi_png_test_file        (FILE *f);
 
268
extern stbi_uc *stbi_png_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
 
269
extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);
 
270
#endif
 
271
 
 
272
// is it a bmp?
 
273
extern int      stbi_bmp_test_memory      (stbi_uc const *buffer, int len);
 
274
 
 
275
extern stbi_uc *stbi_bmp_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);
 
276
extern stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
277
#ifndef STBI_NO_STDIO
 
278
extern int      stbi_bmp_test_file        (FILE *f);
 
279
extern stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
 
280
#endif
 
281
 
 
282
// is it a tga?
 
283
extern int      stbi_tga_test_memory      (stbi_uc const *buffer, int len);
 
284
 
 
285
extern stbi_uc *stbi_tga_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);
 
286
extern stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
287
#ifndef STBI_NO_STDIO
 
288
extern int      stbi_tga_test_file        (FILE *f);
 
289
extern stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
 
290
#endif
 
291
 
 
292
// is it a psd?
 
293
extern int      stbi_psd_test_memory      (stbi_uc const *buffer, int len);
 
294
 
 
295
extern stbi_uc *stbi_psd_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);
 
296
extern stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
297
#ifndef STBI_NO_STDIO
 
298
extern int      stbi_psd_test_file        (FILE *f);
 
299
extern stbi_uc *stbi_psd_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
 
300
#endif
 
301
 
 
302
// is it an hdr?
 
303
extern int      stbi_hdr_test_memory      (stbi_uc const *buffer, int len);
 
304
 
 
305
extern float *  stbi_hdr_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);
 
306
extern float *  stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
307
#ifndef STBI_NO_STDIO
 
308
extern int      stbi_hdr_test_file        (FILE *f);
 
309
extern float *  stbi_hdr_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
 
310
#endif
 
311
 
 
312
// define new loaders
 
313
typedef struct
 
314
{
 
315
   int       (*test_memory)(stbi_uc const *buffer, int len);
 
316
   stbi_uc * (*load_from_memory)(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
 
317
   #ifndef STBI_NO_STDIO
 
318
   int       (*test_file)(FILE *f);
 
319
   stbi_uc * (*load_from_file)(FILE *f, int *x, int *y, int *comp, int req_comp);
 
320
   #endif
 
321
} stbi_loader;
 
322
 
 
323
// register a loader by filling out the above structure (you must defined ALL functions)
 
324
// returns 1 if added or already added, 0 if not added (too many loaders)
 
325
// NOT THREADSAFE
 
326
extern int stbi_register_loader(stbi_loader *loader);
 
327
 
 
328
// define faster low-level operations (typically SIMD support)
 
329
#if STBI_SIMD
 
330
typedef void (*stbi_idct_8x8)(uint8 *out, int out_stride, short data[64], unsigned short *dequantize);
 
331
// compute an integer IDCT on "input"
 
332
//     input[x] = data[x] * dequantize[x]
 
333
//     write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
 
334
//                             CLAMP results to 0..255
 
335
typedef void (*stbi_YCbCr_to_RGB_run)(uint8 *output, uint8 const *y, uint8 const *cb, uint8 const *cr, int count, int step);
 
336
// compute a conversion from YCbCr to RGB
 
337
//     'count' pixels
 
338
//     write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
 
339
//     y: Y input channel
 
340
//     cb: Cb input channel; scale/biased to be 0..255
 
341
//     cr: Cr input channel; scale/biased to be 0..255
 
342
 
 
343
extern void stbi_install_idct(stbi_idct_8x8 func);
 
344
extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
 
345
#endif // STBI_SIMD
 
346
 
 
347
#ifdef __cplusplus
 
348
}
 
349
#endif
 
350
 
 
351
//
 
352
//
 
353
////   end header file   /////////////////////////////////////////////////////
 
354
#endif // STBI_INCLUDE_STB_IMAGE_H
 
355
 
 
356
#ifndef STBI_HEADER_FILE_ONLY
 
357
 
 
358
#ifndef STBI_NO_HDR
 
359
#include <math.h>  // ldexp
 
360
#include <string.h> // strcmp
 
361
#endif
 
362
 
 
363
#ifndef STBI_NO_STDIO
 
364
#include <stdio.h>
 
365
#endif
 
366
#include <stdlib.h>
 
367
#include <memory.h>
 
368
#include <assert.h>
 
369
#include <stdarg.h>
 
370
 
 
371
#ifndef _MSC_VER
 
372
  #ifdef __cplusplus
 
373
  #define __forceinline inline
 
374
  #else
 
375
  #define __forceinline
 
376
  #endif
 
377
#endif
 
378
 
 
379
 
 
380
// implementation:
 
381
typedef unsigned char uint8;
 
382
typedef unsigned short uint16;
 
383
typedef   signed short  int16;
 
384
typedef unsigned int   uint32;
 
385
typedef   signed int    int32;
 
386
typedef unsigned int   uint;
 
387
 
 
388
// should produce compiler error if size is wrong
 
389
typedef unsigned char validate_uint32[sizeof(uint32)==4];
 
390
 
 
391
#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
 
392
#define STBI_NO_WRITE
 
393
#endif
 
394
 
 
395
//////////////////////////////////////////////////////////////////////////////
 
396
//
 
397
// Generic API that works on all image types
 
398
//
 
399
 
 
400
// this is not threadsafe
 
401
static char *failure_reason;
 
402
 
 
403
char *stbi_failure_reason(void)
 
404
{
 
405
   return failure_reason;
 
406
}
 
407
 
 
408
static int e(char *str)
 
409
{
 
410
   failure_reason = str;
 
411
   return 0;
 
412
}
 
413
 
 
414
#ifdef STBI_NO_FAILURE_STRINGS
 
415
   #define e(x,y)  0
 
416
#elif defined(STBI_FAILURE_USERMSG)
 
417
   #define e(x,y)  e(y)
 
418
#else
 
419
   #define e(x,y)  e(x)
 
420
#endif
 
421
 
 
422
#define epf(x,y)   ((float *) (e(x,y)?NULL:NULL))
 
423
#define epuc(x,y)  ((unsigned char *) (e(x,y)?NULL:NULL))
 
424
 
 
425
void stbi_image_free(void *retval_from_stbi_load)
 
426
{
 
427
   free(retval_from_stbi_load);
 
428
}
 
429
 
 
430
#define MAX_LOADERS  32
 
431
stbi_loader *loaders[MAX_LOADERS];
 
432
static int max_loaders = 0;
 
433
 
 
434
int stbi_register_loader(stbi_loader *loader)
 
435
{
 
436
   int i;
 
437
   for (i=0; i < MAX_LOADERS; ++i) {
 
438
      // already present?
 
439
      if (loaders[i] == loader)
 
440
         return 1;
 
441
      // end of the list?
 
442
      if (loaders[i] == NULL) {
 
443
         loaders[i] = loader;
 
444
         max_loaders = i+1;
 
445
         return 1;
 
446
      }
 
447
   }
 
448
   // no room for it
 
449
   return 0;
 
450
}
 
451
 
 
452
#ifndef STBI_NO_HDR
 
453
static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
 
454
static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp);
 
455
#endif
 
456
 
 
457
#ifndef STBI_NO_STDIO
 
458
unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
 
459
{
 
460
   FILE *f = fopen(filename, "rb");
 
461
   unsigned char *result;
 
462
   if (!f) return epuc("can't fopen", "Unable to open file");
 
463
   result = stbi_load_from_file(f,x,y,comp,req_comp);
 
464
   fclose(f);
 
465
   return result;
 
466
}
 
467
 
 
468
unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
 
469
{
 
470
   int i;
 
471
   if (stbi_jpeg_test_file(f))
 
472
      return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);
 
473
   if (stbi_png_test_file(f))
 
474
      return stbi_png_load_from_file(f,x,y,comp,req_comp);
 
475
   if (stbi_bmp_test_file(f))
 
476
      return stbi_bmp_load_from_file(f,x,y,comp,req_comp);
 
477
   if (stbi_psd_test_file(f))
 
478
      return stbi_psd_load_from_file(f,x,y,comp,req_comp);
 
479
   #ifndef STBI_NO_HDR
 
480
   if (stbi_hdr_test_file(f)) {
 
481
      float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp);
 
482
      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
 
483
   }
 
484
   #endif
 
485
   for (i=0; i < max_loaders; ++i)
 
486
      if (loaders[i]->test_file(f))
 
487
         return loaders[i]->load_from_file(f,x,y,comp,req_comp);
 
488
   // test tga last because it's a crappy test!
 
489
   if (stbi_tga_test_file(f))
 
490
      return stbi_tga_load_from_file(f,x,y,comp,req_comp);
 
491
   return epuc("unknown image type", "Image not of any known type, or corrupt");
 
492
}
 
493
#endif
 
494
 
 
495
unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
 
496
{
 
497
   int i;
 
498
   if (stbi_jpeg_test_memory(buffer,len))
 
499
      return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);
 
500
   if (stbi_png_test_memory(buffer,len))
 
501
      return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);
 
502
   if (stbi_bmp_test_memory(buffer,len))
 
503
      return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);
 
504
   if (stbi_psd_test_memory(buffer,len))
 
505
      return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);
 
506
   #ifndef STBI_NO_HDR
 
507
   if (stbi_hdr_test_memory(buffer, len)) {
 
508
      float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
 
509
      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
 
510
   }
 
511
   #endif
 
512
   for (i=0; i < max_loaders; ++i)
 
513
      if (loaders[i]->test_memory(buffer,len))
 
514
         return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp);
 
515
   // test tga last because it's a crappy test!
 
516
   if (stbi_tga_test_memory(buffer,len))
 
517
      return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp);
 
518
   return epuc("unknown image type", "Image not of any known type, or corrupt");
 
519
}
 
520
 
 
521
#ifndef STBI_NO_HDR
 
522
 
 
523
#ifndef STBI_NO_STDIO
 
524
float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
 
525
{
 
526
   FILE *f = fopen(filename, "rb");
 
527
   float *result;
 
528
   if (!f) return epf("can't fopen", "Unable to open file");
 
529
   result = stbi_loadf_from_file(f,x,y,comp,req_comp);
 
530
   fclose(f);
 
531
   return result;
 
532
}
 
533
 
 
534
float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
 
535
{
 
536
   unsigned char *data;
 
537
   #ifndef STBI_NO_HDR
 
538
   if (stbi_hdr_test_file(f))
 
539
      return stbi_hdr_load_from_file(f,x,y,comp,req_comp);
 
540
   #endif
 
541
   data = stbi_load_from_file(f, x, y, comp, req_comp);
 
542
   if (data)
 
543
      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
 
544
   return epf("unknown image type", "Image not of any known type, or corrupt");
 
545
}
 
546
#endif
 
547
 
 
548
float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
 
549
{
 
550
   stbi_uc *data;
 
551
   #ifndef STBI_NO_HDR
 
552
   if (stbi_hdr_test_memory(buffer, len))
 
553
      return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
 
554
   #endif
 
555
   data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp);
 
556
   if (data)
 
557
      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
 
558
   return epf("unknown image type", "Image not of any known type, or corrupt");
 
559
}
 
560
#endif
 
561
 
 
562
// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
 
563
// defined, for API simplicity; if STBI_NO_HDR is defined, it always
 
564
// reports false!
 
565
 
 
566
int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
 
567
{
 
568
   #ifndef STBI_NO_HDR
 
569
   return stbi_hdr_test_memory(buffer, len);
 
570
   #else
 
571
   return 0;
 
572
   #endif
 
573
}
 
574
 
 
575
#ifndef STBI_NO_STDIO
 
576
extern int      stbi_is_hdr          (char const *filename)
 
577
{
 
578
   FILE *f = fopen(filename, "rb");
 
579
   int result=0;
 
580
   if (f) {
 
581
      result = stbi_is_hdr_from_file(f);
 
582
      fclose(f);
 
583
   }
 
584
   return result;
 
585
}
 
586
 
 
587
extern int      stbi_is_hdr_from_file(FILE *f)
 
588
{
 
589
   #ifndef STBI_NO_HDR
 
590
   return stbi_hdr_test_file(f);
 
591
   #else
 
592
   return 0;
 
593
   #endif
 
594
}
 
595
 
 
596
#endif
 
597
 
 
598
// @TODO: get image dimensions & components without fully decoding
 
599
#ifndef STBI_NO_STDIO
 
600
extern int      stbi_info            (char const *filename,           int *x, int *y, int *comp);
 
601
extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
 
602
#endif
 
603
extern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
 
604
 
 
605
#ifndef STBI_NO_HDR
 
606
static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
 
607
static float l2h_gamma=2.2f, l2h_scale=1.0f;
 
608
 
 
609
void   stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
 
610
void   stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
 
611
 
 
612
void   stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
 
613
void   stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
 
614
#endif
 
615
 
 
616
 
 
617
//////////////////////////////////////////////////////////////////////////////
 
618
//
 
619
// Common code used by all image loaders
 
620
//
 
621
 
 
622
enum
 
623
{
 
624
   SCAN_load=0,
 
625
   SCAN_type,
 
626
   SCAN_header,
 
627
};
 
628
 
 
629
typedef struct
 
630
{
 
631
   uint32 img_x, img_y;
 
632
   int img_n, img_out_n;
 
633
 
 
634
   #ifndef STBI_NO_STDIO
 
635
   FILE  *img_file;
 
636
   #endif
 
637
   uint8 *img_buffer, *img_buffer_end;
 
638
} stbi;
 
639
 
 
640
#ifndef STBI_NO_STDIO
 
641
static void start_file(stbi *s, FILE *f)
 
642
{
 
643
   s->img_file = f;
 
644
}
 
645
#endif
 
646
 
 
647
static void start_mem(stbi *s, uint8 const *buffer, int len)
 
648
{
 
649
#ifndef STBI_NO_STDIO
 
650
   s->img_file = NULL;
 
651
#endif
 
652
   s->img_buffer = (uint8 *) buffer;
 
653
   s->img_buffer_end = (uint8 *) buffer+len;
 
654
}
 
655
 
 
656
__forceinline static int get8(stbi *s)
 
657
{
 
658
#ifndef STBI_NO_STDIO
 
659
   if (s->img_file) {
 
660
      int c = fgetc(s->img_file);
 
661
      return c == EOF ? 0 : c;
 
662
   }
 
663
#endif
 
664
   if (s->img_buffer < s->img_buffer_end)
 
665
      return *s->img_buffer++;
 
666
   return 0;
 
667
}
 
668
 
 
669
__forceinline static int at_eof(stbi *s)
 
670
{
 
671
#ifndef STBI_NO_STDIO
 
672
   if (s->img_file)
 
673
      return feof(s->img_file);
 
674
#endif
 
675
   return s->img_buffer >= s->img_buffer_end;   
 
676
}
 
677
 
 
678
__forceinline static uint8 get8u(stbi *s)
 
679
{
 
680
   return (uint8) get8(s);
 
681
}
 
682
 
 
683
static void skip(stbi *s, int n)
 
684
{
 
685
#ifndef STBI_NO_STDIO
 
686
   if (s->img_file)
 
687
      fseek(s->img_file, n, SEEK_CUR);
 
688
   else
 
689
#endif
 
690
      s->img_buffer += n;
 
691
}
 
692
 
 
693
static int get16(stbi *s)
 
694
{
 
695
   int z = get8(s);
 
696
   return (z << 8) + get8(s);
 
697
}
 
698
 
 
699
static uint32 get32(stbi *s)
 
700
{
 
701
   uint32 z = get16(s);
 
702
   return (z << 16) + get16(s);
 
703
}
 
704
 
 
705
static int get16le(stbi *s)
 
706
{
 
707
   int z = get8(s);
 
708
   return z + (get8(s) << 8);
 
709
}
 
710
 
 
711
static uint32 get32le(stbi *s)
 
712
{
 
713
   uint32 z = get16le(s);
 
714
   return z + (get16le(s) << 16);
 
715
}
 
716
 
 
717
static void getn(stbi *s, stbi_uc *buffer, int n)
 
718
{
 
719
#ifndef STBI_NO_STDIO
 
720
   if (s->img_file) {
 
721
      fread(buffer, 1, n, s->img_file);
 
722
      return;
 
723
   }
 
724
#endif
 
725
   memcpy(buffer, s->img_buffer, n);
 
726
   s->img_buffer += n;
 
727
}
 
728
 
 
729
//////////////////////////////////////////////////////////////////////////////
 
730
//
 
731
//  generic converter from built-in img_n to req_comp
 
732
//    individual types do this automatically as much as possible (e.g. jpeg
 
733
//    does all cases internally since it needs to colorspace convert anyway,
 
734
//    and it never has alpha, so very few cases ). png can automatically
 
735
//    interleave an alpha=255 channel, but falls back to this for other cases
 
736
//
 
737
//  assume data buffer is malloced, so malloc a new one and free that one
 
738
//  only failure mode is malloc failing
 
739
 
 
740
static uint8 compute_y(int r, int g, int b)
 
741
{
 
742
   return (uint8) (((r*77) + (g*150) +  (29*b)) >> 8);
 
743
}
 
744
 
 
745
static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
 
746
{
 
747
   int i,j;
 
748
   unsigned char *good;
 
749
 
 
750
   if (req_comp == img_n) return data;
 
751
   assert(req_comp >= 1 && req_comp <= 4);
 
752
 
 
753
   good = (unsigned char *) malloc(req_comp * x * y);
 
754
   if (good == NULL) {
 
755
      free(data);
 
756
      return epuc("outofmem", "Out of memory");
 
757
   }
 
758
 
 
759
   for (j=0; j < (int) y; ++j) {
 
760
      unsigned char *src  = data + j * x * img_n   ;
 
761
      unsigned char *dest = good + j * x * req_comp;
 
762
 
 
763
      #define COMBO(a,b)  ((a)*8+(b))
 
764
      #define CASE(a,b)   case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
 
765
      // convert source image with img_n components to one with req_comp components;
 
766
      // avoid switch per pixel, so use switch per scanline and massive macros
 
767
      switch(COMBO(img_n, req_comp)) {
 
768
         CASE(1,2) dest[0]=src[0], dest[1]=255; break;
 
769
         CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
 
770
         CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
 
771
         CASE(2,1) dest[0]=src[0]; break;
 
772
         CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
 
773
         CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
 
774
         CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
 
775
         CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
 
776
         CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
 
777
         CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
 
778
         CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
 
779
         CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
 
780
         default: assert(0);
 
781
      }
 
782
      #undef CASE
 
783
   }
 
784
 
 
785
   free(data);
 
786
   return good;
 
787
}
 
788
 
 
789
#ifndef STBI_NO_HDR
 
790
static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
 
791
{
 
792
   int i,k,n;
 
793
   float *output = (float *) malloc(x * y * comp * sizeof(float));
 
794
   if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }
 
795
   // compute number of non-alpha components
 
796
   if (comp & 1) n = comp; else n = comp-1;
 
797
   for (i=0; i < x*y; ++i) {
 
798
      for (k=0; k < n; ++k) {
 
799
         output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
 
800
      }
 
801
      if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
 
802
   }
 
803
   free(data);
 
804
   return output;
 
805
}
 
806
 
 
807
#define float2int(x)   ((int) (x))
 
808
static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp)
 
809
{
 
810
   int i,k,n;
 
811
   stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
 
812
   if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }
 
813
   // compute number of non-alpha components
 
814
   if (comp & 1) n = comp; else n = comp-1;
 
815
   for (i=0; i < x*y; ++i) {
 
816
      for (k=0; k < n; ++k) {
 
817
         float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
 
818
         if (z < 0) z = 0;
 
819
         if (z > 255) z = 255;
 
820
         output[i*comp + k] = float2int(z);
 
821
      }
 
822
      if (k < comp) {
 
823
         float z = data[i*comp+k] * 255 + 0.5f;
 
824
         if (z < 0) z = 0;
 
825
         if (z > 255) z = 255;
 
826
         output[i*comp + k] = float2int(z);
 
827
      }
 
828
   }
 
829
   free(data);
 
830
   return output;
 
831
}
 
832
#endif
 
833
 
 
834
//////////////////////////////////////////////////////////////////////////////
 
835
//
 
836
//  "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
 
837
//
 
838
//    simple implementation
 
839
//      - channel subsampling of at most 2 in each dimension
 
840
//      - doesn't support delayed output of y-dimension
 
841
//      - simple interface (only one output format: 8-bit interleaved RGB)
 
842
//      - doesn't try to recover corrupt jpegs
 
843
//      - doesn't allow partial loading, loading multiple at once
 
844
//      - still fast on x86 (copying globals into locals doesn't help x86)
 
845
//      - allocates lots of intermediate memory (full size of all components)
 
846
//        - non-interleaved case requires this anyway
 
847
//        - allows good upsampling (see next)
 
848
//    high-quality
 
849
//      - upsampled channels are bilinearly interpolated, even across blocks
 
850
//      - quality integer IDCT derived from IJG's 'slow'
 
851
//    performance
 
852
//      - fast huffman; reasonable integer IDCT
 
853
//      - uses a lot of intermediate memory, could cache poorly
 
854
//      - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
 
855
//          stb_jpeg:   1.34 seconds (MSVC6, default release build)
 
856
//          stb_jpeg:   1.06 seconds (MSVC6, processor = Pentium Pro)
 
857
//          IJL11.dll:  1.08 seconds (compiled by intel)
 
858
//          IJG 1998:   0.98 seconds (MSVC6, makefile provided by IJG)
 
859
//          IJG 1998:   0.95 seconds (MSVC6, makefile + proc=PPro)
 
860
 
 
861
// huffman decoding acceleration
 
862
#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache
 
863
 
 
864
typedef struct
 
865
{
 
866
   uint8  fast[1 << FAST_BITS];
 
867
   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
 
868
   uint16 code[256];
 
869
   uint8  values[256];
 
870
   uint8  size[257];
 
871
   unsigned int maxcode[18];
 
872
   int    delta[17];   // old 'firstsymbol' - old 'firstcode'
 
873
} huffman;
 
874
 
 
875
typedef struct
 
876
{
 
877
   #if STBI_SIMD
 
878
   unsigned short dequant2[4][64];
 
879
   #endif
 
880
   stbi s;
 
881
   huffman huff_dc[4];
 
882
   huffman huff_ac[4];
 
883
   uint8 dequant[4][64];
 
884
 
 
885
// sizes for components, interleaved MCUs
 
886
   int img_h_max, img_v_max;
 
887
   int img_mcu_x, img_mcu_y;
 
888
   int img_mcu_w, img_mcu_h;
 
889
 
 
890
// definition of jpeg image component
 
891
   struct
 
892
   {
 
893
      int id;
 
894
      int h,v;
 
895
      int tq;
 
896
      int hd,ha;
 
897
      int dc_pred;
 
898
 
 
899
      int x,y,w2,h2;
 
900
      uint8 *data;
 
901
      void *raw_data;
 
902
      uint8 *linebuf;
 
903
   } img_comp[4];
 
904
 
 
905
   uint32         code_buffer; // jpeg entropy-coded buffer
 
906
   int            code_bits;   // number of valid bits
 
907
   unsigned char  marker;      // marker seen while filling entropy buffer
 
908
   int            nomore;      // flag if we saw a marker so must stop
 
909
 
 
910
   int scan_n, order[4];
 
911
   int restart_interval, todo;
 
912
} jpeg;
 
913
 
 
914
static int build_huffman(huffman *h, int *count)
 
915
{
 
916
   int i,j,k=0,code;
 
917
   // build size list for each symbol (from JPEG spec)
 
918
   for (i=0; i < 16; ++i)
 
919
      for (j=0; j < count[i]; ++j)
 
920
         h->size[k++] = (uint8) (i+1);
 
921
   h->size[k] = 0;
 
922
 
 
923
   // compute actual symbols (from jpeg spec)
 
924
   code = 0;
 
925
   k = 0;
 
926
   for(j=1; j <= 16; ++j) {
 
927
      // compute delta to add to code to compute symbol id
 
928
      h->delta[j] = k - code;
 
929
      if (h->size[k] == j) {
 
930
         while (h->size[k] == j)
 
931
            h->code[k++] = (uint16) (code++);
 
932
         if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");
 
933
      }
 
934
      // compute largest code + 1 for this size, preshifted as needed later
 
935
      h->maxcode[j] = code << (16-j);
 
936
      code <<= 1;
 
937
   }
 
938
   h->maxcode[j] = 0xffffffff;
 
939
 
 
940
   // build non-spec acceleration table; 255 is flag for not-accelerated
 
941
   memset(h->fast, 255, 1 << FAST_BITS);
 
942
   for (i=0; i < k; ++i) {
 
943
      int s = h->size[i];
 
944
      if (s <= FAST_BITS) {
 
945
         int c = h->code[i] << (FAST_BITS-s);
 
946
         int m = 1 << (FAST_BITS-s);
 
947
         for (j=0; j < m; ++j) {
 
948
            h->fast[c+j] = (uint8) i;
 
949
         }
 
950
      }
 
951
   }
 
952
   return 1;
 
953
}
 
954
 
 
955
static void grow_buffer_unsafe(jpeg *j)
 
956
{
 
957
   do {
 
958
      int b = j->nomore ? 0 : get8(&j->s);
 
959
      if (b == 0xff) {
 
960
         int c = get8(&j->s);
 
961
         if (c != 0) {
 
962
            j->marker = (unsigned char) c;
 
963
            j->nomore = 1;
 
964
            return;
 
965
         }
 
966
      }
 
967
      j->code_buffer = (j->code_buffer << 8) | b;
 
968
      j->code_bits += 8;
 
969
   } while (j->code_bits <= 24);
 
970
}
 
971
 
 
972
// (1 << n) - 1
 
973
static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
 
974
 
 
975
// decode a jpeg huffman value from the bitstream
 
976
__forceinline static int decode(jpeg *j, huffman *h)
 
977
{
 
978
   unsigned int temp;
 
979
   int c,k;
 
980
 
 
981
   if (j->code_bits < 16) grow_buffer_unsafe(j);
 
982
 
 
983
   // look at the top FAST_BITS and determine what symbol ID it is,
 
984
   // if the code is <= FAST_BITS
 
985
   c = (j->code_buffer >> (j->code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1);
 
986
   k = h->fast[c];
 
987
   if (k < 255) {
 
988
      if (h->size[k] > j->code_bits)
 
989
         return -1;
 
990
      j->code_bits -= h->size[k];
 
991
      return h->values[k];
 
992
   }
 
993
 
 
994
   // naive test is to shift the code_buffer down so k bits are
 
995
   // valid, then test against maxcode. To speed this up, we've
 
996
   // preshifted maxcode left so that it has (16-k) 0s at the
 
997
   // end; in other words, regardless of the number of bits, it
 
998
   // wants to be compared against something shifted to have 16;
 
999
   // that way we don't need to shift inside the loop.
 
1000
   if (j->code_bits < 16)
 
1001
      temp = (j->code_buffer << (16 - j->code_bits)) & 0xffff;
 
1002
   else
 
1003
      temp = (j->code_buffer >> (j->code_bits - 16)) & 0xffff;
 
1004
   for (k=FAST_BITS+1 ; ; ++k)
 
1005
      if (temp < h->maxcode[k])
 
1006
         break;
 
1007
   if (k == 17) {
 
1008
      // error! code not found
 
1009
      j->code_bits -= 16;
 
1010
      return -1;
 
1011
   }
 
1012
 
 
1013
   if (k > j->code_bits)
 
1014
      return -1;
 
1015
 
 
1016
   // convert the huffman code to the symbol id
 
1017
   c = ((j->code_buffer >> (j->code_bits - k)) & bmask[k]) + h->delta[k];
 
1018
   assert((((j->code_buffer) >> (j->code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
 
1019
 
 
1020
   // convert the id to a symbol
 
1021
   j->code_bits -= k;
 
1022
   return h->values[c];
 
1023
}
 
1024
 
 
1025
// combined JPEG 'receive' and JPEG 'extend', since baseline
 
1026
// always extends everything it receives.
 
1027
__forceinline static int extend_receive(jpeg *j, int n)
 
1028
{
 
1029
   unsigned int m = 1 << (n-1);
 
1030
   unsigned int k;
 
1031
   if (j->code_bits < n) grow_buffer_unsafe(j);
 
1032
   k = (j->code_buffer >> (j->code_bits - n)) & bmask[n];
 
1033
   j->code_bits -= n;
 
1034
   // the following test is probably a random branch that won't
 
1035
   // predict well. I tried to table accelerate it but failed.
 
1036
   // maybe it's compiling as a conditional move?
 
1037
   if (k < m)
 
1038
      return (-1 << n) + k + 1;
 
1039
   else
 
1040
      return k;
 
1041
}
 
1042
 
 
1043
// given a value that's at position X in the zigzag stream,
 
1044
// where does it appear in the 8x8 matrix coded as row-major?
 
1045
static uint8 dezigzag[64+15] =
 
1046
{
 
1047
    0,  1,  8, 16,  9,  2,  3, 10,
 
1048
   17, 24, 32, 25, 18, 11,  4,  5,
 
1049
   12, 19, 26, 33, 40, 48, 41, 34,
 
1050
   27, 20, 13,  6,  7, 14, 21, 28,
 
1051
   35, 42, 49, 56, 57, 50, 43, 36,
 
1052
   29, 22, 15, 23, 30, 37, 44, 51,
 
1053
   58, 59, 52, 45, 38, 31, 39, 46,
 
1054
   53, 60, 61, 54, 47, 55, 62, 63,
 
1055
   // let corrupt input sample past end
 
1056
   63, 63, 63, 63, 63, 63, 63, 63,
 
1057
   63, 63, 63, 63, 63, 63, 63
 
1058
};
 
1059
 
 
1060
// decode one 64-entry block--
 
1061
static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
 
1062
{
 
1063
   int diff,dc,k;
 
1064
   int t = decode(j, hdc);
 
1065
   if (t < 0) return e("bad huffman code","Corrupt JPEG");
 
1066
 
 
1067
   // 0 all the ac values now so we can do it 32-bits at a time
 
1068
   memset(data,0,64*sizeof(data[0]));
 
1069
 
 
1070
   diff = t ? extend_receive(j, t) : 0;
 
1071
   dc = j->img_comp[b].dc_pred + diff;
 
1072
   j->img_comp[b].dc_pred = dc;
 
1073
   data[0] = (short) dc;
 
1074
 
 
1075
   // decode AC components, see JPEG spec
 
1076
   k = 1;
 
1077
   do {
 
1078
      int r,s;
 
1079
      int rs = decode(j, hac);
 
1080
      if (rs < 0) return e("bad huffman code","Corrupt JPEG");
 
1081
      s = rs & 15;
 
1082
      r = rs >> 4;
 
1083
      if (s == 0) {
 
1084
         if (rs != 0xf0) break; // end block
 
1085
         k += 16;
 
1086
      } else {
 
1087
         k += r;
 
1088
         // decode into unzigzag'd location
 
1089
         data[dezigzag[k++]] = (short) extend_receive(j,s);
 
1090
      }
 
1091
   } while (k < 64);
 
1092
   return 1;
 
1093
}
 
1094
 
 
1095
// take a -128..127 value and clamp it and convert to 0..255
 
1096
__forceinline static uint8 clamp(int x)
 
1097
{
 
1098
   x += 128;
 
1099
   // trick to use a single test to catch both cases
 
1100
   if ((unsigned int) x > 255) {
 
1101
      if (x < 0) return 0;
 
1102
      if (x > 255) return 255;
 
1103
   }
 
1104
   return (uint8) x;
 
1105
}
 
1106
 
 
1107
#define f2f(x)  (int) (((x) * 4096 + 0.5))
 
1108
#define fsh(x)  ((x) << 12)
 
1109
 
 
1110
// derived from jidctint -- DCT_ISLOW
 
1111
#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7)       \
 
1112
   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
 
1113
   p2 = s2;                                    \
 
1114
   p3 = s6;                                    \
 
1115
   p1 = (p2+p3) * f2f(0.5411961f);             \
 
1116
   t2 = p1 + p3*f2f(-1.847759065f);            \
 
1117
   t3 = p1 + p2*f2f( 0.765366865f);            \
 
1118
   p2 = s0;                                    \
 
1119
   p3 = s4;                                    \
 
1120
   t0 = fsh(p2+p3);                            \
 
1121
   t1 = fsh(p2-p3);                            \
 
1122
   x0 = t0+t3;                                 \
 
1123
   x3 = t0-t3;                                 \
 
1124
   x1 = t1+t2;                                 \
 
1125
   x2 = t1-t2;                                 \
 
1126
   t0 = s7;                                    \
 
1127
   t1 = s5;                                    \
 
1128
   t2 = s3;                                    \
 
1129
   t3 = s1;                                    \
 
1130
   p3 = t0+t2;                                 \
 
1131
   p4 = t1+t3;                                 \
 
1132
   p1 = t0+t3;                                 \
 
1133
   p2 = t1+t2;                                 \
 
1134
   p5 = (p3+p4)*f2f( 1.175875602f);            \
 
1135
   t0 = t0*f2f( 0.298631336f);                 \
 
1136
   t1 = t1*f2f( 2.053119869f);                 \
 
1137
   t2 = t2*f2f( 3.072711026f);                 \
 
1138
   t3 = t3*f2f( 1.501321110f);                 \
 
1139
   p1 = p5 + p1*f2f(-0.899976223f);            \
 
1140
   p2 = p5 + p2*f2f(-2.562915447f);            \
 
1141
   p3 = p3*f2f(-1.961570560f);                 \
 
1142
   p4 = p4*f2f(-0.390180644f);                 \
 
1143
   t3 += p1+p4;                                \
 
1144
   t2 += p2+p3;                                \
 
1145
   t1 += p2+p4;                                \
 
1146
   t0 += p1+p3;
 
1147
 
 
1148
#if !STBI_SIMD
 
1149
// .344 seconds on 3*anemones.jpg
 
1150
static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize)
 
1151
{
 
1152
   int i,val[64],*v=val;
 
1153
   uint8 *o,*dq = dequantize;
 
1154
   short *d = data;
 
1155
 
 
1156
   // columns
 
1157
   for (i=0; i < 8; ++i,++d,++dq, ++v) {
 
1158
      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
 
1159
      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
 
1160
           && d[40]==0 && d[48]==0 && d[56]==0) {
 
1161
         //    no shortcut                 0     seconds
 
1162
         //    (1|2|3|4|5|6|7)==0          0     seconds
 
1163
         //    all separate               -0.047 seconds
 
1164
         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds
 
1165
         int dcterm = d[0] * dq[0] << 2;
 
1166
         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
 
1167
      } else {
 
1168
         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
 
1169
                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
 
1170
         // constants scaled things up by 1<<12; let's bring them back
 
1171
         // down, but keep 2 extra bits of precision
 
1172
         x0 += 512; x1 += 512; x2 += 512; x3 += 512;
 
1173
         v[ 0] = (x0+t3) >> 10;
 
1174
         v[56] = (x0-t3) >> 10;
 
1175
         v[ 8] = (x1+t2) >> 10;
 
1176
         v[48] = (x1-t2) >> 10;
 
1177
         v[16] = (x2+t1) >> 10;
 
1178
         v[40] = (x2-t1) >> 10;
 
1179
         v[24] = (x3+t0) >> 10;
 
1180
         v[32] = (x3-t0) >> 10;
 
1181
      }
 
1182
   }
 
1183
 
 
1184
   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
 
1185
      // no fast case since the first 1D IDCT spread components out
 
1186
      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
 
1187
      // constants scaled things up by 1<<12, plus we had 1<<2 from first
 
1188
      // loop, plus horizontal and vertical each scale by sqrt(8) so together
 
1189
      // we've got an extra 1<<3, so 1<<17 total we need to remove.
 
1190
      x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
 
1191
      o[0] = clamp((x0+t3) >> 17);
 
1192
      o[7] = clamp((x0-t3) >> 17);
 
1193
      o[1] = clamp((x1+t2) >> 17);
 
1194
      o[6] = clamp((x1-t2) >> 17);
 
1195
      o[2] = clamp((x2+t1) >> 17);
 
1196
      o[5] = clamp((x2-t1) >> 17);
 
1197
      o[3] = clamp((x3+t0) >> 17);
 
1198
      o[4] = clamp((x3-t0) >> 17);
 
1199
   }
 
1200
}
 
1201
#else
 
1202
static void idct_block(uint8 *out, int out_stride, short data[64], unsigned short *dequantize)
 
1203
{
 
1204
   int i,val[64],*v=val;
 
1205
   uint8 *o;
 
1206
   unsigned short *dq = dequantize;
 
1207
   short *d = data;
 
1208
 
 
1209
   // columns
 
1210
   for (i=0; i < 8; ++i,++d,++dq, ++v) {
 
1211
      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
 
1212
      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
 
1213
           && d[40]==0 && d[48]==0 && d[56]==0) {
 
1214
         //    no shortcut                 0     seconds
 
1215
         //    (1|2|3|4|5|6|7)==0          0     seconds
 
1216
         //    all separate               -0.047 seconds
 
1217
         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds
 
1218
         int dcterm = d[0] * dq[0] << 2;
 
1219
         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
 
1220
      } else {
 
1221
         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
 
1222
                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
 
1223
         // constants scaled things up by 1<<12; let's bring them back
 
1224
         // down, but keep 2 extra bits of precision
 
1225
         x0 += 512; x1 += 512; x2 += 512; x3 += 512;
 
1226
         v[ 0] = (x0+t3) >> 10;
 
1227
         v[56] = (x0-t3) >> 10;
 
1228
         v[ 8] = (x1+t2) >> 10;
 
1229
         v[48] = (x1-t2) >> 10;
 
1230
         v[16] = (x2+t1) >> 10;
 
1231
         v[40] = (x2-t1) >> 10;
 
1232
         v[24] = (x3+t0) >> 10;
 
1233
         v[32] = (x3-t0) >> 10;
 
1234
      }
 
1235
   }
 
1236
 
 
1237
   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
 
1238
      // no fast case since the first 1D IDCT spread components out
 
1239
      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
 
1240
      // constants scaled things up by 1<<12, plus we had 1<<2 from first
 
1241
      // loop, plus horizontal and vertical each scale by sqrt(8) so together
 
1242
      // we've got an extra 1<<3, so 1<<17 total we need to remove.
 
1243
      x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
 
1244
      o[0] = clamp((x0+t3) >> 17);
 
1245
      o[7] = clamp((x0-t3) >> 17);
 
1246
      o[1] = clamp((x1+t2) >> 17);
 
1247
      o[6] = clamp((x1-t2) >> 17);
 
1248
      o[2] = clamp((x2+t1) >> 17);
 
1249
      o[5] = clamp((x2-t1) >> 17);
 
1250
      o[3] = clamp((x3+t0) >> 17);
 
1251
      o[4] = clamp((x3-t0) >> 17);
 
1252
   }
 
1253
}
 
1254
static stbi_idct_8x8 stbi_idct_installed = idct_block;
 
1255
 
 
1256
extern void stbi_install_idct(stbi_idct_8x8 func)
 
1257
{
 
1258
   stbi_idct_installed = func;
 
1259
}
 
1260
#endif
 
1261
 
 
1262
#define MARKER_none  0xff
 
1263
// if there's a pending marker from the entropy stream, return that
 
1264
// otherwise, fetch from the stream and get a marker. if there's no
 
1265
// marker, return 0xff, which is never a valid marker value
 
1266
static uint8 get_marker(jpeg *j)
 
1267
{
 
1268
   uint8 x;
 
1269
   if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }
 
1270
   x = get8u(&j->s);
 
1271
   if (x != 0xff) return MARKER_none;
 
1272
   while (x == 0xff)
 
1273
      x = get8u(&j->s);
 
1274
   return x;
 
1275
}
 
1276
 
 
1277
// in each scan, we'll have scan_n components, and the order
 
1278
// of the components is specified by order[]
 
1279
#define RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)
 
1280
 
 
1281
// after a restart interval, reset the entropy decoder and
 
1282
// the dc prediction
 
1283
static void reset(jpeg *j)
 
1284
{
 
1285
   j->code_bits = 0;
 
1286
   j->code_buffer = 0;
 
1287
   j->nomore = 0;
 
1288
   j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
 
1289
   j->marker = MARKER_none;
 
1290
   j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
 
1291
   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
 
1292
   // since we don't even allow 1<<30 pixels
 
1293
}
 
1294
 
 
1295
static int parse_entropy_coded_data(jpeg *z)
 
1296
{
 
1297
   reset(z);
 
1298
   if (z->scan_n == 1) {
 
1299
      int i,j;
 
1300
      #if STBI_SIMD
 
1301
      __declspec(align(16))
 
1302
      #endif
 
1303
      short data[64];
 
1304
      int n = z->order[0];
 
1305
      // non-interleaved data, we just need to process one block at a time,
 
1306
      // in trivial scanline order
 
1307
      // number of blocks to do just depends on how many actual "pixels" this
 
1308
      // component has, independent of interleaved MCU blocking and such
 
1309
      int w = (z->img_comp[n].x+7) >> 3;
 
1310
      int h = (z->img_comp[n].y+7) >> 3;
 
1311
      for (j=0; j < h; ++j) {
 
1312
         for (i=0; i < w; ++i) {
 
1313
            if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
 
1314
            #if STBI_SIMD
 
1315
            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]);
 
1316
            #else
 
1317
            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]);
 
1318
            #endif
 
1319
            // every data block is an MCU, so countdown the restart interval
 
1320
            if (--z->todo <= 0) {
 
1321
               if (z->code_bits < 24) grow_buffer_unsafe(z);
 
1322
               // if it's NOT a restart, then just bail, so we get corrupt data
 
1323
               // rather than no data
 
1324
               if (!RESTART(z->marker)) return 1;
 
1325
               reset(z);
 
1326
            }
 
1327
         }
 
1328
      }
 
1329
   } else { // interleaved!
 
1330
      int i,j,k,x,y;
 
1331
      short data[64];
 
1332
      for (j=0; j < z->img_mcu_y; ++j) {
 
1333
         for (i=0; i < z->img_mcu_x; ++i) {
 
1334
            // scan an interleaved mcu... process scan_n components in order
 
1335
            for (k=0; k < z->scan_n; ++k) {
 
1336
               int n = z->order[k];
 
1337
               // scan out an mcu's worth of this component; that's just determined
 
1338
               // by the basic H and V specified for the component
 
1339
               for (y=0; y < z->img_comp[n].v; ++y) {
 
1340
                  for (x=0; x < z->img_comp[n].h; ++x) {
 
1341
                     int x2 = (i*z->img_comp[n].h + x)*8;
 
1342
                     int y2 = (j*z->img_comp[n].v + y)*8;
 
1343
                     if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
 
1344
                     #if STBI_SIMD
 
1345
                     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]);
 
1346
                     #else
 
1347
                     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]);
 
1348
                     #endif
 
1349
                  }
 
1350
               }
 
1351
            }
 
1352
            // after all interleaved components, that's an interleaved MCU,
 
1353
            // so now count down the restart interval
 
1354
            if (--z->todo <= 0) {
 
1355
               if (z->code_bits < 24) grow_buffer_unsafe(z);
 
1356
               // if it's NOT a restart, then just bail, so we get corrupt data
 
1357
               // rather than no data
 
1358
               if (!RESTART(z->marker)) return 1;
 
1359
               reset(z);
 
1360
            }
 
1361
         }
 
1362
      }
 
1363
   }
 
1364
   return 1;
 
1365
}
 
1366
 
 
1367
static int process_marker(jpeg *z, int m)
 
1368
{
 
1369
   int L;
 
1370
   switch (m) {
 
1371
      case MARKER_none: // no marker found
 
1372
         return e("expected marker","Corrupt JPEG");
 
1373
 
 
1374
      case 0xC2: // SOF - progressive
 
1375
         return e("progressive jpeg","JPEG format not supported (progressive)");
 
1376
 
 
1377
      case 0xDD: // DRI - specify restart interval
 
1378
         if (get16(&z->s) != 4) return e("bad DRI len","Corrupt JPEG");
 
1379
         z->restart_interval = get16(&z->s);
 
1380
         return 1;
 
1381
 
 
1382
      case 0xDB: // DQT - define quantization table
 
1383
         L = get16(&z->s)-2;
 
1384
         while (L > 0) {
 
1385
            int q = get8(&z->s);
 
1386
            int p = q >> 4;
 
1387
            int t = q & 15,i;
 
1388
            if (p != 0) return e("bad DQT type","Corrupt JPEG");
 
1389
            if (t > 3) return e("bad DQT table","Corrupt JPEG");
 
1390
            for (i=0; i < 64; ++i)
 
1391
               z->dequant[t][dezigzag[i]] = get8u(&z->s);
 
1392
            #if STBI_SIMD
 
1393
            for (i=0; i < 64; ++i)
 
1394
               z->dequant2[t][i] = z->dequant[t][i];
 
1395
            #endif
 
1396
            L -= 65;
 
1397
         }
 
1398
         return L==0;
 
1399
 
 
1400
      case 0xC4: // DHT - define huffman table
 
1401
         L = get16(&z->s)-2;
 
1402
         while (L > 0) {
 
1403
            uint8 *v;
 
1404
            int sizes[16],i,m=0;
 
1405
            int q = get8(&z->s);
 
1406
            int tc = q >> 4;
 
1407
            int th = q & 15;
 
1408
            if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");
 
1409
            for (i=0; i < 16; ++i) {
 
1410
               sizes[i] = get8(&z->s);
 
1411
               m += sizes[i];
 
1412
            }
 
1413
            L -= 17;
 
1414
            if (tc == 0) {
 
1415
               if (!build_huffman(z->huff_dc+th, sizes)) return 0;
 
1416
               v = z->huff_dc[th].values;
 
1417
            } else {
 
1418
               if (!build_huffman(z->huff_ac+th, sizes)) return 0;
 
1419
               v = z->huff_ac[th].values;
 
1420
            }
 
1421
            for (i=0; i < m; ++i)
 
1422
               v[i] = get8u(&z->s);
 
1423
            L -= m;
 
1424
         }
 
1425
         return L==0;
 
1426
   }
 
1427
   // check for comment block or APP blocks
 
1428
   if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
 
1429
      skip(&z->s, get16(&z->s)-2);
 
1430
      return 1;
 
1431
   }
 
1432
   return 0;
 
1433
}
 
1434
 
 
1435
// after we see SOS
 
1436
static int process_scan_header(jpeg *z)
 
1437
{
 
1438
   int i;
 
1439
   int Ls = get16(&z->s);
 
1440
   z->scan_n = get8(&z->s);
 
1441
   if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s.img_n) return e("bad SOS component count","Corrupt JPEG");
 
1442
   if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG");
 
1443
   for (i=0; i < z->scan_n; ++i) {
 
1444
      int id = get8(&z->s), which;
 
1445
      int q = get8(&z->s);
 
1446
      for (which = 0; which < z->s.img_n; ++which)
 
1447
         if (z->img_comp[which].id == id)
 
1448
            break;
 
1449
      if (which == z->s.img_n) return 0;
 
1450
      z->img_comp[which].hd = q >> 4;   if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");
 
1451
      z->img_comp[which].ha = q & 15;   if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");
 
1452
      z->order[i] = which;
 
1453
   }
 
1454
   if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG");
 
1455
   get8(&z->s); // should be 63, but might be 0
 
1456
   if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG");
 
1457
 
 
1458
   return 1;
 
1459
}
 
1460
 
 
1461
static int process_frame_header(jpeg *z, int scan)
 
1462
{
 
1463
   stbi *s = &z->s;
 
1464
   int Lf,p,i,q, h_max=1,v_max=1,c;
 
1465
   Lf = get16(s);         if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG
 
1466
   p  = get8(s);          if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
 
1467
   s->img_y = get16(s);   if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
 
1468
   s->img_x = get16(s);   if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires
 
1469
   c = get8(s);
 
1470
   if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG");    // JFIF requires
 
1471
   s->img_n = c;
 
1472
   for (i=0; i < c; ++i) {
 
1473
      z->img_comp[i].data = NULL;
 
1474
      z->img_comp[i].linebuf = NULL;
 
1475
   }
 
1476
 
 
1477
   if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG");
 
1478
 
 
1479
   for (i=0; i < s->img_n; ++i) {
 
1480
      z->img_comp[i].id = get8(s);
 
1481
      if (z->img_comp[i].id != i+1)   // JFIF requires
 
1482
         if (z->img_comp[i].id != i)  // some version of jpegtran outputs non-JFIF-compliant files!
 
1483
            return e("bad component ID","Corrupt JPEG");
 
1484
      q = get8(s);
 
1485
      z->img_comp[i].h = (q >> 4);  if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG");
 
1486
      z->img_comp[i].v = q & 15;    if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG");
 
1487
      z->img_comp[i].tq = get8(s);  if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");
 
1488
   }
 
1489
 
 
1490
   if (scan != SCAN_load) return 1;
 
1491
 
 
1492
   if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");
 
1493
 
 
1494
   for (i=0; i < s->img_n; ++i) {
 
1495
      if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
 
1496
      if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
 
1497
   }
 
1498
 
 
1499
   // compute interleaved mcu info
 
1500
   z->img_h_max = h_max;
 
1501
   z->img_v_max = v_max;
 
1502
   z->img_mcu_w = h_max * 8;
 
1503
   z->img_mcu_h = v_max * 8;
 
1504
   z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
 
1505
   z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
 
1506
 
 
1507
   for (i=0; i < s->img_n; ++i) {
 
1508
      // number of effective pixels (e.g. for non-interleaved MCU)
 
1509
      z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
 
1510
      z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
 
1511
      // to simplify generation, we'll allocate enough memory to decode
 
1512
      // the bogus oversized data from using interleaved MCUs and their
 
1513
      // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
 
1514
      // discard the extra data until colorspace conversion
 
1515
      z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
 
1516
      z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
 
1517
      z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
 
1518
      if (z->img_comp[i].raw_data == NULL) {
 
1519
         for(--i; i >= 0; --i) {
 
1520
            free(z->img_comp[i].raw_data);
 
1521
            z->img_comp[i].data = NULL;
 
1522
         }
 
1523
         return e("outofmem", "Out of memory");
 
1524
      }
 
1525
      // align blocks for installable-idct using mmx/sse
 
1526
      z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
 
1527
      z->img_comp[i].linebuf = NULL;
 
1528
   }
 
1529
 
 
1530
   return 1;
 
1531
}
 
1532
 
 
1533
// use comparisons since in some cases we handle more than one case (e.g. SOF)
 
1534
#define DNL(x)         ((x) == 0xdc)
 
1535
#define SOI(x)         ((x) == 0xd8)
 
1536
#define EOI(x)         ((x) == 0xd9)
 
1537
#define SOF(x)         ((x) == 0xc0 || (x) == 0xc1)
 
1538
#define SOS(x)         ((x) == 0xda)
 
1539
 
 
1540
static int decode_jpeg_header(jpeg *z, int scan)
 
1541
{
 
1542
   int m;
 
1543
   z->marker = MARKER_none; // initialize cached marker to empty
 
1544
   m = get_marker(z);
 
1545
   if (!SOI(m)) return e("no SOI","Corrupt JPEG");
 
1546
   if (scan == SCAN_type) return 1;
 
1547
   m = get_marker(z);
 
1548
   while (!SOF(m)) {
 
1549
      if (!process_marker(z,m)) return 0;
 
1550
      m = get_marker(z);
 
1551
      while (m == MARKER_none) {
 
1552
         // some files have extra padding after their blocks, so ok, we'll scan
 
1553
         if (at_eof(&z->s)) return e("no SOF", "Corrupt JPEG");
 
1554
         m = get_marker(z);
 
1555
      }
 
1556
   }
 
1557
   if (!process_frame_header(z, scan)) return 0;
 
1558
   return 1;
 
1559
}
 
1560
 
 
1561
static int decode_jpeg_image(jpeg *j)
 
1562
{
 
1563
   int m;
 
1564
   j->restart_interval = 0;
 
1565
   if (!decode_jpeg_header(j, SCAN_load)) return 0;
 
1566
   m = get_marker(j);
 
1567
   while (!EOI(m)) {
 
1568
      if (SOS(m)) {
 
1569
         if (!process_scan_header(j)) return 0;
 
1570
         if (!parse_entropy_coded_data(j)) return 0;
 
1571
      } else {
 
1572
         if (!process_marker(j, m)) return 0;
 
1573
      }
 
1574
      m = get_marker(j);
 
1575
   }
 
1576
   return 1;
 
1577
}
 
1578
 
 
1579
// static jfif-centered resampling (across block boundaries)
 
1580
 
 
1581
typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,
 
1582
                                    int w, int hs);
 
1583
 
 
1584
#define div4(x) ((uint8) ((x) >> 2))
 
1585
 
 
1586
static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
 
1587
{
 
1588
   return in_near;
 
1589
}
 
1590
 
 
1591
static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
 
1592
{
 
1593
   // need to generate two samples vertically for every one in input
 
1594
   int i;
 
1595
   for (i=0; i < w; ++i)
 
1596
      out[i] = div4(3*in_near[i] + in_far[i] + 2);
 
1597
   return out;
 
1598
}
 
1599
 
 
1600
static uint8*  resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
 
1601
{
 
1602
   // need to generate two samples horizontally for every one in input
 
1603
   int i;
 
1604
   uint8 *input = in_near;
 
1605
   if (w == 1) {
 
1606
      // if only one sample, can't do any interpolation
 
1607
      out[0] = out[1] = input[0];
 
1608
      return out;
 
1609
   }
 
1610
 
 
1611
   out[0] = input[0];
 
1612
   out[1] = div4(input[0]*3 + input[1] + 2);
 
1613
   for (i=1; i < w-1; ++i) {
 
1614
      int n = 3*input[i]+2;
 
1615
      out[i*2+0] = div4(n+input[i-1]);
 
1616
      out[i*2+1] = div4(n+input[i+1]);
 
1617
   }
 
1618
   out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2);
 
1619
   out[i*2+1] = input[w-1];
 
1620
   return out;
 
1621
}
 
1622
 
 
1623
#define div16(x) ((uint8) ((x) >> 4))
 
1624
 
 
1625
static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
 
1626
{
 
1627
   // need to generate 2x2 samples for every one in input
 
1628
   int i,t0,t1;
 
1629
   if (w == 1) {
 
1630
      out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2);
 
1631
      return out;
 
1632
   }
 
1633
 
 
1634
   t1 = 3*in_near[0] + in_far[0];
 
1635
   out[0] = div4(t1+2);
 
1636
   for (i=1; i < w; ++i) {
 
1637
      t0 = t1;
 
1638
      t1 = 3*in_near[i]+in_far[i];
 
1639
      out[i*2-1] = div16(3*t0 + t1 + 8);
 
1640
      out[i*2  ] = div16(3*t1 + t0 + 8);
 
1641
   }
 
1642
   out[w*2-1] = div4(t1+2);
 
1643
   return out;
 
1644
}
 
1645
 
 
1646
static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
 
1647
{
 
1648
   // resample with nearest-neighbor
 
1649
   int i,j;
 
1650
   for (i=0; i < w; ++i)
 
1651
      for (j=0; j < hs; ++j)
 
1652
         out[i*hs+j] = in_near[i];
 
1653
   return out;
 
1654
}
 
1655
 
 
1656
#define float2fixed(x)  ((int) ((x) * 65536 + 0.5))
 
1657
 
 
1658
// 0.38 seconds on 3*anemones.jpg   (0.25 with processor = Pro)
 
1659
// VC6 without processor=Pro is generating multiple LEAs per multiply!
 
1660
static void YCbCr_to_RGB_row(uint8 *out, const uint8 *y, const uint8 *pcb, const uint8 *pcr, int count, int step)
 
1661
{
 
1662
   int i;
 
1663
   for (i=0; i < count; ++i) {
 
1664
      int y_fixed = (y[i] << 16) + 32768; // rounding
 
1665
      int r,g,b;
 
1666
      int cr = pcr[i] - 128;
 
1667
      int cb = pcb[i] - 128;
 
1668
      r = y_fixed + cr*float2fixed(1.40200f);
 
1669
      g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
 
1670
      b = y_fixed                            + cb*float2fixed(1.77200f);
 
1671
      r >>= 16;
 
1672
      g >>= 16;
 
1673
      b >>= 16;
 
1674
      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
 
1675
      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
 
1676
      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
 
1677
      out[0] = (uint8)r;
 
1678
      out[1] = (uint8)g;
 
1679
      out[2] = (uint8)b;
 
1680
      out[3] = 255;
 
1681
      out += step;
 
1682
   }
 
1683
}
 
1684
 
 
1685
#if STBI_SIMD
 
1686
static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;
 
1687
 
 
1688
void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
 
1689
{
 
1690
   stbi_YCbCr_installed = func;
 
1691
}
 
1692
#endif
 
1693
 
 
1694
 
 
1695
// clean up the temporary component buffers
 
1696
static void cleanup_jpeg(jpeg *j)
 
1697
{
 
1698
   int i;
 
1699
   for (i=0; i < j->s.img_n; ++i) {
 
1700
      if (j->img_comp[i].data) {
 
1701
         free(j->img_comp[i].raw_data);
 
1702
         j->img_comp[i].data = NULL;
 
1703
      }
 
1704
      if (j->img_comp[i].linebuf) {
 
1705
         free(j->img_comp[i].linebuf);
 
1706
         j->img_comp[i].linebuf = NULL;
 
1707
      }
 
1708
   }
 
1709
}
 
1710
 
 
1711
typedef struct
 
1712
{
 
1713
   resample_row_func resample;
 
1714
   uint8 *line0,*line1;
 
1715
   int hs,vs;   // expansion factor in each axis
 
1716
   int w_lores; // horizontal pixels pre-expansion 
 
1717
   int ystep;   // how far through vertical expansion we are
 
1718
   int ypos;    // which pre-expansion row we're on
 
1719
} stbi_resample;
 
1720
 
 
1721
static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
 
1722
{
 
1723
   int n, decode_n;
 
1724
   // validate req_comp
 
1725
   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
 
1726
   z->s.img_n = 0;
 
1727
 
 
1728
   // load a jpeg image from whichever source
 
1729
   if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }
 
1730
 
 
1731
   // determine actual number of components to generate
 
1732
   n = req_comp ? req_comp : z->s.img_n;
 
1733
 
 
1734
   if (z->s.img_n == 3 && n < 3)
 
1735
      decode_n = 1;
 
1736
   else
 
1737
      decode_n = z->s.img_n;
 
1738
 
 
1739
   // resample and color-convert
 
1740
   {
 
1741
      int k;
 
1742
      uint i,j;
 
1743
      uint8 *output;
 
1744
      uint8 *coutput[4];
 
1745
 
 
1746
      stbi_resample res_comp[4];
 
1747
 
 
1748
      for (k=0; k < decode_n; ++k) {
 
1749
         stbi_resample *r = &res_comp[k];
 
1750
 
 
1751
         // allocate line buffer big enough for upsampling off the edges
 
1752
         // with upsample factor of 4
 
1753
         z->img_comp[k].linebuf = (uint8 *) malloc(z->s.img_x + 3);
 
1754
         if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
 
1755
 
 
1756
         r->hs      = z->img_h_max / z->img_comp[k].h;
 
1757
         r->vs      = z->img_v_max / z->img_comp[k].v;
 
1758
         r->ystep   = r->vs >> 1;
 
1759
         r->w_lores = (z->s.img_x + r->hs-1) / r->hs;
 
1760
         r->ypos    = 0;
 
1761
         r->line0   = r->line1 = z->img_comp[k].data;
 
1762
 
 
1763
         if      (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
 
1764
         else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;
 
1765
         else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;
 
1766
         else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;
 
1767
         else                               r->resample = resample_row_generic;
 
1768
      }
 
1769
 
 
1770
      // can't error after this so, this is safe
 
1771
      output = (uint8 *) malloc(n * z->s.img_x * z->s.img_y + 1);
 
1772
      if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
 
1773
 
 
1774
      // now go ahead and resample
 
1775
      for (j=0; j < z->s.img_y; ++j) {
 
1776
         uint8 *out = output + n * z->s.img_x * j;
 
1777
         for (k=0; k < decode_n; ++k) {
 
1778
            stbi_resample *r = &res_comp[k];
 
1779
            int y_bot = r->ystep >= (r->vs >> 1);
 
1780
            coutput[k] = r->resample(z->img_comp[k].linebuf,
 
1781
                                     y_bot ? r->line1 : r->line0,
 
1782
                                     y_bot ? r->line0 : r->line1,
 
1783
                                     r->w_lores, r->hs);
 
1784
            if (++r->ystep >= r->vs) {
 
1785
               r->ystep = 0;
 
1786
               r->line0 = r->line1;
 
1787
               if (++r->ypos < z->img_comp[k].y)
 
1788
                  r->line1 += z->img_comp[k].w2;
 
1789
            }
 
1790
         }
 
1791
         if (n >= 3) {
 
1792
            uint8 *y = coutput[0];
 
1793
            if (z->s.img_n == 3) {
 
1794
               #if STBI_SIMD
 
1795
               stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n);
 
1796
               #else
 
1797
               YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s.img_x, n);
 
1798
               #endif
 
1799
            } else
 
1800
               for (i=0; i < z->s.img_x; ++i) {
 
1801
                  out[0] = out[1] = out[2] = y[i];
 
1802
                  out[3] = 255; // not used if n==3
 
1803
                  out += n;
 
1804
               }
 
1805
         } else {
 
1806
            uint8 *y = coutput[0];
 
1807
            if (n == 1)
 
1808
               for (i=0; i < z->s.img_x; ++i) out[i] = y[i];
 
1809
            else
 
1810
               for (i=0; i < z->s.img_x; ++i) *out++ = y[i], *out++ = 255;
 
1811
         }
 
1812
      }
 
1813
      cleanup_jpeg(z);
 
1814
      *out_x = z->s.img_x;
 
1815
      *out_y = z->s.img_y;
 
1816
      if (comp) *comp  = z->s.img_n; // report original components, not output
 
1817
      return output;
 
1818
   }
 
1819
}
 
1820
 
 
1821
#ifndef STBI_NO_STDIO
 
1822
unsigned char *stbi_jpeg_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
 
1823
{
 
1824
   jpeg j;
 
1825
   start_file(&j.s, f);
 
1826
   return load_jpeg_image(&j, x,y,comp,req_comp);
 
1827
}
 
1828
 
 
1829
unsigned char *stbi_jpeg_load(char const *filename, int *x, int *y, int *comp, int req_comp)
 
1830
{
 
1831
   unsigned char *data;
 
1832
   FILE *f = fopen(filename, "rb");
 
1833
   if (!f) return NULL;
 
1834
   data = stbi_jpeg_load_from_file(f,x,y,comp,req_comp);
 
1835
   fclose(f);
 
1836
   return data;
 
1837
}
 
1838
#endif
 
1839
 
 
1840
unsigned char *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
 
1841
{
 
1842
   jpeg j;
 
1843
   start_mem(&j.s, buffer,len);
 
1844
   return load_jpeg_image(&j, x,y,comp,req_comp);
 
1845
}
 
1846
 
 
1847
#ifndef STBI_NO_STDIO
 
1848
int stbi_jpeg_test_file(FILE *f)
 
1849
{
 
1850
   int n,r;
 
1851
   jpeg j;
 
1852
   n = ftell(f);
 
1853
   start_file(&j.s, f);
 
1854
   r = decode_jpeg_header(&j, SCAN_type);
 
1855
   fseek(f,n,SEEK_SET);
 
1856
   return r;
 
1857
}
 
1858
#endif
 
1859
 
 
1860
int stbi_jpeg_test_memory(stbi_uc const *buffer, int len)
 
1861
{
 
1862
   jpeg j;
 
1863
   start_mem(&j.s, buffer,len);
 
1864
   return decode_jpeg_header(&j, SCAN_type);
 
1865
}
 
1866
 
 
1867
// @TODO:
 
1868
#ifndef STBI_NO_STDIO
 
1869
extern int      stbi_jpeg_info            (char const *filename,           int *x, int *y, int *comp);
 
1870
extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
 
1871
#endif
 
1872
extern int      stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
 
1873
 
 
1874
// public domain zlib decode    v0.2  Sean Barrett 2006-11-18
 
1875
//    simple implementation
 
1876
//      - all input must be provided in an upfront buffer
 
1877
//      - all output is written to a single output buffer (can malloc/realloc)
 
1878
//    performance
 
1879
//      - fast huffman
 
1880
 
 
1881
// fast-way is faster to check than jpeg huffman, but slow way is slower
 
1882
#define ZFAST_BITS  9 // accelerate all cases in default tables
 
1883
#define ZFAST_MASK  ((1 << ZFAST_BITS) - 1)
 
1884
 
 
1885
// zlib-style huffman encoding
 
1886
// (jpegs packs from left, zlib from right, so can't share code)
 
1887
typedef struct
 
1888
{
 
1889
   uint16 fast[1 << ZFAST_BITS];
 
1890
   uint16 firstcode[16];
 
1891
   int maxcode[17];
 
1892
   uint16 firstsymbol[16];
 
1893
   uint8  size[288];
 
1894
   uint16 value[288]; 
 
1895
} zhuffman;
 
1896
 
 
1897
__forceinline static int bitreverse16(int n)
 
1898
{
 
1899
  n = ((n & 0xAAAA) >>  1) | ((n & 0x5555) << 1);
 
1900
  n = ((n & 0xCCCC) >>  2) | ((n & 0x3333) << 2);
 
1901
  n = ((n & 0xF0F0) >>  4) | ((n & 0x0F0F) << 4);
 
1902
  n = ((n & 0xFF00) >>  8) | ((n & 0x00FF) << 8);
 
1903
  return n;
 
1904
}
 
1905
 
 
1906
__forceinline static int bit_reverse(int v, int bits)
 
1907
{
 
1908
   assert(bits <= 16);
 
1909
   // to bit reverse n bits, reverse 16 and shift
 
1910
   // e.g. 11 bits, bit reverse and shift away 5
 
1911
   return bitreverse16(v) >> (16-bits);
 
1912
}
 
1913
 
 
1914
static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)
 
1915
{
 
1916
   int i,k=0;
 
1917
   int code, next_code[16], sizes[17];
 
1918
 
 
1919
   // DEFLATE spec for generating codes
 
1920
   memset(sizes, 0, sizeof(sizes));
 
1921
   memset(z->fast, 255, sizeof(z->fast));
 
1922
   for (i=0; i < num; ++i) 
 
1923
      ++sizes[sizelist[i]];
 
1924
   sizes[0] = 0;
 
1925
   for (i=1; i < 16; ++i)
 
1926
      assert(sizes[i] <= (1 << i));
 
1927
   code = 0;
 
1928
   for (i=1; i < 16; ++i) {
 
1929
      next_code[i] = code;
 
1930
      z->firstcode[i] = (uint16) code;
 
1931
      z->firstsymbol[i] = (uint16) k;
 
1932
      code = (code + sizes[i]);
 
1933
      if (sizes[i])
 
1934
         if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");
 
1935
      z->maxcode[i] = code << (16-i); // preshift for inner loop
 
1936
      code <<= 1;
 
1937
      k += sizes[i];
 
1938
   }
 
1939
   z->maxcode[16] = 0x10000; // sentinel
 
1940
   for (i=0; i < num; ++i) {
 
1941
      int s = sizelist[i];
 
1942
      if (s) {
 
1943
         int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
 
1944
         z->size[c] = (uint8)s;
 
1945
         z->value[c] = (uint16)i;
 
1946
         if (s <= ZFAST_BITS) {
 
1947
            int k = bit_reverse(next_code[s],s);
 
1948
            while (k < (1 << ZFAST_BITS)) {
 
1949
               z->fast[k] = (uint16) c;
 
1950
               k += (1 << s);
 
1951
            }
 
1952
         }
 
1953
         ++next_code[s];
 
1954
      }
 
1955
   }
 
1956
   return 1;
 
1957
}
 
1958
 
 
1959
// zlib-from-memory implementation for PNG reading
 
1960
//    because PNG allows splitting the zlib stream arbitrarily,
 
1961
//    and it's annoying structurally to have PNG call ZLIB call PNG,
 
1962
//    we require PNG read all the IDATs and combine them into a single
 
1963
//    memory buffer
 
1964
 
 
1965
typedef struct
 
1966
{
 
1967
   uint8 *zbuffer, *zbuffer_end;
 
1968
   int num_bits;
 
1969
   uint32 code_buffer;
 
1970
 
 
1971
   char *zout;
 
1972
   char *zout_start;
 
1973
   char *zout_end;
 
1974
   int   z_expandable;
 
1975
 
 
1976
   zhuffman z_length, z_distance;
 
1977
} zbuf;
 
1978
 
 
1979
__forceinline static int zget8(zbuf *z)
 
1980
{
 
1981
   if (z->zbuffer >= z->zbuffer_end) return 0;
 
1982
   return *z->zbuffer++;
 
1983
}
 
1984
 
 
1985
static void fill_bits(zbuf *z)
 
1986
{
 
1987
   do {
 
1988
      assert(z->code_buffer < (1U << z->num_bits));
 
1989
      z->code_buffer |= zget8(z) << z->num_bits;
 
1990
      z->num_bits += 8;
 
1991
   } while (z->num_bits <= 24);
 
1992
}
 
1993
 
 
1994
__forceinline static unsigned int zreceive(zbuf *z, int n)
 
1995
{
 
1996
   unsigned int k;
 
1997
   if (z->num_bits < n) fill_bits(z);
 
1998
   k = z->code_buffer & ((1 << n) - 1);
 
1999
   z->code_buffer >>= n;
 
2000
   z->num_bits -= n;
 
2001
   return k;   
 
2002
}
 
2003
 
 
2004
__forceinline static int zhuffman_decode(zbuf *a, zhuffman *z)
 
2005
{
 
2006
   int b,s,k;
 
2007
   if (a->num_bits < 16) fill_bits(a);
 
2008
   b = z->fast[a->code_buffer & ZFAST_MASK];
 
2009
   if (b < 0xffff) {
 
2010
      s = z->size[b];
 
2011
      a->code_buffer >>= s;
 
2012
      a->num_bits -= s;
 
2013
      return z->value[b];
 
2014
   }
 
2015
 
 
2016
   // not resolved by fast table, so compute it the slow way
 
2017
   // use jpeg approach, which requires MSbits at top
 
2018
   k = bit_reverse(a->code_buffer, 16);
 
2019
   for (s=ZFAST_BITS+1; ; ++s)
 
2020
      if (k < z->maxcode[s])
 
2021
         break;
 
2022
   if (s == 16) return -1; // invalid code!
 
2023
   // code size is s, so:
 
2024
   b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
 
2025
   assert(z->size[b] == s);
 
2026
   a->code_buffer >>= s;
 
2027
   a->num_bits -= s;
 
2028
   return z->value[b];
 
2029
}
 
2030
 
 
2031
static int expand(zbuf *z, int n)  // need to make room for n bytes
 
2032
{
 
2033
   char *q;
 
2034
   int cur, limit;
 
2035
   if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");
 
2036
   cur   = (int) (z->zout     - z->zout_start);
 
2037
   limit = (int) (z->zout_end - z->zout_start);
 
2038
   while (cur + n > limit)
 
2039
      limit *= 2;
 
2040
   q = (char *) realloc(z->zout_start, limit);
 
2041
   if (q == NULL) return e("outofmem", "Out of memory");
 
2042
   z->zout_start = q;
 
2043
   z->zout       = q + cur;
 
2044
   z->zout_end   = q + limit;
 
2045
   return 1;
 
2046
}
 
2047
 
 
2048
static int length_base[31] = {
 
2049
   3,4,5,6,7,8,9,10,11,13,
 
2050
   15,17,19,23,27,31,35,43,51,59,
 
2051
   67,83,99,115,131,163,195,227,258,0,0 };
 
2052
 
 
2053
static int length_extra[31]= 
 
2054
{ 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 };
 
2055
 
 
2056
static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
 
2057
257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
 
2058
 
 
2059
static int dist_extra[32] =
 
2060
{ 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};
 
2061
 
 
2062
static int parse_huffman_block(zbuf *a)
 
2063
{
 
2064
   for(;;) {
 
2065
      int z = zhuffman_decode(a, &a->z_length);
 
2066
      if (z < 256) {
 
2067
         if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes
 
2068
         if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;
 
2069
         *a->zout++ = (char) z;
 
2070
      } else {
 
2071
         uint8 *p;
 
2072
         int len,dist;
 
2073
         if (z == 256) return 1;
 
2074
         z -= 257;
 
2075
         len = length_base[z];
 
2076
         if (length_extra[z]) len += zreceive(a, length_extra[z]);
 
2077
         z = zhuffman_decode(a, &a->z_distance);
 
2078
         if (z < 0) return e("bad huffman code","Corrupt PNG");
 
2079
         dist = dist_base[z];
 
2080
         if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);
 
2081
         if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");
 
2082
         if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;
 
2083
         p = (uint8 *) (a->zout - dist);
 
2084
         while (len--)
 
2085
            *a->zout++ = *p++;
 
2086
      }
 
2087
   }
 
2088
}
 
2089
 
 
2090
static int compute_huffman_codes(zbuf *a)
 
2091
{
 
2092
   static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
 
2093
   zhuffman z_codelength;
 
2094
   uint8 lencodes[286+32+137];//padding for maximum single op
 
2095
   uint8 codelength_sizes[19];
 
2096
   int i,n;
 
2097
 
 
2098
   int hlit  = zreceive(a,5) + 257;
 
2099
   int hdist = zreceive(a,5) + 1;
 
2100
   int hclen = zreceive(a,4) + 4;
 
2101
 
 
2102
   memset(codelength_sizes, 0, sizeof(codelength_sizes));
 
2103
   for (i=0; i < hclen; ++i) {
 
2104
      int s = zreceive(a,3);
 
2105
      codelength_sizes[length_dezigzag[i]] = (uint8) s;
 
2106
   }
 
2107
   if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
 
2108
 
 
2109
   n = 0;
 
2110
   while (n < hlit + hdist) {
 
2111
      int c = zhuffman_decode(a, &z_codelength);
 
2112
      assert(c >= 0 && c < 19);
 
2113
      if (c < 16)
 
2114
         lencodes[n++] = (uint8) c;
 
2115
      else if (c == 16) {
 
2116
         c = zreceive(a,2)+3;
 
2117
         memset(lencodes+n, lencodes[n-1], c);
 
2118
         n += c;
 
2119
      } else if (c == 17) {
 
2120
         c = zreceive(a,3)+3;
 
2121
         memset(lencodes+n, 0, c);
 
2122
         n += c;
 
2123
      } else {
 
2124
         assert(c == 18);
 
2125
         c = zreceive(a,7)+11;
 
2126
         memset(lencodes+n, 0, c);
 
2127
         n += c;
 
2128
      }
 
2129
   }
 
2130
   if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");
 
2131
   if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
 
2132
   if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
 
2133
   return 1;
 
2134
}
 
2135
 
 
2136
static int parse_uncompressed_block(zbuf *a)
 
2137
{
 
2138
   uint8 header[4];
 
2139
   int len,nlen,k;
 
2140
   if (a->num_bits & 7)
 
2141
      zreceive(a, a->num_bits & 7); // discard
 
2142
   // drain the bit-packed data into header
 
2143
   k = 0;
 
2144
   while (a->num_bits > 0) {
 
2145
      header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns?
 
2146
      a->code_buffer >>= 8;
 
2147
      a->num_bits -= 8;
 
2148
   }
 
2149
   assert(a->num_bits == 0);
 
2150
   // now fill header the normal way
 
2151
   while (k < 4)
 
2152
      header[k++] = (uint8) zget8(a);
 
2153
   len  = header[1] * 256 + header[0];
 
2154
   nlen = header[3] * 256 + header[2];
 
2155
   if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");
 
2156
   if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");
 
2157
   if (a->zout + len > a->zout_end)
 
2158
      if (!expand(a, len)) return 0;
 
2159
   memcpy(a->zout, a->zbuffer, len);
 
2160
   a->zbuffer += len;
 
2161
   a->zout += len;
 
2162
   return 1;
 
2163
}
 
2164
 
 
2165
static int parse_zlib_header(zbuf *a)
 
2166
{
 
2167
   int cmf   = zget8(a);
 
2168
   int cm    = cmf & 15;
 
2169
   /* int cinfo = cmf >> 4; */
 
2170
   int flg   = zget8(a);
 
2171
   if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec
 
2172
   if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
 
2173
   if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png
 
2174
   // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
 
2175
   return 1;
 
2176
}
 
2177
 
 
2178
// @TODO: should statically initialize these for optimal thread safety
 
2179
static uint8 default_length[288], default_distance[32];
 
2180
static void init_defaults(void)
 
2181
{
 
2182
   int i;   // use <= to match clearly with spec
 
2183
   for (i=0; i <= 143; ++i)     default_length[i]   = 8;
 
2184
   for (   ; i <= 255; ++i)     default_length[i]   = 9;
 
2185
   for (   ; i <= 279; ++i)     default_length[i]   = 7;
 
2186
   for (   ; i <= 287; ++i)     default_length[i]   = 8;
 
2187
 
 
2188
   for (i=0; i <=  31; ++i)     default_distance[i] = 5;
 
2189
}
 
2190
 
 
2191
int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead
 
2192
static int parse_zlib(zbuf *a, int parse_header)
 
2193
{
 
2194
   int final, type;
 
2195
   if (parse_header)
 
2196
      if (!parse_zlib_header(a)) return 0;
 
2197
   a->num_bits = 0;
 
2198
   a->code_buffer = 0;
 
2199
   do {
 
2200
      final = zreceive(a,1);
 
2201
      type = zreceive(a,2);
 
2202
      if (type == 0) {
 
2203
         if (!parse_uncompressed_block(a)) return 0;
 
2204
      } else if (type == 3) {
 
2205
         return 0;
 
2206
      } else {
 
2207
         if (type == 1) {
 
2208
            // use fixed code lengths
 
2209
            if (!default_distance[31]) init_defaults();
 
2210
            if (!zbuild_huffman(&a->z_length  , default_length  , 288)) return 0;
 
2211
            if (!zbuild_huffman(&a->z_distance, default_distance,  32)) return 0;
 
2212
         } else {
 
2213
            if (!compute_huffman_codes(a)) return 0;
 
2214
         }
 
2215
         if (!parse_huffman_block(a)) return 0;
 
2216
      }
 
2217
      if (stbi_png_partial && a->zout - a->zout_start > 65536)
 
2218
         break;
 
2219
   } while (!final);
 
2220
   return 1;
 
2221
}
 
2222
 
 
2223
static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)
 
2224
{
 
2225
   a->zout_start = obuf;
 
2226
   a->zout       = obuf;
 
2227
   a->zout_end   = obuf + olen;
 
2228
   a->z_expandable = exp;
 
2229
 
 
2230
   return parse_zlib(a, parse_header);
 
2231
}
 
2232
 
 
2233
char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
 
2234
{
 
2235
   zbuf a;
 
2236
   char *p = (char *) malloc(initial_size);
 
2237
   if (p == NULL) return NULL;
 
2238
   a.zbuffer = (uint8 *) buffer;
 
2239
   a.zbuffer_end = (uint8 *) buffer + len;
 
2240
   if (do_zlib(&a, p, initial_size, 1, 1)) {
 
2241
      if (outlen) *outlen = (int) (a.zout - a.zout_start);
 
2242
      return a.zout_start;
 
2243
   } else {
 
2244
      free(a.zout_start);
 
2245
      return NULL;
 
2246
   }
 
2247
}
 
2248
 
 
2249
char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
 
2250
{
 
2251
   return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
 
2252
}
 
2253
 
 
2254
int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
 
2255
{
 
2256
   zbuf a;
 
2257
   a.zbuffer = (uint8 *) ibuffer;
 
2258
   a.zbuffer_end = (uint8 *) ibuffer + ilen;
 
2259
   if (do_zlib(&a, obuffer, olen, 0, 1))
 
2260
      return (int) (a.zout - a.zout_start);
 
2261
   else
 
2262
      return -1;
 
2263
}
 
2264
 
 
2265
char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
 
2266
{
 
2267
   zbuf a;
 
2268
   char *p = (char *) malloc(16384);
 
2269
   if (p == NULL) return NULL;
 
2270
   a.zbuffer = (uint8 *) buffer;
 
2271
   a.zbuffer_end = (uint8 *) buffer+len;
 
2272
   if (do_zlib(&a, p, 16384, 1, 0)) {
 
2273
      if (outlen) *outlen = (int) (a.zout - a.zout_start);
 
2274
      return a.zout_start;
 
2275
   } else {
 
2276
      free(a.zout_start);
 
2277
      return NULL;
 
2278
   }
 
2279
}
 
2280
 
 
2281
int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
 
2282
{
 
2283
   zbuf a;
 
2284
   a.zbuffer = (uint8 *) ibuffer;
 
2285
   a.zbuffer_end = (uint8 *) ibuffer + ilen;
 
2286
   if (do_zlib(&a, obuffer, olen, 0, 0))
 
2287
      return (int) (a.zout - a.zout_start);
 
2288
   else
 
2289
      return -1;
 
2290
}
 
2291
 
 
2292
// public domain "baseline" PNG decoder   v0.10  Sean Barrett 2006-11-18
 
2293
//    simple implementation
 
2294
//      - only 8-bit samples
 
2295
//      - no CRC checking
 
2296
//      - allocates lots of intermediate memory
 
2297
//        - avoids problem of streaming data between subsystems
 
2298
//        - avoids explicit window management
 
2299
//    performance
 
2300
//      - uses stb_zlib, a PD zlib implementation with fast huffman decoding
 
2301
 
 
2302
 
 
2303
typedef struct
 
2304
{
 
2305
   uint32 length;
 
2306
   uint32 type;
 
2307
} chunk;
 
2308
 
 
2309
#define PNG_TYPE(a,b,c,d)  (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
 
2310
 
 
2311
static chunk get_chunk_header(stbi *s)
 
2312
{
 
2313
   chunk c;
 
2314
   c.length = get32(s);
 
2315
   c.type   = get32(s);
 
2316
   return c;
 
2317
}
 
2318
 
 
2319
static int check_png_header(stbi *s)
 
2320
{
 
2321
   static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };
 
2322
   int i;
 
2323
   for (i=0; i < 8; ++i)
 
2324
      if (get8(s) != png_sig[i]) return e("bad png sig","Not a PNG");
 
2325
   return 1;
 
2326
}
 
2327
 
 
2328
typedef struct
 
2329
{
 
2330
   stbi s;
 
2331
   uint8 *idata, *expanded, *out;
 
2332
} png;
 
2333
 
 
2334
 
 
2335
enum {
 
2336
   F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,
 
2337
   F_avg_first, F_paeth_first,
 
2338
};
 
2339
 
 
2340
static uint8 first_row_filter[5] =
 
2341
{
 
2342
   F_none, F_sub, F_none, F_avg_first, F_paeth_first
 
2343
};
 
2344
 
 
2345
static int paeth(int a, int b, int c)
 
2346
{
 
2347
   int p = a + b - c;
 
2348
   int pa = abs(p-a);
 
2349
   int pb = abs(p-b);
 
2350
   int pc = abs(p-c);
 
2351
   if (pa <= pb && pa <= pc) return a;
 
2352
   if (pb <= pc) return b;
 
2353
   return c;
 
2354
}
 
2355
 
 
2356
// create the png data from post-deflated data
 
2357
static int create_png_image_raw(png *a, uint8 *raw, uint32 raw_len, int out_n, uint32 x, uint32 y)
 
2358
{
 
2359
   stbi *s = &a->s;
 
2360
   uint32 i,j,stride = x*out_n;
 
2361
   int k;
 
2362
   int img_n = s->img_n; // copy it into a local for later
 
2363
   assert(out_n == s->img_n || out_n == s->img_n+1);
 
2364
   if (stbi_png_partial) y = 1;
 
2365
   a->out = (uint8 *) malloc(x * y * out_n);
 
2366
   if (!a->out) return e("outofmem", "Out of memory");
 
2367
   if (!stbi_png_partial) {
 
2368
      if (s->img_x == x && s->img_y == y)
 
2369
         if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
 
2370
      else // interlaced:
 
2371
         if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
 
2372
   }
 
2373
   for (j=0; j < y; ++j) {
 
2374
      uint8 *cur = a->out + stride*j;
 
2375
      uint8 *prior = cur - stride;
 
2376
      int filter = *raw++;
 
2377
      if (filter > 4) return e("invalid filter","Corrupt PNG");
 
2378
      // if first row, use special filter that doesn't sample previous row
 
2379
      if (j == 0) filter = first_row_filter[filter];
 
2380
      // handle first pixel explicitly
 
2381
      for (k=0; k < img_n; ++k) {
 
2382
         switch(filter) {
 
2383
            case F_none       : cur[k] = raw[k]; break;
 
2384
            case F_sub        : cur[k] = raw[k]; break;
 
2385
            case F_up         : cur[k] = raw[k] + prior[k]; break;
 
2386
            case F_avg        : cur[k] = raw[k] + (prior[k]>>1); break;
 
2387
            case F_paeth      : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;
 
2388
            case F_avg_first  : cur[k] = raw[k]; break;
 
2389
            case F_paeth_first: cur[k] = raw[k]; break;
 
2390
         }
 
2391
      }
 
2392
      if (img_n != out_n) cur[img_n] = 255;
 
2393
      raw += img_n;
 
2394
      cur += out_n;
 
2395
      prior += out_n;
 
2396
      // this is a little gross, so that we don't switch per-pixel or per-component
 
2397
      if (img_n == out_n) {
 
2398
         #define CASE(f) \
 
2399
             case f:     \
 
2400
                for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \
 
2401
                   for (k=0; k < img_n; ++k)
 
2402
         switch(filter) {
 
2403
            CASE(F_none)  cur[k] = raw[k]; break;
 
2404
            CASE(F_sub)   cur[k] = raw[k] + cur[k-img_n]; break;
 
2405
            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;
 
2406
            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;
 
2407
            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
 
2408
            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-img_n] >> 1); break;
 
2409
            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;
 
2410
         }
 
2411
         #undef CASE
 
2412
      } else {
 
2413
         assert(img_n+1 == out_n);
 
2414
         #define CASE(f) \
 
2415
             case f:     \
 
2416
                for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
 
2417
                   for (k=0; k < img_n; ++k)
 
2418
         switch(filter) {
 
2419
            CASE(F_none)  cur[k] = raw[k]; break;
 
2420
            CASE(F_sub)   cur[k] = raw[k] + cur[k-out_n]; break;
 
2421
            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;
 
2422
            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;
 
2423
            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
 
2424
            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-out_n] >> 1); break;
 
2425
            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;
 
2426
         }
 
2427
         #undef CASE
 
2428
      }
 
2429
   }
 
2430
   return 1;
 
2431
}
 
2432
 
 
2433
static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n, int interlaced)
 
2434
{
 
2435
   uint8 *final;
 
2436
   int p;
 
2437
   int save;
 
2438
   if (!interlaced)
 
2439
      return create_png_image_raw(a, raw, raw_len, out_n, a->s.img_x, a->s.img_y);
 
2440
   save = stbi_png_partial;
 
2441
   stbi_png_partial = 0;
 
2442
 
 
2443
   // de-interlacing
 
2444
   final = (uint8 *) malloc(a->s.img_x * a->s.img_y * out_n);
 
2445
   for (p=0; p < 7; ++p) {
 
2446
      int xorig[] = { 0,4,0,2,0,1,0 };
 
2447
      int yorig[] = { 0,0,4,0,2,0,1 };
 
2448
      int xspc[]  = { 8,8,4,4,2,2,1 };
 
2449
      int yspc[]  = { 8,8,8,4,4,2,2 };
 
2450
      int i,j,x,y;
 
2451
      // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
 
2452
      x = (a->s.img_x - xorig[p] + xspc[p]-1) / xspc[p];
 
2453
      y = (a->s.img_y - yorig[p] + yspc[p]-1) / yspc[p];
 
2454
      if (x && y) {
 
2455
         if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {
 
2456
            free(final);
 
2457
            return 0;
 
2458
         }
 
2459
         for (j=0; j < y; ++j)
 
2460
            for (i=0; i < x; ++i)
 
2461
               memcpy(final + (j*yspc[p]+yorig[p])*a->s.img_x*out_n + (i*xspc[p]+xorig[p])*out_n,
 
2462
                      a->out + (j*x+i)*out_n, out_n);
 
2463
         free(a->out);
 
2464
         raw += (x*out_n+1)*y;
 
2465
         raw_len -= (x*out_n+1)*y;
 
2466
      }
 
2467
   }
 
2468
   a->out = final;
 
2469
 
 
2470
   stbi_png_partial = save;
 
2471
   return 1;
 
2472
}
 
2473
 
 
2474
static int compute_transparency(png *z, uint8 tc[3], int out_n)
 
2475
{
 
2476
   stbi *s = &z->s;
 
2477
   uint32 i, pixel_count = s->img_x * s->img_y;
 
2478
   uint8 *p = z->out;
 
2479
 
 
2480
   // compute color-based transparency, assuming we've
 
2481
   // already got 255 as the alpha value in the output
 
2482
   assert(out_n == 2 || out_n == 4);
 
2483
 
 
2484
   if (out_n == 2) {
 
2485
      for (i=0; i < pixel_count; ++i) {
 
2486
         p[1] = (p[0] == tc[0] ? 0 : 255);
 
2487
         p += 2;
 
2488
      }
 
2489
   } else {
 
2490
      for (i=0; i < pixel_count; ++i) {
 
2491
         if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
 
2492
            p[3] = 0;
 
2493
         p += 4;
 
2494
      }
 
2495
   }
 
2496
   return 1;
 
2497
}
 
2498
 
 
2499
static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n)
 
2500
{
 
2501
   uint32 i, pixel_count = a->s.img_x * a->s.img_y;
 
2502
   uint8 *p, *temp_out, *orig = a->out;
 
2503
 
 
2504
   p = (uint8 *) malloc(pixel_count * pal_img_n);
 
2505
   if (p == NULL) return e("outofmem", "Out of memory");
 
2506
 
 
2507
   // between here and free(out) below, exitting would leak
 
2508
   temp_out = p;
 
2509
 
 
2510
   if (pal_img_n == 3) {
 
2511
      for (i=0; i < pixel_count; ++i) {
 
2512
         int n = orig[i]*4;
 
2513
         p[0] = palette[n  ];
 
2514
         p[1] = palette[n+1];
 
2515
         p[2] = palette[n+2];
 
2516
         p += 3;
 
2517
      }
 
2518
   } else {
 
2519
      for (i=0; i < pixel_count; ++i) {
 
2520
         int n = orig[i]*4;
 
2521
         p[0] = palette[n  ];
 
2522
         p[1] = palette[n+1];
 
2523
         p[2] = palette[n+2];
 
2524
         p[3] = palette[n+3];
 
2525
         p += 4;
 
2526
      }
 
2527
   }
 
2528
   free(a->out);
 
2529
   a->out = temp_out;
 
2530
   return 1;
 
2531
}
 
2532
 
 
2533
static int parse_png_file(png *z, int scan, int req_comp)
 
2534
{
 
2535
   uint8 palette[1024], pal_img_n=0;
 
2536
   uint8 has_trans=0, tc[3];
 
2537
   uint32 ioff=0, idata_limit=0, i, pal_len=0;
 
2538
   int first=1,k,interlace=0;
 
2539
   stbi *s = &z->s;
 
2540
 
 
2541
   if (!check_png_header(s)) return 0;
 
2542
 
 
2543
   if (scan == SCAN_type) return 1;
 
2544
 
 
2545
   for(;;first=0) {
 
2546
      chunk c = get_chunk_header(s);
 
2547
      if (first && c.type != PNG_TYPE('I','H','D','R'))
 
2548
         return e("first not IHDR","Corrupt PNG");
 
2549
      switch (c.type) {
 
2550
         case PNG_TYPE('I','H','D','R'): {
 
2551
            int depth,color,comp,filter;
 
2552
            if (!first) return e("multiple IHDR","Corrupt PNG");
 
2553
            if (c.length != 13) return e("bad IHDR len","Corrupt PNG");
 
2554
            s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");
 
2555
            s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");
 
2556
            depth = get8(s);  if (depth != 8)        return e("8bit only","PNG not supported: 8-bit only");
 
2557
            color = get8(s);  if (color > 6)         return e("bad ctype","Corrupt PNG");
 
2558
            if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");
 
2559
            comp  = get8(s);  if (comp) return e("bad comp method","Corrupt PNG");
 
2560
            filter= get8(s);  if (filter) return e("bad filter method","Corrupt PNG");
 
2561
            interlace = get8(s); if (interlace>1) return e("bad interlace method","Corrupt PNG");
 
2562
            if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG");
 
2563
            if (!pal_img_n) {
 
2564
               s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
 
2565
               if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");
 
2566
               if (scan == SCAN_header) return 1;
 
2567
            } else {
 
2568
               // if paletted, then pal_n is our final components, and
 
2569
               // img_n is # components to decompress/filter.
 
2570
               s->img_n = 1;
 
2571
               if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG");
 
2572
               // if SCAN_header, have to scan to see if we have a tRNS
 
2573
            }
 
2574
            break;
 
2575
         }
 
2576
 
 
2577
         case PNG_TYPE('P','L','T','E'):  {
 
2578
            if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");
 
2579
            pal_len = c.length / 3;
 
2580
            if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");
 
2581
            for (i=0; i < pal_len; ++i) {
 
2582
               palette[i*4+0] = get8u(s);
 
2583
               palette[i*4+1] = get8u(s);
 
2584
               palette[i*4+2] = get8u(s);
 
2585
               palette[i*4+3] = 255;
 
2586
            }
 
2587
            break;
 
2588
         }
 
2589
 
 
2590
         case PNG_TYPE('t','R','N','S'): {
 
2591
            if (z->idata) return e("tRNS after IDAT","Corrupt PNG");
 
2592
            if (pal_img_n) {
 
2593
               if (scan == SCAN_header) { s->img_n = 4; return 1; }
 
2594
               if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");
 
2595
               if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");
 
2596
               pal_img_n = 4;
 
2597
               for (i=0; i < c.length; ++i)
 
2598
                  palette[i*4+3] = get8u(s);
 
2599
            } else {
 
2600
               if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");
 
2601
               if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");
 
2602
               has_trans = 1;
 
2603
               for (k=0; k < s->img_n; ++k)
 
2604
                  tc[k] = (uint8) get16(s); // non 8-bit images will be larger
 
2605
            }
 
2606
            break;
 
2607
         }
 
2608
 
 
2609
         case PNG_TYPE('I','D','A','T'): {
 
2610
            if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");
 
2611
            if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }
 
2612
            if (ioff + c.length > idata_limit) {
 
2613
               uint8 *p;
 
2614
               if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
 
2615
               while (ioff + c.length > idata_limit)
 
2616
                  idata_limit *= 2;
 
2617
               p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");
 
2618
               z->idata = p;
 
2619
            }
 
2620
            #ifndef STBI_NO_STDIO
 
2621
            if (s->img_file)
 
2622
            {
 
2623
               if (fread(z->idata+ioff,1,c.length,s->img_file) != c.length) return e("outofdata","Corrupt PNG");
 
2624
            }
 
2625
            else
 
2626
            #endif
 
2627
            {
 
2628
               memcpy(z->idata+ioff, s->img_buffer, c.length);
 
2629
               s->img_buffer += c.length;
 
2630
            }
 
2631
            ioff += c.length;
 
2632
            break;
 
2633
         }
 
2634
 
 
2635
         case PNG_TYPE('I','E','N','D'): {
 
2636
            uint32 raw_len;
 
2637
            if (scan != SCAN_load) return 1;
 
2638
            if (z->idata == NULL) return e("no IDAT","Corrupt PNG");
 
2639
            z->expanded = (uint8 *) stbi_zlib_decode_malloc((char *) z->idata, ioff, (int *) &raw_len);
 
2640
            if (z->expanded == NULL) return 0; // zlib should set error
 
2641
            free(z->idata); z->idata = NULL;
 
2642
            if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
 
2643
               s->img_out_n = s->img_n+1;
 
2644
            else
 
2645
               s->img_out_n = s->img_n;
 
2646
            if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;
 
2647
            if (has_trans)
 
2648
               if (!compute_transparency(z, tc, s->img_out_n)) return 0;
 
2649
            if (pal_img_n) {
 
2650
               // pal_img_n == 3 or 4
 
2651
               s->img_n = pal_img_n; // record the actual colors we had
 
2652
               s->img_out_n = pal_img_n;
 
2653
               if (req_comp >= 3) s->img_out_n = req_comp;
 
2654
               if (!expand_palette(z, palette, pal_len, s->img_out_n))
 
2655
                  return 0;
 
2656
            }
 
2657
            free(z->expanded); z->expanded = NULL;
 
2658
            return 1;
 
2659
         }
 
2660
 
 
2661
         default:
 
2662
            // if critical, fail
 
2663
            if ((c.type & (1 << 29)) == 0) {
 
2664
               #ifndef STBI_NO_FAILURE_STRINGS
 
2665
               // not threadsafe
 
2666
               static char invalid_chunk[] = "XXXX chunk not known";
 
2667
               invalid_chunk[0] = (uint8) (c.type >> 24);
 
2668
               invalid_chunk[1] = (uint8) (c.type >> 16);
 
2669
               invalid_chunk[2] = (uint8) (c.type >>  8);
 
2670
               invalid_chunk[3] = (uint8) (c.type >>  0);
 
2671
               #endif
 
2672
               return e(invalid_chunk, "PNG not supported: unknown chunk type");
 
2673
            }
 
2674
            skip(s, c.length);
 
2675
            break;
 
2676
      }
 
2677
      // end of chunk, read and skip CRC
 
2678
      get32(s);
 
2679
   }
 
2680
}
 
2681
 
 
2682
static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)
 
2683
{
 
2684
   unsigned char *result=NULL;
 
2685
   p->expanded = NULL;
 
2686
   p->idata = NULL;
 
2687
   p->out = NULL;
 
2688
   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
 
2689
   if (parse_png_file(p, SCAN_load, req_comp)) {
 
2690
      result = p->out;
 
2691
      p->out = NULL;
 
2692
      if (req_comp && req_comp != p->s.img_out_n) {
 
2693
         result = convert_format(result, p->s.img_out_n, req_comp, p->s.img_x, p->s.img_y);
 
2694
         p->s.img_out_n = req_comp;
 
2695
         if (result == NULL) return result;
 
2696
      }
 
2697
      *x = p->s.img_x;
 
2698
      *y = p->s.img_y;
 
2699
      if (n) *n = p->s.img_n;
 
2700
   }
 
2701
   free(p->out);      p->out      = NULL;
 
2702
   free(p->expanded); p->expanded = NULL;
 
2703
   free(p->idata);    p->idata    = NULL;
 
2704
 
 
2705
   return result;
 
2706
}
 
2707
 
 
2708
#ifndef STBI_NO_STDIO
 
2709
unsigned char *stbi_png_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
 
2710
{
 
2711
   png p;
 
2712
   start_file(&p.s, f);
 
2713
   return do_png(&p, x,y,comp,req_comp);
 
2714
}
 
2715
 
 
2716
unsigned char *stbi_png_load(char const *filename, int *x, int *y, int *comp, int req_comp)
 
2717
{
 
2718
   unsigned char *data;
 
2719
   FILE *f = fopen(filename, "rb");
 
2720
   if (!f) return NULL;
 
2721
   data = stbi_png_load_from_file(f,x,y,comp,req_comp);
 
2722
   fclose(f);
 
2723
   return data;
 
2724
}
 
2725
#endif
 
2726
 
 
2727
unsigned char *stbi_png_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
 
2728
{
 
2729
   png p;
 
2730
   start_mem(&p.s, buffer,len);
 
2731
   return do_png(&p, x,y,comp,req_comp);
 
2732
}
 
2733
 
 
2734
#ifndef STBI_NO_STDIO
 
2735
int stbi_png_test_file(FILE *f)
 
2736
{
 
2737
   png p;
 
2738
   int n,r;
 
2739
   n = ftell(f);
 
2740
   start_file(&p.s, f);
 
2741
   r = parse_png_file(&p, SCAN_type,STBI_default);
 
2742
   fseek(f,n,SEEK_SET);
 
2743
   return r;
 
2744
}
 
2745
#endif
 
2746
 
 
2747
int stbi_png_test_memory(stbi_uc const *buffer, int len)
 
2748
{
 
2749
   png p;
 
2750
   start_mem(&p.s, buffer, len);
 
2751
   return parse_png_file(&p, SCAN_type,STBI_default);
 
2752
}
 
2753
 
 
2754
// TODO: load header from png
 
2755
#ifndef STBI_NO_STDIO
 
2756
int      stbi_png_info             (char const *filename,           int *x, int *y, int *comp)
 
2757
{
 
2758
   png p;
 
2759
   FILE *f = fopen(filename, "rb");
 
2760
   if (!f) return 0;
 
2761
   start_file(&p.s, f);
 
2762
   if (parse_png_file(&p, SCAN_header, 0)) {
 
2763
      if(x) *x = p.s.img_x;
 
2764
      if(y) *y = p.s.img_y;
 
2765
      if (comp) *comp = p.s.img_n;
 
2766
      fclose(f);
 
2767
      return 1;
 
2768
   }
 
2769
   fclose(f);
 
2770
   return 0;
 
2771
}
 
2772
 
 
2773
extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);
 
2774
#endif
 
2775
extern int      stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);
 
2776
 
 
2777
// Microsoft/Windows BMP image
 
2778
 
 
2779
static int bmp_test(stbi *s)
 
2780
{
 
2781
   int sz;
 
2782
   if (get8(s) != 'B') return 0;
 
2783
   if (get8(s) != 'M') return 0;
 
2784
   get32le(s); // discard filesize
 
2785
   get16le(s); // discard reserved
 
2786
   get16le(s); // discard reserved
 
2787
   get32le(s); // discard data offset
 
2788
   sz = get32le(s);
 
2789
   if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;
 
2790
   return 0;
 
2791
}
 
2792
 
 
2793
#ifndef STBI_NO_STDIO
 
2794
int      stbi_bmp_test_file        (FILE *f)
 
2795
{
 
2796
   stbi s;
 
2797
   int r,n = ftell(f);
 
2798
   start_file(&s,f);
 
2799
   r = bmp_test(&s);
 
2800
   fseek(f,n,SEEK_SET);
 
2801
   return r;
 
2802
}
 
2803
#endif
 
2804
 
 
2805
int      stbi_bmp_test_memory      (stbi_uc const *buffer, int len)
 
2806
{
 
2807
   stbi s;
 
2808
   start_mem(&s, buffer, len);
 
2809
   return bmp_test(&s);
 
2810
}
 
2811
 
 
2812
// returns 0..31 for the highest set bit
 
2813
static int high_bit(unsigned int z)
 
2814
{
 
2815
   int n=0;
 
2816
   if (z == 0) return -1;
 
2817
   if (z >= 0x10000) n += 16, z >>= 16;
 
2818
   if (z >= 0x00100) n +=  8, z >>=  8;
 
2819
   if (z >= 0x00010) n +=  4, z >>=  4;
 
2820
   if (z >= 0x00004) n +=  2, z >>=  2;
 
2821
   if (z >= 0x00002) n +=  1, z >>=  1;
 
2822
   return n;
 
2823
}
 
2824
 
 
2825
static int bitcount(unsigned int a)
 
2826
{
 
2827
   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2
 
2828
   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4
 
2829
   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
 
2830
   a = (a + (a >> 8)); // max 16 per 8 bits
 
2831
   a = (a + (a >> 16)); // max 32 per 8 bits
 
2832
   return a & 0xff;
 
2833
}
 
2834
 
 
2835
static int shiftsigned(int v, int shift, int bits)
 
2836
{
 
2837
   int result;
 
2838
   int z=0;
 
2839
 
 
2840
   if (shift < 0) v <<= -shift;
 
2841
   else v >>= shift;
 
2842
   result = v;
 
2843
 
 
2844
   z = bits;
 
2845
   while (z < 8) {
 
2846
      result += v >> z;
 
2847
      z += bits;
 
2848
   }
 
2849
   return result;
 
2850
}
 
2851
 
 
2852
static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
 
2853
{
 
2854
   uint8 *out;
 
2855
   unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
 
2856
   stbi_uc pal[256][4];
 
2857
   int psize=0,i,j,compress=0,width;
 
2858
   int bpp, flip_vertically, pad, target, offset, hsz;
 
2859
   if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");
 
2860
   get32le(s); // discard filesize
 
2861
   get16le(s); // discard reserved
 
2862
   get16le(s); // discard reserved
 
2863
   offset = get32le(s);
 
2864
   hsz = get32le(s);
 
2865
   if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");
 
2866
   failure_reason = "bad BMP";
 
2867
   if (hsz == 12) {
 
2868
      s->img_x = get16le(s);
 
2869
      s->img_y = get16le(s);
 
2870
   } else {
 
2871
      s->img_x = get32le(s);
 
2872
      s->img_y = get32le(s);
 
2873
   }
 
2874
   if (get16le(s) != 1) return 0;
 
2875
   bpp = get16le(s);
 
2876
   if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");
 
2877
   flip_vertically = ((int) s->img_y) > 0;
 
2878
   s->img_y = abs((int) s->img_y);
 
2879
   if (hsz == 12) {
 
2880
      if (bpp < 24)
 
2881
         psize = (offset - 14 - 24) / 3;
 
2882
   } else {
 
2883
      compress = get32le(s);
 
2884
      if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");
 
2885
      get32le(s); // discard sizeof
 
2886
      get32le(s); // discard hres
 
2887
      get32le(s); // discard vres
 
2888
      get32le(s); // discard colorsused
 
2889
      get32le(s); // discard max important
 
2890
      if (hsz == 40 || hsz == 56) {
 
2891
         if (hsz == 56) {
 
2892
            get32le(s);
 
2893
            get32le(s);
 
2894
            get32le(s);
 
2895
            get32le(s);
 
2896
         }
 
2897
         if (bpp == 16 || bpp == 32) {
 
2898
            mr = mg = mb = 0;
 
2899
            if (compress == 0) {
 
2900
               if (bpp == 32) {
 
2901
                  mr = 0xff << 16;
 
2902
                  mg = 0xff <<  8;
 
2903
                  mb = 0xff <<  0;
 
2904
                  ma = 0xff << 24;
 
2905
                  fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
 
2906
               } else {
 
2907
                  mr = 31 << 10;
 
2908
                  mg = 31 <<  5;
 
2909
                  mb = 31 <<  0;
 
2910
               }
 
2911
            } else if (compress == 3) {
 
2912
               mr = get32le(s);
 
2913
               mg = get32le(s);
 
2914
               mb = get32le(s);
 
2915
               // not documented, but generated by photoshop and handled by mspaint
 
2916
               if (mr == mg && mg == mb) {
 
2917
                  // ?!?!?
 
2918
                  return NULL;
 
2919
               }
 
2920
            } else
 
2921
               return NULL;
 
2922
         }
 
2923
      } else {
 
2924
         assert(hsz == 108);
 
2925
         mr = get32le(s);
 
2926
         mg = get32le(s);
 
2927
         mb = get32le(s);
 
2928
         ma = get32le(s);
 
2929
         get32le(s); // discard color space
 
2930
         for (i=0; i < 12; ++i)
 
2931
            get32le(s); // discard color space parameters
 
2932
      }
 
2933
      if (bpp < 16)
 
2934
         psize = (offset - 14 - hsz) >> 2;
 
2935
   }
 
2936
   s->img_n = ma ? 4 : 3;
 
2937
   if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
 
2938
      target = req_comp;
 
2939
   else
 
2940
      target = s->img_n; // if they want monochrome, we'll post-convert
 
2941
   out = (stbi_uc *) malloc(target * s->img_x * s->img_y);
 
2942
   if (!out) return epuc("outofmem", "Out of memory");
 
2943
   if (bpp < 16) {
 
2944
      int z=0;
 
2945
      if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }
 
2946
      for (i=0; i < psize; ++i) {
 
2947
         pal[i][2] = get8(s);
 
2948
         pal[i][1] = get8(s);
 
2949
         pal[i][0] = get8(s);
 
2950
         if (hsz != 12) get8(s);
 
2951
         pal[i][3] = 255;
 
2952
      }
 
2953
      skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
 
2954
      if (bpp == 4) width = (s->img_x + 1) >> 1;
 
2955
      else if (bpp == 8) width = s->img_x;
 
2956
      else { free(out); return epuc("bad bpp", "Corrupt BMP"); }
 
2957
      pad = (-width)&3;
 
2958
      for (j=0; j < (int) s->img_y; ++j) {
 
2959
         for (i=0; i < (int) s->img_x; i += 2) {
 
2960
            int v=get8(s),v2=0;
 
2961
            if (bpp == 4) {
 
2962
               v2 = v & 15;
 
2963
               v >>= 4;
 
2964
            }
 
2965
            out[z++] = pal[v][0];
 
2966
            out[z++] = pal[v][1];
 
2967
            out[z++] = pal[v][2];
 
2968
            if (target == 4) out[z++] = 255;
 
2969
            if (i+1 == (int) s->img_x) break;
 
2970
            v = (bpp == 8) ? get8(s) : v2;
 
2971
            out[z++] = pal[v][0];
 
2972
            out[z++] = pal[v][1];
 
2973
            out[z++] = pal[v][2];
 
2974
            if (target == 4) out[z++] = 255;
 
2975
         }
 
2976
         skip(s, pad);
 
2977
      }
 
2978
   } else {
 
2979
      int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
 
2980
      int z = 0;
 
2981
      int easy=0;
 
2982
      skip(s, offset - 14 - hsz);
 
2983
      if (bpp == 24) width = 3 * s->img_x;
 
2984
      else if (bpp == 16) width = 2*s->img_x;
 
2985
      else /* bpp = 32 and pad = 0 */ width=0;
 
2986
      pad = (-width) & 3;
 
2987
      if (bpp == 24) {
 
2988
         easy = 1;
 
2989
      } else if (bpp == 32) {
 
2990
         if (mb == 0xff && mg == 0xff00 && mr == 0xff000000 && ma == 0xff000000)
 
2991
            easy = 2;
 
2992
      }
 
2993
      if (!easy) {
 
2994
         if (!mr || !mg || !mb) return epuc("bad masks", "Corrupt BMP");
 
2995
         // right shift amt to put high bit in position #7
 
2996
         rshift = high_bit(mr)-7; rcount = bitcount(mr);
 
2997
         gshift = high_bit(mg)-7; gcount = bitcount(mr);
 
2998
         bshift = high_bit(mb)-7; bcount = bitcount(mr);
 
2999
         ashift = high_bit(ma)-7; acount = bitcount(mr);
 
3000
      }
 
3001
      for (j=0; j < (int) s->img_y; ++j) {
 
3002
         if (easy) {
 
3003
            for (i=0; i < (int) s->img_x; ++i) {
 
3004
               int a;
 
3005
               out[z+2] = get8(s);
 
3006
               out[z+1] = get8(s);
 
3007
               out[z+0] = get8(s);
 
3008
               z += 3;
 
3009
               a = (easy == 2 ? get8(s) : 255);
 
3010
               if (target == 4) out[z++] = a;
 
3011
            }
 
3012
         } else {
 
3013
            for (i=0; i < (int) s->img_x; ++i) {
 
3014
               uint32 v = (bpp == 16 ? get16le(s) : get32le(s));
 
3015
               int a;
 
3016
               out[z++] = shiftsigned(v & mr, rshift, rcount);
 
3017
               out[z++] = shiftsigned(v & mg, gshift, gcount);
 
3018
               out[z++] = shiftsigned(v & mb, bshift, bcount);
 
3019
               a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);
 
3020
               if (target == 4) out[z++] = a; 
 
3021
            }
 
3022
         }
 
3023
         skip(s, pad);
 
3024
      }
 
3025
   }
 
3026
   if (flip_vertically) {
 
3027
      stbi_uc t;
 
3028
      for (j=0; j < (int) s->img_y>>1; ++j) {
 
3029
         stbi_uc *p1 = out +      j     *s->img_x*target;
 
3030
         stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
 
3031
         for (i=0; i < (int) s->img_x*target; ++i) {
 
3032
            t = p1[i], p1[i] = p2[i], p2[i] = t;
 
3033
         }
 
3034
      }
 
3035
   }
 
3036
 
 
3037
   if (req_comp && req_comp != target) {
 
3038
      out = convert_format(out, target, req_comp, s->img_x, s->img_y);
 
3039
      if (out == NULL) return out; // convert_format frees input on failure
 
3040
   }
 
3041
 
 
3042
   *x = s->img_x;
 
3043
   *y = s->img_y;
 
3044
   if (comp) *comp = target;
 
3045
   return out;
 
3046
}
 
3047
 
 
3048
#ifndef STBI_NO_STDIO
 
3049
stbi_uc *stbi_bmp_load             (char const *filename,           int *x, int *y, int *comp, int req_comp)
 
3050
{
 
3051
   stbi_uc *data;
 
3052
   FILE *f = fopen(filename, "rb");
 
3053
   if (!f) return NULL;
 
3054
   data = stbi_bmp_load_from_file(f, x,y,comp,req_comp);
 
3055
   fclose(f);
 
3056
   return data;
 
3057
}
 
3058
 
 
3059
stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)
 
3060
{
 
3061
   stbi s;
 
3062
   start_file(&s, f);
 
3063
   return bmp_load(&s, x,y,comp,req_comp);
 
3064
}
 
3065
#endif
 
3066
 
 
3067
stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
 
3068
{
 
3069
   stbi s;
 
3070
   start_mem(&s, buffer, len);
 
3071
   return bmp_load(&s, x,y,comp,req_comp);
 
3072
}
 
3073
 
 
3074
// Targa Truevision - TGA
 
3075
// by Jonathan Dummer
 
3076
 
 
3077
static int tga_test(stbi *s)
 
3078
{
 
3079
        int sz;
 
3080
        get8u(s);               //      discard Offset
 
3081
        sz = get8u(s);  //      color type
 
3082
        if( sz > 1 ) return 0;  //      only RGB or indexed allowed
 
3083
        sz = get8u(s);  //      image type
 
3084
        if( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0;    //      only RGB or grey allowed, +/- RLE
 
3085
        get16(s);               //      discard palette start
 
3086
        get16(s);               //      discard palette length
 
3087
        get8(s);                        //      discard bits per palette color entry
 
3088
        get16(s);               //      discard x origin
 
3089
        get16(s);               //      discard y origin
 
3090
        if( get16(s) < 1 ) return 0;            //      test width
 
3091
        if( get16(s) < 1 ) return 0;            //      test height
 
3092
        sz = get8(s);   //      bits per pixel
 
3093
        if( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0;     //      only RGB or RGBA or grey allowed
 
3094
        return 1;               //      seems to have passed everything
 
3095
}
 
3096
 
 
3097
#ifndef STBI_NO_STDIO
 
3098
int      stbi_tga_test_file        (FILE *f)
 
3099
{
 
3100
   stbi s;
 
3101
   int r,n = ftell(f);
 
3102
   start_file(&s, f);
 
3103
   r = tga_test(&s);
 
3104
   fseek(f,n,SEEK_SET);
 
3105
   return r;
 
3106
}
 
3107
#endif
 
3108
 
 
3109
int      stbi_tga_test_memory      (stbi_uc const *buffer, int len)
 
3110
{
 
3111
   stbi s;
 
3112
   start_mem(&s, buffer, len);
 
3113
   return tga_test(&s);
 
3114
}
 
3115
 
 
3116
static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
 
3117
{
 
3118
        //      read in the TGA header stuff
 
3119
        int tga_offset = get8u(s);
 
3120
        int tga_indexed = get8u(s);
 
3121
        int tga_image_type = get8u(s);
 
3122
        int tga_is_RLE = 0;
 
3123
        int tga_palette_start = get16le(s);
 
3124
        int tga_palette_len = get16le(s);
 
3125
        int tga_palette_bits = get8u(s);
 
3126
        int tga_x_origin = get16le(s);
 
3127
        int tga_y_origin = get16le(s);
 
3128
        int tga_width = get16le(s);
 
3129
        int tga_height = get16le(s);
 
3130
        int tga_bits_per_pixel = get8u(s);
 
3131
        int tga_inverted = get8u(s);
 
3132
        //      image data
 
3133
        unsigned char *tga_data;
 
3134
        unsigned char *tga_palette = NULL;
 
3135
        int i, j;
 
3136
        unsigned char raw_data[4];
 
3137
        unsigned char trans_data[4];
 
3138
        int RLE_count = 0;
 
3139
        int RLE_repeating = 0;
 
3140
        int read_next_pixel = 1;
 
3141
        //      do a tiny bit of precessing
 
3142
        if( tga_image_type >= 8 )
 
3143
        {
 
3144
                tga_image_type -= 8;
 
3145
                tga_is_RLE = 1;
 
3146
        }
 
3147
        /* int tga_alpha_bits = tga_inverted & 15; */
 
3148
        tga_inverted = 1 - ((tga_inverted >> 5) & 1);
 
3149
 
 
3150
        //      error check
 
3151
        if( //(tga_indexed) ||
 
3152
                (tga_width < 1) || (tga_height < 1) ||
 
3153
                (tga_image_type < 1) || (tga_image_type > 3) ||
 
3154
                ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
 
3155
                (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
 
3156
                )
 
3157
        {
 
3158
                return NULL;
 
3159
        }
 
3160
 
 
3161
        //      If I'm paletted, then I'll use the number of bits from the palette
 
3162
        if( tga_indexed )
 
3163
        {
 
3164
                tga_bits_per_pixel = tga_palette_bits;
 
3165
        }
 
3166
 
 
3167
        //      tga info
 
3168
        *x = tga_width;
 
3169
        *y = tga_height;
 
3170
        if( (req_comp < 1) || (req_comp > 4) )
 
3171
        {
 
3172
                //      just use whatever the file was
 
3173
                req_comp = tga_bits_per_pixel / 8;
 
3174
                *comp = req_comp;
 
3175
        } else
 
3176
        {
 
3177
                //      force a new number of components
 
3178
                *comp = tga_bits_per_pixel/8;
 
3179
        }
 
3180
        tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );
 
3181
 
 
3182
        //      skip to the data's starting position (offset usually = 0)
 
3183
        skip(s, tga_offset );
 
3184
        //      do I need to load a palette?
 
3185
        if( tga_indexed )
 
3186
        {
 
3187
                //      any data to skip? (offset usually = 0)
 
3188
                skip(s, tga_palette_start );
 
3189
                //      load the palette
 
3190
                tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );
 
3191
                getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 );
 
3192
        }
 
3193
        //      load the data
 
3194
        for( i = 0; i < tga_width * tga_height; ++i )
 
3195
        {
 
3196
                //      if I'm in RLE mode, do I need to get a RLE chunk?
 
3197
                if( tga_is_RLE )
 
3198
                {
 
3199
                        if( RLE_count == 0 )
 
3200
                        {
 
3201
                                //      yep, get the next byte as a RLE command
 
3202
                                int RLE_cmd = get8u(s);
 
3203
                                RLE_count = 1 + (RLE_cmd & 127);
 
3204
                                RLE_repeating = RLE_cmd >> 7;
 
3205
                                read_next_pixel = 1;
 
3206
                        } else if( !RLE_repeating )
 
3207
                        {
 
3208
                                read_next_pixel = 1;
 
3209
                        }
 
3210
                } else
 
3211
                {
 
3212
                        read_next_pixel = 1;
 
3213
                }
 
3214
                //      OK, if I need to read a pixel, do it now
 
3215
                if( read_next_pixel )
 
3216
                {
 
3217
                        //      load however much data we did have
 
3218
                        if( tga_indexed )
 
3219
                        {
 
3220
                                //      read in 1 byte, then perform the lookup
 
3221
                                int pal_idx = get8u(s);
 
3222
                                if( pal_idx >= tga_palette_len )
 
3223
                                {
 
3224
                                        //      invalid index
 
3225
                                        pal_idx = 0;
 
3226
                                }
 
3227
                                pal_idx *= tga_bits_per_pixel / 8;
 
3228
                                for( j = 0; j*8 < tga_bits_per_pixel; ++j )
 
3229
                                {
 
3230
                                        raw_data[j] = tga_palette[pal_idx+j];
 
3231
                                }
 
3232
                        } else
 
3233
                        {
 
3234
                                //      read in the data raw
 
3235
                                for( j = 0; j*8 < tga_bits_per_pixel; ++j )
 
3236
                                {
 
3237
                                        raw_data[j] = get8u(s);
 
3238
                                }
 
3239
                        }
 
3240
                        //      convert raw to the intermediate format
 
3241
                        switch( tga_bits_per_pixel )
 
3242
                        {
 
3243
                        case 8:
 
3244
                                //      Luminous => RGBA
 
3245
                                trans_data[0] = raw_data[0];
 
3246
                                trans_data[1] = raw_data[0];
 
3247
                                trans_data[2] = raw_data[0];
 
3248
                                trans_data[3] = 255;
 
3249
                                break;
 
3250
                        case 16:
 
3251
                                //      Luminous,Alpha => RGBA
 
3252
                                trans_data[0] = raw_data[0];
 
3253
                                trans_data[1] = raw_data[0];
 
3254
                                trans_data[2] = raw_data[0];
 
3255
                                trans_data[3] = raw_data[1];
 
3256
                                break;
 
3257
                        case 24:
 
3258
                                //      BGR => RGBA
 
3259
                                trans_data[0] = raw_data[2];
 
3260
                                trans_data[1] = raw_data[1];
 
3261
                                trans_data[2] = raw_data[0];
 
3262
                                trans_data[3] = 255;
 
3263
                                break;
 
3264
                        case 32:
 
3265
                                //      BGRA => RGBA
 
3266
                                trans_data[0] = raw_data[2];
 
3267
                                trans_data[1] = raw_data[1];
 
3268
                                trans_data[2] = raw_data[0];
 
3269
                                trans_data[3] = raw_data[3];
 
3270
                                break;
 
3271
                        }
 
3272
                        //      clear the reading flag for the next pixel
 
3273
                        read_next_pixel = 0;
 
3274
                } // end of reading a pixel
 
3275
                //      convert to final format
 
3276
                switch( req_comp )
 
3277
                {
 
3278
                case 1:
 
3279
                        //      RGBA => Luminance
 
3280
                        tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
 
3281
                        break;
 
3282
                case 2:
 
3283
                        //      RGBA => Luminance,Alpha
 
3284
                        tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
 
3285
                        tga_data[i*req_comp+1] = trans_data[3];
 
3286
                        break;
 
3287
                case 3:
 
3288
                        //      RGBA => RGB
 
3289
                        tga_data[i*req_comp+0] = trans_data[0];
 
3290
                        tga_data[i*req_comp+1] = trans_data[1];
 
3291
                        tga_data[i*req_comp+2] = trans_data[2];
 
3292
                        break;
 
3293
                case 4:
 
3294
                        //      RGBA => RGBA
 
3295
                        tga_data[i*req_comp+0] = trans_data[0];
 
3296
                        tga_data[i*req_comp+1] = trans_data[1];
 
3297
                        tga_data[i*req_comp+2] = trans_data[2];
 
3298
                        tga_data[i*req_comp+3] = trans_data[3];
 
3299
                        break;
 
3300
                }
 
3301
                //      in case we're in RLE mode, keep counting down
 
3302
                --RLE_count;
 
3303
        }
 
3304
        //      do I need to invert the image?
 
3305
        if( tga_inverted )
 
3306
        {
 
3307
                for( j = 0; j*2 < tga_height; ++j )
 
3308
                {
 
3309
                        int index1 = j * tga_width * req_comp;
 
3310
                        int index2 = (tga_height - 1 - j) * tga_width * req_comp;
 
3311
                        for( i = tga_width * req_comp; i > 0; --i )
 
3312
                        {
 
3313
                                unsigned char temp = tga_data[index1];
 
3314
                                tga_data[index1] = tga_data[index2];
 
3315
                                tga_data[index2] = temp;
 
3316
                                ++index1;
 
3317
                                ++index2;
 
3318
                        }
 
3319
                }
 
3320
        }
 
3321
        //      clear my palette, if I had one
 
3322
        if( tga_palette != NULL )
 
3323
        {
 
3324
                free( tga_palette );
 
3325
        }
 
3326
        //      the things I do to get rid of an error message, and yet keep
 
3327
        //      Microsoft's C compilers happy... [8^(
 
3328
        tga_palette_start = tga_palette_len = tga_palette_bits =
 
3329
                        tga_x_origin = tga_y_origin = 0;
 
3330
        //      OK, done
 
3331
        return tga_data;
 
3332
}
 
3333
 
 
3334
#ifndef STBI_NO_STDIO
 
3335
stbi_uc *stbi_tga_load             (char const *filename,           int *x, int *y, int *comp, int req_comp)
 
3336
{
 
3337
   stbi_uc *data;
 
3338
   FILE *f = fopen(filename, "rb");
 
3339
   if (!f) return NULL;
 
3340
   data = stbi_tga_load_from_file(f, x,y,comp,req_comp);
 
3341
   fclose(f);
 
3342
   return data;
 
3343
}
 
3344
 
 
3345
stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)
 
3346
{
 
3347
   stbi s;
 
3348
   start_file(&s, f);
 
3349
   return tga_load(&s, x,y,comp,req_comp);
 
3350
}
 
3351
#endif
 
3352
 
 
3353
stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
 
3354
{
 
3355
   stbi s;
 
3356
   start_mem(&s, buffer, len);
 
3357
   return tga_load(&s, x,y,comp,req_comp);
 
3358
}
 
3359
 
 
3360
 
 
3361
// *************************************************************************************************
 
3362
// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicholas Schulz, tweaked by STB
 
3363
 
 
3364
static int psd_test(stbi *s)
 
3365
{
 
3366
        if (get32(s) != 0x38425053) return 0;   // "8BPS"
 
3367
        else return 1;
 
3368
}
 
3369
 
 
3370
#ifndef STBI_NO_STDIO
 
3371
int stbi_psd_test_file(FILE *f)
 
3372
{
 
3373
   stbi s;
 
3374
   int r,n = ftell(f);
 
3375
   start_file(&s, f);
 
3376
   r = psd_test(&s);
 
3377
   fseek(f,n,SEEK_SET);
 
3378
   return r;
 
3379
}
 
3380
#endif
 
3381
 
 
3382
int stbi_psd_test_memory(stbi_uc const *buffer, int len)
 
3383
{
 
3384
   stbi s;
 
3385
   start_mem(&s, buffer, len);
 
3386
   return psd_test(&s);
 
3387
}
 
3388
 
 
3389
static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
 
3390
{
 
3391
        int     pixelCount;
 
3392
        int channelCount, compression;
 
3393
        int channel, i, count, len;
 
3394
   int w,h;
 
3395
   uint8 *out;
 
3396
 
 
3397
        // Check identifier
 
3398
        if (get32(s) != 0x38425053)     // "8BPS"
 
3399
                return epuc("not PSD", "Corrupt PSD image");
 
3400
 
 
3401
        // Check file type version.
 
3402
        if (get16(s) != 1)
 
3403
                return epuc("wrong version", "Unsupported version of PSD image");
 
3404
 
 
3405
        // Skip 6 reserved bytes.
 
3406
        skip(s, 6 );
 
3407
 
 
3408
        // Read the number of channels (R, G, B, A, etc).
 
3409
        channelCount = get16(s);
 
3410
        if (channelCount < 0 || channelCount > 16)
 
3411
                return epuc("wrong channel count", "Unsupported number of channels in PSD image");
 
3412
 
 
3413
        // Read the rows and columns of the image.
 
3414
   h = get32(s);
 
3415
   w = get32(s);
 
3416
        
 
3417
        // Make sure the depth is 8 bits.
 
3418
        if (get16(s) != 8)
 
3419
                return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");
 
3420
 
 
3421
        // Make sure the color mode is RGB.
 
3422
        // Valid options are:
 
3423
        //   0: Bitmap
 
3424
        //   1: Grayscale
 
3425
        //   2: Indexed color
 
3426
        //   3: RGB color
 
3427
        //   4: CMYK color
 
3428
        //   7: Multichannel
 
3429
        //   8: Duotone
 
3430
        //   9: Lab color
 
3431
        if (get16(s) != 3)
 
3432
                return epuc("wrong color format", "PSD is not in RGB color format");
 
3433
 
 
3434
        // Skip the Mode Data.  (It's the palette for indexed color; other info for other modes.)
 
3435
        skip(s,get32(s) );
 
3436
 
 
3437
        // Skip the image resources.  (resolution, pen tool paths, etc)
 
3438
        skip(s, get32(s) );
 
3439
 
 
3440
        // Skip the reserved data.
 
3441
        skip(s, get32(s) );
 
3442
 
 
3443
        // Find out if the data is compressed.
 
3444
        // Known values:
 
3445
        //   0: no compression
 
3446
        //   1: RLE compressed
 
3447
        compression = get16(s);
 
3448
        if (compression > 1)
 
3449
                return epuc("bad compression", "PSD has an unknown compression format");
 
3450
 
 
3451
        // Create the destination image.
 
3452
        out = (stbi_uc *) malloc(4 * w*h);
 
3453
        if (!out) return epuc("outofmem", "Out of memory");
 
3454
   pixelCount = w*h;
 
3455
 
 
3456
        // Initialize the data to zero.
 
3457
        //memset( out, 0, pixelCount * 4 );
 
3458
        
 
3459
        // Finally, the image data.
 
3460
        if (compression) {
 
3461
                // RLE as used by .PSD and .TIFF
 
3462
                // Loop until you get the number of unpacked bytes you are expecting:
 
3463
                //     Read the next source byte into n.
 
3464
                //     If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
 
3465
                //     Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
 
3466
                //     Else if n is 128, noop.
 
3467
                // Endloop
 
3468
 
 
3469
                // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
 
3470
                // which we're going to just skip.
 
3471
                skip(s, h * channelCount * 2 );
 
3472
 
 
3473
                // Read the RLE data by channel.
 
3474
                for (channel = 0; channel < 4; channel++) {
 
3475
                        uint8 *p;
 
3476
                        
 
3477
         p = out+channel;
 
3478
                        if (channel >= channelCount) {
 
3479
                                // Fill this channel with default data.
 
3480
                                for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
 
3481
                        } else {
 
3482
                                // Read the RLE data.
 
3483
                                count = 0;
 
3484
                                while (count < pixelCount) {
 
3485
                                        len = get8(s);
 
3486
                                        if (len == 128) {
 
3487
                                                // No-op.
 
3488
                                        } else if (len < 128) {
 
3489
                                                // Copy next len+1 bytes literally.
 
3490
                                                len++;
 
3491
                                                count += len;
 
3492
                                                while (len) {
 
3493
                                                        *p = get8(s);
 
3494
                     p += 4;
 
3495
                                                        len--;
 
3496
                                                }
 
3497
                                        } else if (len > 128) {
 
3498
                                                uint32  val;
 
3499
                                                // Next -len+1 bytes in the dest are replicated from next source byte.
 
3500
                                                // (Interpret len as a negative 8-bit int.)
 
3501
                                                len ^= 0x0FF;
 
3502
                                                len += 2;
 
3503
                  val = get8(s);
 
3504
                                                count += len;
 
3505
                                                while (len) {
 
3506
                                                        *p = val;
 
3507
                     p += 4;
 
3508
                                                        len--;
 
3509
                                                }
 
3510
                                        }
 
3511
                                }
 
3512
                        }
 
3513
                }
 
3514
                
 
3515
        } else {
 
3516
                // We're at the raw image data.  It's each channel in order (Red, Green, Blue, Alpha, ...)
 
3517
                // where each channel consists of an 8-bit value for each pixel in the image.
 
3518
                
 
3519
                // Read the data by channel.
 
3520
                for (channel = 0; channel < 4; channel++) {
 
3521
                        uint8 *p;
 
3522
                        
 
3523
         p = out + channel;
 
3524
                        if (channel > channelCount) {
 
3525
                                // Fill this channel with default data.
 
3526
                                for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
 
3527
                        } else {
 
3528
                                // Read the data.
 
3529
                                count = 0;
 
3530
                                for (i = 0; i < pixelCount; i++)
 
3531
                                        *p = get8(s), p += 4;
 
3532
                        }
 
3533
                }
 
3534
        }
 
3535
 
 
3536
        if (req_comp && req_comp != 4) {
 
3537
                out = convert_format(out, 4, req_comp, w, h);
 
3538
                if (out == NULL) return out; // convert_format frees input on failure
 
3539
        }
 
3540
 
 
3541
        if (comp) *comp = channelCount;
 
3542
        *y = h;
 
3543
        *x = w;
 
3544
        
 
3545
        return out;
 
3546
}
 
3547
 
 
3548
#ifndef STBI_NO_STDIO
 
3549
stbi_uc *stbi_psd_load(char const *filename, int *x, int *y, int *comp, int req_comp)
 
3550
{
 
3551
   stbi_uc *data;
 
3552
   FILE *f = fopen(filename, "rb");
 
3553
   if (!f) return NULL;
 
3554
   data = stbi_psd_load_from_file(f, x,y,comp,req_comp);
 
3555
   fclose(f);
 
3556
   return data;
 
3557
}
 
3558
 
 
3559
stbi_uc *stbi_psd_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
 
3560
{
 
3561
   stbi s;
 
3562
   start_file(&s, f);
 
3563
   return psd_load(&s, x,y,comp,req_comp);
 
3564
}
 
3565
#endif
 
3566
 
 
3567
stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
 
3568
{
 
3569
   stbi s;
 
3570
   start_mem(&s, buffer, len);
 
3571
   return psd_load(&s, x,y,comp,req_comp);
 
3572
}
 
3573
 
 
3574
 
 
3575
// *************************************************************************************************
 
3576
// Radiance RGBE HDR loader
 
3577
// originally by Nicolas Schulz
 
3578
#ifndef STBI_NO_HDR
 
3579
static int hdr_test(stbi *s)
 
3580
{
 
3581
   char *signature = "#?RADIANCE\n";
 
3582
   int i;
 
3583
   for (i=0; signature[i]; ++i)
 
3584
      if (get8(s) != signature[i])
 
3585
         return 0;
 
3586
        return 1;
 
3587
}
 
3588
 
 
3589
int stbi_hdr_test_memory(stbi_uc const *buffer, int len)
 
3590
{
 
3591
   stbi s;
 
3592
        start_mem(&s, buffer, len);
 
3593
        return hdr_test(&s);
 
3594
}
 
3595
 
 
3596
#ifndef STBI_NO_STDIO
 
3597
int stbi_hdr_test_file(FILE *f)
 
3598
{
 
3599
   stbi s;
 
3600
   int r,n = ftell(f);
 
3601
   start_file(&s, f);
 
3602
   r = hdr_test(&s);
 
3603
   fseek(f,n,SEEK_SET);
 
3604
   return r;
 
3605
}
 
3606
#endif
 
3607
 
 
3608
#define HDR_BUFLEN  1024
 
3609
static char *hdr_gettoken(stbi *z, char *buffer)
 
3610
{
 
3611
   int len=0;
 
3612
        char *s = buffer, c = '\0';
 
3613
 
 
3614
   c = get8(z);
 
3615
 
 
3616
        while (!at_eof(z) && c != '\n') {
 
3617
                buffer[len++] = c;
 
3618
      if (len == HDR_BUFLEN-1) {
 
3619
         // flush to end of line
 
3620
         while (!at_eof(z) && get8(z) != '\n')
 
3621
            ;
 
3622
         break;
 
3623
      }
 
3624
      c = get8(z);
 
3625
        }
 
3626
 
 
3627
   buffer[len] = 0;
 
3628
        return buffer;
 
3629
}
 
3630
 
 
3631
static void hdr_convert(float *output, stbi_uc *input, int req_comp)
 
3632
{
 
3633
        if( input[3] != 0 ) {
 
3634
      float f1;
 
3635
                // Exponent
 
3636
                f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
 
3637
      if (req_comp <= 2)
 
3638
         output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
 
3639
      else {
 
3640
         output[0] = input[0] * f1;
 
3641
         output[1] = input[1] * f1;
 
3642
         output[2] = input[2] * f1;
 
3643
      }
 
3644
      if (req_comp == 2) output[1] = 1;
 
3645
      if (req_comp == 4) output[3] = 1;
 
3646
        } else {
 
3647
      switch (req_comp) {
 
3648
         case 4: output[3] = 1; /* fallthrough */
 
3649
         case 3: output[0] = output[1] = output[2] = 0;
 
3650
                 break;
 
3651
         case 2: output[1] = 1; /* fallthrough */
 
3652
         case 1: output[0] = 0;
 
3653
                 break;
 
3654
      }
 
3655
        }
 
3656
}
 
3657
 
 
3658
 
 
3659
static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
 
3660
{
 
3661
   char buffer[HDR_BUFLEN];
 
3662
        char *token;
 
3663
        int valid = 0;
 
3664
        int width, height;
 
3665
   stbi_uc *scanline;
 
3666
        float *hdr_data;
 
3667
        int len;
 
3668
        unsigned char count, value;
 
3669
        int i, j, k, c1,c2, z;
 
3670
 
 
3671
 
 
3672
        // Check identifier
 
3673
        if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
 
3674
                return epf("not HDR", "Corrupt HDR image");
 
3675
        
 
3676
        // Parse header
 
3677
        while(1) {
 
3678
                token = hdr_gettoken(s,buffer);
 
3679
      if (token[0] == 0) break;
 
3680
                if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
 
3681
   }
 
3682
 
 
3683
        if (!valid)    return epf("unsupported format", "Unsupported HDR format");
 
3684
 
 
3685
   // Parse width and height
 
3686
   // can't use sscanf() if we're not using stdio!
 
3687
   token = hdr_gettoken(s,buffer);
 
3688
   if (strncmp(token, "-Y ", 3))  return epf("unsupported data layout", "Unsupported HDR format");
 
3689
   token += 3;
 
3690
   height = strtol(token, &token, 10);
 
3691
   while (*token == ' ') ++token;
 
3692
   if (strncmp(token, "+X ", 3))  return epf("unsupported data layout", "Unsupported HDR format");
 
3693
   token += 3;
 
3694
   width = strtol(token, NULL, 10);
 
3695
 
 
3696
        *x = width;
 
3697
        *y = height;
 
3698
 
 
3699
   *comp = 3;
 
3700
        if (req_comp == 0) req_comp = 3;
 
3701
 
 
3702
        // Read data
 
3703
        hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));
 
3704
 
 
3705
        // Load image data
 
3706
   // image data is stored as some number of sca
 
3707
        if( width < 8 || width >= 32768) {
 
3708
                // Read flat data
 
3709
      for (j=0; j < height; ++j) {
 
3710
         for (i=0; i < width; ++i) {
 
3711
            stbi_uc rgbe[4];
 
3712
           main_decode_loop:
 
3713
            getn(s, rgbe, 4);
 
3714
            hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
 
3715
         }
 
3716
      }
 
3717
        } else {
 
3718
                // Read RLE-encoded data
 
3719
                scanline = NULL;
 
3720
 
 
3721
                for (j = 0; j < height; ++j) {
 
3722
         c1 = get8(s);
 
3723
         c2 = get8(s);
 
3724
         len = get8(s);
 
3725
         if (c1 != 2 || c2 != 2 || (len & 0x80)) {
 
3726
            // not run-length encoded, so we have to actually use THIS data as a decoded
 
3727
            // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
 
3728
            stbi_uc rgbe[4] = { c1,c2,len, get8(s) };
 
3729
            hdr_convert(hdr_data, rgbe, req_comp);
 
3730
            i = 1;
 
3731
            j = 0;
 
3732
            free(scanline);
 
3733
            goto main_decode_loop; // yes, this is fucking insane; blame the fucking insane format
 
3734
         }
 
3735
         len <<= 8;
 
3736
         len |= get8(s);
 
3737
         if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }
 
3738
         if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);
 
3739
                                
 
3740
                        for (k = 0; k < 4; ++k) {
 
3741
                                i = 0;
 
3742
                                while (i < width) {
 
3743
                                        count = get8(s);
 
3744
                                        if (count > 128) {
 
3745
                                                // Run
 
3746
                                                value = get8(s);
 
3747
                  count -= 128;
 
3748
                                                for (z = 0; z < count; ++z)
 
3749
                                                        scanline[i++ * 4 + k] = value;
 
3750
                                        } else {
 
3751
                                                // Dump
 
3752
                                                for (z = 0; z < count; ++z)
 
3753
                                                        scanline[i++ * 4 + k] = get8(s);
 
3754
                                        }
 
3755
                                }
 
3756
                        }
 
3757
         for (i=0; i < width; ++i)
 
3758
            hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
 
3759
                }
 
3760
      free(scanline);
 
3761
        }
 
3762
 
 
3763
   return hdr_data;
 
3764
}
 
3765
 
 
3766
#ifndef STBI_NO_STDIO
 
3767
float *stbi_hdr_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
 
3768
{
 
3769
   stbi s;
 
3770
   start_file(&s,f);
 
3771
   return hdr_load(&s,x,y,comp,req_comp);
 
3772
}
 
3773
#endif
 
3774
 
 
3775
float *stbi_hdr_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
 
3776
{
 
3777
   stbi s;
 
3778
   start_mem(&s,buffer, len);
 
3779
   return hdr_load(&s,x,y,comp,req_comp);
 
3780
}
 
3781
 
 
3782
#endif // STBI_NO_HDR
 
3783
 
 
3784
/////////////////////// write image ///////////////////////
 
3785
 
 
3786
#ifndef STBI_NO_WRITE
 
3787
 
 
3788
static void write8(FILE *f, int x) { uint8 z = (uint8) x; fwrite(&z,1,1,f); }
 
3789
 
 
3790
static void writefv(FILE *f, char *fmt, va_list v)
 
3791
{
 
3792
   while (*fmt) {
 
3793
      switch (*fmt++) {
 
3794
         case ' ': break;
 
3795
         case '1': { uint8 x = va_arg(v, int); write8(f,x); break; }
 
3796
         case '2': { int16 x = va_arg(v, int); write8(f,x); write8(f,x>>8); break; }
 
3797
         case '4': { int32 x = va_arg(v, int); write8(f,x); write8(f,x>>8); write8(f,x>>16); write8(f,x>>24); break; }
 
3798
         default:
 
3799
            assert(0);
 
3800
            va_end(v);
 
3801
            return;
 
3802
      }
 
3803
   }
 
3804
}
 
3805
 
 
3806
static void writef(FILE *f, char *fmt, ...)
 
3807
{
 
3808
   va_list v;
 
3809
   va_start(v, fmt);
 
3810
   writefv(f,fmt,v);
 
3811
   va_end(v);
 
3812
}
 
3813
 
 
3814
static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad)
 
3815
{
 
3816
   uint8 bg[3] = { 255, 0, 255}, px[3];
 
3817
   uint32 zero = 0;
 
3818
   int i,j,k, j_end;
 
3819
 
 
3820
   if (vdir < 0) 
 
3821
      j_end = -1, j = y-1;
 
3822
   else
 
3823
      j_end =  y, j = 0;
 
3824
 
 
3825
   for (; j != j_end; j += vdir) {
 
3826
      for (i=0; i < x; ++i) {
 
3827
         uint8 *d = (uint8 *) data + (j*x+i)*comp;
 
3828
         if (write_alpha < 0)
 
3829
            fwrite(&d[comp-1], 1, 1, f);
 
3830
         switch (comp) {
 
3831
            case 1:
 
3832
            case 2: writef(f, "111", d[0],d[0],d[0]);
 
3833
                    break;
 
3834
            case 4:
 
3835
               if (!write_alpha) {
 
3836
                  for (k=0; k < 3; ++k)
 
3837
                     px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;
 
3838
                  writef(f, "111", px[1-rgb_dir],px[1],px[1+rgb_dir]);
 
3839
                  break;
 
3840
               }
 
3841
               /* FALLTHROUGH */
 
3842
            case 3:
 
3843
               writef(f, "111", d[1-rgb_dir],d[1],d[1+rgb_dir]);
 
3844
               break;
 
3845
         }
 
3846
         if (write_alpha > 0)
 
3847
            fwrite(&d[comp-1], 1, 1, f);
 
3848
      }
 
3849
      fwrite(&zero,scanline_pad,1,f);
 
3850
   }
 
3851
}
 
3852
 
 
3853
static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, char *fmt, ...)
 
3854
{
 
3855
   FILE *f = fopen(filename, "wb");
 
3856
   if (f) {
 
3857
      va_list v;
 
3858
      va_start(v, fmt);
 
3859
      writefv(f, fmt, v);
 
3860
      va_end(v);
 
3861
      write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);
 
3862
      fclose(f);
 
3863
   }
 
3864
   return f != NULL;
 
3865
}
 
3866
 
 
3867
int stbi_write_bmp(char const *filename, int x, int y, int comp, void *data)
 
3868
{
 
3869
   int pad = (-x*3) & 3;
 
3870
   return outfile(filename,-1,-1,x,y,comp,data,0,pad,
 
3871
           "11 4 22 4" "4 44 22 444444",
 
3872
           'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40,  // file header
 
3873
            40, x,y, 1,24, 0,0,0,0,0,0);             // bitmap header
 
3874
}
 
3875
 
 
3876
int stbi_write_tga(char const *filename, int x, int y, int comp, void *data)
 
3877
{
 
3878
   int has_alpha = !(comp & 1);
 
3879
   return outfile(filename, -1,-1, x, y, comp, data, has_alpha, 0,
 
3880
                  "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);
 
3881
}
 
3882
 
 
3883
// any other image formats that do interleaved rgb data?
 
3884
//    PNG: requires adler32,crc32 -- significant amount of code
 
3885
//    PSD: no, channels output separately
 
3886
//    TIFF: no, stripwise-interleaved... i think
 
3887
 
 
3888
#endif // STBI_NO_WRITE
 
3889
 
 
3890
#endif // STBI_HEADER_FILE_ONLY
 
3891