stb_image.c
author Ryan C. Gordon <icculus@icculus.org>
Thu, 18 Jun 2015 12:18:57 -0400
changeset 879 c2afc800b743
parent 830 7987cf8de5df
permissions -rw-r--r--
Assorted spelling fixes (thanks, Francois!).
icculus@371
     1
// (Changes to this code are wrapped in __MOJOSETUP__ sections.  --ryan.)
icculus@371
     2
// (Changes to JUST THIS FILE are also public domain. The rest of MojoSetup
icculus@371
     3
//  falls under different licensing terms. --ryan.)
icculus@371
     4
#if !__MOJOSETUP__
icculus@371
     5
#error This file is probably miscompiled.
icculus@371
     6
#endif
icculus@371
     7
icculus@370
     8
/* stbi-1.08 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
icculus@370
     9
                      when you control the images you're loading
icculus@370
    10
icculus@370
    11
   QUICK NOTES:
icculus@370
    12
      Primarily of interest to game developers and other people who can
icculus@370
    13
          avoid problematic images and only need the trivial interface
icculus@370
    14
icculus@370
    15
      JPEG baseline (no JPEG progressive, no oddball channel decimations)
icculus@370
    16
      PNG non-interlaced
icculus@370
    17
      BMP non-1bpp, non-RLE
icculus@370
    18
      TGA (not sure what subset, if a subset)
icculus@370
    19
      PSD (composite view only, no extra channels)
icculus@370
    20
      HDR (radiance rgbE format)
icculus@370
    21
      writes BMP,TGA (define STBI_NO_WRITE to remove code)
icculus@370
    22
      decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)
icculus@370
    23
        
icculus@370
    24
   TODO:
icculus@370
    25
      stbi_info_*
icculus@370
    26
  
icculus@370
    27
   history:
icculus@370
    28
      1.08   Thatcher Ulrich's PSD code integrated by Nicolas Schulz
icculus@370
    29
      1.07   attempt to fix C++ warning/errors again
icculus@370
    30
      1.06   attempt to fix C++ warning/errors again
icculus@370
    31
      1.05   fix TGA loading to return correct *comp and use good luminance calc
icculus@370
    32
      1.04   default float alpha is 1, not 255; use 'void *' for stbi_image_free
icculus@370
    33
      1.03   bugfixes to STBI_NO_STDIO, STBI_NO_HDR
icculus@370
    34
      1.02   support for (subset of) HDR files, float interface for preferred access to them
icculus@370
    35
      1.01   fix bug: possible bug in handling right-side up bmps... not sure
icculus@370
    36
             fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all
icculus@370
    37
      1.00   interface to zlib that skips zlib header
icculus@370
    38
      0.99   correct handling of alpha in palette
icculus@370
    39
      0.98   TGA loader by lonesock; dynamically add loaders (untested)
icculus@370
    40
      0.97   jpeg errors on too large a file; also catch another malloc failure
icculus@370
    41
      0.96   fix detection of invalid v value - particleman@mollyrocket forum
icculus@370
    42
      0.95   during header scan, seek to markers in case of padding
icculus@370
    43
      0.94   STBI_NO_STDIO to disable stdio usage; rename all #defines the same
icculus@370
    44
      0.93   handle jpegtran output; verbose errors
icculus@370
    45
      0.92   read 4,8,16,24,32-bit BMP files of several formats
icculus@370
    46
      0.91   output 24-bit Windows 3.0 BMP files
icculus@370
    47
      0.90   fix a few more warnings; bump version number to approach 1.0
icculus@370
    48
      0.61   bugfixes due to Marc LeBlanc, Christopher Lloyd
icculus@370
    49
      0.60   fix compiling as c++
icculus@370
    50
      0.59   fix warnings: merge Dave Moore's -Wall fixes
icculus@370
    51
      0.58   fix bug: zlib uncompressed mode len/nlen was wrong endian
icculus@370
    52
      0.57   fix bug: jpg last huffman symbol before marker was >9 bits but less
icculus@370
    53
                      than 16 available
icculus@370
    54
      0.56   fix bug: zlib uncompressed mode len vs. nlen
icculus@370
    55
      0.55   fix bug: restart_interval not initialized to 0
icculus@370
    56
      0.54   allow NULL for 'int *comp'
icculus@370
    57
      0.53   fix bug in png 3->4; speedup png decoding
icculus@370
    58
      0.52   png handles req_comp=3,4 directly; minor cleanup; jpeg comments
icculus@370
    59
      0.51   obey req_comp requests, 1-component jpegs return as 1-component,
icculus@370
    60
             on 'test' only check type, not whether we support this variant
icculus@370
    61
*/
icculus@370
    62
icculus@371
    63
#if __MOJOSETUP__
icculus@371
    64
#  include "universal.h"  // catches xmalloc() defines, etc.
icculus@371
    65
#  undef malloc
icculus@371
    66
#  define malloc(x) xmalloc(x)
icculus@371
    67
#  undef realloc
icculus@371
    68
#  define realloc(x, y) xrealloc(x, y)
icculus@371
    69
icculus@371
    70
#  define STBI_NO_WRITE 1
icculus@371
    71
#  define STBI_NO_STDIO 1
icculus@371
    72
#  define STBI_NO_FAILURE_STRINGS 1
icculus@373
    73
#  if !SUPPORT_HDR
icculus@371
    74
#    define STBI_NO_HDR 1
icculus@371
    75
#  endif
icculus@373
    76
#  if !SUPPORT_TGA
icculus@371
    77
#    define STBI_NO_TGA 1
icculus@371
    78
#  endif
icculus@373
    79
#  if !SUPPORT_JPG
icculus@371
    80
#    define STBI_NO_JPEG 1
icculus@371
    81
#  endif
icculus@373
    82
#  if !SUPPORT_BMP
icculus@371
    83
#    define STBI_NO_BMP 1
icculus@371
    84
#  endif
icculus@373
    85
#  if !SUPPORT_PSD
icculus@371
    86
#    define STBI_NO_PSD 1
icculus@371
    87
#  endif
icculus@373
    88
#  if !SUPPORT_PNG
icculus@371
    89
#    define STBI_NO_PNG 1
icculus@371
    90
#    define STBI_NO_ZLIB 1
icculus@371
    91
#  endif
icculus@371
    92
#endif
icculus@370
    93
icculus@370
    94
////   begin header file  ////////////////////////////////////////////////////
icculus@370
    95
//
icculus@370
    96
// Limitations:
icculus@370
    97
//    - no progressive/interlaced support (jpeg, png)
icculus@370
    98
//    - 8-bit samples only (jpeg, png)
icculus@370
    99
//    - not threadsafe
icculus@370
   100
//    - channel subsampling of at most 2 in each dimension (jpeg)
icculus@370
   101
//    - no delayed line count (jpeg) -- IJG doesn't support either
icculus@370
   102
//
icculus@370
   103
// Basic usage (see HDR discussion below):
icculus@370
   104
//    int x,y,n;
icculus@370
   105
//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
icculus@370
   106
//    // ... process data if not NULL ... 
icculus@370
   107
//    // ... x = width, y = height, n = # 8-bit components per pixel ...
icculus@370
   108
//    // ... replace '0' with '1'..'4' to force that many components per pixel
icculus@370
   109
//    stbi_image_free(data)
icculus@370
   110
//
icculus@370
   111
// Standard parameters:
icculus@370
   112
//    int *x       -- outputs image width in pixels
icculus@370
   113
//    int *y       -- outputs image height in pixels
icculus@370
   114
//    int *comp    -- outputs # of image components in image file
icculus@370
   115
//    int req_comp -- if non-zero, # of image components requested in result
icculus@370
   116
//
icculus@370
   117
// The return value from an image loader is an 'unsigned char *' which points
icculus@370
   118
// to the pixel data. The pixel data consists of *y scanlines of *x pixels,
icculus@370
   119
// with each pixel consisting of N interleaved 8-bit components; the first
icculus@370
   120
// pixel pointed to is top-left-most in the image. There is no padding between
icculus@370
   121
// image scanlines or between pixels, regardless of format. The number of
icculus@370
   122
// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
icculus@370
   123
// If req_comp is non-zero, *comp has the number of components that _would_
icculus@370
   124
// have been output otherwise. E.g. if you set req_comp to 4, you will always
icculus@370
   125
// get RGBA output, but you can check *comp to easily see if it's opaque.
icculus@370
   126
//
icculus@370
   127
// An output image with N components has the following components interleaved
icculus@370
   128
// in this order in each pixel:
icculus@370
   129
//
icculus@370
   130
//     N=#comp     components
icculus@370
   131
//       1           grey
icculus@370
   132
//       2           grey, alpha
icculus@370
   133
//       3           red, green, blue
icculus@370
   134
//       4           red, green, blue, alpha
icculus@370
   135
//
icculus@370
   136
// If image loading fails for any reason, the return value will be NULL,
icculus@370
   137
// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
icculus@370
   138
// can be queried for an extremely brief, end-user unfriendly explanation
icculus@370
   139
// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
icculus@370
   140
// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
icculus@370
   141
// more user-friendly ones.
icculus@370
   142
//
icculus@370
   143
// Paletted PNG and BMP images are automatically depalettized.
icculus@370
   144
//
icculus@370
   145
//
icculus@370
   146
// ===========================================================================
icculus@370
   147
//
icculus@370
   148
// HDR image support   (disable by defining STBI_NO_HDR)
icculus@370
   149
//
icculus@370
   150
// stb_image now supports loading HDR images in general, and currently
icculus@370
   151
// the Radiance .HDR file format, although the support is provided
icculus@370
   152
// generically. You can still load any file through the existing interface;
icculus@370
   153
// if you attempt to load an HDR file, it will be automatically remapped to
icculus@370
   154
// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
icculus@370
   155
// both of these constants can be reconfigured through this interface:
icculus@370
   156
//
icculus@370
   157
//     stbi_hdr_to_ldr_gamma(2.2f);
icculus@370
   158
//     stbi_hdr_to_ldr_scale(1.0f);
icculus@370
   159
//
icculus@370
   160
// (note, do not use _inverse_ constants; stbi_image will invert them
icculus@370
   161
// appropriately).
icculus@370
   162
//
icculus@370
   163
// Additionally, there is a new, parallel interface for loading files as
icculus@370
   164
// (linear) floats to preserve the full dynamic range:
icculus@370
   165
//
icculus@370
   166
//    float *data = stbi_loadf(filename, &x, &y, &n, 0);
icculus@370
   167
// 
icculus@370
   168
// If you load LDR images through this interface, those images will
icculus@370
   169
// be promoted to floating point values, run through the inverse of
icculus@370
   170
// constants corresponding to the above:
icculus@370
   171
//
icculus@370
   172
//     stbi_ldr_to_hdr_scale(1.0f);
icculus@370
   173
//     stbi_ldr_to_hdr_gamma(2.2f);
icculus@370
   174
//
icculus@370
   175
// Finally, given a filename (or an open file or memory block--see header
icculus@370
   176
// file for details) containing image data, you can query for the "most
icculus@370
   177
// appropriate" interface to use (that is, whether the image is HDR or
icculus@370
   178
// not), using:
icculus@370
   179
//
icculus@370
   180
//     stbi_is_hdr(char *filename);
icculus@370
   181
icculus@370
   182
icculus@370
   183
#ifndef STBI_NO_STDIO
icculus@370
   184
#include <stdio.h>
icculus@370
   185
#endif
icculus@370
   186
icculus@370
   187
#ifndef STBI_NO_HDR
icculus@370
   188
#include <math.h>  // ldexp
icculus@370
   189
#include <string.h> // strcmp
icculus@370
   190
#endif
icculus@370
   191
icculus@370
   192
enum
icculus@370
   193
{
icculus@370
   194
   STBI_default = 0, // only used for req_comp
icculus@370
   195
icculus@370
   196
   STBI_grey       = 1,
icculus@370
   197
   STBI_grey_alpha = 2,
icculus@370
   198
   STBI_rgb        = 3,
icculus@370
   199
   STBI_rgb_alpha  = 4,
icculus@370
   200
};
icculus@370
   201
icculus@370
   202
typedef unsigned char stbi_uc;
icculus@370
   203
icculus@370
   204
#ifdef __cplusplus
icculus@370
   205
extern "C" {
icculus@370
   206
#endif
icculus@370
   207
icculus@370
   208
// WRITING API
icculus@370
   209
icculus@370
   210
#if !defined(STBI_NO_WRITE) && !defined(STBI_NO_STDIO)
icculus@370
   211
// write a BMP/TGA file given tightly packed 'comp' channels (no padding, nor bmp-stride-padding)
icculus@370
   212
// (you must include the appropriate extension in the filename).
icculus@370
   213
// returns TRUE on success, FALSE if couldn't open file, error writing file
icculus@370
   214
extern int      stbi_write_bmp       (char *filename,           int x, int y, int comp, void *data);
icculus@370
   215
extern int      stbi_write_tga       (char *filename,           int x, int y, int comp, void *data);
icculus@370
   216
#endif
icculus@370
   217
icculus@370
   218
// PRIMARY API - works on images of any type
icculus@370
   219
icculus@370
   220
// load image by filename, open file, or memory buffer
icculus@370
   221
#ifndef STBI_NO_STDIO
icculus@370
   222
extern stbi_uc *stbi_load            (char *filename,           int *x, int *y, int *comp, int req_comp);
icculus@370
   223
extern stbi_uc *stbi_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);
icculus@370
   224
extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
icculus@370
   225
#endif
icculus@370
   226
extern stbi_uc *stbi_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   227
// for stbi_load_from_file, file pointer is left pointing immediately after image
icculus@370
   228
icculus@370
   229
#ifndef STBI_NO_HDR
icculus@370
   230
#ifndef STBI_NO_STDIO
icculus@370
   231
extern float *stbi_loadf            (char *filename,           int *x, int *y, int *comp, int req_comp);
icculus@370
   232
extern float *stbi_loadf_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);
icculus@370
   233
#endif
icculus@370
   234
extern float *stbi_loadf_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   235
icculus@370
   236
extern void   stbi_hdr_to_ldr_gamma(float gamma);
icculus@370
   237
extern void   stbi_hdr_to_ldr_scale(float scale);
icculus@370
   238
icculus@370
   239
extern void   stbi_ldr_to_hdr_gamma(float gamma);
icculus@370
   240
extern void   stbi_ldr_to_hdr_scale(float scale);
icculus@370
   241
icculus@370
   242
#endif // STBI_NO_HDR
icculus@370
   243
icculus@370
   244
// get a VERY brief reason for failure
icculus@370
   245
extern char    *stbi_failure_reason  (void);
icculus@370
   246
icculus@370
   247
// free the loaded image -- this is just free()
icculus@370
   248
extern void     stbi_image_free      (void *retval_from_stbi_load);
icculus@370
   249
icculus@370
   250
// get image dimensions & components without fully decoding
icculus@370
   251
extern int      stbi_info_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp);
icculus@370
   252
extern int      stbi_is_hdr_from_memory(stbi_uc *buffer, int len);
icculus@370
   253
#ifndef STBI_NO_STDIO
icculus@370
   254
extern int      stbi_info            (char *filename,           int *x, int *y, int *comp);
icculus@370
   255
extern int      stbi_is_hdr          (char *filename);
icculus@370
   256
extern int      stbi_is_hdr_from_file(FILE *f);
icculus@370
   257
#endif
icculus@370
   258
icculus@370
   259
// ZLIB client - used by PNG, available for other purposes
icculus@370
   260
icculus@370
   261
extern char *stbi_zlib_decode_malloc_guesssize(int initial_size, int *outlen);
icculus@370
   262
extern char *stbi_zlib_decode_malloc(char *buffer, int len, int *outlen);
icculus@370
   263
extern int   stbi_zlib_decode_buffer(char *obuffer, int olen, char *ibuffer, int ilen);
icculus@370
   264
icculus@370
   265
extern char *stbi_zlib_decode_noheader_malloc(char *buffer, int len, int *outlen);
icculus@370
   266
extern int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, char *ibuffer, int ilen);
icculus@370
   267
icculus@370
   268
icculus@370
   269
// TYPE-SPECIFIC ACCESS
icculus@370
   270
icculus@370
   271
// is it a jpeg?
icculus@370
   272
extern int      stbi_jpeg_test_memory     (stbi_uc *buffer, int len);
icculus@370
   273
extern stbi_uc *stbi_jpeg_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   274
extern int      stbi_jpeg_info_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp);
icculus@370
   275
icculus@370
   276
#ifndef STBI_NO_STDIO
icculus@370
   277
extern stbi_uc *stbi_jpeg_load            (char *filename,           int *x, int *y, int *comp, int req_comp);
icculus@370
   278
extern int      stbi_jpeg_test_file       (FILE *f);
icculus@370
   279
extern stbi_uc *stbi_jpeg_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);
icculus@370
   280
icculus@370
   281
extern int      stbi_jpeg_info            (char *filename,           int *x, int *y, int *comp);
icculus@370
   282
extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
icculus@370
   283
#endif
icculus@370
   284
icculus@370
   285
extern int      stbi_jpeg_dc_only; // only decode DC component
icculus@370
   286
icculus@370
   287
// is it a png?
icculus@370
   288
extern int      stbi_png_test_memory      (stbi_uc *buffer, int len);
icculus@370
   289
extern stbi_uc *stbi_png_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   290
extern int      stbi_png_info_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp);
icculus@370
   291
icculus@370
   292
#ifndef STBI_NO_STDIO
icculus@370
   293
extern stbi_uc *stbi_png_load             (char *filename,           int *x, int *y, int *comp, int req_comp);
icculus@370
   294
extern int      stbi_png_info             (char *filename,           int *x, int *y, int *comp);
icculus@370
   295
extern int      stbi_png_test_file        (FILE *f);
icculus@370
   296
extern stbi_uc *stbi_png_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
icculus@370
   297
extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);
icculus@370
   298
#endif
icculus@370
   299
icculus@370
   300
// is it a bmp?
icculus@370
   301
extern int      stbi_bmp_test_memory      (stbi_uc *buffer, int len);
icculus@370
   302
icculus@370
   303
extern stbi_uc *stbi_bmp_load             (char *filename,           int *x, int *y, int *comp, int req_comp);
icculus@370
   304
extern stbi_uc *stbi_bmp_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   305
#ifndef STBI_NO_STDIO
icculus@370
   306
extern int      stbi_bmp_test_file        (FILE *f);
icculus@370
   307
extern stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
icculus@370
   308
#endif
icculus@370
   309
icculus@370
   310
// is it a tga?
icculus@370
   311
extern int      stbi_tga_test_memory      (stbi_uc *buffer, int len);
icculus@370
   312
icculus@370
   313
extern stbi_uc *stbi_tga_load             (char *filename,           int *x, int *y, int *comp, int req_comp);
icculus@370
   314
extern stbi_uc *stbi_tga_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   315
#ifndef STBI_NO_STDIO
icculus@370
   316
extern int      stbi_tga_test_file        (FILE *f);
icculus@370
   317
extern stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
icculus@370
   318
#endif
icculus@370
   319
icculus@370
   320
// is it a psd?
icculus@370
   321
extern int      stbi_psd_test_memory      (stbi_uc *buffer, int len);
icculus@370
   322
icculus@370
   323
extern stbi_uc *stbi_psd_load             (char *filename,           int *x, int *y, int *comp, int req_comp);
icculus@370
   324
extern stbi_uc *stbi_psd_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   325
#ifndef STBI_NO_STDIO
icculus@370
   326
extern int      stbi_psd_test_file        (FILE *f);
icculus@370
   327
extern stbi_uc *stbi_psd_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
icculus@370
   328
#endif
icculus@370
   329
icculus@370
   330
// is it an hdr?
icculus@370
   331
extern int      stbi_hdr_test_memory      (stbi_uc *buffer, int len);
icculus@370
   332
icculus@370
   333
extern float *  stbi_hdr_load             (char *filename,           int *x, int *y, int *comp, int req_comp);
icculus@370
   334
extern float *  stbi_hdr_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   335
#ifndef STBI_NO_STDIO
icculus@370
   336
extern int      stbi_hdr_test_file        (FILE *f);
icculus@370
   337
extern float *  stbi_hdr_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);
icculus@370
   338
#endif
icculus@370
   339
icculus@370
   340
// define new loaders
icculus@370
   341
typedef struct
icculus@370
   342
{
icculus@370
   343
   int       (*test_memory)(stbi_uc *buffer, int len);
icculus@370
   344
   stbi_uc * (*load_from_memory)(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);
icculus@370
   345
   #ifndef STBI_NO_STDIO
icculus@370
   346
   int       (*test_file)(FILE *f);
icculus@370
   347
   stbi_uc * (*load_from_file)(FILE *f, int *x, int *y, int *comp, int req_comp);
icculus@370
   348
   #endif
icculus@370
   349
} stbi_loader;
icculus@370
   350
icculus@370
   351
// register a loader by filling out the above structure (you must defined ALL functions)
icculus@370
   352
// returns 1 if added or already added, 0 if not added (too many loaders)
icculus@370
   353
extern int stbi_register_loader(stbi_loader *loader);
icculus@370
   354
icculus@370
   355
#ifdef __cplusplus
icculus@370
   356
}
icculus@370
   357
#endif
icculus@370
   358
icculus@370
   359
//
icculus@370
   360
//
icculus@370
   361
////   end header file   /////////////////////////////////////////////////////
icculus@370
   362
icculus@370
   363
#ifndef STBI_NO_STDIO
icculus@370
   364
#include <stdio.h>
icculus@370
   365
#endif
icculus@370
   366
#include <stdlib.h>
icculus@370
   367
#include <memory.h>
icculus@370
   368
#include <assert.h>
icculus@370
   369
#include <stdarg.h>
icculus@370
   370
icculus@370
   371
#ifndef _MSC_VER
icculus@370
   372
#define __forceinline
icculus@370
   373
#endif
icculus@370
   374
icculus@370
   375
// implementation:
icculus@371
   376
#if !__MOJOSETUP__  // (we define these in universal.h ...)
icculus@370
   377
typedef unsigned char uint8;
icculus@370
   378
typedef unsigned short uint16;
icculus@370
   379
typedef   signed short  int16;
icculus@370
   380
typedef unsigned int   uint32;
icculus@370
   381
typedef   signed int    int32;
icculus@370
   382
typedef unsigned int   uint;
icculus@371
   383
#endif
icculus@370
   384
icculus@370
   385
// should produce compiler error if size is wrong
icculus@370
   386
typedef unsigned char validate_uint32[sizeof(uint32)==4];
icculus@370
   387
icculus@370
   388
#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
icculus@370
   389
#define STBI_NO_WRITE
icculus@370
   390
#endif
icculus@370
   391
icculus@370
   392
//////////////////////////////////////////////////////////////////////////////
icculus@370
   393
//
icculus@370
   394
// Generic API that works on all image types
icculus@370
   395
//
icculus@370
   396
icculus@370
   397
static char *failure_reason;
icculus@370
   398
icculus@370
   399
char *stbi_failure_reason(void)
icculus@370
   400
{
icculus@370
   401
   return failure_reason;
icculus@370
   402
}
icculus@370
   403
icculus@371
   404
#if __MOJOSETUP__ && !defined(STBI_NO_FAILURE_STRINGS)
icculus@370
   405
static int e(char *str)
icculus@370
   406
{
icculus@370
   407
   failure_reason = str;
icculus@370
   408
   return 0;
icculus@370
   409
}
icculus@371
   410
#endif // __MOJOSETUP__
icculus@370
   411
icculus@370
   412
#ifdef STBI_NO_FAILURE_STRINGS
icculus@370
   413
   #define e(x,y)  0
icculus@370
   414
#elif defined(STBI_FAILURE_USERMSG)
icculus@370
   415
   #define e(x,y)  e(y)
icculus@370
   416
#else
icculus@370
   417
   #define e(x,y)  e(x)
icculus@370
   418
#endif
icculus@370
   419
icculus@370
   420
#define epf(x,y)   ((float *) (e(x,y)?NULL:NULL))
icculus@370
   421
#define epuc(x,y)  ((unsigned char *) (e(x,y)?NULL:NULL))
icculus@370
   422
icculus@370
   423
void stbi_image_free(void *retval_from_stbi_load)
icculus@370
   424
{
icculus@370
   425
   free(retval_from_stbi_load);
icculus@370
   426
}
icculus@370
   427
icculus@370
   428
#define MAX_LOADERS  32
icculus@370
   429
stbi_loader *loaders[MAX_LOADERS];
icculus@370
   430
static int max_loaders = 0;
icculus@370
   431
icculus@370
   432
int stbi_register_loader(stbi_loader *loader)
icculus@370
   433
{
icculus@370
   434
   int i;
icculus@370
   435
   for (i=0; i < MAX_LOADERS; ++i) {
icculus@370
   436
      // already present?
icculus@370
   437
      if (loaders[i] == loader)
icculus@370
   438
         return 1;
icculus@370
   439
      // end of the list?
icculus@370
   440
      if (loaders[i] == NULL) {
icculus@370
   441
         loaders[i] = loader;
icculus@370
   442
         max_loaders = i+1;
icculus@370
   443
         return 1;
icculus@370
   444
      }
icculus@370
   445
   }
icculus@370
   446
   // no room for it
icculus@370
   447
   return 0;
icculus@370
   448
}
icculus@370
   449
icculus@370
   450
#ifndef STBI_NO_HDR
icculus@370
   451
static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
icculus@370
   452
static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp);
icculus@370
   453
#endif
icculus@370
   454
icculus@370
   455
#ifndef STBI_NO_STDIO
icculus@370
   456
unsigned char *stbi_load(char *filename, int *x, int *y, int *comp, int req_comp)
icculus@370
   457
{
icculus@370
   458
   FILE *f = fopen(filename, "rb");
icculus@370
   459
   unsigned char *result;
icculus@370
   460
   if (!f) return epuc("can't fopen", "Unable to open file");
icculus@370
   461
   result = stbi_load_from_file(f,x,y,comp,req_comp);
icculus@370
   462
   fclose(f);
icculus@370
   463
   return result;
icculus@370
   464
}
icculus@370
   465
icculus@370
   466
unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
icculus@370
   467
{
icculus@370
   468
   int i;
icculus@371
   469
icculus@371
   470
   #ifndef STBI_NO_JPEG  // __MOJOSETUP__
icculus@370
   471
   if (stbi_jpeg_test_file(f))
icculus@370
   472
      return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);
icculus@371
   473
   #endif  // __MOJOSETUP__
icculus@371
   474
icculus@371
   475
   #ifndef STBI_NO_PNG  // __MOJOSETUP__
icculus@370
   476
   if (stbi_png_test_file(f))
icculus@370
   477
      return stbi_png_load_from_file(f,x,y,comp,req_comp);
icculus@371
   478
   #endif  // __MOJOSETUP__
icculus@371
   479
icculus@371
   480
   #ifndef STBI_NO_BMP  // __MOJOSETUP__
icculus@370
   481
   if (stbi_bmp_test_file(f))
icculus@370
   482
      return stbi_bmp_load_from_file(f,x,y,comp,req_comp);
icculus@371
   483
   #endif  // __MOJOSETUP__
icculus@371
   484
icculus@371
   485
   #ifndef STBI_NO_PSD  // __MOJOSETUP__
icculus@370
   486
   if (stbi_psd_test_file(f))
icculus@370
   487
      return stbi_psd_load_from_file(f,x,y,comp,req_comp);
icculus@371
   488
   #endif // __MOJOSETUP__
icculus@371
   489
icculus@370
   490
   #ifndef STBI_NO_HDR
icculus@370
   491
   if (stbi_hdr_test_file(f)) {
icculus@370
   492
      float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp);
icculus@370
   493
      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
icculus@370
   494
   }
icculus@370
   495
   #endif
icculus@371
   496
icculus@370
   497
   for (i=0; i < max_loaders; ++i)
icculus@370
   498
      if (loaders[i]->test_file(f))
icculus@370
   499
         return loaders[i]->load_from_file(f,x,y,comp,req_comp);
icculus@371
   500
icculus@371
   501
   #ifndef STBI_NO_TGA  // __MOJOSETUP__
icculus@370
   502
   // test tga last because it's a crappy test!
icculus@370
   503
   if (stbi_tga_test_file(f))
icculus@370
   504
      return stbi_tga_load_from_file(f,x,y,comp,req_comp);
icculus@371
   505
   #endif  // __MOJOSETUP__
icculus@371
   506
icculus@370
   507
   return epuc("unknown image type", "Image not of any known type, or corrupt");
icculus@370
   508
}
icculus@370
   509
#endif
icculus@370
   510
icculus@370
   511
unsigned char *stbi_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)
icculus@370
   512
{
icculus@370
   513
   int i;
icculus@371
   514
icculus@371
   515
   #ifndef STBI_NO_JPEG  // __MOJOSETUP__
icculus@370
   516
   if (stbi_jpeg_test_memory(buffer,len))
icculus@370
   517
      return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);
icculus@371
   518
   #endif  // __MOJOSETUP__
icculus@371
   519
icculus@371
   520
   #ifndef STBI_NO_PNG  // __MOJOSETUP__
icculus@370
   521
   if (stbi_png_test_memory(buffer,len))
icculus@370
   522
      return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);
icculus@371
   523
   #endif  // __MOJOSETUP__
icculus@371
   524
icculus@371
   525
   #ifndef STBI_NO_BMP  // __MOJOSETUP__
icculus@370
   526
   if (stbi_bmp_test_memory(buffer,len))
icculus@370
   527
      return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);
icculus@371
   528
   #endif  // __MOJOSETUP__
icculus@371
   529
icculus@371
   530
   #ifndef STBI_NO_PSD  // __MOJOSETUP__
icculus@370
   531
   if (stbi_psd_test_memory(buffer,len))
icculus@370
   532
      return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);
icculus@371
   533
   #endif  // __MOJOSETUP__
icculus@371
   534
icculus@370
   535
   #ifndef STBI_NO_HDR
icculus@370
   536
   if (stbi_hdr_test_memory(buffer, len)) {
icculus@370
   537
      float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
icculus@370
   538
      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
icculus@370
   539
   }
icculus@370
   540
   #endif
icculus@371
   541
icculus@370
   542
   for (i=0; i < max_loaders; ++i)
icculus@370
   543
      if (loaders[i]->test_memory(buffer,len))
icculus@370
   544
         return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp);
icculus@371
   545
icculus@371
   546
   #ifndef STBI_NO_TGA  // __MOJOSETUP__
icculus@370
   547
   // test tga last because it's a crappy test!
icculus@370
   548
   if (stbi_tga_test_memory(buffer,len))
icculus@370
   549
      return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp);
icculus@371
   550
   #endif  // __MOJOSETUP__
icculus@371
   551
icculus@370
   552
   return epuc("unknown image type", "Image not of any known type, or corrupt");
icculus@370
   553
}
icculus@370
   554
icculus@370
   555
#ifndef STBI_NO_HDR
icculus@370
   556
icculus@370
   557
#ifndef STBI_NO_STDIO
icculus@370
   558
float *stbi_loadf(char *filename, int *x, int *y, int *comp, int req_comp)
icculus@370
   559
{
icculus@370
   560
   FILE *f = fopen(filename, "rb");
icculus@370
   561
   float *result;
icculus@370
   562
   if (!f) return epf("can't fopen", "Unable to open file");
icculus@370
   563
   result = stbi_loadf_from_file(f,x,y,comp,req_comp);
icculus@370
   564
   fclose(f);
icculus@370
   565
   return result;
icculus@370
   566
}
icculus@370
   567
icculus@370
   568
float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
icculus@370
   569
{
icculus@370
   570
   unsigned char *data;
icculus@370
   571
   #ifndef STBI_NO_HDR
icculus@370
   572
   if (stbi_hdr_test_file(f))
icculus@370
   573
      return stbi_hdr_load_from_file(f,x,y,comp,req_comp);
icculus@370
   574
   #endif
icculus@370
   575
   data = stbi_load_from_file(f, x, y, comp, req_comp);
icculus@370
   576
   if (data)
icculus@370
   577
      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
icculus@370
   578
   return epf("unknown image type", "Image not of any known type, or corrupt");
icculus@370
   579
}
icculus@370
   580
#endif
icculus@370
   581
icculus@370
   582
float *stbi_loadf_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)
icculus@370
   583
{
icculus@370
   584
   stbi_uc *data;
icculus@370
   585
   #ifndef STBI_NO_HDR
icculus@370
   586
   if (stbi_hdr_test_memory(buffer, len))
icculus@370
   587
      return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
icculus@370
   588
   #endif
icculus@370
   589
   data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp);
icculus@370
   590
   if (data)
icculus@370
   591
      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
icculus@370
   592
   return epf("unknown image type", "Image not of any known type, or corrupt");
icculus@370
   593
}
icculus@370
   594
#endif
icculus@370
   595
icculus@370
   596
// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
icculus@370
   597
// defined, for API simplicity; if STBI_NO_HDR is defined, it always
icculus@370
   598
// reports false!
icculus@370
   599
icculus@370
   600
extern int      stbi_is_hdr_from_memory(stbi_uc *buffer, int len)
icculus@370
   601
{
icculus@370
   602
   #ifndef STBI_NO_HDR
icculus@370
   603
   return stbi_hdr_test_memory(buffer, len);
icculus@370
   604
   #else
icculus@370
   605
   return 0;
icculus@370
   606
   #endif
icculus@370
   607
}
icculus@370
   608
icculus@370
   609
#ifndef STBI_NO_STDIO
icculus@370
   610
extern int      stbi_is_hdr          (char *filename)
icculus@370
   611
{
icculus@370
   612
   FILE *f = fopen(filename, "rb");
icculus@370
   613
   int result=0;
icculus@370
   614
   if (f) {
icculus@370
   615
      result = stbi_is_hdr_from_file(f);
icculus@370
   616
      fclose(f);
icculus@370
   617
   }
icculus@370
   618
   return result;
icculus@370
   619
}
icculus@370
   620
icculus@370
   621
extern int      stbi_is_hdr_from_file(FILE *f)
icculus@370
   622
{
icculus@370
   623
   #ifndef STBI_NO_HDR
icculus@370
   624
   return stbi_hdr_test_file(f);
icculus@370
   625
   #else
icculus@370
   626
   return 0;
icculus@370
   627
   #endif
icculus@370
   628
}
icculus@370
   629
icculus@370
   630
#endif
icculus@370
   631
icculus@370
   632
// @TODO: get image dimensions & components without fully decoding
icculus@370
   633
#ifndef STBI_NO_STDIO
icculus@370
   634
extern int      stbi_info            (char *filename,           int *x, int *y, int *comp);
icculus@370
   635
extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
icculus@370
   636
#endif
icculus@370
   637
extern int      stbi_info_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp);
icculus@370
   638
icculus@370
   639
#ifndef STBI_NO_HDR
icculus@370
   640
static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
icculus@370
   641
static float l2h_gamma=2.2f, l2h_scale=1.0f;
icculus@370
   642
icculus@370
   643
void   stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
icculus@370
   644
void   stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
icculus@370
   645
icculus@370
   646
void   stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
icculus@370
   647
void   stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
icculus@370
   648
#endif
icculus@370
   649
icculus@370
   650
icculus@370
   651
//////////////////////////////////////////////////////////////////////////////
icculus@370
   652
//
icculus@370
   653
// Common code used by all image loaders
icculus@370
   654
//
icculus@370
   655
icculus@370
   656
// image width, height, # components
icculus@370
   657
static uint32 img_x, img_y;
icculus@370
   658
static int img_n, img_out_n;
icculus@370
   659
icculus@375
   660
#if __MOJOSETUP__  // moved here from elsewhere for #ifdef safety.
icculus@375
   661
static uint8 *idata, *expanded, *out;
icculus@380
   662
static uint32 code_buffer; // jpeg entropy-coded buffer
icculus@375
   663
#endif
icculus@375
   664
icculus@370
   665
enum
icculus@370
   666
{
icculus@370
   667
   SCAN_load=0,
icculus@370
   668
   SCAN_type,
icculus@370
   669
   SCAN_header,
icculus@370
   670
};
icculus@370
   671
icculus@370
   672
// An API for reading either from memory or file.
icculus@370
   673
#ifndef STBI_NO_STDIO
icculus@370
   674
static FILE  *img_file;
icculus@370
   675
#endif
icculus@370
   676
static uint8 *img_buffer, *img_buffer_end;
icculus@370
   677
icculus@370
   678
#ifndef STBI_NO_STDIO
icculus@370
   679
static void start_file(FILE *f)
icculus@370
   680
{
icculus@370
   681
   img_file = f;
icculus@370
   682
}
icculus@370
   683
#endif
icculus@370
   684
icculus@370
   685
static void start_mem(uint8 *buffer, int len)
icculus@370
   686
{
icculus@370
   687
#ifndef STBI_NO_STDIO
icculus@370
   688
   img_file = NULL;
icculus@370
   689
#endif
icculus@370
   690
   img_buffer = buffer;
icculus@370
   691
   img_buffer_end = buffer+len;
icculus@370
   692
}
icculus@370
   693
icculus@370
   694
static int get8(void)
icculus@370
   695
{
icculus@370
   696
#ifndef STBI_NO_STDIO
icculus@370
   697
   if (img_file) {
icculus@370
   698
      int c = fgetc(img_file);
icculus@370
   699
      return c == EOF ? 0 : c;
icculus@370
   700
   }
icculus@370
   701
#endif
icculus@370
   702
   if (img_buffer < img_buffer_end)
icculus@370
   703
      return *img_buffer++;
icculus@370
   704
   return 0;
icculus@370
   705
}
icculus@370
   706
icculus@370
   707
static int at_eof(void)
icculus@370
   708
{
icculus@370
   709
#ifndef STBI_NO_STDIO
icculus@370
   710
   if (img_file)
icculus@370
   711
      return feof(img_file);
icculus@370
   712
#endif
icculus@370
   713
   return img_buffer >= img_buffer_end;   
icculus@370
   714
}
icculus@370
   715
icculus@370
   716
static uint8 get8u(void)
icculus@370
   717
{
icculus@370
   718
   return (uint8) get8();
icculus@370
   719
}
icculus@370
   720
icculus@370
   721
static void skip(int n)
icculus@370
   722
{
icculus@370
   723
#ifndef STBI_NO_STDIO
icculus@370
   724
   if (img_file)
icculus@370
   725
      fseek(img_file, n, SEEK_CUR);
icculus@370
   726
   else
icculus@370
   727
#endif
icculus@370
   728
      img_buffer += n;
icculus@370
   729
}
icculus@370
   730
icculus@370
   731
static int get16(void)
icculus@370
   732
{
icculus@370
   733
   int z = get8();
icculus@370
   734
   return (z << 8) + get8();
icculus@370
   735
}
icculus@370
   736
icculus@370
   737
static uint32 get32(void)
icculus@370
   738
{
icculus@370
   739
   uint32 z = get16();
icculus@370
   740
   return (z << 16) + get16();
icculus@370
   741
}
icculus@370
   742
icculus@370
   743
static int get16le(void)
icculus@370
   744
{
icculus@370
   745
   int z = get8();
icculus@370
   746
   return z + (get8() << 8);
icculus@370
   747
}
icculus@370
   748
icculus@370
   749
static uint32 get32le(void)
icculus@370
   750
{
icculus@370
   751
   uint32 z = get16le();
icculus@370
   752
   return z + (get16le() << 16);
icculus@370
   753
}
icculus@370
   754
icculus@370
   755
static void getn(stbi_uc *buffer, int n)
icculus@370
   756
{
icculus@370
   757
#ifndef STBI_NO_STDIO
icculus@370
   758
   if (img_file) {
icculus@370
   759
      fread(buffer, 1, n, img_file);
icculus@370
   760
      return;
icculus@370
   761
   }
icculus@370
   762
#endif
icculus@370
   763
   memcpy(buffer, img_buffer, n);
icculus@370
   764
   img_buffer += n;
icculus@370
   765
}
icculus@370
   766
icculus@370
   767
//////////////////////////////////////////////////////////////////////////////
icculus@370
   768
//
icculus@370
   769
//  generic converter from built-in img_n to req_comp
icculus@370
   770
//    individual types do this automatically as much as possible (e.g. jpeg
icculus@370
   771
//    does all cases internally since it needs to colorspace convert anyway,
icculus@370
   772
//    and it never has alpha, so very few cases ). png can automatically
icculus@370
   773
//    interleave an alpha=255 channel, but falls back to this for other cases
icculus@370
   774
//
icculus@370
   775
//  assume data buffer is malloced, so malloc a new one and free that one
icculus@370
   776
//  only failure mode is malloc failing
icculus@370
   777
icculus@370
   778
static uint8 compute_y(int r, int g, int b)
icculus@370
   779
{
icculus@370
   780
   return (uint8) (((r*77) + (g*150) +  (29*b)) >> 8);
icculus@370
   781
}
icculus@370
   782
icculus@370
   783
static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp)
icculus@370
   784
{
icculus@422
   785
#if __MOJOSETUP__
icculus@422
   786
   //uint i,j;
icculus@422
   787
   uint32 i,j;
icculus@422
   788
#endif
icculus@370
   789
   unsigned char *good;
icculus@370
   790
icculus@370
   791
   if (req_comp == img_n) return data;
icculus@370
   792
   assert(req_comp >= 1 && req_comp <= 4);
icculus@370
   793
icculus@370
   794
   good = (unsigned char *) malloc(req_comp * img_x * img_y);
icculus@370
   795
   if (good == NULL) {
icculus@370
   796
      free(data);
icculus@370
   797
      return epuc("outofmem", "Out of memory");
icculus@370
   798
   }
icculus@370
   799
icculus@370
   800
   for (j=0; j < img_y; ++j) {
icculus@370
   801
      unsigned char *src  = data + j * img_x * img_n   ;
icculus@370
   802
      unsigned char *dest = good + j * img_x * req_comp;
icculus@370
   803
icculus@370
   804
      #define COMBO(a,b)  ((a)*8+(b))
icculus@370
   805
      #define CASE(a,b)   case COMBO(a,b): for(i=0; i < img_x; ++i, src += a, dest += b)
icculus@370
   806
icculus@370
   807
      // convert source image with img_n components to one with req_comp components;
icculus@370
   808
      // avoid switch per pixel, so use switch per scanline and massive macros
icculus@370
   809
      switch(COMBO(img_n, req_comp)) {
icculus@370
   810
         CASE(1,2) dest[0]=src[0], dest[1]=255; break;
icculus@370
   811
         CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
icculus@370
   812
         CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
icculus@370
   813
         CASE(2,1) dest[0]=src[0]; break;
icculus@370
   814
         CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
icculus@370
   815
         CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
icculus@370
   816
         CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
icculus@370
   817
         CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
icculus@370
   818
         CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
icculus@370
   819
         CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
icculus@370
   820
         CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
icculus@370
   821
         CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
icculus@370
   822
         default: assert(0);
icculus@370
   823
      }
icculus@370
   824
      #undef CASE
icculus@370
   825
   }
icculus@370
   826
icculus@370
   827
   free(data);
icculus@370
   828
   img_out_n = req_comp;
icculus@370
   829
   return good;
icculus@370
   830
}
icculus@370
   831
icculus@370
   832
#ifndef STBI_NO_HDR
icculus@370
   833
static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
icculus@370
   834
{
icculus@370
   835
   int i,k,n;
icculus@370
   836
   float *output = (float *) malloc(x * y * comp * sizeof(float));
icculus@370
   837
   if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }
icculus@370
   838
   // compute number of non-alpha components
icculus@370
   839
   if (comp & 1) n = comp; else n = comp-1;
icculus@370
   840
   for (i=0; i < x*y; ++i) {
icculus@370
   841
      for (k=0; k < n; ++k) {
icculus@370
   842
         output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
icculus@370
   843
      }
icculus@370
   844
      if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
icculus@370
   845
   }
icculus@370
   846
   free(data);
icculus@370
   847
   return output;
icculus@370
   848
}
icculus@370
   849
icculus@370
   850
#define float2int(x)   ((int) (x))
icculus@370
   851
static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp)
icculus@370
   852
{
icculus@370
   853
   int i,k,n;
icculus@370
   854
   stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
icculus@370
   855
   if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }
icculus@370
   856
   // compute number of non-alpha components
icculus@370
   857
   if (comp & 1) n = comp; else n = comp-1;
icculus@370
   858
   for (i=0; i < x*y; ++i) {
icculus@370
   859
      for (k=0; k < n; ++k) {
icculus@370
   860
         float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
icculus@370
   861
         if (z < 0) z = 0;
icculus@370
   862
         if (z > 255) z = 255;
icculus@370
   863
         output[i*comp + k] = float2int(z);
icculus@370
   864
      }
icculus@370
   865
      if (k < comp) {
icculus@370
   866
         float z = data[i*comp+k] * 255 + 0.5f;
icculus@370
   867
         if (z < 0) z = 0;
icculus@370
   868
         if (z > 255) z = 255;
icculus@370
   869
         output[i*comp + k] = float2int(z);
icculus@370
   870
      }
icculus@370
   871
   }
icculus@370
   872
   free(data);
icculus@370
   873
   return output;
icculus@370
   874
}
icculus@370
   875
#endif
icculus@370
   876
icculus@371
   877
icculus@371
   878
#ifndef STBI_NO_JPEG  // __MOJOSETUP__
icculus@371
   879
icculus@370
   880
//////////////////////////////////////////////////////////////////////////////
icculus@370
   881
//
icculus@370
   882
//  "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
icculus@370
   883
//
icculus@370
   884
//    simple implementation
icculus@370
   885
//      - channel subsampling of at most 2 in each dimension
icculus@370
   886
//      - doesn't support delayed output of y-dimension
icculus@370
   887
//      - simple interface (only one output format: 8-bit interleaved RGB)
icculus@370
   888
//      - doesn't try to recover corrupt jpegs
icculus@370
   889
//      - doesn't allow partial loading, loading multiple at once
icculus@370
   890
//      - still fast on x86 (copying globals into locals doesn't help x86)
icculus@370
   891
//      - allocates lots of intermediate memory (full size of all components)
icculus@370
   892
//        - non-interleaved case requires this anyway
icculus@370
   893
//        - allows good upsampling (see next)
icculus@370
   894
//    high-quality
icculus@370
   895
//      - upsampled channels are bilinearly interpolated, even across blocks
icculus@370
   896
//      - quality integer IDCT derived from IJG's 'slow'
icculus@370
   897
//    performance
icculus@370
   898
//      - fast huffman; reasonable integer IDCT
icculus@370
   899
//      - uses a lot of intermediate memory, could cache poorly
icculus@370
   900
//      - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
icculus@370
   901
//          stb_jpeg:   1.34 seconds (MSVC6, default release build)
icculus@370
   902
//          stb_jpeg:   1.06 seconds (MSVC6, processor = Pentium Pro)
icculus@370
   903
//          IJL11.dll:  1.08 seconds (compiled by intel)
icculus@370
   904
//          IJG 1998:   0.98 seconds (MSVC6, makefile provided by IJG)
icculus@370
   905
//          IJG 1998:   0.95 seconds (MSVC6, makefile + proc=PPro)
icculus@370
   906
icculus@370
   907
int stbi_jpeg_dc_only;
icculus@370
   908
icculus@370
   909
// huffman decoding acceleration
icculus@370
   910
#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache
icculus@370
   911
icculus@370
   912
typedef struct
icculus@370
   913
{
icculus@370
   914
   uint8  fast[1 << FAST_BITS];
icculus@370
   915
   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
icculus@370
   916
   uint16 code[256];
icculus@370
   917
   uint8  values[256];
icculus@370
   918
   uint8  size[257];
icculus@370
   919
   unsigned int maxcode[18];
icculus@370
   920
   int    delta[17];   // old 'firstsymbol' - old 'firstcode'
icculus@370
   921
} huffman;
icculus@370
   922
icculus@370
   923
static huffman huff_dc[4];  // baseline is 2 tables, extended is 4
icculus@370
   924
static huffman huff_ac[4];
icculus@370
   925
static uint8 dequant[4][64];
icculus@370
   926
icculus@370
   927
static int build_huffman(huffman *h, int *count)
icculus@370
   928
{
icculus@370
   929
   int i,j,k=0,code;
icculus@370
   930
   // build size list for each symbol (from JPEG spec)
icculus@370
   931
   for (i=0; i < 16; ++i)
icculus@370
   932
      for (j=0; j < count[i]; ++j)
icculus@370
   933
         h->size[k++] = (uint8) (i+1);
icculus@370
   934
   h->size[k] = 0;
icculus@370
   935
icculus@370
   936
   // compute actual symbols (from jpeg spec)
icculus@370
   937
   code = 0;
icculus@370
   938
   k = 0;
icculus@370
   939
   for(j=1; j <= 16; ++j) {
icculus@370
   940
      // compute delta to add to code to compute symbol id
icculus@370
   941
      h->delta[j] = k - code;
icculus@370
   942
      if (h->size[k] == j) {
icculus@370
   943
         while (h->size[k] == j)
icculus@370
   944
            h->code[k++] = (uint16) (code++);
icculus@370
   945
         if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");
icculus@370
   946
      }
icculus@370
   947
      // compute largest code + 1 for this size, preshifted as needed later
icculus@370
   948
      h->maxcode[j] = code << (16-j);
icculus@370
   949
      code <<= 1;
icculus@370
   950
   }
icculus@370
   951
   h->maxcode[j] = 0xffffffff;
icculus@370
   952
icculus@370
   953
   // build non-spec acceleration table; 255 is flag for not-accelerated
icculus@370
   954
   memset(h->fast, 255, 1 << FAST_BITS);
icculus@370
   955
   for (i=0; i < k; ++i) {
icculus@370
   956
      int s = h->size[i];
icculus@370
   957
      if (s <= FAST_BITS) {
icculus@370
   958
         int c = h->code[i] << (FAST_BITS-s);
icculus@370
   959
         int m = 1 << (FAST_BITS-s);
icculus@370
   960
         for (j=0; j < m; ++j) {
icculus@370
   961
            h->fast[c+j] = (uint8) i;
icculus@370
   962
         }
icculus@370
   963
      }
icculus@370
   964
   }
icculus@370
   965
   return 1;
icculus@370
   966
}
icculus@370
   967
icculus@370
   968
// sizes for components, interleaved MCUs
icculus@370
   969
static int img_h_max, img_v_max;
icculus@370
   970
static int img_mcu_x, img_mcu_y;
icculus@370
   971
static int img_mcu_w, img_mcu_h;
icculus@370
   972
icculus@370
   973
// definition of jpeg image component
icculus@370
   974
static struct
icculus@370
   975
{
icculus@370
   976
   int id;
icculus@370
   977
   int h,v;
icculus@370
   978
   int tq;
icculus@370
   979
   int hd,ha;
icculus@370
   980
   int dc_pred;
icculus@370
   981
icculus@370
   982
   int x,y,w2,h2;
icculus@370
   983
   uint8 *data;
icculus@370
   984
} img_comp[4];
icculus@370
   985
icculus@375
   986
#if !__MOJOSETUP__  // moved elsewhere for #ifdef safety.
icculus@370
   987
static unsigned long  code_buffer; // jpeg entropy-coded buffer
icculus@375
   988
#endif
icculus@370
   989
static int            code_bits;   // number of valid bits
icculus@370
   990
static unsigned char  marker;      // marker seen while filling entropy buffer
icculus@370
   991
static int            nomore;      // flag if we saw a marker so must stop
icculus@375
   992
icculus@370
   993
static void grow_buffer_unsafe(void)
icculus@370
   994
{
icculus@370
   995
   do {
icculus@370
   996
      int b = nomore ? 0 : get8();
icculus@370
   997
      if (b == 0xff) {
icculus@370
   998
         int c = get8();
icculus@370
   999
         if (c != 0) {
icculus@370
  1000
            marker = (unsigned char) c;
icculus@370
  1001
            nomore = 1;
icculus@370
  1002
            return;
icculus@370
  1003
         }
icculus@370
  1004
      }
icculus@370
  1005
      code_buffer = (code_buffer << 8) | b;
icculus@370
  1006
      code_bits += 8;
icculus@370
  1007
   } while (code_bits <= 24);
icculus@370
  1008
}
icculus@370
  1009
icculus@370
  1010
// (1 << n) - 1
icculus@370
  1011
static unsigned long bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
icculus@370
  1012
icculus@370
  1013
// decode a jpeg huffman value from the bitstream
icculus@370
  1014
__forceinline static int decode(huffman *h)
icculus@370
  1015
{
icculus@370
  1016
   unsigned int temp;
icculus@370
  1017
   int c,k;
icculus@370
  1018
icculus@370
  1019
   if (code_bits < 16) grow_buffer_unsafe();
icculus@370
  1020
icculus@370
  1021
   // look at the top FAST_BITS and determine what symbol ID it is,
icculus@370
  1022
   // if the code is <= FAST_BITS
icculus@370
  1023
   c = (code_buffer >> (code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1);
icculus@370
  1024
   k = h->fast[c];
icculus@370
  1025
   if (k < 255) {
icculus@370
  1026
      if (h->size[k] > code_bits)
icculus@370
  1027
         return -1;
icculus@370
  1028
      code_bits -= h->size[k];
icculus@370
  1029
      return h->values[k];
icculus@370
  1030
   }
icculus@370
  1031
icculus@370
  1032
   // naive test is to shift the code_buffer down so k bits are
icculus@370
  1033
   // valid, then test against maxcode. To speed this up, we've
icculus@370
  1034
   // preshifted maxcode left so that it has (16-k) 0s at the
icculus@370
  1035
   // end; in other words, regardless of the number of bits, it
icculus@370
  1036
   // wants to be compared against something shifted to have 16;
icculus@370
  1037
   // that way we don't need to shift inside the loop.
icculus@370
  1038
   if (code_bits < 16)
icculus@370
  1039
      temp = (code_buffer << (16 - code_bits)) & 0xffff;
icculus@370
  1040
   else
icculus@370
  1041
      temp = (code_buffer >> (code_bits - 16)) & 0xffff;
icculus@370
  1042
   for (k=FAST_BITS+1 ; ; ++k)
icculus@370
  1043
      if (temp < h->maxcode[k])
icculus@370
  1044
         break;
icculus@370
  1045
   if (k == 17) {
icculus@370
  1046
      // error! code not found
icculus@370
  1047
      code_bits -= 16;
icculus@370
  1048
      return -1;
icculus@370
  1049
   }
icculus@370
  1050
icculus@370
  1051
   if (k > code_bits)
icculus@370
  1052
      return -1;
icculus@370
  1053
icculus@370
  1054
   // convert the huffman code to the symbol id
icculus@370
  1055
   c = ((code_buffer >> (code_bits - k)) & bmask[k]) + h->delta[k];
icculus@370
  1056
   assert((((code_buffer) >> (code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
icculus@370
  1057
icculus@370
  1058
   // convert the id to a symbol
icculus@370
  1059
   code_bits -= k;
icculus@370
  1060
   return h->values[c];
icculus@370
  1061
}
icculus@370
  1062
icculus@370
  1063
// combined JPEG 'receive' and JPEG 'extend', since baseline
icculus@370
  1064
// always extends everything it receives.
icculus@370
  1065
__forceinline static int extend_receive(int n)
icculus@370
  1066
{
icculus@370
  1067
   unsigned int m = 1 << (n-1);
icculus@370
  1068
   unsigned int k;
icculus@370
  1069
   if (code_bits < n) grow_buffer_unsafe();
icculus@370
  1070
   k = (code_buffer >> (code_bits - n)) & bmask[n];
icculus@370
  1071
   code_bits -= n;
icculus@370
  1072
   // the following test is probably a random branch that won't
icculus@370
  1073
   // predict well. I tried to table accelerate it but failed.
icculus@370
  1074
   // maybe it's compiling as a conditional move?
icculus@370
  1075
   if (k < m)
icculus@370
  1076
      return (-1 << n) + k + 1;
icculus@370
  1077
   else
icculus@370
  1078
      return k;
icculus@370
  1079
}
icculus@370
  1080
icculus@370
  1081
// given a value that's at position X in the zigzag stream,
icculus@370
  1082
// where does it appear in the 8x8 matrix coded as row-major?
icculus@370
  1083
static uint8 dezigzag[64+15] =
icculus@370
  1084
{
icculus@370
  1085
    0,  1,  8, 16,  9,  2,  3, 10,
icculus@370
  1086
   17, 24, 32, 25, 18, 11,  4,  5,
icculus@370
  1087
   12, 19, 26, 33, 40, 48, 41, 34,
icculus@370
  1088
   27, 20, 13,  6,  7, 14, 21, 28,
icculus@370
  1089
   35, 42, 49, 56, 57, 50, 43, 36,
icculus@370
  1090
   29, 22, 15, 23, 30, 37, 44, 51,
icculus@370
  1091
   58, 59, 52, 45, 38, 31, 39, 46,
icculus@370
  1092
   53, 60, 61, 54, 47, 55, 62, 63,
icculus@370
  1093
   // let corrupt input sample past end
icculus@370
  1094
   63, 63, 63, 63, 63, 63, 63, 63,
icculus@370
  1095
   63, 63, 63, 63, 63, 63, 63
icculus@370
  1096
};
icculus@370
  1097
icculus@370
  1098
// decode one 64-entry block--
icculus@370
  1099
static int decode_block(short data[64], huffman *hdc, huffman *hac, int b)
icculus@370
  1100
{
icculus@370
  1101
   int diff,dc,k;
icculus@370
  1102
   int t = decode(hdc);
icculus@370
  1103
   if (t < 0) return e("bad huffman code","Corrupt JPEG");
icculus@370
  1104
icculus@370
  1105
   // 0 all the ac values now so we can do it 32-bits at a time
icculus@370
  1106
   memset(data,0,64*sizeof(data[0]));
icculus@370
  1107
icculus@370
  1108
   diff = t ? extend_receive(t) : 0;
icculus@370
  1109
   dc = img_comp[b].dc_pred + diff;
icculus@370
  1110
   img_comp[b].dc_pred = dc;
icculus@370
  1111
   data[0] = (short) dc;
icculus@370
  1112
icculus@370
  1113
   // decode AC components, see JPEG spec
icculus@370
  1114
   k = 1;
icculus@370
  1115
   do {
icculus@370
  1116
      int r,s;
icculus@370
  1117
      int rs = decode(hac);
icculus@370
  1118
      if (rs < 0) return e("bad huffman code","Corrupt JPEG");
icculus@370
  1119
      s = rs & 15;
icculus@370
  1120
      r = rs >> 4;
icculus@370
  1121
      if (s == 0) {
icculus@370
  1122
         if (rs != 0xf0) break; // end block
icculus@370
  1123
         k += 16;
icculus@370
  1124
      } else {
icculus@370
  1125
         k += r;
icculus@370
  1126
         // decode into unzigzag'd location
icculus@370
  1127
         data[dezigzag[k++]] = (short) extend_receive(s);
icculus@370
  1128
      }
icculus@370
  1129
   } while (k < 64);
icculus@370
  1130
   return 1;
icculus@370
  1131
}
icculus@370
  1132
icculus@370
  1133
// take a -128..127 value and clamp it and convert to 0..255
icculus@370
  1134
__forceinline static uint8 clamp(int x)
icculus@370
  1135
{
icculus@370
  1136
   x += 128;
icculus@370
  1137
   // trick to use a single test to catch both cases
icculus@370
  1138
   if ((unsigned int) x > 255) {
icculus@370
  1139
      if (x < 0) return 0;
icculus@370
  1140
      if (x > 255) return 255;
icculus@370
  1141
   }
icculus@370
  1142
   return (uint8) x;
icculus@370
  1143
}
icculus@370
  1144
icculus@370
  1145
#define f2f(x)  (int) (((x) * 4096 + 0.5))
icculus@370
  1146
#define fsh(x)  ((x) << 12)
icculus@370
  1147
icculus@370
  1148
// derived from jidctint -- DCT_ISLOW
icculus@370
  1149
#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7)       \
icculus@370
  1150
   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
icculus@370
  1151
   p2 = s2;                                    \
icculus@370
  1152
   p3 = s6;                                    \
icculus@370
  1153
   p1 = (p2+p3) * f2f(0.5411961f);             \
icculus@370
  1154
   t2 = p1 + p3*f2f(-1.847759065f);            \
icculus@370
  1155
   t3 = p1 + p2*f2f( 0.765366865f);            \
icculus@370
  1156
   p2 = s0;                                    \
icculus@370
  1157
   p3 = s4;                                    \
icculus@370
  1158
   t0 = fsh(p2+p3);                            \
icculus@370
  1159
   t1 = fsh(p2-p3);                            \
icculus@370
  1160
   x0 = t0+t3;                                 \
icculus@370
  1161
   x3 = t0-t3;                                 \
icculus@370
  1162
   x1 = t1+t2;                                 \
icculus@370
  1163
   x2 = t1-t2;                                 \
icculus@370
  1164
   t0 = s7;                                    \
icculus@370
  1165
   t1 = s5;                                    \
icculus@370
  1166
   t2 = s3;                                    \
icculus@370
  1167
   t3 = s1;                                    \
icculus@370
  1168
   p3 = t0+t2;                                 \
icculus@370
  1169
   p4 = t1+t3;                                 \
icculus@370
  1170
   p1 = t0+t3;                                 \
icculus@370
  1171
   p2 = t1+t2;                                 \
icculus@370
  1172
   p5 = (p3+p4)*f2f( 1.175875602f);            \
icculus@370
  1173
   t0 = t0*f2f( 0.298631336f);                 \
icculus@370
  1174
   t1 = t1*f2f( 2.053119869f);                 \
icculus@370
  1175
   t2 = t2*f2f( 3.072711026f);                 \
icculus@370
  1176
   t3 = t3*f2f( 1.501321110f);                 \
icculus@370
  1177
   p1 = p5 + p1*f2f(-0.899976223f);            \
icculus@370
  1178
   p2 = p5 + p2*f2f(-2.562915447f);            \
icculus@370
  1179
   p3 = p3*f2f(-1.961570560f);                 \
icculus@370
  1180
   p4 = p4*f2f(-0.390180644f);                 \
icculus@370
  1181
   t3 += p1+p4;                                \
icculus@370
  1182
   t2 += p2+p3;                                \
icculus@370
  1183
   t1 += p2+p4;                                \
icculus@370
  1184
   t0 += p1+p3;
icculus@370
  1185
icculus@370
  1186
// .344 seconds on 3*anemones.jpg
icculus@370
  1187
static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize)
icculus@370
  1188
{
icculus@370
  1189
   int i,val[64],*v=val;
icculus@370
  1190
   uint8 *o,*dq = dequantize;
icculus@370
  1191
   short *d = data;
icculus@370
  1192
icculus@370
  1193
   if (stbi_jpeg_dc_only) {
icculus@370
  1194
      // ok, I don't really know why this is right, but it seems to be:
icculus@370
  1195
      int z = 128 + ((d[0] * dq[0]) >> 3);
icculus@370
  1196
      for (i=0; i < 8; ++i) {
icculus@370
  1197
         out[0] = out[1] = out[2] = out[3] = out[4] = out[5] = out[6] = out[7] = z;
icculus@370
  1198
         out += out_stride;
icculus@370
  1199
      }
icculus@370
  1200
      return;
icculus@370
  1201
   }
icculus@370
  1202
icculus@370
  1203
   // columns
icculus@370
  1204
   for (i=0; i < 8; ++i,++d,++dq, ++v) {
icculus@370
  1205
      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
icculus@370
  1206
      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
icculus@370
  1207
           && d[40]==0 && d[48]==0 && d[56]==0) {
icculus@370
  1208
         //    no shortcut                 0     seconds
icculus@370
  1209
         //    (1|2|3|4|5|6|7)==0          0     seconds
icculus@370
  1210
         //    all separate               -0.047 seconds
icculus@370
  1211
         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds
icculus@370
  1212
         int dcterm = d[0] * dq[0] << 2;
icculus@370
  1213
         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
icculus@370
  1214
      } else {
icculus@370
  1215
         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
icculus@370
  1216
                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
icculus@370
  1217
         // constants scaled things up by 1<<12; let's bring them back
icculus@370
  1218
         // down, but keep 2 extra bits of precision
icculus@370
  1219
         x0 += 512; x1 += 512; x2 += 512; x3 += 512;
icculus@370
  1220
         v[ 0] = (x0+t3) >> 10;
icculus@370
  1221
         v[56] = (x0-t3) >> 10;
icculus@370
  1222
         v[ 8] = (x1+t2) >> 10;
icculus@370
  1223
         v[48] = (x1-t2) >> 10;
icculus@370
  1224
         v[16] = (x2+t1) >> 10;
icculus@370
  1225
         v[40] = (x2-t1) >> 10;
icculus@370
  1226
         v[24] = (x3+t0) >> 10;
icculus@370
  1227
         v[32] = (x3-t0) >> 10;
icculus@370
  1228
      }
icculus@370
  1229
   }
icculus@370
  1230
icculus@370
  1231
   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
icculus@370
  1232
      // no fast case since the first 1D IDCT spread components out
icculus@370
  1233
      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
icculus@370
  1234
      // constants scaled things up by 1<<12, plus we had 1<<2 from first
icculus@370
  1235
      // loop, plus horizontal and vertical each scale by sqrt(8) so together
icculus@370
  1236
      // we've got an extra 1<<3, so 1<<17 total we need to remove.
icculus@370
  1237
      x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
icculus@370
  1238
      o[0] = clamp((x0+t3) >> 17);
icculus@370
  1239
      o[7] = clamp((x0-t3) >> 17);
icculus@370
  1240
      o[1] = clamp((x1+t2) >> 17);
icculus@370
  1241
      o[6] = clamp((x1-t2) >> 17);
icculus@370
  1242
      o[2] = clamp((x2+t1) >> 17);
icculus@370
  1243
      o[5] = clamp((x2-t1) >> 17);
icculus@370
  1244
      o[3] = clamp((x3+t0) >> 17);
icculus@370
  1245
      o[4] = clamp((x3-t0) >> 17);
icculus@370
  1246
   }
icculus@370
  1247
}
icculus@370
  1248
icculus@370
  1249
#define MARKER_none  0xff
icculus@370
  1250
// if there's a pending marker from the entropy stream, return that
icculus@370
  1251
// otherwise, fetch from the stream and get a marker. if there's no
icculus@370
  1252
// marker, return 0xff, which is never a valid marker value
icculus@370
  1253
static uint8 get_marker(void)
icculus@370
  1254
{
icculus@370
  1255
   uint8 x;
icculus@370
  1256
   if (marker != MARKER_none) { x = marker; marker = MARKER_none; return x; }
icculus@370
  1257
   x = get8u();
icculus@370
  1258
   if (x != 0xff) return MARKER_none;
icculus@370
  1259
   while (x == 0xff)
icculus@370
  1260
      x = get8u();
icculus@370
  1261
   return x;
icculus@370
  1262
}
icculus@370
  1263
icculus@370
  1264
// in each scan, we'll have scan_n components, and the order
icculus@370
  1265
// of the components is specified by order[]
icculus@370
  1266
static int scan_n, order[4];
icculus@370
  1267
static int restart_interval, todo;
icculus@370
  1268
#define RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)
icculus@370
  1269
icculus@370
  1270
// after a restart interval, reset the entropy decoder and
icculus@370
  1271
// the dc prediction
icculus@370
  1272
static void reset(void)
icculus@370
  1273
{
icculus@370
  1274
   code_bits = 0;
icculus@370
  1275
   code_buffer = 0;
icculus@370
  1276
   nomore = 0;
icculus@370
  1277
   img_comp[0].dc_pred = img_comp[1].dc_pred = img_comp[2].dc_pred = 0;
icculus@370
  1278
   marker = MARKER_none;
icculus@370
  1279
   todo = restart_interval ? restart_interval : 0x7fffffff;
icculus@370
  1280
   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
icculus@370
  1281
   // since we don't even allow 1<<30 pixels
icculus@370
  1282
}
icculus@370
  1283
icculus@370
  1284
static int parse_entropy_coded_data(void)
icculus@370
  1285
{
icculus@370
  1286
   reset();
icculus@370
  1287
   if (scan_n == 1) {
icculus@370
  1288
      int i,j;
icculus@370
  1289
      short data[64];
icculus@370
  1290
      int n = order[0];
icculus@370
  1291
      // non-interleaved data, we just need to process one block at a time,
icculus@370
  1292
      // in trivial scanline order
icculus@370
  1293
      // number of blocks to do just depends on how many actual "pixels" this
icculus@370
  1294
      // component has, independent of interleaved MCU blocking and such
icculus@370
  1295
      int w = (img_comp[n].x+7) >> 3;
icculus@370
  1296
      int h = (img_comp[n].y+7) >> 3;
icculus@370
  1297
      for (j=0; j < h; ++j) {
icculus@370
  1298
         for (i=0; i < w; ++i) {
icculus@370
  1299
            if (!decode_block(data, huff_dc+img_comp[n].hd, huff_ac+img_comp[n].ha, n)) return 0;
icculus@370
  1300
            idct_block(img_comp[n].data+img_comp[n].w2*j*8+i*8, img_comp[n].w2, data, dequant[img_comp[n].tq]);
icculus@370
  1301
            // every data block is an MCU, so countdown the restart interval
icculus@370
  1302
            if (--todo <= 0) {
icculus@370
  1303
               if (code_bits < 24) grow_buffer_unsafe();
icculus@370
  1304
               // if it's NOT a restart, then just bail, so we get corrupt data
icculus@370
  1305
               // rather than no data
icculus@370
  1306
               if (!RESTART(marker)) return 1;
icculus@370
  1307
               reset();
icculus@370
  1308
            }
icculus@370
  1309
         }
icculus@370
  1310
      }
icculus@370
  1311
   } else { // interleaved!
icculus@370
  1312
      int i,j,k,x,y;
icculus@370
  1313
      short data[64];
icculus@370
  1314
      for (j=0; j < img_mcu_y; ++j) {
icculus@370
  1315
         for (i=0; i < img_mcu_x; ++i) {
icculus@370
  1316
            // scan an interleaved mcu... process scan_n components in order
icculus@370
  1317
            for (k=0; k < scan_n; ++k) {
icculus@370
  1318
               int n = order[k];
icculus@370
  1319
               // scan out an mcu's worth of this component; that's just determined
icculus@370
  1320
               // by the basic H and V specified for the component
icculus@370
  1321
               for (y=0; y < img_comp[n].v; ++y) {
icculus@370
  1322
                  for (x=0; x < img_comp[n].h; ++x) {
icculus@370
  1323
                     int x2 = (i*img_comp[n].h + x)*8;
icculus@370
  1324
                     int y2 = (j*img_comp[n].v + y)*8;
icculus@370
  1325
                     if (!decode_block(data, huff_dc+img_comp[n].hd, huff_ac+img_comp[n].ha, n)) return 0;
icculus@370
  1326
                     idct_block(img_comp[n].data+img_comp[n].w2*y2+x2, img_comp[n].w2, data, dequant[img_comp[n].tq]);
icculus@370
  1327
                  }
icculus@370
  1328
               }
icculus@370
  1329
            }
icculus@370
  1330
            // after all interleaved components, that's an interleaved MCU,
icculus@370
  1331
            // so now count down the restart interval
icculus@370
  1332
            if (--todo <= 0) {
icculus@370
  1333
               if (code_bits < 24) grow_buffer_unsafe();
icculus@370
  1334
               // if it's NOT a restart, then just bail, so we get corrupt data
icculus@370
  1335
               // rather than no data
icculus@370
  1336
               if (!RESTART(marker)) return 1;
icculus@370
  1337
               reset();
icculus@370
  1338
            }
icculus@370
  1339
         }
icculus@370
  1340
      }
icculus@370
  1341
   }
icculus@370
  1342
   return 1;
icculus@370
  1343
}
icculus@370
  1344
icculus@370
  1345
static int process_marker(int m)
icculus@370
  1346
{
icculus@370
  1347
   int L;
icculus@370
  1348
   switch (m) {
icculus@370
  1349
      case MARKER_none: // no marker found
icculus@370
  1350
         return e("expected marker","Corrupt JPEG");
icculus@370
  1351
icculus@370
  1352
      case 0xC2: // SOF - progressive
icculus@370
  1353
         return e("progressive jpeg","JPEG format not supported (progressive)");
icculus@370
  1354
icculus@370
  1355
      case 0xDD: // DRI - specify restart interval
icculus@370
  1356
         if (get16() != 4) return e("bad DRI len","Corrupt JPEG");
icculus@370
  1357
         restart_interval = get16();
icculus@370
  1358
         return 1;
icculus@370
  1359
icculus@370
  1360
      case 0xDB: // DQT - define quantization table
icculus@370
  1361
         L = get16()-2;
icculus@370
  1362
         while (L > 0) {
icculus@370
  1363
            int z = get8();
icculus@370
  1364
            int p = z >> 4;
icculus@370
  1365
            int t = z & 15,i;
icculus@370
  1366
            if (p != 0) return e("bad DQT type","Corrupt JPEG");
icculus@370
  1367
            if (t > 3) return e("bad DQT table","Corrupt JPEG");
icculus@370
  1368
            for (i=0; i < 64; ++i)
icculus@370
  1369
               dequant[t][dezigzag[i]] = get8u();
icculus@370
  1370
            L -= 65;
icculus@370
  1371
         }
icculus@370
  1372
         return L==0;
icculus@370
  1373
icculus@370
  1374
      case 0xC4: // DHT - define huffman table
icculus@370
  1375
         L = get16()-2;
icculus@370
  1376
         while (L > 0) {
icculus@370
  1377
            uint8 *v;
icculus@370
  1378
            int sizes[16],i,m=0;
icculus@370
  1379
            int z = get8();
icculus@370
  1380
            int tc = z >> 4;
icculus@370
  1381
            int th = z & 15;
icculus@370
  1382
            if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");
icculus@370
  1383
            for (i=0; i < 16; ++i) {
icculus@370
  1384
               sizes[i] = get8();
icculus@370
  1385
               m += sizes[i];
icculus@370
  1386
            }
icculus@370
  1387
            L -= 17;
icculus@370
  1388
            if (tc == 0) {
icculus@370
  1389
               if (!build_huffman(huff_dc+th, sizes)) return 0;
icculus@370
  1390
               v = huff_dc[th].values;
icculus@370
  1391
            } else {
icculus@370
  1392
               if (!build_huffman(huff_ac+th, sizes)) return 0;
icculus@370
  1393
               v = huff_ac[th].values;
icculus@370
  1394
            }
icculus@370
  1395
            for (i=0; i < m; ++i)
icculus@370
  1396
               v[i] = get8u();
icculus@370
  1397
            L -= m;
icculus@370
  1398
         }
icculus@370
  1399
         return L==0;
icculus@370
  1400
   }
icculus@370
  1401
   // check for comment block or APP blocks
icculus@370
  1402
   if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
icculus@370
  1403
      skip(get16()-2);
icculus@370
  1404
      return 1;
icculus@370
  1405
   }
icculus@370
  1406
   return 0;
icculus@370
  1407
}
icculus@370
  1408
icculus@370
  1409
// after we see SOS
icculus@370
  1410
static int process_scan_header(void)
icculus@370
  1411
{
icculus@370
  1412
   int i;
icculus@370
  1413
   int Ls = get16();
icculus@370
  1414
   scan_n = get8();
icculus@370
  1415
   if (scan_n < 1 || scan_n > 4 || scan_n > (int) img_n) return e("bad SOS component count","Corrupt JPEG");
icculus@370
  1416
   if (Ls != 6+2*scan_n) return e("bad SOS len","Corrupt JPEG");
icculus@370
  1417
   for (i=0; i < scan_n; ++i) {
icculus@370
  1418
      int id = get8(), which;
icculus@370
  1419
      int z = get8();
icculus@370
  1420
      for (which = 0; which < img_n; ++which)
icculus@370
  1421
         if (img_comp[which].id == id)
icculus@370
  1422
            break;
icculus@370
  1423
      if (which == img_n) return 0;
icculus@370
  1424
      img_comp[which].hd = z >> 4;   if (img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");
icculus@370
  1425
      img_comp[which].ha = z & 15;   if (img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");
icculus@370
  1426
      order[i] = which;
icculus@370
  1427
   }
icculus@370
  1428
   if (get8() != 0) return e("bad SOS","Corrupt JPEG");
icculus@370
  1429
   get8(); // should be 63, but might be 0
icculus@370
  1430
   if (get8() != 0) return e("bad SOS","Corrupt JPEG");
icculus@370
  1431
icculus@370
  1432
   return 1;
icculus@370
  1433
}
icculus@370
  1434
icculus@370
  1435
static int process_frame_header(int scan)
icculus@370
  1436
{
icculus@370
  1437
   int Lf,p,i,z, h_max=1,v_max=1;
icculus@370
  1438
   Lf = get16();         if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG
icculus@370
  1439
   p  = get8();          if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
icculus@370
  1440
   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
icculus@370
  1441
   img_x = get16();      if (img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires
icculus@370
  1442
   img_n = get8();
icculus@370
  1443
   if (img_n != 3 && img_n != 1) return e("bad component count","Corrupt JPEG");    // JFIF requires
icculus@370
  1444
icculus@370
  1445
   if (Lf != 8+3*img_n) return e("bad SOF len","Corrupt JPEG");
icculus@370
  1446
icculus@370
  1447
   for (i=0; i < img_n; ++i) {
icculus@370
  1448
      img_comp[i].id = get8();
icculus@370
  1449
      if (img_comp[i].id != i+1)   // JFIF requires
icculus@370
  1450
         if (img_comp[i].id != i)  // jpegtran outputs non-JFIF-compliant files!
icculus@370
  1451
            return e("bad component ID","Corrupt JPEG");
icculus@370
  1452
      z = get8();
icculus@370
  1453
      img_comp[i].h = (z >> 4);  if (!img_comp[i].h || img_comp[i].h > 4) return e("bad H","Corrupt JPEG");
icculus@370
  1454
      img_comp[i].v = z & 15;    if (!img_comp[i].v || img_comp[i].v > 4) return e("bad V","Corrupt JPEG");
icculus@370
  1455
      img_comp[i].tq = get8();   if (img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");
icculus@370
  1456
   }
icculus@370
  1457
icculus@370
  1458
   if (scan != SCAN_load) return 1;
icculus@370
  1459
icculus@370
  1460
   if ((1 << 30) / img_x / img_n < img_y) return e("too large", "Image too large to decode");
icculus@370
  1461
icculus@370
  1462
   for (i=0; i < img_n; ++i) {
icculus@370
  1463
      if (img_comp[i].h > h_max) h_max = img_comp[i].h;
icculus@370
  1464
      if (img_comp[i].v > v_max) v_max = img_comp[i].v;
icculus@370
  1465
   }
icculus@370
  1466
icculus@370
  1467
   // compute interleaved mcu info
icculus@370
  1468
   img_h_max = h_max;
icculus@370
  1469
   img_v_max = v_max;
icculus@370
  1470
   img_mcu_w = h_max * 8;
icculus@370
  1471
   img_mcu_h = v_max * 8;
icculus@370
  1472
   img_mcu_x = (img_x + img_mcu_w-1) / img_mcu_w;
icculus@370
  1473
   img_mcu_y = (img_y + img_mcu_h-1) / img_mcu_h;
icculus@370
  1474
icculus@370
  1475
   for (i=0; i < img_n; ++i) {
icculus@370
  1476
      // number of effective pixels (e.g. for non-interleaved MCU)
icculus@370
  1477
      img_comp[i].x = (img_x * img_comp[i].h + h_max-1) / h_max;
icculus@370
  1478
      img_comp[i].y = (img_y * img_comp[i].v + v_max-1) / v_max;
icculus@370
  1479
      // to simplify generation, we'll allocate enough memory to decode
icculus@370
  1480
      // the bogus oversized data from using interleaved MCUs and their
icculus@370
  1481
      // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
icculus@370
  1482
      // discard the extra data until colorspace conversion
icculus@370
  1483
      img_comp[i].w2 = img_mcu_x * img_comp[i].h * 8;
icculus@370
  1484
      img_comp[i].h2 = img_mcu_y * img_comp[i].v * 8;
icculus@370
  1485
      img_comp[i].data = (uint8 *) malloc(img_comp[i].w2 * img_comp[i].h2);
icculus@370
  1486
      if (img_comp[i].data == NULL) {
icculus@370
  1487
         for(--i; i >= 0; --i)
icculus@370
  1488
            free(img_comp[i].data);
icculus@370
  1489
         return e("outofmem", "Out of memory");
icculus@370
  1490
      }
icculus@370
  1491
   }
icculus@370
  1492
icculus@370
  1493
   return 1;
icculus@370
  1494
}
icculus@370
  1495
icculus@370
  1496
// use comparisons since in some cases we handle more than one case (e.g. SOF)
icculus@370
  1497
#define DNL(x)         ((x) == 0xdc)
icculus@370
  1498
#define SOI(x)         ((x) == 0xd8)
icculus@370
  1499
#define EOI(x)         ((x) == 0xd9)
icculus@370
  1500
#define SOF(x)         ((x) == 0xc0 || (x) == 0xc1)
icculus@370
  1501
#define SOS(x)         ((x) == 0xda)
icculus@370
  1502
icculus@370
  1503
static int decode_jpeg_header(int scan)
icculus@370
  1504
{
icculus@370
  1505
   int m;
icculus@370
  1506
   marker = MARKER_none; // initialize cached marker to empty
icculus@370
  1507
   m = get_marker();
icculus@370
  1508
   if (!SOI(m)) return e("no SOI","Corrupt JPEG");
icculus@370
  1509
   if (scan == SCAN_type) return 1;
icculus@370
  1510
   m = get_marker();
icculus@370
  1511
   while (!SOF(m)) {
icculus@370
  1512
      if (!process_marker(m)) return 0;
icculus@370
  1513
      m = get_marker();
icculus@370
  1514
      while (m == MARKER_none) {
icculus@370
  1515
         // some files have extra padding after their blocks, so ok, we'll scan
icculus@370
  1516
         if (at_eof()) return e("no SOF", "Corrupt JPEG");
icculus@370
  1517
         m = get_marker();
icculus@370
  1518
      }
icculus@370
  1519
   }
icculus@370
  1520
   if (!process_frame_header(scan)) return 0;
icculus@370
  1521
   return 1;
icculus@370
  1522
}
icculus@370
  1523
icculus@370
  1524
static int decode_jpeg_image(void)
icculus@370
  1525
{
icculus@370
  1526
   int m;
icculus@370
  1527
   restart_interval = 0;
icculus@370
  1528
   if (!decode_jpeg_header(SCAN_load)) return 0;
icculus@370
  1529
   m = get_marker();
icculus@370
  1530
   while (!EOI(m)) {
icculus@370
  1531
      if (SOS(m)) {
icculus@370
  1532
         if (!process_scan_header()) return 0;
icculus@370
  1533
         if (!parse_entropy_coded_data()) return 0;
icculus@370
  1534
      } else {
icculus@370
  1535
         if (!process_marker(m)) return 0;
icculus@370
  1536
      }
icculus@370
  1537
      m = get_marker();
icculus@370
  1538
   }
icculus@370
  1539
   return 1;
icculus@370
  1540
}
icculus@370
  1541
icculus@370
  1542
// static jfif-centered resampling with cross-block smoothing
icculus@370
  1543
// here by cross-block smoothing what I mean is that the resampling
icculus@370
  1544
// is bilerp and crosses blocks; I dunno what IJG means
icculus@370
  1545
icculus@370
  1546
#define div4(x) ((uint8) ((x) >> 2))
icculus@370
  1547
icculus@370
  1548
static void resample_v_2(uint8 *out1, uint8 *input, int w, int h, int s)
icculus@370
  1549
{
icculus@370
  1550
   // need to generate two samples vertically for every one in input
icculus@370
  1551
   uint8 *above;
icculus@370
  1552
   uint8 *below;
icculus@370
  1553
   uint8 *source;
icculus@370
  1554
   uint8 *out2;
icculus@370
  1555
   int i,j;
icculus@370
  1556
   source = input;
icculus@370
  1557
   out2 = out1+w;
icculus@370
  1558
   for (j=0; j < h; ++j) {
icculus@370
  1559
      above = source;
icculus@370
  1560
      source = input + j*s;
icculus@370
  1561
      below = source + s; if (j == h-1) below = source;
icculus@370
  1562
      for (i=0; i < w; ++i) {
icculus@370
  1563
         int n = source[i]*3;
icculus@370
  1564
         out1[i] = div4(above[i] + n);
icculus@370
  1565
         out2[i] = div4(below[i] + n);
icculus@370
  1566
      }
icculus@370
  1567
      out1 += w*2;
icculus@370
  1568
      out2 += w*2;
icculus@370
  1569
   }
icculus@370
  1570
}
icculus@370
  1571
icculus@370
  1572
static void resample_h_2(uint8 *out, uint8 *input, int w, int h, int s)
icculus@370
  1573
{
icculus@370
  1574
   // need to generate two samples horizontally for every one in input
icculus@370
  1575
   int i,j;
icculus@370
  1576
   if (w == 1) {
icculus@370
  1577
      for (j=0; j < h; ++j)
icculus@370
  1578
         out[j*2+0] = out[j*2+1] = input[j*s];
icculus@370
  1579
      return;
icculus@370
  1580
   }
icculus@370
  1581
   for (j=0; j < h; ++j) {
icculus@370
  1582
      out[0] = input[0];
icculus@370
  1583
      out[1] = div4(input[0]*3 + input[1]);
icculus@370
  1584
      for (i=1; i < w-1; ++i) {
icculus@370
  1585
         int n = input[i]*3;
icculus@370
  1586
         out[i*2-2] = div4(input[i-1] + n);
icculus@370
  1587
         out[i*2-1] = div4(input[i+1] + n);
icculus@370
  1588
      }
icculus@370
  1589
      out[w*2-2] = div4(input[w-2]*3 + input[w-1]);
icculus@370
  1590
      out[w*2-1] = input[w-1];
icculus@370
  1591
      out += w*2;
icculus@370
  1592
      input += s;
icculus@370
  1593
   }
icculus@370
  1594
}
icculus@370
  1595
icculus@370
  1596
// .172 seconds on 3*anemones.jpg
icculus@370
  1597
static void resample_hv_2(uint8 *out, uint8 *input, int w, int h, int s)
icculus@370
  1598
{
icculus@370
  1599
   // need to generate 2x2 samples for every one in input
icculus@370
  1600
   int i,j;
icculus@370
  1601
   int os = w*2;
icculus@370
  1602
   // generate edge samples... @TODO lerp them!
icculus@370
  1603
   for (i=0; i < w; ++i) {
icculus@370
  1604
      out[i*2+0] = out[i*2+1] = input[i];
icculus@370
  1605
      out[i*2+(2*h-1)*os+0] = out[i*2+(2*h-1)*os+1] = input[i+(h-1)*w];
icculus@370
  1606
   }
icculus@370
  1607
   for (j=0; j < h; ++j) {
icculus@370
  1608
      out[j*os*2+0] = out[j*os*2+os+0] = input[j*w];
icculus@370
  1609
      out[j*os*2+os-1] = out[j*os*2+os+os-1] = input[j*w+i-1];
icculus@370
  1610
   }
icculus@370
  1611
   // now generate interior samples; i & j point to top left of input
icculus@370
  1612
   for (j=0; j < h-1; ++j) {
icculus@370
  1613
      uint8 *in1 = input+j*s;
icculus@370
  1614
      uint8 *in2 = in1 + s;
icculus@370
  1615
      uint8 *out1 = out + (j*2+1)*os + 1;
icculus@370
  1616
      uint8 *out2 = out1 + os;
icculus@370
  1617
      for (i=0; i < w-1; ++i) {
icculus@370
  1618
         int p00 = in1[0], p01=in1[1], p10=in2[0], p11=in2[1];
icculus@370
  1619
         int p00_3 = p00*3, p01_3 = p01*3, p10_3 = p10*3, p11_3 = p11*3;
icculus@370
  1620
icculus@370
  1621
         #define div16(x)  ((uint8) ((x) >> 4))
icculus@370
  1622
icculus@370
  1623
         out1[0] = div16(p00*9 + p01_3 + p10_3 + p11);
icculus@370
  1624
         out1[1] = div16(p01*9 + p00_3 + p01_3 + p10);
icculus@370
  1625
         out2[0] = div16(p10*9 + p11_3 + p00_3 + p01);
icculus@370
  1626
         out2[1] = div16(p11*9 + p10_3 + p01_3 + p00);
icculus@370
  1627
         out1 += 2;
icculus@370
  1628
         out2 += 2;                                                         
icculus@370
  1629
         ++in1;
icculus@370
  1630
         ++in2;
icculus@370
  1631
      }
icculus@370
  1632
   }
icculus@370
  1633
}
icculus@370
  1634
icculus@370
  1635
#define float2fixed(x)  ((int) ((x) * 65536 + 0.5))
icculus@370
  1636
icculus@370
  1637
// 0.38 seconds on 3*anemones.jpg   (0.25 with processor = Pro)
icculus@370
  1638
// VC6 without processor=Pro is generating multiple LEAs per multiply!
icculus@370
  1639
static void YCbCr_to_RGB_row(uint8 *out, uint8 *y, uint8 *pcb, uint8 *pcr, int count, int step)
icculus@370
  1640
{
icculus@370
  1641
   int i;
icculus@370
  1642
   for (i=0; i < count; ++i) {
icculus@370
  1643
      int y_fixed = (y[i] << 16) + 32768; // rounding
icculus@370
  1644
      int r,g,b;
icculus@370
  1645
      int cr = pcr[i] - 128;
icculus@370
  1646
      int cb = pcb[i] - 128;
icculus@370
  1647
      r = y_fixed + cr*float2fixed(1.40200f);
icculus@370
  1648
      g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
icculus@370
  1649
      b = y_fixed                            + cb*float2fixed(1.77200f);
icculus@370
  1650
      r >>= 16;
icculus@370
  1651
      g >>= 16;
icculus@370
  1652
      b >>= 16;
icculus@370
  1653
      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
icculus@370
  1654
      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
icculus@370
  1655
      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
icculus@370
  1656
      out[0] = (uint8)r;
icculus@370
  1657
      out[1] = (uint8)g;
icculus@370
  1658
      out[2] = (uint8)b;
icculus@370
  1659
      if (step == 4) out[3] = 255;
icculus@370
  1660
      out += step;
icculus@370
  1661
   }
icculus@370
  1662
}
icculus@370
  1663
icculus@370
  1664
// clean up the temporary component buffers
icculus@370
  1665
static void cleanup_jpeg(void)
icculus@370
  1666
{
icculus@370
  1667
   int i;
icculus@370
  1668
   for (i=0; i < img_n; ++i) {
icculus@370
  1669
      if (img_comp[i].data) {
icculus@370
  1670
         free(img_comp[i].data);
icculus@370
  1671
         img_comp[i].data = NULL;
icculus@370
  1672
      }
icculus@370
  1673
   }
icculus@370
  1674
}
icculus@370
  1675
icculus@370
  1676
static uint8 *load_jpeg_image(int *out_x, int *out_y, int *comp, int req_comp)
icculus@370
  1677
{
icculus@370
  1678
   int i, n;
icculus@370
  1679
   // validate req_comp
icculus@370
  1680
   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
icculus@370
  1681
icculus@370
  1682
   // load a jpeg image from whichever source
icculus@370
  1683
   if (!decode_jpeg_image()) { cleanup_jpeg(); return NULL; }
icculus@370
  1684
icculus@370
  1685
   // determine actual number of components to generate
icculus@370
  1686
   n = req_comp ? req_comp : img_n;
icculus@370
  1687
icculus@370
  1688
   // resample components to full size... memory wasteful, but this
icculus@370
  1689
   // lets us bilerp across blocks while upsampling
icculus@370
  1690
   for (i=0; i < img_n; ++i) {
icculus@370
  1691
      // if we're outputting fewer than 3 components, we're grey not RGB;
icculus@370
  1692
      // in that case, don't bother upsampling Cb or Cr
icculus@370
  1693
      if (n < 3 && i) continue;
icculus@370
  1694
icculus@370
  1695
      // check if the component scale is less than max; if so it needs upsampling
icculus@370
  1696
      if (img_comp[i].h != img_h_max || img_comp[i].v != img_v_max) {
icculus@370
  1697
         int stride = img_x;
icculus@370
  1698
         // allocate final size; make sure it's big enough for upsampling off
icculus@370
  1699
         // the edges with upsample up to 4x4 (although we only support 2x2
icculus@370
  1700
         // currently)
icculus@370
  1701
         uint8 *new_data = (uint8 *) malloc((img_x+3)*(img_y+3));
icculus@370
  1702
         if (new_data == NULL) {
icculus@370
  1703
            cleanup_jpeg();
icculus@370
  1704
            return epuc("outofmem", "Out of memory (image too large?)");
icculus@370
  1705
         }
icculus@370
  1706
         if (img_comp[i].h*2 == img_h_max && img_comp[i].v*2 == img_v_max) {
icculus@370
  1707
            int tx = (img_x+1)>>1;
icculus@370
  1708
            resample_hv_2(new_data, img_comp[i].data, tx,(img_y+1)>>1, img_comp[i].w2);
icculus@370
  1709
            stride = tx*2;
icculus@370
  1710
         } else if (img_comp[i].h == img_h_max && img_comp[i].v*2 == img_v_max) {
icculus@370
  1711
            resample_v_2(new_data, img_comp[i].data, img_x,(img_y+1)>>1, img_comp[i].w2);
icculus@370
  1712
         } else if (img_comp[i].h*2 == img_h_max && img_comp[i].v == img_v_max) {
icculus@370
  1713
            int tx = (img_x+1)>>1;
icculus@370
  1714
            resample_h_2(new_data, img_comp[i].data, tx,img_y, img_comp[i].w2);
icculus@370
  1715
            stride = tx*2;
icculus@370
  1716
         } else {
icculus@370
  1717
            // @TODO resample uncommon sampling pattern with nearest neighbor
icculus@370
  1718
            free(new_data);
icculus@370
  1719
            cleanup_jpeg();
icculus@370
  1720
            return epuc("uncommon H or V", "JPEG not supported: atypical downsampling mode");
icculus@370
  1721
         }
icculus@370
  1722
         img_comp[i].w2 = stride;
icculus@370
  1723
         free(img_comp[i].data);
icculus@370
  1724
         img_comp[i].data = new_data;
icculus@370
  1725
      }
icculus@370
  1726
   }
icculus@370
  1727
icculus@370
  1728
   // now convert components to output image
icculus@370
  1729
   {
icculus@370
  1730
      uint32 i,j;
icculus@370
  1731
      uint8 *output = (uint8 *) malloc(n * img_x * img_y + 1);
icculus@370
  1732
      if (n >= 3) { // output STBI_rgb_*
icculus@370
  1733
         for (j=0; j < img_y; ++j) {
icculus@370
  1734
            uint8 *y  = img_comp[0].data + j*img_comp[0].w2;
icculus@370
  1735
            uint8 *out = output + n * img_x * j;
icculus@370
  1736
            if (img_n == 3) {
icculus@370
  1737
               uint8 *cb = img_comp[1].data + j*img_comp[1].w2;
icculus@370
  1738
               uint8 *cr = img_comp[2].data + j*img_comp[2].w2;
icculus@370
  1739
               YCbCr_to_RGB_row(out, y, cb, cr, img_x, n);
icculus@370
  1740
            } else {
icculus@370
  1741
               for (i=0; i < img_x; ++i) {
icculus@370
  1742
                  out[0] = out[1] = out[2] = y[i];
icculus@370
  1743
                  out[3] = 255; // not used if n == 3
icculus@370
  1744
                  out += n;
icculus@370
  1745
               }
icculus@370
  1746
            }
icculus@370
  1747
         }
icculus@370
  1748
      } else {      // output STBI_grey_*
icculus@370
  1749
         for (j=0; j < img_y; ++j) {
icculus@370
  1750
            uint8 *y  = img_comp[0].data + j*img_comp[0].w2;
icculus@370
  1751
            uint8 *out = output + n * img_x * j;
icculus@370
  1752
            if (n == 1)
icculus@370
  1753
               for (i=0; i < img_x; ++i) *out++ = *y++;
icculus@370
  1754
            else
icculus@370
  1755
               for (i=0; i < img_x; ++i) *out++ = *y++, *out++ = 255;
icculus@370
  1756
         }
icculus@370
  1757
      }
icculus@370
  1758
      cleanup_jpeg();
icculus@370
  1759
      *out_x = img_x;
icculus@370
  1760
      *out_y = img_y;
icculus@370
  1761
      if (comp) *comp  = img_n; // report original components, not output
icculus@370
  1762
      return output;
icculus@370
  1763
   }
icculus@370
  1764
}
icculus@370
  1765
icculus@370
  1766
#ifndef STBI_NO_STDIO
icculus@370
  1767
unsigned char *stbi_jpeg_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
icculus@370
  1768
{
icculus@370
  1769
   start_file(f);
icculus@370
  1770
   return load_jpeg_image(x,y,comp,req_comp);
icculus@370
  1771
}
icculus@370
  1772
icculus@370
  1773
unsigned char *stbi_jpeg_load(char *filename, int *x, int *y, int *comp, int req_comp)
icculus@370
  1774
{
icculus@370
  1775
   unsigned char *data;
icculus@370
  1776
   FILE *f = fopen(filename, "rb");
icculus@370
  1777
   if (!f) return NULL;
icculus@370
  1778
   data = stbi_jpeg_load_from_file(f,x,y,comp,req_comp);
icculus@370
  1779
   fclose(f);
icculus@370
  1780
   return data;
icculus@370
  1781
}
icculus@370
  1782
#endif
icculus@370
  1783
icculus@370
  1784
unsigned char *stbi_jpeg_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)
icculus@370
  1785
{
icculus@370
  1786
   start_mem(buffer,len);
icculus@370
  1787
   return load_jpeg_image(x,y,comp,req_comp);
icculus@370
  1788
}
icculus@370
  1789
icculus@370
  1790
#ifndef STBI_NO_STDIO
icculus@370
  1791
int stbi_jpeg_test_file(FILE *f)
icculus@370
  1792
{
icculus@370
  1793
   int n,r;
icculus@370
  1794
   n = ftell(f);
icculus@370
  1795
   start_file(f);
icculus@370
  1796
   r = decode_jpeg_header(SCAN_type);
icculus@370
  1797
   fseek(f,n,SEEK_SET);
icculus@370
  1798
   return r;
icculus@370
  1799
}
icculus@370
  1800
#endif
icculus@370
  1801
icculus@371
  1802
#endif  // __MOJOSETUP__
icculus@371
  1803
icculus@370
  1804
int stbi_jpeg_test_memory(unsigned char *buffer, int len)
icculus@370
  1805
{
icculus@371
  1806
#ifndef STBI_NO_JPEG  // __MOJOSETUP__
icculus@370
  1807
   start_mem(buffer,len);
icculus@370
  1808
   return decode_jpeg_header(SCAN_type);
icculus@371
  1809
#else
icculus@371
  1810
   return 0;
icculus@371
  1811
#endif  // __MOJOSETUP__
icculus@370
  1812
}
icculus@370
  1813
icculus@370
  1814
// @TODO:
icculus@370
  1815
#ifndef STBI_NO_STDIO
icculus@370
  1816
extern int      stbi_jpeg_info            (char *filename,           int *x, int *y, int *comp);
icculus@370
  1817
extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
icculus@370
  1818
#endif
icculus@370
  1819
extern int      stbi_jpeg_info_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp);
icculus@370
  1820
icculus@371
  1821
icculus@371
  1822
#ifndef STBI_NO_ZLIB  // __MOJOSETUP__
icculus@371
  1823
icculus@370
  1824
// public domain zlib decode    v0.2  Sean Barrett 2006-11-18
icculus@370
  1825
//    simple implementation
icculus@370
  1826
//      - all input must be provided in an upfront buffer
icculus@370
  1827
//      - all output is written to a single output buffer (can malloc/realloc)
icculus@370
  1828
//    performance
icculus@370
  1829
//      - fast huffman
icculus@370
  1830
icculus@370
  1831
// fast-way is faster to check than jpeg huffman, but slow way is slower
icculus@370
  1832
#define ZFAST_BITS  9 // accelerate all cases in default tables
icculus@370
  1833
#define ZFAST_MASK  ((1 << ZFAST_BITS) - 1)
icculus@370
  1834
icculus@370
  1835
// zlib-style huffman encoding
icculus@370
  1836
// (jpegs packs from left, zlib from right, so can't share code)
icculus@370
  1837
typedef struct
icculus@370
  1838
{
icculus@370
  1839
   uint16 fast[1 << ZFAST_BITS];
icculus@370
  1840
   uint16 firstcode[16];
icculus@370
  1841
   int maxcode[17];
icculus@370
  1842
   uint16 firstsymbol[16];
icculus@370
  1843
   uint8  size[288];
icculus@370
  1844
   uint16 value[288]; 
icculus@370
  1845
} zhuffman;
icculus@370
  1846
icculus@370
  1847
__forceinline static int bitreverse16(int n)
icculus@370
  1848
{
icculus@370
  1849
  n = ((n & 0xAAAA) >>  1) | ((n & 0x5555) << 1);
icculus@370
  1850
  n = ((n & 0xCCCC) >>  2) | ((n & 0x3333) << 2);
icculus@370
  1851
  n = ((n & 0xF0F0) >>  4) | ((n & 0x0F0F) << 4);
icculus@370
  1852
  n = ((n & 0xFF00) >>  8) | ((n & 0x00FF) << 8);
icculus@370
  1853
  return n;
icculus@370
  1854
}
icculus@370
  1855
icculus@370
  1856
__forceinline static int bit_reverse(int v, int bits)
icculus@370
  1857
{
icculus@370
  1858
   assert(bits <= 16);
icculus@370
  1859
   // to bit reverse n bits, reverse 16 and shift
icculus@370
  1860
   // e.g. 11 bits, bit reverse and shift away 5
icculus@370
  1861
   return bitreverse16(v) >> (16-bits);
icculus@370
  1862
}
icculus@370
  1863
icculus@370
  1864
static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)
icculus@370
  1865
{
icculus@370
  1866
   int i,k=0;
icculus@370
  1867
   int code, next_code[16], sizes[17];
icculus@370
  1868
icculus@370
  1869
   // DEFLATE spec for generating codes
icculus@370
  1870
   memset(sizes, 0, sizeof(sizes));
icculus@370
  1871
   memset(z->fast, 255, sizeof(z->fast));
icculus@370
  1872
   for (i=0; i < num; ++i) 
icculus@370
  1873
      ++sizes[sizelist[i]];
icculus@370
  1874
   sizes[0] = 0;
icculus@370
  1875
   for (i=1; i < 16; ++i)
icculus@370
  1876
      assert(sizes[i] <= (1 << i));
icculus@370
  1877
   code = 0;
icculus@370
  1878
   for (i=1; i < 16; ++i) {
icculus@370
  1879
      next_code[i] = code;
icculus@370
  1880
      z->firstcode[i] = (uint16) code;
icculus@370
  1881
      z->firstsymbol[i] = (uint16) k;
icculus@370
  1882
      code = (code + sizes[i]);
icculus@370
  1883
      if (sizes[i])
icculus@370
  1884
         if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");
icculus@370
  1885
      z->maxcode[i] = code << (16-i); // preshift for inner loop
icculus@370
  1886
      code <<= 1;
icculus@370
  1887
      k += sizes[i];
icculus@370
  1888
   }
icculus@370
  1889
   z->maxcode[16] = 0x10000; // sentinel
icculus@370
  1890
   for (i=0; i < num; ++i) {
icculus@370
  1891
      int s = sizelist[i];
icculus@370
  1892
      if (s) {
icculus@370
  1893
         int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
icculus@370
  1894
         z->size[c] = (uint8)s;
icculus@370
  1895
         z->value[c] = (uint16)i;
icculus@370
  1896
         if (s <= ZFAST_BITS) {
icculus@370
  1897
            int k = bit_reverse(next_code[s],s);
icculus@370
  1898
            while (k < (1 << ZFAST_BITS)) {
icculus@370
  1899
               z->fast[k] = (uint16) c;
icculus@370
  1900
               k += (1 << s);
icculus@370
  1901
            }
icculus@370
  1902
         }
icculus@370
  1903
         ++next_code[s];
icculus@370
  1904
      }
icculus@370
  1905
   }
icculus@370
  1906
   return 1;
icculus@370
  1907
}
icculus@370
  1908
icculus@370
  1909
// zlib-from-memory implementation for PNG reading
icculus@370
  1910
//    because PNG allows splitting the zlib stream arbitrarily,
icculus@370
  1911
//    and it's annoying structurally to have PNG call ZLIB call PNG,
icculus@370
  1912
//    we require PNG read all the IDATs and combine them into a single
icculus@370
  1913
//    memory buffer
icculus@370
  1914
icculus@370
  1915
static uint8 *zbuffer, *zbuffer_end;
icculus@370
  1916
icculus@370
  1917
__forceinline static int zget8(void)
icculus@370
  1918
{
icculus@370
  1919
   if (zbuffer >= zbuffer_end) return 0;
icculus@370
  1920
   return *zbuffer++;
icculus@370
  1921
}
icculus@370
  1922
icculus@370
  1923
//static unsigned long code_buffer;
icculus@370
  1924
static int           num_bits;
icculus@370
  1925
icculus@370
  1926
static void fill_bits(void)
icculus@370
  1927
{
icculus@370
  1928
   do {
icculus@370
  1929
      assert(code_buffer < (1U << num_bits));
icculus@370
  1930
      code_buffer |= zget8() << num_bits;
icculus@370
  1931
      num_bits += 8;
icculus@370
  1932
   } while (num_bits <= 24);
icculus@370
  1933
}
icculus@370
  1934
icculus@370
  1935
__forceinline static unsigned int zreceive(int n)
icculus@370
  1936
{
icculus@370
  1937
   unsigned int k;
icculus@370
  1938
   if (num_bits < n) fill_bits();
icculus@370
  1939
   k = code_buffer & ((1 << n) - 1);
icculus@370
  1940
   code_buffer >>= n;
icculus@370
  1941
   num_bits -= n;
icculus@370
  1942
   return k;   
icculus@370
  1943
}
icculus@370
  1944
icculus@370
  1945
__forceinline static int zhuffman_decode(zhuffman *z)
icculus@370
  1946
{
icculus@370
  1947
   int b,s,k;
icculus@370
  1948
   if (num_bits < 16) fill_bits();
icculus@370
  1949
   b = z->fast[code_buffer & ZFAST_MASK];
icculus@370
  1950
   if (b < 0xffff) {
icculus@370
  1951
      s = z->size[b];
icculus@370
  1952
      code_buffer >>= s;
icculus@370
  1953
      num_bits -= s;
icculus@370
  1954
      return z->value[b];
icculus@370
  1955
   }
icculus@370
  1956
icculus@370
  1957
   // not resolved by fast table, so compute it the slow way
icculus@370
  1958
   // use jpeg approach, which requires MSbits at top
icculus@370
  1959
   k = bit_reverse(code_buffer, 16);
icculus@370
  1960
   for (s=ZFAST_BITS+1; ; ++s)
icculus@370
  1961
      if (k < z->maxcode[s])
icculus@370
  1962
         break;
icculus@370
  1963
   if (s == 16) return -1; // invalid code!
icculus@370
  1964
   // code size is s, so:
icculus@370
  1965
   b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
icculus@370
  1966
   assert(z->size[b] == s);
icculus@370
  1967
   code_buffer >>= s;
icculus@370
  1968
   num_bits -= s;
icculus@370
  1969
   return z->value[b];
icculus@370
  1970
}
icculus@370
  1971
icculus@370
  1972
static char *zout;
icculus@370
  1973
static char *zout_start;
icculus@370
  1974
static char *zout_end;
icculus@370
  1975
static int   z_expandable;
icculus@370
  1976
icculus@370
  1977
static int expand(int n)  // need to make room for n bytes
icculus@370
  1978
{
icculus@370
  1979
   char *q;
icculus@370
  1980
   int cur, limit;
icculus@370
  1981
   if (!z_expandable) return e("output buffer limit","Corrupt PNG");
icculus@370
  1982
   cur   = (int) (zout     - zout_start);
icculus@370
  1983
   limit = (int) (zout_end - zout_start);
icculus@370
  1984
   while (cur + n > limit)
icculus@370
  1985
      limit *= 2;
icculus@370
  1986
   q = (char *) realloc(zout_start, limit);
icculus@370
  1987
   if (q == NULL) return e("outofmem", "Out of memory");
icculus@370
  1988
   zout_start = q;
icculus@370
  1989
   zout       = q + cur;
icculus@370
  1990
   zout_end   = q + limit;
icculus@370
  1991
   return 1;
icculus@370
  1992
}
icculus@370
  1993
icculus@370
  1994
static zhuffman z_length, z_distance;
icculus@370
  1995
icculus@370
  1996
static int length_base[31] = {
icculus@370
  1997
   3,4,5,6,7,8,9,10,11,13,
icculus@370
  1998
   15,17,19,23,27,31,35,43,51,59,
icculus@370
  1999
   67,83,99,115,131,163,195,227,258,0,0 };
icculus@370
  2000
icculus@370
  2001
static int length_extra[31]= 
icculus@370
  2002
{ 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 };
icculus@370
  2003
icculus@370
  2004
static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
icculus@370
  2005
257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
icculus@370
  2006
icculus@370
  2007
static int dist_extra[32] =
icculus@370
  2008
{ 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};
icculus@370
  2009
icculus@370
  2010
static int parse_huffman_block(void)
icculus@370
  2011
{
icculus@370
  2012
   for(;;) {
icculus@370
  2013
      int z = zhuffman_decode(&z_length);
icculus@370
  2014
      if (z < 256) {
icculus@370
  2015
         if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes
icculus@370
  2016
         if (zout >= zout_end) if (!expand(1)) return 0;
icculus@370
  2017
         *zout++ = (char) z;
icculus@370
  2018
      } else {
icculus@370
  2019
         uint8 *p;
icculus@370
  2020
         int len,dist;
icculus@370
  2021
         if (z == 256) return 1;
icculus@370
  2022
         z -= 257;
icculus@370
  2023
         len = length_base[z];
icculus@370
  2024
         if (length_extra[z]) len += zreceive(length_extra[z]);
icculus@370
  2025
         z = zhuffman_decode(&z_distance);
icculus@370
  2026
         if (z < 0) return e("bad huffman code","Corrupt PNG");
icculus@370
  2027
         dist = dist_base[z];
icculus@370
  2028
         if (dist_extra[z]) dist += zreceive(dist_extra[z]);
icculus@370
  2029
         if (zout - zout_start < dist) return e("bad dist","Corrupt PNG");
icculus@370
  2030
         if (zout + len > zout_end) if (!expand(len)) return 0;
icculus@370
  2031
         p = (uint8 *) (zout - dist);
icculus@370
  2032
         while (len--)
icculus@370
  2033
            *zout++ = *p++;
icculus@370
  2034
      }
icculus@370
  2035
   }
icculus@370
  2036
}
icculus@370
  2037
icculus@370
  2038
static int compute_huffman_codes(void)
icculus@370
  2039
{
icculus@370
  2040
   static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
icculus@370
  2041
   static zhuffman z_codelength; // static just to save stack space
icculus@370
  2042
   uint8 lencodes[286+32+137];//padding for maximum single op
icculus@370
  2043
   uint8 codelength_sizes[19];
icculus@370
  2044
   int i,n;
icculus@370
  2045
icculus@370
  2046
   int hlit  = zreceive(5) + 257;
icculus@370
  2047
   int hdist = zreceive(5) + 1;
icculus@370
  2048
   int hclen = zreceive(4) + 4;
icculus@370
  2049
icculus@370
  2050
   memset(codelength_sizes, 0, sizeof(codelength_sizes));
icculus@370
  2051
   for (i=0; i < hclen; ++i) {
icculus@370
  2052
      int s = zreceive(3);
icculus@370
  2053
      codelength_sizes[length_dezigzag[i]] = (uint8) s;
icculus@370
  2054
   }
icculus@370
  2055
   if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
icculus@370
  2056
icculus@370
  2057
   n = 0;
icculus@370
  2058
   while (n < hlit + hdist) {
icculus@370
  2059
      int c = zhuffman_decode(&z_codelength);
icculus@370
  2060
      assert(c >= 0 && c < 19);
icculus@370
  2061
      if (c < 16)
icculus@370
  2062
         lencodes[n++] = (uint8) c;
icculus@370
  2063
      else if (c == 16) {
icculus@370
  2064
         c = zreceive(2)+3;
icculus@370
  2065
         memset(lencodes+n, lencodes[n-1], c);
icculus@370
  2066
         n += c;
icculus@370
  2067
      } else if (c == 17) {
icculus@370
  2068
         c = zreceive(3)+3;
icculus@370
  2069
         memset(lencodes+n, 0, c);
icculus@370
  2070
         n += c;
icculus@370
  2071
      } else {
icculus@370
  2072
         assert(c == 18);
icculus@370
  2073
         c = zreceive(7)+11;
icculus@370
  2074
         memset(lencodes+n, 0, c);
icculus@370
  2075
         n += c;
icculus@370
  2076
      }
icculus@370
  2077
   }
icculus@370
  2078
   if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");
icculus@370
  2079
   if (!zbuild_huffman(&z_length, lencodes, hlit)) return 0;
icculus@370
  2080
   if (!zbuild_huffman(&z_distance, lencodes+hlit, hdist)) return 0;
icculus@370
  2081
   return 1;
icculus@370
  2082
}
icculus@370
  2083
icculus@370
  2084
static int parse_uncompressed_block(void)
icculus@370
  2085
{
icculus@370
  2086
   uint8 header[4];
icculus@370
  2087
   int len,nlen,k;
icculus@370
  2088
   if (num_bits & 7)
icculus@370
  2089
      zreceive(num_bits & 7); // discard
icculus@370
  2090
   // drain the bit-packed data into header
icculus@370
  2091
   k = 0;
icculus@370
  2092
   while (num_bits > 0) {
icculus@370
  2093
      header[k++] = (uint8) (code_buffer & 255); // wtf this warns?
icculus@370
  2094
      code_buffer >>= 8;
icculus@370
  2095
      num_bits -= 8;
icculus@370
  2096
   }
icculus@370
  2097
   assert(num_bits == 0);
icculus@370
  2098
   // now fill header the normal way
icculus@370
  2099
   while (k < 4)
icculus@370
  2100
      header[k++] = (uint8) zget8();
icculus@370
  2101
   len  = header[1] * 256 + header[0];
icculus@370
  2102
   nlen = header[3] * 256 + header[2];
icculus@370
  2103
   if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");
icculus@370
  2104
   if (zbuffer + len > zbuffer_end) return e("read past buffer","Corrupt PNG");
icculus@370
  2105
   if (zout + len > zout_end)
icculus@370
  2106
      if (!expand(len)) return 0;
icculus@370
  2107
   memcpy(zout, zbuffer, len);
icculus@370
  2108
   zbuffer += len;
icculus@370
  2109
   zout += len;
icculus@370
  2110
   return 1;
icculus@370
  2111
}
icculus@370
  2112
icculus@370
  2113
static int parse_zlib_header(void)
icculus@370
  2114
{
icculus@370
  2115
   int cmf   = zget8();
icculus@370
  2116
   int cm    = cmf & 15;
icculus@370
  2117
   /* int cinfo = cmf >> 4; */
icculus@370
  2118
   int flg   = zget8();
icculus@370
  2119
   if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec
icculus@370
  2120
   if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
icculus@370
  2121
   if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png
icculus@370
  2122
   // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
icculus@370
  2123
   return 1;
icculus@370
  2124
}
icculus@370
  2125
icculus@370
  2126
static uint8 default_length[288], default_distance[32];
icculus@370
  2127
static void init_defaults(void)
icculus@370
  2128
{
icculus@370
  2129
   int i;   // use <= to match clearly with spec
icculus@370
  2130
   for (i=0; i <= 143; ++i)     default_length[i]   = 8;
icculus@370
  2131
   for (   ; i <= 255; ++i)     default_length[i]   = 9;
icculus@370
  2132
   for (   ; i <= 279; ++i)     default_length[i]   = 7;
icculus@370
  2133
   for (   ; i <= 287; ++i)     default_length[i]   = 8;
icculus@370
  2134
icculus@370
  2135
   for (i=0; i <=  31; ++i)     default_distance[i] = 5;
icculus@370
  2136
}
icculus@370
  2137
icculus@370
  2138
static int parse_zlib(int parse_header)
icculus@370
  2139
{
icculus@370
  2140
   int final, type;
icculus@370
  2141
   if (parse_header)
icculus@370
  2142
      if (!parse_zlib_header()) return 0;
icculus@370
  2143
   num_bits = 0;
icculus@370
  2144
   code_buffer = 0;
icculus@370
  2145
   do {
icculus@370
  2146
      final = zreceive(1);
icculus@370
  2147
      type = zreceive(2);
icculus@370
  2148
      if (type == 0) {
icculus@370
  2149
         if (!parse_uncompressed_block()) return 0;
icculus@370
  2150
      } else if (type == 3) {
icculus@370
  2151
         return 0;
icculus@370
  2152
      } else {
icculus@370
  2153
         if (type == 1) {
icculus@370
  2154
            // use fixed code lengths
icculus@370
  2155
            if (!default_length[0]) init_defaults();
icculus@370
  2156
            if (!zbuild_huffman(&z_length  , default_length  , 288)) return 0;
icculus@370
  2157
            if (!zbuild_huffman(&z_distance, default_distance,  32)) return 0;
icculus@370
  2158
         } else {
icculus@370
  2159
            if (!compute_huffman_codes()) return 0;
icculus@370
  2160
         }
icculus@370
  2161
         if (!parse_huffman_block()) return 0;
icculus@370
  2162
      }
icculus@370
  2163
   } while (!final);
icculus@370
  2164
   return 1;
icculus@370
  2165
}
icculus@370
  2166
icculus@370
  2167
static int do_zlib(char *obuf, int olen, int exp, int parse_header)
icculus@370
  2168
{
icculus@370
  2169
   zout_start = obuf;
icculus@370
  2170
   zout       = obuf;
icculus@370
  2171
   zout_end   = obuf + olen;
icculus@370
  2172
   z_expandable = exp;
icculus@370
  2173
icculus@370
  2174
   return parse_zlib(parse_header);
icculus@370
  2175
}
icculus@370
  2176
icculus@370
  2177
char *stbi_zlib_decode_malloc_guesssize(int initial_size, int *outlen)
icculus@370
  2178
{
icculus@370
  2179
   char *p = (char *) malloc(initial_size);
icculus@370
  2180
   if (p == NULL) return NULL;
icculus@370
  2181
   if (do_zlib(p, initial_size, 1, 1)) {
icculus@370
  2182
      *outlen = (int) (zout - zout_start);
icculus@370
  2183
      return zout_start;
icculus@370
  2184
   } else {
icculus@370
  2185
      free(zout_start);
icculus@370
  2186
      return NULL;
icculus@370
  2187
   }
icculus@370
  2188
}
icculus@370
  2189
icculus@370
  2190
char *stbi_zlib_decode_malloc(char *buffer, int len, int *outlen)
icculus@370
  2191
{
icculus@370
  2192
   zbuffer = (uint8 *) buffer;
icculus@370
  2193
   zbuffer_end = (uint8 *) buffer+len;
icculus@370
  2194
   return stbi_zlib_decode_malloc_guesssize(16384, outlen);
icculus@370
  2195
}
icculus@370
  2196
icculus@370
  2197
int stbi_zlib_decode_buffer(char *obuffer, int olen, char *ibuffer, int ilen)
icculus@370
  2198
{
icculus@370
  2199
   zbuffer = (uint8 *) ibuffer;
icculus@370
  2200
   zbuffer_end = (uint8 *) ibuffer + ilen;
icculus@370
  2201
   if (do_zlib(obuffer, olen, 0, 1))
icculus@370
  2202
      return (int) (zout - zout_start);
icculus@370
  2203
   else
icculus@370
  2204
      return -1;
icculus@370
  2205
}
icculus@370
  2206
icculus@370
  2207
char *stbi_zlib_decode_noheader_malloc(char *buffer, int len, int *outlen)
icculus@370
  2208
{
icculus@370
  2209
   char *p = (char *) malloc(16384);
icculus@370
  2210
   if (p == NULL) return NULL;
icculus@370
  2211
   zbuffer = (uint8 *) buffer;
icculus@370
  2212
   zbuffer_end = (uint8 *) buffer+len;
icculus@370
  2213
   if (do_zlib(p, 16384, 1, 0)) {
icculus@370
  2214
      *outlen = (int) (zout - zout_start);
icculus@370
  2215
      return zout_start;
icculus@370
  2216
   } else {
icculus@370
  2217
      free(zout_start);
icculus@370
  2218
      return NULL;
icculus@370
  2219
   }
icculus@370
  2220
}
icculus@370
  2221
icculus@370
  2222
int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, char *ibuffer, int ilen)
icculus@370
  2223
{
icculus@370
  2224
   zbuffer = (uint8 *) ibuffer;
icculus@370
  2225
   zbuffer_end = (uint8 *) ibuffer + ilen;
icculus@370
  2226
   if (do_zlib(obuffer, olen, 0, 0))
icculus@370
  2227
      return (int) (zout - zout_start);
icculus@370
  2228
   else
icculus@370
  2229
      return -1;
icculus@370
  2230
}
icculus@370
  2231
icculus@371
  2232
#endif  // __MOJOSETUP__
icculus@371
  2233
icculus@371
  2234
icculus@371
  2235
#ifndef STBI_NO_PNG  // __MOJOSETUP__
icculus@371
  2236
icculus@370
  2237
// public domain "baseline" PNG decoder   v0.10  Sean Barrett 2006-11-18
icculus@370
  2238
//    simple implementation
icculus@370
  2239
//      - only 8-bit samples
icculus@370
  2240
//      - no CRC checking
icculus@370
  2241
//      - allocates lots of intermediate memory
icculus@370
  2242
//        - avoids problem of streaming data between subsystems
icculus@370
  2243
//        - avoids explicit window management
icculus@370
  2244
//    performance
icculus@370
  2245
//      - uses stb_zlib, a PD zlib implementation with fast huffman decoding
icculus@370
  2246
icculus@370
  2247
icculus@370
  2248
typedef struct
icculus@370
  2249
{
icculus@370
  2250
   unsigned long length;
icculus@370
  2251
   unsigned long type;
icculus@370
  2252
} chunk;
icculus@370
  2253
icculus@370
  2254
#define PNG_TYPE(a,b,c,d)  (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
icculus@370
  2255
icculus@370
  2256
static chunk get_chunk_header(void)
icculus@370
  2257
{
icculus@370
  2258
   chunk c;
icculus@370
  2259
   c.length = get32();
icculus@370
  2260
   c.type   = get32();
icculus@370
  2261
   return c;
icculus@370
  2262
}
icculus@370
  2263
icculus@370
  2264
static int check_png_header(void)
icculus@370
  2265
{
icculus@370
  2266
   static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };
icculus@370
  2267
   int i;
icculus@370
  2268
   for (i=0; i < 8; ++i)
icculus@370
  2269
      if (get8() != png_sig[i]) return e("bad png sig","Not a PNG");
icculus@370
  2270
   return 1;
icculus@370
  2271
}
icculus@370
  2272
icculus@375
  2273
#if !__MOJOSETUP__  // moved elsewhere for #ifdef safety.
icculus@370
  2274
static uint8 *idata, *expanded, *out;
icculus@375
  2275
#endif
icculus@370
  2276
icculus@370
  2277
enum {
icculus@370
  2278
   F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,
icculus@370
  2279
   F_avg_first, F_paeth_first,
icculus@370
  2280
};
icculus@370
  2281
icculus@370
  2282
static uint8 first_row_filter[5] =
icculus@370
  2283
{
icculus@370
  2284
   F_none, F_sub, F_none, F_avg_first, F_paeth_first
icculus@370
  2285
};
icculus@370
  2286
icculus@370
  2287
static int paeth(int a, int b, int c)
icculus@370
  2288
{
icculus@370
  2289
   int p = a + b - c;
icculus@370
  2290
   int pa = abs(p-a);
icculus@370
  2291
   int pb = abs(p-b);
icculus@370
  2292
   int pc = abs(p-c);
icculus@370
  2293
   if (pa <= pb && pa <= pc) return a;
icculus@370
  2294
   if (pb <= pc) return b;
icculus@370
  2295
   return c;
icculus@370
  2296
}
icculus@370
  2297
icculus@370
  2298
// create the png data from post-deflated data
icculus@370
  2299
static int create_png_image(uint8 *raw, uint32 raw_len, int out_n)
icculus@370
  2300
{
icculus@370
  2301
   uint32 i,j,stride = img_x*out_n;
icculus@370
  2302
   int k;
icculus@370
  2303
   assert(out_n == img_n || out_n == img_n+1);
icculus@370
  2304
   out = (uint8 *) malloc(img_x * img_y * out_n);
icculus@370
  2305
   if (!out) return e("outofmem", "Out of memory");
icculus@370
  2306
   if (raw_len != (img_n * img_x + 1) * img_y) return e("not enough pixels","Corrupt PNG");
icculus@370
  2307
   for (j=0; j < img_y; ++j) {
icculus@370
  2308
      uint8 *cur = out + stride*j;
icculus@370
  2309
      uint8 *prior = cur - stride;
icculus@370
  2310
      int filter = *raw++;
icculus@370
  2311
      if (filter > 4) return e("invalid filter","Corrupt PNG");
icculus@370
  2312
      // if first row, use special filter that doesn't sample previous row
icculus@370
  2313
      if (j == 0) filter = first_row_filter[filter];
icculus@370
  2314
      // handle first pixel explicitly
icculus@370
  2315
      for (k=0; k < img_n; ++k) {
icculus@370
  2316
         switch(filter) {
icculus@370
  2317
            case F_none       : cur[k] = raw[k]; break;
icculus@370
  2318
            case F_sub        : cur[k] = raw[k]; break;
icculus@370
  2319
            case F_up         : cur[k] = raw[k] + prior[k]; break;
icculus@370
  2320
            case F_avg        : cur[k] = raw[k] + (prior[k]>>1); break;
icculus@370
  2321
            case F_paeth      : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;
icculus@370
  2322
            case F_avg_first  : cur[k] = raw[k]; break;
icculus@370
  2323
            case F_paeth_first: cur[k] = raw[k]; break;
icculus@370
  2324
         }
icculus@370
  2325
      }
icculus@370
  2326
      if (img_n != out_n) cur[img_n] = 255;
icculus@370
  2327
      raw += img_n;
icculus@370
  2328
      cur += out_n;
icculus@370
  2329
      prior += out_n;
icculus@370
  2330
      // this is a little gross, so that we don't switch per-pixel or per-component
icculus@370
  2331
      if (img_n == out_n) {
icculus@370
  2332
         #define CASE(f) \
icculus@370
  2333
             case f:     \
icculus@370
  2334
                for (i=1; i < img_x; ++i, raw+=img_n,cur+=img_n,prior+=img_n) \
icculus@370
  2335
                   for (k=0; k < img_n; ++k)
icculus@370
  2336
         switch(filter) {
icculus@370
  2337
            CASE(F_none)  cur[k] = raw[k]; break;
icculus@370
  2338
            CASE(F_sub)   cur[k] = raw[k] + cur[k-img_n]; break;
icculus@370
  2339
            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;
icculus@370
  2340
            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;
icculus@370
  2341
            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
icculus@370
  2342
            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-img_n] >> 1); break;
icculus@370
  2343
            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;
icculus@370
  2344
         }
icculus@370
  2345
         #undef CASE
icculus@370
  2346
      } else {
icculus@370
  2347
         assert(img_n+1 == out_n);
icculus@370
  2348
         #define CASE(f) \
icculus@370
  2349
             case f:     \
icculus@370
  2350
                for (i=1; i < img_x; ++i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
icculus@370
  2351
                   for (k=0; k < img_n; ++k)
icculus@370
  2352
         switch(filter) {
icculus@370
  2353
            CASE(F_none)  cur[k] = raw[k]; break;
icculus@370
  2354
            CASE(F_sub)   cur[k] = raw[k] + cur[k-out_n]; break;
icculus@370
  2355
            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;
icculus@370
  2356
            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;
icculus@370
  2357
            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
icculus@370
  2358
            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-out_n] >> 1); break;
icculus@370
  2359
            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;
icculus@370
  2360
         }
icculus@370
  2361
         #undef CASE
icculus@370
  2362
      }
icculus@370
  2363
   }
icculus@370
  2364
   return 1;
icculus@370
  2365
}
icculus@370
  2366
icculus@370
  2367
static int compute_transparency(uint8 tc[3], int out_n)
icculus@370
  2368
{
icculus@370
  2369
   uint32 i, pixel_count = img_x * img_y;
icculus@370
  2370
   uint8 *p = out;
icculus@370
  2371
icculus@370
  2372
   // compute color-based transparency, assuming we've
icculus@370
  2373
   // already got 255 as the alpha value in the output
icculus@370
  2374
   assert(out_n == 2 || out_n == 4);
icculus@370
  2375
icculus@370
  2376
   if (out_n == 2) {
icculus@370
  2377
      for (i=0; i < pixel_count; ++i) {
icculus@370
  2378
         p[1] = (p[0] == tc[0] ? 0 : 255);
icculus@370
  2379
         p += 2;
icculus@370
  2380
      }
icculus@370
  2381
   } else {
icculus@370
  2382
      for (i=0; i < pixel_count; ++i) {
icculus@370
  2383
         if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
icculus@370
  2384
            p[3] = 0;
icculus@370
  2385
         p += 4;
icculus@370
  2386
      }
icculus@370
  2387
   }
icculus@370
  2388
   return 1;
icculus@370
  2389
}
icculus@370
  2390
icculus@370
  2391
static int expand_palette(uint8 *palette, int len, int pal_img_n)
icculus@370
  2392
{
icculus@370
  2393
   uint32 i, pixel_count = img_x * img_y;
icculus@370
  2394
   uint8 *p, *temp_out, *orig = out;
icculus@370
  2395
icculus@370
  2396
   p = (uint8 *) malloc(pixel_count * pal_img_n);
icculus@370
  2397
   if (p == NULL) return e("outofmem", "Out of memory");
icculus@370
  2398
icculus@370
  2399
   // between here and free(out) below, exitting would leak
icculus@370
  2400
   temp_out = p;
icculus@370
  2401
icculus@370
  2402
   if (pal_img_n == 3) {
icculus@370
  2403
      for (i=0; i < pixel_count; ++i) {
icculus@370
  2404
         int n = orig[i]*4;
icculus@370
  2405
         p[0] = palette[n  ];
icculus@370
  2406
         p[1] = palette[n+1];
icculus@370
  2407
         p[2] = palette[n+2];
icculus@370
  2408
         p += 3;
icculus@370
  2409
      }
icculus@370
  2410
   } else {
icculus@370
  2411
      for (i=0; i < pixel_count; ++i) {
icculus@370
  2412
         int n = orig[i]*4;
icculus@370
  2413
         p[0] = palette[n  ];
icculus@370
  2414
         p[1] = palette[n+1];
icculus@370
  2415
         p[2] = palette[n+2];
icculus@370
  2416
         p[3] = palette[n+3];
icculus@370
  2417
         p += 4;
icculus@370
  2418
      }
icculus@370
  2419
   }
icculus@370
  2420
   free(out);
icculus@370
  2421
   out = temp_out;
icculus@370
  2422
   return 1;
icculus@370
  2423
}
icculus@370
  2424
icculus@370
  2425
static int parse_png_file(int scan, int req_comp)
icculus@370
  2426
{
icculus@370
  2427
   uint8 palette[1024], pal_img_n=0;
icculus@370
  2428
   uint8 has_trans=0, tc[3];
icculus@370
  2429
   uint32 ioff=0, idata_limit=0, i, pal_len=0;
icculus@370
  2430
   int first=1,k;
icculus@370
  2431
icculus@370
  2432
   if (!check_png_header()) return 0;
icculus@370
  2433
icculus@370
  2434
   if (scan == SCAN_type) return 1;
icculus@370
  2435
icculus@370
  2436
   for(;;first=0) {
icculus@370
  2437
      chunk c = get_chunk_header();
icculus@370
  2438
      if (first && c.type != PNG_TYPE('I','H','D','R'))
icculus@370
  2439
         return e("first not IHDR","Corrupt PNG");
icculus@370
  2440
      switch (c.type) {
icculus@370
  2441
         case PNG_TYPE('I','H','D','R'): {
icculus@370
  2442
            int depth,color,interlace,comp,filter;
icculus@370
  2443
            if (!first) return e("multiple IHDR","Corrupt PNG");
icculus@370
  2444
            if (c.length != 13) return e("bad IHDR len","Corrupt PNG");
icculus@370
  2445
            img_x = get32(); if (img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");
icculus@370
  2446
            img_y = get32(); if (img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");
icculus@370
  2447
            depth = get8();  if (depth != 8)        return e("8bit only","PNG not supported: 8-bit only");
icculus@370
  2448
            color = get8();  if (color > 6)         return e("bad ctype","Corrupt PNG");
icculus@370
  2449
            if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");
icculus@370
  2450
            comp  = get8();  if (comp) return e("bad comp method","Corrupt PNG");
icculus@370
  2451
            filter= get8();  if (filter) return e("bad filter method","Corrupt PNG");
icculus@370
  2452
            interlace = get8(); if (interlace) return e("interlaced","PNG not supported: interlaced mode");
icculus@370
  2453
            if (!img_x || !img_y) return e("0-pixel image","Corrupt PNG");
icculus@370
  2454
            if (!pal_img_n) {
icculus@370
  2455
               img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
icculus@370
  2456
               if ((1 << 30) / img_x / img_n < img_y) return e("too large", "Image too large to decode");
icculus@370
  2457
               if (scan == SCAN_header) return 1;
icculus@370
  2458
            } else {
icculus@370
  2459
               // if paletted, then pal_n is our final components, and
icculus@370
  2460
               // img_n is # components to decompress/filter.
icculus@370
  2461
               img_n = 1;
icculus@370
  2462
               if ((1 << 30) / img_x / 4 < img_y) return e("too large","Corrupt PNG");
icculus@370
  2463
               // if SCAN_header, have to scan to see if we have a tRNS
icculus@370
  2464
            }
icculus@370
  2465
            break;
icculus@370
  2466
         }
icculus@370
  2467
icculus@370
  2468
         case PNG_TYPE('P','L','T','E'):  {
icculus@370
  2469
            if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");
icculus@370
  2470
            pal_len = c.length / 3;
icculus@370
  2471
            if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");
icculus@370
  2472
            for (i=0; i < pal_len; ++i) {
icculus@370
  2473
               palette[i*4+0] = get8u();
icculus@370
  2474
               palette[i*4+1] = get8u();
icculus@370
  2475
               palette[i*4+2] = get8u();
icculus@370
  2476
               palette[i*4+3] = 255;
icculus@370
  2477
            }
icculus@370
  2478
            break;
icculus@370
  2479
         }
icculus@370
  2480
icculus@370
  2481
         case PNG_TYPE('t','R','N','S'): {
icculus@370
  2482
            if (idata) return e("tRNS after IDAT","Corrupt PNG");
icculus@370
  2483
            if (pal_img_n) {
icculus@370
  2484
               if (scan == SCAN_header) { img_n = 4; return 1; }
icculus@370
  2485
               if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");
icculus@370
  2486
               if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");
icculus@370
  2487
               pal_img_n = 4;
icculus@370
  2488
               for (i=0; i < c.length; ++i)
icculus@370
  2489
                  palette[i*4+3] = get8u();
icculus@370
  2490
            } else {
icculus@370
  2491
               if (!(img_n & 1)) return e("tRNS with alpha","Corrupt PNG");
icculus@370
  2492
               if (c.length != (uint32) img_n*2) return e("bad tRNS len","Corrupt PNG");
icculus@370
  2493
               has_trans = 1;
icculus@370
  2494
               for (k=0; k < img_n; ++k)
icculus@370
  2495
                  tc[k] = (uint8) get16(); // non 8-bit images will be larger
icculus@370
  2496
            }
icculus@370
  2497
            break;
icculus@370
  2498
         }
icculus@370
  2499
icculus@370
  2500
         case PNG_TYPE('I','D','A','T'): {
icculus@370
  2501
            if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");
icculus@370
  2502
            if (scan == SCAN_header) { img_n = pal_img_n; return 1; }
icculus@370
  2503
            if (ioff + c.length > idata_limit) {
icculus@370
  2504
               uint8 *p;
icculus@370
  2505
               if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
icculus@370
  2506
               while (ioff + c.length > idata_limit)
icculus@370
  2507
                  idata_limit *= 2;
icculus@370
  2508
               p = (uint8 *) realloc(idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");
icculus@370
  2509
               idata = p;
icculus@370
  2510
            }
icculus@370
  2511
            #ifndef STBI_NO_STDIO
icculus@370
  2512
            if (img_file)
icculus@370
  2513
            {
icculus@370
  2514
               if (fread(idata+ioff,1,c.length,img_file) != c.length) return e("outofdata","Corrupt PNG");
icculus@370
  2515
            }
icculus@370
  2516
            else
icculus@370
  2517
            #endif
icculus@370
  2518
            {
icculus@370
  2519
               memcpy(idata+ioff, img_buffer, c.length);
icculus@370
  2520
               img_buffer += c.length;
icculus@370
  2521
            }
icculus@370
  2522
            ioff += c.length;
icculus@370
  2523
            break;
icculus@370
  2524
         }
icculus@370
  2525
icculus@370
  2526
         case PNG_TYPE('I','E','N','D'): {
icculus@370
  2527
            uint32 raw_len;
icculus@370
  2528
            if (scan != SCAN_load) return 1;
icculus@370
  2529
            if (idata == NULL) return e("no IDAT","Corrupt PNG");
icculus@370
  2530
            expanded = (uint8 *) stbi_zlib_decode_malloc((char *) idata, ioff, (int *) &raw_len);
icculus@370
  2531
            if (expanded == NULL) return 0; // zlib should set error
icculus@370
  2532
            free(idata); idata = NULL;
icculus@370
  2533
            if ((req_comp == img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
icculus@370
  2534
               img_out_n = img_n+1;
icculus@370
  2535
            else
icculus@370
  2536
               img_out_n = img_n;
icculus@370
  2537
            if (!create_png_image(expanded, raw_len, img_out_n)) return 0;
icculus@370
  2538
            if (has_trans)
icculus@370
  2539
               if (!compute_transparency(tc, img_out_n)) return 0;
icculus@370
  2540
            if (pal_img_n) {
icculus@370
  2541
               // pal_img_n == 3 or 4
icculus@370
  2542
               img_n = pal_img_n; // record the actual colors we had
icculus@370
  2543
               img_out_n = pal_img_n;
icculus@370
  2544
               if (req_comp >= 3) img_out_n = req_comp;
icculus@370
  2545
               if (!expand_palette(palette, pal_len, img_out_n))
icculus@370
  2546
                  return 0;
icculus@370
  2547
            }
icculus@370
  2548
            free(expanded); expanded = NULL;
icculus@370
  2549
            return 1;
icculus@370
  2550
         }
icculus@370
  2551
icculus@370
  2552
         default:
icculus@370
  2553
            // if critical, fail
icculus@370
  2554
            if ((c.type & (1 << 29)) == 0) {
icculus@370
  2555
               #ifndef STBI_NO_FAILURE_STRINGS
icculus@370
  2556
               static char invalid_chunk[] = "XXXX chunk not known";
icculus@370
  2557
               invalid_chunk[0] = (uint8) (c.type >> 24);
icculus@370
  2558
               invalid_chunk[1] = (uint8) (c.type >> 16);
icculus@370
  2559
               invalid_chunk[2] = (uint8) (c.type >>  8);
icculus@370
  2560
               invalid_chunk[3] = (uint8) (c.type >>  0);
icculus@370
  2561
               #endif
icculus@370
  2562
               return e(invalid_chunk, "PNG not supported: unknown chunk type");
icculus@370
  2563
            }
icculus@370
  2564
            skip(c.length);
icculus@370
  2565
            break;
icculus@370
  2566
      }
icculus@370
  2567
      // end of chunk, read and skip CRC
icculus@370
  2568
      get8(); get8(); get8(); get8();
icculus@370
  2569
   }
icculus@370
  2570
}
icculus@370
  2571
icculus@370
  2572
static unsigned char *do_png(int *x, int *y, int *n, int req_comp)
icculus@370
  2573
{
icculus@370
  2574
   unsigned char *result=NULL;
icculus@370
  2575
   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
icculus@370
  2576
   if (parse_png_file(SCAN_load, req_comp)) {
icculus@370
  2577
      result = out;
icculus@370
  2578
      out = NULL;
icculus@370
  2579
      if (req_comp && req_comp != img_out_n) {
icculus@370
  2580
         result = convert_format(result, img_out_n, req_comp);
icculus@370
  2581
         if (result == NULL) return result;
icculus@370
  2582
      }
icculus@370
  2583
      *x = img_x;
icculus@370
  2584
      *y = img_y;
icculus@370
  2585
      if (n) *n = img_n;
icculus@370
  2586
   }
icculus@370
  2587
   free(out);      out      = NULL;
icculus@370
  2588
   free(expanded); expanded = NULL;
icculus@370
  2589
   free(idata);    idata    = NULL;
icculus@370
  2590
icculus@370
  2591
   return result;
icculus@370
  2592
}
icculus@370
  2593
icculus@370
  2594
#ifndef STBI_NO_STDIO
icculus@370
  2595
unsigned char *stbi_png_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
icculus@370
  2596
{
icculus@370
  2597
   start_file(f);
icculus@370
  2598
   return do_png(x,y,comp,req_comp);
icculus@370
  2599
}
icculus@370
  2600
icculus@370
  2601
unsigned char *stbi_png_load(char *filename, int *x, int *y, int *comp, int req_comp)
icculus@370
  2602
{
icculus@370
  2603
   unsigned char *data;
icculus@370
  2604
   FILE *f = fopen(filename, "rb");
icculus@370
  2605
   if (!f) return NULL;
icculus@370
  2606
   data = stbi_png_load_from_file(f,x,y,comp,req_comp);
icculus@370
  2607
   fclose(f);
icculus@370
  2608
   return data;
icculus@370
  2609
}
icculus@370
  2610
#endif
icculus@370
  2611
icculus@370
  2612
unsigned char *stbi_png_load_from_memory(unsigned char *buffer, int len, int *x, int *y, int *comp, int req_comp)
icculus@370
  2613
{
icculus@370
  2614
   start_mem(buffer,len);
icculus@370
  2615
   return do_png(x,y,comp,req_comp);
icculus@370
  2616
}
icculus@370
  2617
icculus@370
  2618
#ifndef STBI_NO_STDIO
icculus@370
  2619
int stbi_png_test_file(FILE *f)
icculus@370
  2620
{
icculus@370
  2621
   int n,r;
icculus@370
  2622
   n = ftell(f);
icculus@370
  2623
   start_file(f);
icculus@370
  2624
   r = parse_png_file(SCAN_type,STBI_default);
icculus@370
  2625
   fseek(f,n,SEEK_SET);
icculus@370
  2626
   return r;
icculus@370
  2627
}
icculus@370
  2628
#endif
icculus@370
  2629
icculus@371
  2630
#endif  // __MOJOSETUP__
icculus@371
  2631
icculus@370
  2632
int stbi_png_test_memory(unsigned char *buffer, int len)
icculus@370
  2633
{
icculus@371
  2634
#ifndef STBI_NO_PNG  // __MOJOSETUP__
icculus@370
  2635
   start_mem(buffer, len);
icculus@370
  2636
   return parse_png_file(SCAN_type,STBI_default);
icculus@371
  2637
#else
icculus@371
  2638
   return 0;
icculus@371
  2639
#endif  // __MOJOSETUP__
icculus@370
  2640
}
icculus@370
  2641
icculus@370
  2642
// TODO: load header from png
icculus@370
  2643
#ifndef STBI_NO_STDIO
icculus@370
  2644
extern int      stbi_png_info             (char *filename,           int *x, int *y, int *comp);
icculus@370
  2645
extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);
icculus@370
  2646
#endif
icculus@370
  2647
extern int      stbi_png_info_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp);
icculus@370
  2648
icculus@371
  2649
icculus@371
  2650
#ifndef STBI_NO_BMP  // __MOJOSETUP__
icculus@371
  2651
icculus@370
  2652
// Microsoft/Windows BMP image
icculus@370
  2653
icculus@370
  2654
static int bmp_test(void)
icculus@370
  2655
{
icculus@370
  2656
   int sz;
icculus@370
  2657
   if (get8() != 'B') return 0;
icculus@370
  2658
   if (get8() != 'M') return 0;
icculus@370
  2659
   get32le(); // discard filesize
icculus@370
  2660
   get16le(); // discard reserved
icculus@370
  2661
   get16le(); // discard reserved
icculus@370
  2662
   get32le(); // discard data offset
icculus@370
  2663
   sz = get32le();
icculus@370
  2664
   if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;
icculus@370
  2665
   return 0;
icculus@370
  2666
}
icculus@370
  2667
icculus@370
  2668
#ifndef STBI_NO_STDIO
icculus@370
  2669
int      stbi_bmp_test_file        (FILE *f)
icculus@370
  2670
{
icculus@370
  2671
   int r,n = ftell(f);
icculus@370
  2672
   start_file(f);
icculus@370
  2673
   r = bmp_test();
icculus@370
  2674
   fseek(f,n,SEEK_SET);
icculus@370
  2675
   return r;
icculus@370
  2676
}
icculus@370
  2677
#endif
icculus@370
  2678
icculus@371
  2679
#endif  // __MOJOSETUP__
icculus@371
  2680
icculus@371
  2681
icculus@370
  2682
int      stbi_bmp_test_memory      (stbi_uc *buffer, int len)
icculus@370
  2683
{
icculus@371
  2684
#ifndef STBI_NO_BMP  // __MOJOSETUP__
icculus@370
  2685
   start_mem(buffer, len);
icculus@370
  2686
   return bmp_test();
icculus@371
  2687
#else
icculus@371
  2688
   return 0;
icculus@371
  2689
#endif  // __MOJOSETUP__
icculus@370
  2690
}
icculus@370
  2691
icculus@371
  2692
icculus@371
  2693
#ifndef STBI_NO_BMP  // __MOJOSETUP__
icculus@371
  2694
icculus@370
  2695
// returns 0..31 for the highest set bit
icculus@370
  2696
static int high_bit(unsigned int z)
icculus@370
  2697
{
icculus@370
  2698
   int n=0;
icculus@370
  2699
   if (z == 0) return -1;
icculus@370
  2700
   if (z >= 0x10000) n += 16, z >>= 16;
icculus@370
  2701
   if (z >= 0x00100) n +=  8, z >>=  8;
icculus@370
  2702
   if (z >= 0x00010) n +=  4, z >>=  4;
icculus@370
  2703
   if (z >= 0x00004) n +=  2, z >>=  2;
icculus@370
  2704
   if (z >= 0x00002) n +=  1, z >>=  1;
icculus@370
  2705
   return n;
icculus@370
  2706
}
icculus@370
  2707
icculus@370
  2708
static int bitcount(unsigned int a)
icculus@370
  2709
{
icculus@370
  2710
   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2
icculus@370
  2711
   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4
icculus@370
  2712
   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
icculus@370
  2713
   a = (a + (a >> 8)); // max 16 per 8 bits
icculus@370
  2714
   a = (a + (a >> 16)); // max 32 per 8 bits
icculus@370
  2715
   return a & 0xff;
icculus@370
  2716
}
icculus@370
  2717
icculus@370
  2718
static int shiftsigned(int v, int shift, int bits)
icculus@370
  2719
{
icculus@370
  2720
   int result;
icculus@370
  2721
   int z=0;
icculus@370
  2722
icculus@370
  2723
   if (shift < 0) v <<= -shift;
icculus@370
  2724
   else v >>= shift;
icculus@370
  2725
   result = v;
icculus@370
  2726
icculus@370
  2727
   z = bits;
icculus@370
  2728
   while (z < 8) {
icculus@370
  2729
      result += v >> z;
icculus@370
  2730
      z += bits;
icculus@370
  2731
   }
icculus@370
  2732
   return result;
icculus@370
  2733
}
icculus@370
  2734
icculus@370
  2735
static stbi_uc *bmp_load(int *x, int *y, int *comp, int req_comp)
icculus@370
  2736
{
icculus@370
  2737
   unsigned int mr=0,mg=0,mb=0,ma=0;
icculus@370
  2738
   stbi_uc pal[256][4];
icculus@370
  2739
   int psize=0,i,j,compress=0,width;
icculus@370
  2740
   int bpp, flip_vertically, pad, target, offset, hsz;
icculus@370
  2741
   if (get8() != 'B' || get8() != 'M') return epuc("not BMP", "Corrupt BMP");
icculus@370
  2742
   get32le(); // discard filesize
icculus@370
  2743
   get16le(); // discard reserved
icculus@370
  2744
   get16le(); // discard reserved
icculus@370
  2745
   offset = get32le();
icculus@370
  2746
   hsz = get32le();
icculus@370
  2747
   if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");
icculus@370
  2748
   failure_reason = "bad BMP";
icculus@370
  2749
   if (hsz == 12) {
icculus@370
  2750
      img_x = get16le();
icculus@370
  2751
      img_y = get16le();
icculus@370
  2752
   } else {
icculus@370
  2753
      img_x = get32le();
icculus@370
  2754
      img_y = get32le();
icculus@370
  2755
   }
icculus@370
  2756
   if (get16le() != 1) return 0;
icculus@370
  2757
   bpp = get16le();
icculus@370
  2758
   if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");
icculus@370
  2759
   flip_vertically = ((int) img_y) > 0;
icculus@370
  2760
   img_y = abs((int) img_y);
icculus@370
  2761
   if (hsz == 12) {
icculus@370
  2762
      if (bpp < 24)
icculus@370
  2763
         psize = (offset - 14 - 24) / 3;
icculus@370
  2764
   } else {
icculus@370
  2765
      compress = get32le();
icculus@370
  2766
      if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");
icculus@370
  2767
      get32le(); // discard sizeof
icculus@370
  2768
      get32le(); // discard hres
icculus@370
  2769
      get32le(); // discard vres
icculus@370
  2770