~ubuntu-branches/ubuntu/precise/clutter-1.0/precise

« back to all changes in this revision

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