Merge branch 'master' into working
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
51 files+3280 added−4412 removed
- tests:+0 added−0 removed
- other:+3280 added−4412 removed
Provenance
- Commit
6e9f34d- Tree
57b2f31- Author
Sean Barrett <seanb@radgametools.com>- Committer
Sean Barrett <seanb@radgametools.com>- Parent 1
177b6c6- Parent 2
449758b
51 files changed+3280 added−4412 removed
This commit is too large to show whole: its files are listed by path, without their changes.
added:.github/ISSUE_TEMPLATE/bug_report.md+24 added
1+---2+name: Bug report3+about: if you're having trouble using a library, try the support forum instead4+title: ''5+labels: ''6+assignees: ''7+8+---9+10+**Describe the bug**11+A clear and concise description of what the bug is.12+13+**To Reproduce**14+Steps to reproduce the behavior:15+1. Go to '...'16+2. Click on '....'17+3. Scroll down to '....'18+4. See error19+20+**Expected behavior**21+A clear and concise description of what you expected to happen.22+23+**Screenshots**24+If applicable, add screenshots to help explain your problem.added:.github/ISSUE_TEMPLATE/config.yml+4 added
1+contact_links:2+ - name: support forum3+ url: https://github.com/nothings/stb/discussions/categories/q-a4+ about: having trouble using an stb library? don't create an issue, post in the forumadded:.github/ISSUE_TEMPLATE/feature_request.md+20 added
1+---2+name: Feature request3+about: Suggest an idea for this project4+title: ''5+labels: 4 enhancement6+assignees: ''7+8+---9+10+**Is your feature request related to a problem? Please describe.**11+A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]12+13+**Describe the solution you'd like**14+A clear and concise description of what you want to happen.15+16+**Describe alternatives you've considered**17+A clear and concise description of any alternative solutions or features you've considered.18+19+**Additional context**20+Add any other context or screenshots about the feature request here.added:.github/workflows/ci-fuzz.yml+23 added
1+name: CIFuzz2+on: [pull_request]3+jobs:4+ Fuzzing:5+ runs-on: ubuntu-latest6+ steps:7+ - name: Build Fuzzers8+ uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master9+ with:10+ oss-fuzz-project-name: 'stb'11+ dry-run: false12+ - name: Run Fuzzers13+ uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master14+ with:15+ oss-fuzz-project-name: 'stb'16+ fuzz-seconds: 90017+ dry-run: false18+ - name: Upload Crash19+ uses: actions/upload-artifact@v120+ if: failure()21+ with:22+ name: artifacts23+ path: ./out/artifactsadded:deprecated/stb_image_resize.h+2634 added
1+/* stb_image_resize - v0.97 - public domain image resizing2+ by Jorge L Rodriguez (@VinoBS) - 20143+ http://github.com/nothings/stb4+5+ Written with emphasis on usability, portability, and efficiency. (No6+ SIMD or threads, so it be easily outperformed by libs that use those.)7+ Only scaling and translation is supported, no rotations or shears.8+ Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation.9+10+ COMPILING & LINKING11+ In one C/C++ file that #includes this file, do this:12+ #define STB_IMAGE_RESIZE_IMPLEMENTATION13+ before the #include. That will create the implementation in that file.14+15+ QUICKSTART16+ stbir_resize_uint8( input_pixels , in_w , in_h , 0,17+ output_pixels, out_w, out_h, 0, num_channels)18+ stbir_resize_float(...)19+ stbir_resize_uint8_srgb( input_pixels , in_w , in_h , 0,20+ output_pixels, out_w, out_h, 0,21+ num_channels , alpha_chan , 0)22+ stbir_resize_uint8_srgb_edgemode(23+ input_pixels , in_w , in_h , 0,24+ output_pixels, out_w, out_h, 0,25+ num_channels , alpha_chan , 0, STBIR_EDGE_CLAMP)26+ // WRAP/REFLECT/ZERO27+28+ FULL API29+ See the "header file" section of the source for API documentation.30+31+ ADDITIONAL DOCUMENTATION32+33+ SRGB & FLOATING POINT REPRESENTATION34+ The sRGB functions presume IEEE floating point. If you do not have35+ IEEE floating point, define STBIR_NON_IEEE_FLOAT. This will use36+ a slower implementation.37+38+ MEMORY ALLOCATION39+ The resize functions here perform a single memory allocation using40+ malloc. To control the memory allocation, before the #include that41+ triggers the implementation, do:42+43+ #define STBIR_MALLOC(size,context) ...44+ #define STBIR_FREE(ptr,context) ...45+46+ Each resize function makes exactly one call to malloc/free, so to use47+ temp memory, store the temp memory in the context and return that.48+49+ ASSERT50+ Define STBIR_ASSERT(boolval) to override assert() and not use assert.h51+52+ OPTIMIZATION53+ Define STBIR_SATURATE_INT to compute clamp values in-range using54+ integer operations instead of float operations. This may be faster55+ on some platforms.56+57+ DEFAULT FILTERS58+ For functions which don't provide explicit control over what filters59+ to use, you can change the compile-time defaults with60+61+ #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_something62+ #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_something63+64+ See stbir_filter in the header-file section for the list of filters.65+66+ NEW FILTERS67+ A number of 1D filter kernels are used. For a list of68+ supported filters see the stbir_filter enum. To add a new filter,69+ write a filter function and add it to stbir__filter_info_table.70+71+ PROGRESS72+ For interactive use with slow resize operations, you can install73+ a progress-report callback:74+75+ #define STBIR_PROGRESS_REPORT(val) some_func(val)76+77+ The parameter val is a float which goes from 0 to 1 as progress is made.78+79+ For example:80+81+ static void my_progress_report(float progress);82+ #define STBIR_PROGRESS_REPORT(val) my_progress_report(val)83+84+ #define STB_IMAGE_RESIZE_IMPLEMENTATION85+ #include "stb_image_resize.h"86+87+ static void my_progress_report(float progress)88+ {89+ printf("Progress: %f%%\n", progress*100);90+ }91+92+ MAX CHANNELS93+ If your image has more than 64 channels, define STBIR_MAX_CHANNELS94+ to the max you'll have.95+96+ ALPHA CHANNEL97+ Most of the resizing functions provide the ability to control how98+ the alpha channel of an image is processed. The important things99+ to know about this:100+101+ 1. The best mathematically-behaved version of alpha to use is102+ called "premultiplied alpha", in which the other color channels103+ have had the alpha value multiplied in. If you use premultiplied104+ alpha, linear filtering (such as image resampling done by this105+ library, or performed in texture units on GPUs) does the "right106+ thing". While premultiplied alpha is standard in the movie CGI107+ industry, it is still uncommon in the videogame/real-time world.108+109+ If you linearly filter non-premultiplied alpha, strange effects110+ occur. (For example, the 50/50 average of 99% transparent bright green111+ and 1% transparent black produces 50% transparent dark green when112+ non-premultiplied, whereas premultiplied it produces 50%113+ transparent near-black. The former introduces green energy114+ that doesn't exist in the source image.)115+116+ 2. Artists should not edit premultiplied-alpha images; artists117+ want non-premultiplied alpha images. Thus, art tools generally output118+ non-premultiplied alpha images.119+120+ 3. You will get best results in most cases by converting images121+ to premultiplied alpha before processing them mathematically.122+123+ 4. If you pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, the124+ resizer does not do anything special for the alpha channel;125+ it is resampled identically to other channels. This produces126+ the correct results for premultiplied-alpha images, but produces127+ less-than-ideal results for non-premultiplied-alpha images.128+129+ 5. If you do not pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED,130+ then the resizer weights the contribution of input pixels131+ based on their alpha values, or, equivalently, it multiplies132+ the alpha value into the color channels, resamples, then divides133+ by the resultant alpha value. Input pixels which have alpha=0 do134+ not contribute at all to output pixels unless _all_ of the input135+ pixels affecting that output pixel have alpha=0, in which case136+ the result for that pixel is the same as it would be without137+ STBIR_FLAG_ALPHA_PREMULTIPLIED. However, this is only true for138+ input images in integer formats. For input images in float format,139+ input pixels with alpha=0 have no effect, and output pixels140+ which have alpha=0 will be 0 in all channels. (For float images,141+ you can manually achieve the same result by adding a tiny epsilon142+ value to the alpha channel of every image, and then subtracting143+ or clamping it at the end.)144+145+ 6. You can suppress the behavior described in #5 and make146+ all-0-alpha pixels have 0 in all channels by #defining147+ STBIR_NO_ALPHA_EPSILON.148+149+ 7. You can separately control whether the alpha channel is150+ interpreted as linear or affected by the colorspace. By default151+ it is linear; you almost never want to apply the colorspace.152+ (For example, graphics hardware does not apply sRGB conversion153+ to the alpha channel.)154+155+ CONTRIBUTORS156+ Jorge L Rodriguez: Implementation157+ Sean Barrett: API design, optimizations158+ Aras Pranckevicius: bugfix159+ Nathan Reed: warning fixes160+161+ REVISIONS162+ 0.97 (2020-02-02) fixed warning163+ 0.96 (2019-03-04) fixed warnings164+ 0.95 (2017-07-23) fixed warnings165+ 0.94 (2017-03-18) fixed warnings166+ 0.93 (2017-03-03) fixed bug with certain combinations of heights167+ 0.92 (2017-01-02) fix integer overflow on large (>2GB) images168+ 0.91 (2016-04-02) fix warnings; fix handling of subpixel regions169+ 0.90 (2014-09-17) first released version170+171+ LICENSE172+ See end of file for license information.173+174+ TODO175+ Don't decode all of the image data when only processing a partial tile176+ Don't use full-width decode buffers when only processing a partial tile177+ When processing wide images, break processing into tiles so data fits in L1 cache178+ Installable filters?179+ Resize that respects alpha test coverage180+ (Reference code: FloatImage::alphaTestCoverage and FloatImage::scaleAlphaToCoverage:181+ https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvimage/FloatImage.cpp )182+*/183+184+#ifndef STBIR_INCLUDE_STB_IMAGE_RESIZE_H185+#define STBIR_INCLUDE_STB_IMAGE_RESIZE_H186+187+#ifdef _MSC_VER188+typedef unsigned char stbir_uint8;189+typedef unsigned short stbir_uint16;190+typedef unsigned int stbir_uint32;191+#else192+#include <stdint.h>193+typedef uint8_t stbir_uint8;194+typedef uint16_t stbir_uint16;195+typedef uint32_t stbir_uint32;196+#endif197+198+#ifndef STBIRDEF199+#ifdef STB_IMAGE_RESIZE_STATIC200+#define STBIRDEF static201+#else202+#ifdef __cplusplus203+#define STBIRDEF extern "C"204+#else205+#define STBIRDEF extern206+#endif207+#endif208+#endif209+210+//////////////////////////////////////////////////////////////////////////////211+//212+// Easy-to-use API:213+//214+// * "input pixels" points to an array of image data with 'num_channels' channels (e.g. RGB=3, RGBA=4)215+// * input_w is input image width (x-axis), input_h is input image height (y-axis)216+// * stride is the offset between successive rows of image data in memory, in bytes. you can217+// specify 0 to mean packed continuously in memory218+// * alpha channel is treated identically to other channels.219+// * colorspace is linear or sRGB as specified by function name220+// * returned result is 1 for success or 0 in case of an error.221+// #define STBIR_ASSERT() to trigger an assert on parameter validation errors.222+// * Memory required grows approximately linearly with input and output size, but with223+// discontinuities at input_w == output_w and input_h == output_h.224+// * These functions use a "default" resampling filter defined at compile time. To change the filter,225+// you can change the compile-time defaults by #defining STBIR_DEFAULT_FILTER_UPSAMPLE226+// and STBIR_DEFAULT_FILTER_DOWNSAMPLE, or you can use the medium-complexity API.227+228+STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,229+ unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,230+ int num_channels);231+232+STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,233+ float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,234+ int num_channels);235+236+237+// The following functions interpret image data as gamma-corrected sRGB.238+// Specify STBIR_ALPHA_CHANNEL_NONE if you have no alpha channel,239+// or otherwise provide the index of the alpha channel. Flags value240+// of 0 will probably do the right thing if you're not sure what241+// the flags mean.242+243+#define STBIR_ALPHA_CHANNEL_NONE -1244+245+// Set this flag if your texture has premultiplied alpha. Otherwise, stbir will246+// use alpha-weighted resampling (effectively premultiplying, resampling,247+// then unpremultiplying).248+#define STBIR_FLAG_ALPHA_PREMULTIPLIED (1 << 0)249+// The specified alpha channel should be handled as gamma-corrected value even250+// when doing sRGB operations.251+#define STBIR_FLAG_ALPHA_USES_COLORSPACE (1 << 1)252+253+STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,254+ unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,255+ int num_channels, int alpha_channel, int flags);256+257+258+typedef enum259+{260+ STBIR_EDGE_CLAMP = 1,261+ STBIR_EDGE_REFLECT = 2,262+ STBIR_EDGE_WRAP = 3,263+ STBIR_EDGE_ZERO = 4,264+} stbir_edge;265+266+// This function adds the ability to specify how requests to sample off the edge of the image are handled.267+STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,268+ unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,269+ int num_channels, int alpha_channel, int flags,270+ stbir_edge edge_wrap_mode);271+272+//////////////////////////////////////////////////////////////////////////////273+//274+// Medium-complexity API275+//276+// This extends the easy-to-use API as follows:277+//278+// * Alpha-channel can be processed separately279+// * If alpha_channel is not STBIR_ALPHA_CHANNEL_NONE280+// * Alpha channel will not be gamma corrected (unless flags&STBIR_FLAG_GAMMA_CORRECT)281+// * Filters will be weighted by alpha channel (unless flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)282+// * Filter can be selected explicitly283+// * uint16 image type284+// * sRGB colorspace available for all types285+// * context parameter for passing to STBIR_MALLOC286+287+typedef enum288+{289+ STBIR_FILTER_DEFAULT = 0, // use same filter type that easy-to-use API chooses290+ STBIR_FILTER_BOX = 1, // A trapezoid w/1-pixel wide ramps, same result as box for integer scale ratios291+ STBIR_FILTER_TRIANGLE = 2, // On upsampling, produces same results as bilinear texture filtering292+ STBIR_FILTER_CUBICBSPLINE = 3, // The cubic b-spline (aka Mitchell-Netrevalli with B=1,C=0), gaussian-esque293+ STBIR_FILTER_CATMULLROM = 4, // An interpolating cubic spline294+ STBIR_FILTER_MITCHELL = 5, // Mitchell-Netrevalli filter with B=1/3, C=1/3295+} stbir_filter;296+297+typedef enum298+{299+ STBIR_COLORSPACE_LINEAR,300+ STBIR_COLORSPACE_SRGB,301+302+ STBIR_MAX_COLORSPACES,303+} stbir_colorspace;304+305+// The following functions are all identical except for the type of the image data306+307+STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,308+ unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,309+ int num_channels, int alpha_channel, int flags,310+ stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,311+ void *alloc_context);312+313+STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes,314+ stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes,315+ int num_channels, int alpha_channel, int flags,316+ stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,317+ void *alloc_context);318+319+STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,320+ float *output_pixels , int output_w, int output_h, int output_stride_in_bytes,321+ int num_channels, int alpha_channel, int flags,322+ stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,323+ void *alloc_context);324+325+326+327+//////////////////////////////////////////////////////////////////////////////328+//329+// Full-complexity API330+//331+// This extends the medium API as follows:332+//333+// * uint32 image type334+// * not typesafe335+// * separate filter types for each axis336+// * separate edge modes for each axis337+// * can specify scale explicitly for subpixel correctness338+// * can specify image source tile using texture coordinates339+340+typedef enum341+{342+ STBIR_TYPE_UINT8 ,343+ STBIR_TYPE_UINT16,344+ STBIR_TYPE_UINT32,345+ STBIR_TYPE_FLOAT ,346+347+ STBIR_MAX_TYPES348+} stbir_datatype;349+350+STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,351+ void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,352+ stbir_datatype datatype,353+ int num_channels, int alpha_channel, int flags,354+ stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,355+ stbir_filter filter_horizontal, stbir_filter filter_vertical,356+ stbir_colorspace space, void *alloc_context);357+358+STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,359+ void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,360+ stbir_datatype datatype,361+ int num_channels, int alpha_channel, int flags,362+ stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,363+ stbir_filter filter_horizontal, stbir_filter filter_vertical,364+ stbir_colorspace space, void *alloc_context,365+ float x_scale, float y_scale,366+ float x_offset, float y_offset);367+368+STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,369+ void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,370+ stbir_datatype datatype,371+ int num_channels, int alpha_channel, int flags,372+ stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,373+ stbir_filter filter_horizontal, stbir_filter filter_vertical,374+ stbir_colorspace space, void *alloc_context,375+ float s0, float t0, float s1, float t1);376+// (s0, t0) & (s1, t1) are the top-left and bottom right corner (uv addressing style: [0, 1]x[0, 1]) of a region of the input image to use.377+378+//379+//380+//// end header file /////////////////////////////////////////////////////381+#endif // STBIR_INCLUDE_STB_IMAGE_RESIZE_H382+383+384+385+386+387+#ifdef STB_IMAGE_RESIZE_IMPLEMENTATION388+389+#ifndef STBIR_ASSERT390+#include <assert.h>391+#define STBIR_ASSERT(x) assert(x)392+#endif393+394+// For memset395+#include <string.h>396+397+#include <math.h>398+399+#ifndef STBIR_MALLOC400+#include <stdlib.h>401+// use comma operator to evaluate c, to avoid "unused parameter" warnings402+#define STBIR_MALLOC(size,c) ((void)(c), malloc(size))403+#define STBIR_FREE(ptr,c) ((void)(c), free(ptr))404+#endif405+406+#ifndef _MSC_VER407+#ifdef __cplusplus408+#define stbir__inline inline409+#else410+#define stbir__inline411+#endif412+#else413+#define stbir__inline __forceinline414+#endif415+416+417+// should produce compiler error if size is wrong418+typedef unsigned char stbir__validate_uint32[sizeof(stbir_uint32) == 4 ? 1 : -1];419+420+#ifdef _MSC_VER421+#define STBIR__NOTUSED(v) (void)(v)422+#else423+#define STBIR__NOTUSED(v) (void)sizeof(v)424+#endif425+426+#define STBIR__ARRAY_SIZE(a) (sizeof((a))/sizeof((a)[0]))427+428+#ifndef STBIR_DEFAULT_FILTER_UPSAMPLE429+#define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_CATMULLROM430+#endif431+432+#ifndef STBIR_DEFAULT_FILTER_DOWNSAMPLE433+#define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_MITCHELL434+#endif435+436+#ifndef STBIR_PROGRESS_REPORT437+#define STBIR_PROGRESS_REPORT(float_0_to_1)438+#endif439+440+#ifndef STBIR_MAX_CHANNELS441+#define STBIR_MAX_CHANNELS 64442+#endif443+444+#if STBIR_MAX_CHANNELS > 65536445+#error "Too many channels; STBIR_MAX_CHANNELS must be no more than 65536."446+// because we store the indices in 16-bit variables447+#endif448+449+// This value is added to alpha just before premultiplication to avoid450+// zeroing out color values. It is equivalent to 2^-80. If you don't want451+// that behavior (it may interfere if you have floating point images with452+// very small alpha values) then you can define STBIR_NO_ALPHA_EPSILON to453+// disable it.454+#ifndef STBIR_ALPHA_EPSILON455+#define STBIR_ALPHA_EPSILON ((float)1 / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20))456+#endif457+458+459+460+#ifdef _MSC_VER461+#define STBIR__UNUSED_PARAM(v) (void)(v)462+#else463+#define STBIR__UNUSED_PARAM(v) (void)sizeof(v)464+#endif465+466+// must match stbir_datatype467+static unsigned char stbir__type_size[] = {468+ 1, // STBIR_TYPE_UINT8469+ 2, // STBIR_TYPE_UINT16470+ 4, // STBIR_TYPE_UINT32471+ 4, // STBIR_TYPE_FLOAT472+};473+474+// Kernel function centered at 0475+typedef float (stbir__kernel_fn)(float x, float scale);476+typedef float (stbir__support_fn)(float scale);477+478+typedef struct479+{480+ stbir__kernel_fn* kernel;481+ stbir__support_fn* support;482+} stbir__filter_info;483+484+// When upsampling, the contributors are which source pixels contribute.485+// When downsampling, the contributors are which destination pixels are contributed to.486+typedef struct487+{488+ int n0; // First contributing pixel489+ int n1; // Last contributing pixel490+} stbir__contributors;491+492+typedef struct493+{494+ const void* input_data;495+ int input_w;496+ int input_h;497+ int input_stride_bytes;498+499+ void* output_data;500+ int output_w;501+ int output_h;502+ int output_stride_bytes;503+504+ float s0, t0, s1, t1;505+506+ float horizontal_shift; // Units: output pixels507+ float vertical_shift; // Units: output pixels508+ float horizontal_scale;509+ float vertical_scale;510+511+ int channels;512+ int alpha_channel;513+ stbir_uint32 flags;514+ stbir_datatype type;515+ stbir_filter horizontal_filter;516+ stbir_filter vertical_filter;517+ stbir_edge edge_horizontal;518+ stbir_edge edge_vertical;519+ stbir_colorspace colorspace;520+521+ stbir__contributors* horizontal_contributors;522+ float* horizontal_coefficients;523+524+ stbir__contributors* vertical_contributors;525+ float* vertical_coefficients;526+527+ int decode_buffer_pixels;528+ float* decode_buffer;529+530+ float* horizontal_buffer;531+532+ // cache these because ceil/floor are inexplicably showing up in profile533+ int horizontal_coefficient_width;534+ int vertical_coefficient_width;535+ int horizontal_filter_pixel_width;536+ int vertical_filter_pixel_width;537+ int horizontal_filter_pixel_margin;538+ int vertical_filter_pixel_margin;539+ int horizontal_num_contributors;540+ int vertical_num_contributors;541+542+ int ring_buffer_length_bytes; // The length of an individual entry in the ring buffer. The total number of ring buffers is stbir__get_filter_pixel_width(filter)543+ int ring_buffer_num_entries; // Total number of entries in the ring buffer.544+ int ring_buffer_first_scanline;545+ int ring_buffer_last_scanline;546+ int ring_buffer_begin_index; // first_scanline is at this index in the ring buffer547+ float* ring_buffer;548+549+ float* encode_buffer; // A temporary buffer to store floats so we don't lose precision while we do multiply-adds.550+551+ int horizontal_contributors_size;552+ int horizontal_coefficients_size;553+ int vertical_contributors_size;554+ int vertical_coefficients_size;555+ int decode_buffer_size;556+ int horizontal_buffer_size;557+ int ring_buffer_size;558+ int encode_buffer_size;559+} stbir__info;560+561+562+static const float stbir__max_uint8_as_float = 255.0f;563+static const float stbir__max_uint16_as_float = 65535.0f;564+static const double stbir__max_uint32_as_float = 4294967295.0;565+566+567+static stbir__inline int stbir__min(int a, int b)568+{569+ return a < b ? a : b;570+}571+572+static stbir__inline float stbir__saturate(float x)573+{574+ if (x < 0)575+ return 0;576+577+ if (x > 1)578+ return 1;579+580+ return x;581+}582+583+#ifdef STBIR_SATURATE_INT584+static stbir__inline stbir_uint8 stbir__saturate8(int x)585+{586+ if ((unsigned int) x <= 255)587+ return x;588+589+ if (x < 0)590+ return 0;591+592+ return 255;593+}594+595+static stbir__inline stbir_uint16 stbir__saturate16(int x)596+{597+ if ((unsigned int) x <= 65535)598+ return x;599+600+ if (x < 0)601+ return 0;602+603+ return 65535;604+}605+#endif606+607+static float stbir__srgb_uchar_to_linear_float[256] = {608+ 0.000000f, 0.000304f, 0.000607f, 0.000911f, 0.001214f, 0.001518f, 0.001821f, 0.002125f, 0.002428f, 0.002732f, 0.003035f,609+ 0.003347f, 0.003677f, 0.004025f, 0.004391f, 0.004777f, 0.005182f, 0.005605f, 0.006049f, 0.006512f, 0.006995f, 0.007499f,610+ 0.008023f, 0.008568f, 0.009134f, 0.009721f, 0.010330f, 0.010960f, 0.011612f, 0.012286f, 0.012983f, 0.013702f, 0.014444f,611+ 0.015209f, 0.015996f, 0.016807f, 0.017642f, 0.018500f, 0.019382f, 0.020289f, 0.021219f, 0.022174f, 0.023153f, 0.024158f,612+ 0.025187f, 0.026241f, 0.027321f, 0.028426f, 0.029557f, 0.030713f, 0.031896f, 0.033105f, 0.034340f, 0.035601f, 0.036889f,613+ 0.038204f, 0.039546f, 0.040915f, 0.042311f, 0.043735f, 0.045186f, 0.046665f, 0.048172f, 0.049707f, 0.051269f, 0.052861f,614+ 0.054480f, 0.056128f, 0.057805f, 0.059511f, 0.061246f, 0.063010f, 0.064803f, 0.066626f, 0.068478f, 0.070360f, 0.072272f,615+ 0.074214f, 0.076185f, 0.078187f, 0.080220f, 0.082283f, 0.084376f, 0.086500f, 0.088656f, 0.090842f, 0.093059f, 0.095307f,616+ 0.097587f, 0.099899f, 0.102242f, 0.104616f, 0.107023f, 0.109462f, 0.111932f, 0.114435f, 0.116971f, 0.119538f, 0.122139f,617+ 0.124772f, 0.127438f, 0.130136f, 0.132868f, 0.135633f, 0.138432f, 0.141263f, 0.144128f, 0.147027f, 0.149960f, 0.152926f,618+ 0.155926f, 0.158961f, 0.162029f, 0.165132f, 0.168269f, 0.171441f, 0.174647f, 0.177888f, 0.181164f, 0.184475f, 0.187821f,619+ 0.191202f, 0.194618f, 0.198069f, 0.201556f, 0.205079f, 0.208637f, 0.212231f, 0.215861f, 0.219526f, 0.223228f, 0.226966f,620+ 0.230740f, 0.234551f, 0.238398f, 0.242281f, 0.246201f, 0.250158f, 0.254152f, 0.258183f, 0.262251f, 0.266356f, 0.270498f,621+ 0.274677f, 0.278894f, 0.283149f, 0.287441f, 0.291771f, 0.296138f, 0.300544f, 0.304987f, 0.309469f, 0.313989f, 0.318547f,622+ 0.323143f, 0.327778f, 0.332452f, 0.337164f, 0.341914f, 0.346704f, 0.351533f, 0.356400f, 0.361307f, 0.366253f, 0.371238f,623+ 0.376262f, 0.381326f, 0.386430f, 0.391573f, 0.396755f, 0.401978f, 0.407240f, 0.412543f, 0.417885f, 0.423268f, 0.428691f,624+ 0.434154f, 0.439657f, 0.445201f, 0.450786f, 0.456411f, 0.462077f, 0.467784f, 0.473532f, 0.479320f, 0.485150f, 0.491021f,625+ 0.496933f, 0.502887f, 0.508881f, 0.514918f, 0.520996f, 0.527115f, 0.533276f, 0.539480f, 0.545725f, 0.552011f, 0.558340f,626+ 0.564712f, 0.571125f, 0.577581f, 0.584078f, 0.590619f, 0.597202f, 0.603827f, 0.610496f, 0.617207f, 0.623960f, 0.630757f,627+ 0.637597f, 0.644480f, 0.651406f, 0.658375f, 0.665387f, 0.672443f, 0.679543f, 0.686685f, 0.693872f, 0.701102f, 0.708376f,628+ 0.715694f, 0.723055f, 0.730461f, 0.737911f, 0.745404f, 0.752942f, 0.760525f, 0.768151f, 0.775822f, 0.783538f, 0.791298f,629+ 0.799103f, 0.806952f, 0.814847f, 0.822786f, 0.830770f, 0.838799f, 0.846873f, 0.854993f, 0.863157f, 0.871367f, 0.879622f,630+ 0.887923f, 0.896269f, 0.904661f, 0.913099f, 0.921582f, 0.930111f, 0.938686f, 0.947307f, 0.955974f, 0.964686f, 0.973445f,631+ 0.982251f, 0.991102f, 1.0f632+};633+634+static float stbir__srgb_to_linear(float f)635+{636+ if (f <= 0.04045f)637+ return f / 12.92f;638+ else639+ return (float)pow((f + 0.055f) / 1.055f, 2.4f);640+}641+642+static float stbir__linear_to_srgb(float f)643+{644+ if (f <= 0.0031308f)645+ return f * 12.92f;646+ else647+ return 1.055f * (float)pow(f, 1 / 2.4f) - 0.055f;648+}649+650+#ifndef STBIR_NON_IEEE_FLOAT651+// From https://gist.github.com/rygorous/2203834652+653+typedef union654+{655+ stbir_uint32 u;656+ float f;657+} stbir__FP32;658+659+static const stbir_uint32 fp32_to_srgb8_tab4[104] = {660+ 0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d,661+ 0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a,662+ 0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033,663+ 0x01dc0067, 0x020f0067, 0x02430067, 0x02760067, 0x02aa0067, 0x02dd0067, 0x03110067, 0x03440067,664+ 0x037800ce, 0x03df00ce, 0x044600ce, 0x04ad00ce, 0x051400ce, 0x057b00c5, 0x05dd00bc, 0x063b00b5,665+ 0x06970158, 0x07420142, 0x07e30130, 0x087b0120, 0x090b0112, 0x09940106, 0x0a1700fc, 0x0a9500f2,666+ 0x0b0f01cb, 0x0bf401ae, 0x0ccb0195, 0x0d950180, 0x0e56016e, 0x0f0d015e, 0x0fbc0150, 0x10630143,667+ 0x11070264, 0x1238023e, 0x1357021d, 0x14660201, 0x156601e9, 0x165a01d3, 0x174401c0, 0x182401af,668+ 0x18fe0331, 0x1a9602fe, 0x1c1502d2, 0x1d7e02ad, 0x1ed4028d, 0x201a0270, 0x21520256, 0x227d0240,669+ 0x239f0443, 0x25c003fe, 0x27bf03c4, 0x29a10392, 0x2b6a0367, 0x2d1d0341, 0x2ebe031f, 0x304d0300,670+ 0x31d105b0, 0x34a80555, 0x37520507, 0x39d504c5, 0x3c37048b, 0x3e7c0458, 0x40a8042a, 0x42bd0401,671+ 0x44c20798, 0x488e071e, 0x4c1c06b6, 0x4f76065d, 0x52a50610, 0x55ac05cc, 0x5892058f, 0x5b590559,672+ 0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723,673+};674+675+static stbir_uint8 stbir__linear_to_srgb_uchar(float in)676+{677+ static const stbir__FP32 almostone = { 0x3f7fffff }; // 1-eps678+ static const stbir__FP32 minval = { (127-13) << 23 };679+ stbir_uint32 tab,bias,scale,t;680+ stbir__FP32 f;681+682+ // Clamp to [2^(-13), 1-eps]; these two values map to 0 and 1, respectively.683+ // The tests are carefully written so that NaNs map to 0, same as in the reference684+ // implementation.685+ if (!(in > minval.f)) // written this way to catch NaNs686+ in = minval.f;687+ if (in > almostone.f)688+ in = almostone.f;689+690+ // Do the table lookup and unpack bias, scale691+ f.f = in;692+ tab = fp32_to_srgb8_tab4[(f.u - minval.u) >> 20];693+ bias = (tab >> 16) << 9;694+ scale = tab & 0xffff;695+696+ // Grab next-highest mantissa bits and perform linear interpolation697+ t = (f.u >> 12) & 0xff;698+ return (unsigned char) ((bias + scale*t) >> 16);699+}700+701+#else702+// sRGB transition values, scaled by 1<<28703+static int stbir__srgb_offset_to_linear_scaled[256] =704+{705+ 0, 40738, 122216, 203693, 285170, 366648, 448125, 529603,706+ 611080, 692557, 774035, 855852, 942009, 1033024, 1128971, 1229926,707+ 1335959, 1447142, 1563542, 1685229, 1812268, 1944725, 2082664, 2226148,708+ 2375238, 2529996, 2690481, 2856753, 3028870, 3206888, 3390865, 3580856,709+ 3776916, 3979100, 4187460, 4402049, 4622919, 4850123, 5083710, 5323731,710+ 5570236, 5823273, 6082892, 6349140, 6622065, 6901714, 7188133, 7481369,711+ 7781466, 8088471, 8402427, 8723380, 9051372, 9386448, 9728650, 10078021,712+ 10434603, 10798439, 11169569, 11548036, 11933879, 12327139, 12727857, 13136073,713+ 13551826, 13975156, 14406100, 14844697, 15290987, 15745007, 16206795, 16676389,714+ 17153826, 17639142, 18132374, 18633560, 19142734, 19659934, 20185196, 20718552,715+ 21260042, 21809696, 22367554, 22933648, 23508010, 24090680, 24681686, 25281066,716+ 25888850, 26505076, 27129772, 27762974, 28404716, 29055026, 29713942, 30381490,717+ 31057708, 31742624, 32436272, 33138682, 33849884, 34569912, 35298800, 36036568,718+ 36783260, 37538896, 38303512, 39077136, 39859796, 40651528, 41452360, 42262316,719+ 43081432, 43909732, 44747252, 45594016, 46450052, 47315392, 48190064, 49074096,720+ 49967516, 50870356, 51782636, 52704392, 53635648, 54576432, 55526772, 56486700,721+ 57456236, 58435408, 59424248, 60422780, 61431036, 62449032, 63476804, 64514376,722+ 65561776, 66619028, 67686160, 68763192, 69850160, 70947088, 72053992, 73170912,723+ 74297864, 75434880, 76581976, 77739184, 78906536, 80084040, 81271736, 82469648,724+ 83677792, 84896192, 86124888, 87363888, 88613232, 89872928, 91143016, 92423512,725+ 93714432, 95015816, 96327688, 97650056, 98982952, 100326408, 101680440, 103045072,726+ 104420320, 105806224, 107202800, 108610064, 110028048, 111456776, 112896264, 114346544,727+ 115807632, 117279552, 118762328, 120255976, 121760536, 123276016, 124802440, 126339832,728+ 127888216, 129447616, 131018048, 132599544, 134192112, 135795792, 137410592, 139036528,729+ 140673648, 142321952, 143981456, 145652208, 147334208, 149027488, 150732064, 152447968,730+ 154175200, 155913792, 157663776, 159425168, 161197984, 162982240, 164777968, 166585184,731+ 168403904, 170234160, 172075968, 173929344, 175794320, 177670896, 179559120, 181458992,732+ 183370528, 185293776, 187228736, 189175424, 191133888, 193104112, 195086128, 197079968,733+ 199085648, 201103184, 203132592, 205173888, 207227120, 209292272, 211369392, 213458480,734+ 215559568, 217672656, 219797792, 221934976, 224084240, 226245600, 228419056, 230604656,735+ 232802400, 235012320, 237234432, 239468736, 241715280, 243974080, 246245120, 248528464,736+ 250824112, 253132064, 255452368, 257785040, 260130080, 262487520, 264857376, 267239664,737+};738+739+static stbir_uint8 stbir__linear_to_srgb_uchar(float f)740+{741+ int x = (int) (f * (1 << 28)); // has headroom so you don't need to clamp742+ int v = 0;743+ int i;744+745+ // Refine the guess with a short binary search.746+ i = v + 128; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;747+ i = v + 64; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;748+ i = v + 32; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;749+ i = v + 16; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;750+ i = v + 8; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;751+ i = v + 4; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;752+ i = v + 2; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;753+ i = v + 1; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;754+755+ return (stbir_uint8) v;756+}757+#endif758+759+static float stbir__filter_trapezoid(float x, float scale)760+{761+ float halfscale = scale / 2;762+ float t = 0.5f + halfscale;763+ STBIR_ASSERT(scale <= 1);764+765+ x = (float)fabs(x);766+767+ if (x >= t)768+ return 0;769+ else770+ {771+ float r = 0.5f - halfscale;772+ if (x <= r)773+ return 1;774+ else775+ return (t - x) / scale;776+ }777+}778+779+static float stbir__support_trapezoid(float scale)780+{781+ STBIR_ASSERT(scale <= 1);782+ return 0.5f + scale / 2;783+}784+785+static float stbir__filter_triangle(float x, float s)786+{787+ STBIR__UNUSED_PARAM(s);788+789+ x = (float)fabs(x);790+791+ if (x <= 1.0f)792+ return 1 - x;793+ else794+ return 0;795+}796+797+static float stbir__filter_cubic(float x, float s)798+{799+ STBIR__UNUSED_PARAM(s);800+801+ x = (float)fabs(x);802+803+ if (x < 1.0f)804+ return (4 + x*x*(3*x - 6))/6;805+ else if (x < 2.0f)806+ return (8 + x*(-12 + x*(6 - x)))/6;807+808+ return (0.0f);809+}810+811+static float stbir__filter_catmullrom(float x, float s)812+{813+ STBIR__UNUSED_PARAM(s);814+815+ x = (float)fabs(x);816+817+ if (x < 1.0f)818+ return 1 - x*x*(2.5f - 1.5f*x);819+ else if (x < 2.0f)820+ return 2 - x*(4 + x*(0.5f*x - 2.5f));821+822+ return (0.0f);823+}824+825+static float stbir__filter_mitchell(float x, float s)826+{827+ STBIR__UNUSED_PARAM(s);828+829+ x = (float)fabs(x);830+831+ if (x < 1.0f)832+ return (16 + x*x*(21 * x - 36))/18;833+ else if (x < 2.0f)834+ return (32 + x*(-60 + x*(36 - 7*x)))/18;835+836+ return (0.0f);837+}838+839+static float stbir__support_zero(float s)840+{841+ STBIR__UNUSED_PARAM(s);842+ return 0;843+}844+845+static float stbir__support_one(float s)846+{847+ STBIR__UNUSED_PARAM(s);848+ return 1;849+}850+851+static float stbir__support_two(float s)852+{853+ STBIR__UNUSED_PARAM(s);854+ return 2;855+}856+857+static stbir__filter_info stbir__filter_info_table[] = {858+ { NULL, stbir__support_zero },859+ { stbir__filter_trapezoid, stbir__support_trapezoid },860+ { stbir__filter_triangle, stbir__support_one },861+ { stbir__filter_cubic, stbir__support_two },862+ { stbir__filter_catmullrom, stbir__support_two },863+ { stbir__filter_mitchell, stbir__support_two },864+};865+866+stbir__inline static int stbir__use_upsampling(float ratio)867+{868+ return ratio > 1;869+}870+871+stbir__inline static int stbir__use_width_upsampling(stbir__info* stbir_info)872+{873+ return stbir__use_upsampling(stbir_info->horizontal_scale);874+}875+876+stbir__inline static int stbir__use_height_upsampling(stbir__info* stbir_info)877+{878+ return stbir__use_upsampling(stbir_info->vertical_scale);879+}880+881+// This is the maximum number of input samples that can affect an output sample882+// with the given filter883+static int stbir__get_filter_pixel_width(stbir_filter filter, float scale)884+{885+ STBIR_ASSERT(filter != 0);886+ STBIR_ASSERT(filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));887+888+ if (stbir__use_upsampling(scale))889+ return (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2);890+ else891+ return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2 / scale);892+}893+894+// This is how much to expand buffers to account for filters seeking outside895+// the image boundaries.896+static int stbir__get_filter_pixel_margin(stbir_filter filter, float scale)897+{898+ return stbir__get_filter_pixel_width(filter, scale) / 2;899+}900+901+static int stbir__get_coefficient_width(stbir_filter filter, float scale)902+{903+ if (stbir__use_upsampling(scale))904+ return (int)ceil(stbir__filter_info_table[filter].support(1 / scale) * 2);905+ else906+ return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2);907+}908+909+static int stbir__get_contributors(float scale, stbir_filter filter, int input_size, int output_size)910+{911+ if (stbir__use_upsampling(scale))912+ return output_size;913+ else914+ return (input_size + stbir__get_filter_pixel_margin(filter, scale) * 2);915+}916+917+static int stbir__get_total_horizontal_coefficients(stbir__info* info)918+{919+ return info->horizontal_num_contributors920+ * stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale);921+}922+923+static int stbir__get_total_vertical_coefficients(stbir__info* info)924+{925+ return info->vertical_num_contributors926+ * stbir__get_coefficient_width (info->vertical_filter, info->vertical_scale);927+}928+929+static stbir__contributors* stbir__get_contributor(stbir__contributors* contributors, int n)930+{931+ return &contributors[n];932+}933+934+// For perf reasons this code is duplicated in stbir__resample_horizontal_upsample/downsample,935+// if you change it here change it there too.936+static float* stbir__get_coefficient(float* coefficients, stbir_filter filter, float scale, int n, int c)937+{938+ int width = stbir__get_coefficient_width(filter, scale);939+ return &coefficients[width*n + c];940+}941+942+static int stbir__edge_wrap_slow(stbir_edge edge, int n, int max)943+{944+ switch (edge)945+ {946+ case STBIR_EDGE_ZERO:947+ return 0; // we'll decode the wrong pixel here, and then overwrite with 0s later948+949+ case STBIR_EDGE_CLAMP:950+ if (n < 0)951+ return 0;952+953+ if (n >= max)954+ return max - 1;955+956+ return n; // NOTREACHED957+958+ case STBIR_EDGE_REFLECT:959+ {960+ if (n < 0)961+ {962+ if (n < max)963+ return -n;964+ else965+ return max - 1;966+ }967+968+ if (n >= max)969+ {970+ int max2 = max * 2;971+ if (n >= max2)972+ return 0;973+ else974+ return max2 - n - 1;975+ }976+977+ return n; // NOTREACHED978+ }979+980+ case STBIR_EDGE_WRAP:981+ if (n >= 0)982+ return (n % max);983+ else984+ {985+ int m = (-n) % max;986+987+ if (m != 0)988+ m = max - m;989+990+ return (m);991+ }992+ // NOTREACHED993+994+ default:995+ STBIR_ASSERT(!"Unimplemented edge type");996+ return 0;997+ }998+}999+1000+stbir__inline static int stbir__edge_wrap(stbir_edge edge, int n, int max)1001+{1002+ // avoid per-pixel switch1003+ if (n >= 0 && n < max)1004+ return n;1005+ return stbir__edge_wrap_slow(edge, n, max);1006+}1007+1008+// What input pixels contribute to this output pixel?1009+static void stbir__calculate_sample_range_upsample(int n, float out_filter_radius, float scale_ratio, float out_shift, int* in_first_pixel, int* in_last_pixel, float* in_center_of_out)1010+{1011+ float out_pixel_center = (float)n + 0.5f;1012+ float out_pixel_influence_lowerbound = out_pixel_center - out_filter_radius;1013+ float out_pixel_influence_upperbound = out_pixel_center + out_filter_radius;1014+1015+ float in_pixel_influence_lowerbound = (out_pixel_influence_lowerbound + out_shift) / scale_ratio;1016+ float in_pixel_influence_upperbound = (out_pixel_influence_upperbound + out_shift) / scale_ratio;1017+1018+ *in_center_of_out = (out_pixel_center + out_shift) / scale_ratio;1019+ *in_first_pixel = (int)(floor(in_pixel_influence_lowerbound + 0.5));1020+ *in_last_pixel = (int)(floor(in_pixel_influence_upperbound - 0.5));1021+}1022+1023+// What output pixels does this input pixel contribute to?1024+static void stbir__calculate_sample_range_downsample(int n, float in_pixels_radius, float scale_ratio, float out_shift, int* out_first_pixel, int* out_last_pixel, float* out_center_of_in)1025+{1026+ float in_pixel_center = (float)n + 0.5f;1027+ float in_pixel_influence_lowerbound = in_pixel_center - in_pixels_radius;1028+ float in_pixel_influence_upperbound = in_pixel_center + in_pixels_radius;1029+1030+ float out_pixel_influence_lowerbound = in_pixel_influence_lowerbound * scale_ratio - out_shift;1031+ float out_pixel_influence_upperbound = in_pixel_influence_upperbound * scale_ratio - out_shift;1032+1033+ *out_center_of_in = in_pixel_center * scale_ratio - out_shift;1034+ *out_first_pixel = (int)(floor(out_pixel_influence_lowerbound + 0.5));1035+ *out_last_pixel = (int)(floor(out_pixel_influence_upperbound - 0.5));1036+}1037+1038+static void stbir__calculate_coefficients_upsample(stbir_filter filter, float scale, int in_first_pixel, int in_last_pixel, float in_center_of_out, stbir__contributors* contributor, float* coefficient_group)1039+{1040+ int i;1041+ float total_filter = 0;1042+ float filter_scale;1043+1044+ STBIR_ASSERT(in_last_pixel - in_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical.1045+1046+ contributor->n0 = in_first_pixel;1047+ contributor->n1 = in_last_pixel;1048+1049+ STBIR_ASSERT(contributor->n1 >= contributor->n0);1050+1051+ for (i = 0; i <= in_last_pixel - in_first_pixel; i++)1052+ {1053+ float in_pixel_center = (float)(i + in_first_pixel) + 0.5f;1054+ coefficient_group[i] = stbir__filter_info_table[filter].kernel(in_center_of_out - in_pixel_center, 1 / scale);1055+1056+ // If the coefficient is zero, skip it. (Don't do the <0 check here, we want the influence of those outside pixels.)1057+ if (i == 0 && !coefficient_group[i])1058+ {1059+ contributor->n0 = ++in_first_pixel;1060+ i--;1061+ continue;1062+ }1063+1064+ total_filter += coefficient_group[i];1065+ }1066+1067+ // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be.1068+ // It would be true in exact math but is at best approximately true in floating-point math,1069+ // and it would not make sense to try and put actual bounds on this here because it depends1070+ // on the image aspect ratio which can get pretty extreme.1071+ //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(in_last_pixel + 1) + 0.5f - in_center_of_out, 1/scale) == 0);1072+1073+ STBIR_ASSERT(total_filter > 0.9);1074+ STBIR_ASSERT(total_filter < 1.1f); // Make sure it's not way off.1075+1076+ // Make sure the sum of all coefficients is 1.1077+ filter_scale = 1 / total_filter;1078+1079+ for (i = 0; i <= in_last_pixel - in_first_pixel; i++)1080+ coefficient_group[i] *= filter_scale;1081+1082+ for (i = in_last_pixel - in_first_pixel; i >= 0; i--)1083+ {1084+ if (coefficient_group[i])1085+ break;1086+1087+ // This line has no weight. We can skip it.1088+ contributor->n1 = contributor->n0 + i - 1;1089+ }1090+}1091+1092+static void stbir__calculate_coefficients_downsample(stbir_filter filter, float scale_ratio, int out_first_pixel, int out_last_pixel, float out_center_of_in, stbir__contributors* contributor, float* coefficient_group)1093+{1094+ int i;1095+1096+ STBIR_ASSERT(out_last_pixel - out_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(scale_ratio) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical.1097+1098+ contributor->n0 = out_first_pixel;1099+ contributor->n1 = out_last_pixel;1100+1101+ STBIR_ASSERT(contributor->n1 >= contributor->n0);1102+1103+ for (i = 0; i <= out_last_pixel - out_first_pixel; i++)1104+ {1105+ float out_pixel_center = (float)(i + out_first_pixel) + 0.5f;1106+ float x = out_pixel_center - out_center_of_in;1107+ coefficient_group[i] = stbir__filter_info_table[filter].kernel(x, scale_ratio) * scale_ratio;1108+ }1109+1110+ // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be.1111+ // It would be true in exact math but is at best approximately true in floating-point math,1112+ // and it would not make sense to try and put actual bounds on this here because it depends1113+ // on the image aspect ratio which can get pretty extreme.1114+ //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(out_last_pixel + 1) + 0.5f - out_center_of_in, scale_ratio) == 0);1115+1116+ for (i = out_last_pixel - out_first_pixel; i >= 0; i--)1117+ {1118+ if (coefficient_group[i])1119+ break;1120+1121+ // This line has no weight. We can skip it.1122+ contributor->n1 = contributor->n0 + i - 1;1123+ }1124+}1125+1126+static void stbir__normalize_downsample_coefficients(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, int input_size, int output_size)1127+{1128+ int num_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size);1129+ int num_coefficients = stbir__get_coefficient_width(filter, scale_ratio);1130+ int i, j;1131+ int skip;1132+1133+ for (i = 0; i < output_size; i++)1134+ {1135+ float scale;1136+ float total = 0;1137+1138+ for (j = 0; j < num_contributors; j++)1139+ {1140+ if (i >= contributors[j].n0 && i <= contributors[j].n1)1141+ {1142+ float coefficient = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0);1143+ total += coefficient;1144+ }1145+ else if (i < contributors[j].n0)1146+ break;1147+ }1148+1149+ STBIR_ASSERT(total > 0.9f);1150+ STBIR_ASSERT(total < 1.1f);1151+1152+ scale = 1 / total;1153+1154+ for (j = 0; j < num_contributors; j++)1155+ {1156+ if (i >= contributors[j].n0 && i <= contributors[j].n1)1157+ *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0) *= scale;1158+ else if (i < contributors[j].n0)1159+ break;1160+ }1161+ }1162+1163+ // Optimize: Skip zero coefficients and contributions outside of image bounds.1164+ // Do this after normalizing because normalization depends on the n0/n1 values.1165+ for (j = 0; j < num_contributors; j++)1166+ {1167+ int range, max, width;1168+1169+ skip = 0;1170+ while (*stbir__get_coefficient(coefficients, filter, scale_ratio, j, skip) == 0)1171+ skip++;1172+1173+ contributors[j].n0 += skip;1174+1175+ while (contributors[j].n0 < 0)1176+ {1177+ contributors[j].n0++;1178+ skip++;1179+ }1180+1181+ range = contributors[j].n1 - contributors[j].n0 + 1;1182+ max = stbir__min(num_coefficients, range);1183+1184+ width = stbir__get_coefficient_width(filter, scale_ratio);1185+ for (i = 0; i < max; i++)1186+ {1187+ if (i + skip >= width)1188+ break;1189+1190+ *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i) = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i + skip);1191+ }1192+1193+ continue;1194+ }1195+1196+ // Using min to avoid writing into invalid pixels.1197+ for (i = 0; i < num_contributors; i++)1198+ contributors[i].n1 = stbir__min(contributors[i].n1, output_size - 1);1199+}1200+1201+// Each scan line uses the same kernel values so we should calculate the kernel1202+// values once and then we can use them for every scan line.1203+static void stbir__calculate_filters(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, float shift, int input_size, int output_size)1204+{1205+ int n;1206+ int total_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size);1207+1208+ if (stbir__use_upsampling(scale_ratio))1209+ {1210+ float out_pixels_radius = stbir__filter_info_table[filter].support(1 / scale_ratio) * scale_ratio;1211+1212+ // Looping through out pixels1213+ for (n = 0; n < total_contributors; n++)1214+ {1215+ float in_center_of_out; // Center of the current out pixel in the in pixel space1216+ int in_first_pixel, in_last_pixel;1217+1218+ stbir__calculate_sample_range_upsample(n, out_pixels_radius, scale_ratio, shift, &in_first_pixel, &in_last_pixel, &in_center_of_out);1219+1220+ stbir__calculate_coefficients_upsample(filter, scale_ratio, in_first_pixel, in_last_pixel, in_center_of_out, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0));1221+ }1222+ }1223+ else1224+ {1225+ float in_pixels_radius = stbir__filter_info_table[filter].support(scale_ratio) / scale_ratio;1226+1227+ // Looping through in pixels1228+ for (n = 0; n < total_contributors; n++)1229+ {1230+ float out_center_of_in; // Center of the current out pixel in the in pixel space1231+ int out_first_pixel, out_last_pixel;1232+ int n_adjusted = n - stbir__get_filter_pixel_margin(filter, scale_ratio);1233+1234+ stbir__calculate_sample_range_downsample(n_adjusted, in_pixels_radius, scale_ratio, shift, &out_first_pixel, &out_last_pixel, &out_center_of_in);1235+1236+ stbir__calculate_coefficients_downsample(filter, scale_ratio, out_first_pixel, out_last_pixel, out_center_of_in, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0));1237+ }1238+1239+ stbir__normalize_downsample_coefficients(contributors, coefficients, filter, scale_ratio, input_size, output_size);1240+ }1241+}1242+1243+static float* stbir__get_decode_buffer(stbir__info* stbir_info)1244+{1245+ // The 0 index of the decode buffer starts after the margin. This makes1246+ // it okay to use negative indexes on the decode buffer.1247+ return &stbir_info->decode_buffer[stbir_info->horizontal_filter_pixel_margin * stbir_info->channels];1248+}1249+1250+#define STBIR__DECODE(type, colorspace) ((int)(type) * (STBIR_MAX_COLORSPACES) + (int)(colorspace))1251+1252+static void stbir__decode_scanline(stbir__info* stbir_info, int n)1253+{1254+ int c;1255+ int channels = stbir_info->channels;1256+ int alpha_channel = stbir_info->alpha_channel;1257+ int type = stbir_info->type;1258+ int colorspace = stbir_info->colorspace;1259+ int input_w = stbir_info->input_w;1260+ size_t input_stride_bytes = stbir_info->input_stride_bytes;1261+ float* decode_buffer = stbir__get_decode_buffer(stbir_info);1262+ stbir_edge edge_horizontal = stbir_info->edge_horizontal;1263+ stbir_edge edge_vertical = stbir_info->edge_vertical;1264+ size_t in_buffer_row_offset = stbir__edge_wrap(edge_vertical, n, stbir_info->input_h) * input_stride_bytes;1265+ const void* input_data = (char *) stbir_info->input_data + in_buffer_row_offset;1266+ int max_x = input_w + stbir_info->horizontal_filter_pixel_margin;1267+ int decode = STBIR__DECODE(type, colorspace);1268+1269+ int x = -stbir_info->horizontal_filter_pixel_margin;1270+1271+ // special handling for STBIR_EDGE_ZERO because it needs to return an item that doesn't appear in the input,1272+ // and we want to avoid paying overhead on every pixel if not STBIR_EDGE_ZERO1273+ if (edge_vertical == STBIR_EDGE_ZERO && (n < 0 || n >= stbir_info->input_h))1274+ {1275+ for (; x < max_x; x++)1276+ for (c = 0; c < channels; c++)1277+ decode_buffer[x*channels + c] = 0;1278+ return;1279+ }1280+1281+ switch (decode)1282+ {1283+ case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR):1284+ for (; x < max_x; x++)1285+ {1286+ int decode_pixel_index = x * channels;1287+ int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1288+ for (c = 0; c < channels; c++)1289+ decode_buffer[decode_pixel_index + c] = ((float)((const unsigned char*)input_data)[input_pixel_index + c]) / stbir__max_uint8_as_float;1290+ }1291+ break;1292+1293+ case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB):1294+ for (; x < max_x; x++)1295+ {1296+ int decode_pixel_index = x * channels;1297+ int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1298+ for (c = 0; c < channels; c++)1299+ decode_buffer[decode_pixel_index + c] = stbir__srgb_uchar_to_linear_float[((const unsigned char*)input_data)[input_pixel_index + c]];1300+1301+ if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1302+ decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned char*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint8_as_float;1303+ }1304+ break;1305+1306+ case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR):1307+ for (; x < max_x; x++)1308+ {1309+ int decode_pixel_index = x * channels;1310+ int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1311+ for (c = 0; c < channels; c++)1312+ decode_buffer[decode_pixel_index + c] = ((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float;1313+ }1314+ break;1315+1316+ case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB):1317+ for (; x < max_x; x++)1318+ {1319+ int decode_pixel_index = x * channels;1320+ int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1321+ for (c = 0; c < channels; c++)1322+ decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float);1323+1324+ if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1325+ decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned short*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint16_as_float;1326+ }1327+ break;1328+1329+ case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR):1330+ for (; x < max_x; x++)1331+ {1332+ int decode_pixel_index = x * channels;1333+ int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1334+ for (c = 0; c < channels; c++)1335+ decode_buffer[decode_pixel_index + c] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float);1336+ }1337+ break;1338+1339+ case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB):1340+ for (; x < max_x; x++)1341+ {1342+ int decode_pixel_index = x * channels;1343+ int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1344+ for (c = 0; c < channels; c++)1345+ decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear((float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float));1346+1347+ if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1348+ decode_buffer[decode_pixel_index + alpha_channel] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint32_as_float);1349+ }1350+ break;1351+1352+ case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR):1353+ for (; x < max_x; x++)1354+ {1355+ int decode_pixel_index = x * channels;1356+ int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1357+ for (c = 0; c < channels; c++)1358+ decode_buffer[decode_pixel_index + c] = ((const float*)input_data)[input_pixel_index + c];1359+ }1360+ break;1361+1362+ case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB):1363+ for (; x < max_x; x++)1364+ {1365+ int decode_pixel_index = x * channels;1366+ int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1367+ for (c = 0; c < channels; c++)1368+ decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((const float*)input_data)[input_pixel_index + c]);1369+1370+ if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1371+ decode_buffer[decode_pixel_index + alpha_channel] = ((const float*)input_data)[input_pixel_index + alpha_channel];1372+ }1373+1374+ break;1375+1376+ default:1377+ STBIR_ASSERT(!"Unknown type/colorspace/channels combination.");1378+ break;1379+ }1380+1381+ if (!(stbir_info->flags & STBIR_FLAG_ALPHA_PREMULTIPLIED))1382+ {1383+ for (x = -stbir_info->horizontal_filter_pixel_margin; x < max_x; x++)1384+ {1385+ int decode_pixel_index = x * channels;1386+1387+ // If the alpha value is 0 it will clobber the color values. Make sure it's not.1388+ float alpha = decode_buffer[decode_pixel_index + alpha_channel];1389+#ifndef STBIR_NO_ALPHA_EPSILON1390+ if (stbir_info->type != STBIR_TYPE_FLOAT) {1391+ alpha += STBIR_ALPHA_EPSILON;1392+ decode_buffer[decode_pixel_index + alpha_channel] = alpha;1393+ }1394+#endif1395+ for (c = 0; c < channels; c++)1396+ {1397+ if (c == alpha_channel)1398+ continue;1399+1400+ decode_buffer[decode_pixel_index + c] *= alpha;1401+ }1402+ }1403+ }1404+1405+ if (edge_horizontal == STBIR_EDGE_ZERO)1406+ {1407+ for (x = -stbir_info->horizontal_filter_pixel_margin; x < 0; x++)1408+ {1409+ for (c = 0; c < channels; c++)1410+ decode_buffer[x*channels + c] = 0;1411+ }1412+ for (x = input_w; x < max_x; x++)1413+ {1414+ for (c = 0; c < channels; c++)1415+ decode_buffer[x*channels + c] = 0;1416+ }1417+ }1418+}1419+1420+static float* stbir__get_ring_buffer_entry(float* ring_buffer, int index, int ring_buffer_length)1421+{1422+ return &ring_buffer[index * ring_buffer_length];1423+}1424+1425+static float* stbir__add_empty_ring_buffer_entry(stbir__info* stbir_info, int n)1426+{1427+ int ring_buffer_index;1428+ float* ring_buffer;1429+1430+ stbir_info->ring_buffer_last_scanline = n;1431+1432+ if (stbir_info->ring_buffer_begin_index < 0)1433+ {1434+ ring_buffer_index = stbir_info->ring_buffer_begin_index = 0;1435+ stbir_info->ring_buffer_first_scanline = n;1436+ }1437+ else1438+ {1439+ ring_buffer_index = (stbir_info->ring_buffer_begin_index + (stbir_info->ring_buffer_last_scanline - stbir_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries;1440+ STBIR_ASSERT(ring_buffer_index != stbir_info->ring_buffer_begin_index);1441+ }1442+1443+ ring_buffer = stbir__get_ring_buffer_entry(stbir_info->ring_buffer, ring_buffer_index, stbir_info->ring_buffer_length_bytes / sizeof(float));1444+ memset(ring_buffer, 0, stbir_info->ring_buffer_length_bytes);1445+1446+ return ring_buffer;1447+}1448+1449+1450+static void stbir__resample_horizontal_upsample(stbir__info* stbir_info, float* output_buffer)1451+{1452+ int x, k;1453+ int output_w = stbir_info->output_w;1454+ int channels = stbir_info->channels;1455+ float* decode_buffer = stbir__get_decode_buffer(stbir_info);1456+ stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors;1457+ float* horizontal_coefficients = stbir_info->horizontal_coefficients;1458+ int coefficient_width = stbir_info->horizontal_coefficient_width;1459+1460+ for (x = 0; x < output_w; x++)1461+ {1462+ int n0 = horizontal_contributors[x].n0;1463+ int n1 = horizontal_contributors[x].n1;1464+1465+ int out_pixel_index = x * channels;1466+ int coefficient_group = coefficient_width * x;1467+ int coefficient_counter = 0;1468+1469+ STBIR_ASSERT(n1 >= n0);1470+ STBIR_ASSERT(n0 >= -stbir_info->horizontal_filter_pixel_margin);1471+ STBIR_ASSERT(n1 >= -stbir_info->horizontal_filter_pixel_margin);1472+ STBIR_ASSERT(n0 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin);1473+ STBIR_ASSERT(n1 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin);1474+1475+ switch (channels) {1476+ case 1:1477+ for (k = n0; k <= n1; k++)1478+ {1479+ int in_pixel_index = k * 1;1480+ float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1481+ STBIR_ASSERT(coefficient != 0);1482+ output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1483+ }1484+ break;1485+ case 2:1486+ for (k = n0; k <= n1; k++)1487+ {1488+ int in_pixel_index = k * 2;1489+ float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1490+ STBIR_ASSERT(coefficient != 0);1491+ output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1492+ output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1493+ }1494+ break;1495+ case 3:1496+ for (k = n0; k <= n1; k++)1497+ {1498+ int in_pixel_index = k * 3;1499+ float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1500+ STBIR_ASSERT(coefficient != 0);1501+ output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1502+ output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1503+ output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;1504+ }1505+ break;1506+ case 4:1507+ for (k = n0; k <= n1; k++)1508+ {1509+ int in_pixel_index = k * 4;1510+ float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1511+ STBIR_ASSERT(coefficient != 0);1512+ output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1513+ output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1514+ output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;1515+ output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient;1516+ }1517+ break;1518+ default:1519+ for (k = n0; k <= n1; k++)1520+ {1521+ int in_pixel_index = k * channels;1522+ float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1523+ int c;1524+ STBIR_ASSERT(coefficient != 0);1525+ for (c = 0; c < channels; c++)1526+ output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient;1527+ }1528+ break;1529+ }1530+ }1531+}1532+1533+static void stbir__resample_horizontal_downsample(stbir__info* stbir_info, float* output_buffer)1534+{1535+ int x, k;1536+ int input_w = stbir_info->input_w;1537+ int channels = stbir_info->channels;1538+ float* decode_buffer = stbir__get_decode_buffer(stbir_info);1539+ stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors;1540+ float* horizontal_coefficients = stbir_info->horizontal_coefficients;1541+ int coefficient_width = stbir_info->horizontal_coefficient_width;1542+ int filter_pixel_margin = stbir_info->horizontal_filter_pixel_margin;1543+ int max_x = input_w + filter_pixel_margin * 2;1544+1545+ STBIR_ASSERT(!stbir__use_width_upsampling(stbir_info));1546+1547+ switch (channels) {1548+ case 1:1549+ for (x = 0; x < max_x; x++)1550+ {1551+ int n0 = horizontal_contributors[x].n0;1552+ int n1 = horizontal_contributors[x].n1;1553+1554+ int in_x = x - filter_pixel_margin;1555+ int in_pixel_index = in_x * 1;1556+ int max_n = n1;1557+ int coefficient_group = coefficient_width * x;1558+1559+ for (k = n0; k <= max_n; k++)1560+ {1561+ int out_pixel_index = k * 1;1562+ float coefficient = horizontal_coefficients[coefficient_group + k - n0];1563+ output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1564+ }1565+ }1566+ break;1567+1568+ case 2:1569+ for (x = 0; x < max_x; x++)1570+ {1571+ int n0 = horizontal_contributors[x].n0;1572+ int n1 = horizontal_contributors[x].n1;1573+1574+ int in_x = x - filter_pixel_margin;1575+ int in_pixel_index = in_x * 2;1576+ int max_n = n1;1577+ int coefficient_group = coefficient_width * x;1578+1579+ for (k = n0; k <= max_n; k++)1580+ {1581+ int out_pixel_index = k * 2;1582+ float coefficient = horizontal_coefficients[coefficient_group + k - n0];1583+ output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1584+ output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1585+ }1586+ }1587+ break;1588+1589+ case 3:1590+ for (x = 0; x < max_x; x++)1591+ {1592+ int n0 = horizontal_contributors[x].n0;1593+ int n1 = horizontal_contributors[x].n1;1594+1595+ int in_x = x - filter_pixel_margin;1596+ int in_pixel_index = in_x * 3;1597+ int max_n = n1;1598+ int coefficient_group = coefficient_width * x;1599+1600+ for (k = n0; k <= max_n; k++)1601+ {1602+ int out_pixel_index = k * 3;1603+ float coefficient = horizontal_coefficients[coefficient_group + k - n0];1604+ output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1605+ output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1606+ output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;1607+ }1608+ }1609+ break;1610+1611+ case 4:1612+ for (x = 0; x < max_x; x++)1613+ {1614+ int n0 = horizontal_contributors[x].n0;1615+ int n1 = horizontal_contributors[x].n1;1616+1617+ int in_x = x - filter_pixel_margin;1618+ int in_pixel_index = in_x * 4;1619+ int max_n = n1;1620+ int coefficient_group = coefficient_width * x;1621+1622+ for (k = n0; k <= max_n; k++)1623+ {1624+ int out_pixel_index = k * 4;1625+ float coefficient = horizontal_coefficients[coefficient_group + k - n0];1626+ output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1627+ output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1628+ output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;1629+ output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient;1630+ }1631+ }1632+ break;1633+1634+ default:1635+ for (x = 0; x < max_x; x++)1636+ {1637+ int n0 = horizontal_contributors[x].n0;1638+ int n1 = horizontal_contributors[x].n1;1639+1640+ int in_x = x - filter_pixel_margin;1641+ int in_pixel_index = in_x * channels;1642+ int max_n = n1;1643+ int coefficient_group = coefficient_width * x;1644+1645+ for (k = n0; k <= max_n; k++)1646+ {1647+ int c;1648+ int out_pixel_index = k * channels;1649+ float coefficient = horizontal_coefficients[coefficient_group + k - n0];1650+ for (c = 0; c < channels; c++)1651+ output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient;1652+ }1653+ }1654+ break;1655+ }1656+}1657+1658+static void stbir__decode_and_resample_upsample(stbir__info* stbir_info, int n)1659+{1660+ // Decode the nth scanline from the source image into the decode buffer.1661+ stbir__decode_scanline(stbir_info, n);1662+1663+ // Now resample it into the ring buffer.1664+ if (stbir__use_width_upsampling(stbir_info))1665+ stbir__resample_horizontal_upsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n));1666+ else1667+ stbir__resample_horizontal_downsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n));1668+1669+ // Now it's sitting in the ring buffer ready to be used as source for the vertical sampling.1670+}1671+1672+static void stbir__decode_and_resample_downsample(stbir__info* stbir_info, int n)1673+{1674+ // Decode the nth scanline from the source image into the decode buffer.1675+ stbir__decode_scanline(stbir_info, n);1676+1677+ memset(stbir_info->horizontal_buffer, 0, stbir_info->output_w * stbir_info->channels * sizeof(float));1678+1679+ // Now resample it into the horizontal buffer.1680+ if (stbir__use_width_upsampling(stbir_info))1681+ stbir__resample_horizontal_upsample(stbir_info, stbir_info->horizontal_buffer);1682+ else1683+ stbir__resample_horizontal_downsample(stbir_info, stbir_info->horizontal_buffer);1684+1685+ // Now it's sitting in the horizontal buffer ready to be distributed into the ring buffers.1686+}1687+1688+// Get the specified scan line from the ring buffer.1689+static float* stbir__get_ring_buffer_scanline(int get_scanline, float* ring_buffer, int begin_index, int first_scanline, int ring_buffer_num_entries, int ring_buffer_length)1690+{1691+ int ring_buffer_index = (begin_index + (get_scanline - first_scanline)) % ring_buffer_num_entries;1692+ return stbir__get_ring_buffer_entry(ring_buffer, ring_buffer_index, ring_buffer_length);1693+}1694+1695+1696+static void stbir__encode_scanline(stbir__info* stbir_info, int num_pixels, void *output_buffer, float *encode_buffer, int channels, int alpha_channel, int decode)1697+{1698+ int x;1699+ int n;1700+ int num_nonalpha;1701+ stbir_uint16 nonalpha[STBIR_MAX_CHANNELS];1702+1703+ if (!(stbir_info->flags&STBIR_FLAG_ALPHA_PREMULTIPLIED))1704+ {1705+ for (x=0; x < num_pixels; ++x)1706+ {1707+ int pixel_index = x*channels;1708+1709+ float alpha = encode_buffer[pixel_index + alpha_channel];1710+ float reciprocal_alpha = alpha ? 1.0f / alpha : 0;1711+1712+ // unrolling this produced a 1% slowdown upscaling a large RGBA linear-space image on my machine - stb1713+ for (n = 0; n < channels; n++)1714+ if (n != alpha_channel)1715+ encode_buffer[pixel_index + n] *= reciprocal_alpha;1716+1717+ // We added in a small epsilon to prevent the color channel from being deleted with zero alpha.1718+ // Because we only add it for integer types, it will automatically be discarded on integer1719+ // conversion, so we don't need to subtract it back out (which would be problematic for1720+ // numeric precision reasons).1721+ }1722+ }1723+1724+ // build a table of all channels that need colorspace correction, so1725+ // we don't perform colorspace correction on channels that don't need it.1726+ for (x = 0, num_nonalpha = 0; x < channels; ++x)1727+ {1728+ if (x != alpha_channel || (stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE))1729+ {1730+ nonalpha[num_nonalpha++] = (stbir_uint16)x;1731+ }1732+ }1733+1734+ #define STBIR__ROUND_INT(f) ((int) ((f)+0.5))1735+ #define STBIR__ROUND_UINT(f) ((stbir_uint32) ((f)+0.5))1736+1737+ #ifdef STBIR__SATURATE_INT1738+ #define STBIR__ENCODE_LINEAR8(f) stbir__saturate8 (STBIR__ROUND_INT((f) * stbir__max_uint8_as_float ))1739+ #define STBIR__ENCODE_LINEAR16(f) stbir__saturate16(STBIR__ROUND_INT((f) * stbir__max_uint16_as_float))1740+ #else1741+ #define STBIR__ENCODE_LINEAR8(f) (unsigned char ) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint8_as_float )1742+ #define STBIR__ENCODE_LINEAR16(f) (unsigned short) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint16_as_float)1743+ #endif1744+1745+ switch (decode)1746+ {1747+ case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR):1748+ for (x=0; x < num_pixels; ++x)1749+ {1750+ int pixel_index = x*channels;1751+1752+ for (n = 0; n < channels; n++)1753+ {1754+ int index = pixel_index + n;1755+ ((unsigned char*)output_buffer)[index] = STBIR__ENCODE_LINEAR8(encode_buffer[index]);1756+ }1757+ }1758+ break;1759+1760+ case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB):1761+ for (x=0; x < num_pixels; ++x)1762+ {1763+ int pixel_index = x*channels;1764+1765+ for (n = 0; n < num_nonalpha; n++)1766+ {1767+ int index = pixel_index + nonalpha[n];1768+ ((unsigned char*)output_buffer)[index] = stbir__linear_to_srgb_uchar(encode_buffer[index]);1769+ }1770+1771+ if (!(stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE))1772+ ((unsigned char *)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR8(encode_buffer[pixel_index+alpha_channel]);1773+ }1774+ break;1775+1776+ case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR):1777+ for (x=0; x < num_pixels; ++x)1778+ {1779+ int pixel_index = x*channels;1780+1781+ for (n = 0; n < channels; n++)1782+ {1783+ int index = pixel_index + n;1784+ ((unsigned short*)output_buffer)[index] = STBIR__ENCODE_LINEAR16(encode_buffer[index]);1785+ }1786+ }1787+ break;1788+1789+ case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB):1790+ for (x=0; x < num_pixels; ++x)1791+ {1792+ int pixel_index = x*channels;1793+1794+ for (n = 0; n < num_nonalpha; n++)1795+ {1796+ int index = pixel_index + nonalpha[n];1797+ ((unsigned short*)output_buffer)[index] = (unsigned short)STBIR__ROUND_INT(stbir__linear_to_srgb(stbir__saturate(encode_buffer[index])) * stbir__max_uint16_as_float);1798+ }1799+1800+ if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1801+ ((unsigned short*)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR16(encode_buffer[pixel_index + alpha_channel]);1802+ }1803+1804+ break;1805+1806+ case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR):1807+ for (x=0; x < num_pixels; ++x)1808+ {1809+ int pixel_index = x*channels;1810+1811+ for (n = 0; n < channels; n++)1812+ {1813+ int index = pixel_index + n;1814+ ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__saturate(encode_buffer[index])) * stbir__max_uint32_as_float);1815+ }1816+ }1817+ break;1818+1819+ case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB):1820+ for (x=0; x < num_pixels; ++x)1821+ {1822+ int pixel_index = x*channels;1823+1824+ for (n = 0; n < num_nonalpha; n++)1825+ {1826+ int index = pixel_index + nonalpha[n];1827+ ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__linear_to_srgb(stbir__saturate(encode_buffer[index]))) * stbir__max_uint32_as_float);1828+ }1829+1830+ if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1831+ ((unsigned int*)output_buffer)[pixel_index + alpha_channel] = (unsigned int)STBIR__ROUND_INT(((double)stbir__saturate(encode_buffer[pixel_index + alpha_channel])) * stbir__max_uint32_as_float);1832+ }1833+ break;1834+1835+ case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR):1836+ for (x=0; x < num_pixels; ++x)1837+ {1838+ int pixel_index = x*channels;1839+1840+ for (n = 0; n < channels; n++)1841+ {1842+ int index = pixel_index + n;1843+ ((float*)output_buffer)[index] = encode_buffer[index];1844+ }1845+ }1846+ break;1847+1848+ case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB):1849+ for (x=0; x < num_pixels; ++x)1850+ {1851+ int pixel_index = x*channels;1852+1853+ for (n = 0; n < num_nonalpha; n++)1854+ {1855+ int index = pixel_index + nonalpha[n];1856+ ((float*)output_buffer)[index] = stbir__linear_to_srgb(encode_buffer[index]);1857+ }1858+1859+ if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1860+ ((float*)output_buffer)[pixel_index + alpha_channel] = encode_buffer[pixel_index + alpha_channel];1861+ }1862+ break;1863+1864+ default:1865+ STBIR_ASSERT(!"Unknown type/colorspace/channels combination.");1866+ break;1867+ }1868+}1869+1870+static void stbir__resample_vertical_upsample(stbir__info* stbir_info, int n)1871+{1872+ int x, k;1873+ int output_w = stbir_info->output_w;1874+ stbir__contributors* vertical_contributors = stbir_info->vertical_contributors;1875+ float* vertical_coefficients = stbir_info->vertical_coefficients;1876+ int channels = stbir_info->channels;1877+ int alpha_channel = stbir_info->alpha_channel;1878+ int type = stbir_info->type;1879+ int colorspace = stbir_info->colorspace;1880+ int ring_buffer_entries = stbir_info->ring_buffer_num_entries;1881+ void* output_data = stbir_info->output_data;1882+ float* encode_buffer = stbir_info->encode_buffer;1883+ int decode = STBIR__DECODE(type, colorspace);1884+ int coefficient_width = stbir_info->vertical_coefficient_width;1885+ int coefficient_counter;1886+ int contributor = n;1887+1888+ float* ring_buffer = stbir_info->ring_buffer;1889+ int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index;1890+ int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline;1891+ int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);1892+1893+ int n0,n1, output_row_start;1894+ int coefficient_group = coefficient_width * contributor;1895+1896+ n0 = vertical_contributors[contributor].n0;1897+ n1 = vertical_contributors[contributor].n1;1898+1899+ output_row_start = n * stbir_info->output_stride_bytes;1900+1901+ STBIR_ASSERT(stbir__use_height_upsampling(stbir_info));1902+1903+ memset(encode_buffer, 0, output_w * sizeof(float) * channels);1904+1905+ // I tried reblocking this for better cache usage of encode_buffer1906+ // (using x_outer, k, x_inner), but it lost speed. -- stb1907+1908+ coefficient_counter = 0;1909+ switch (channels) {1910+ case 1:1911+ for (k = n0; k <= n1; k++)1912+ {1913+ int coefficient_index = coefficient_counter++;1914+ float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1915+ float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1916+ for (x = 0; x < output_w; ++x)1917+ {1918+ int in_pixel_index = x * 1;1919+ encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;1920+ }1921+ }1922+ break;1923+ case 2:1924+ for (k = n0; k <= n1; k++)1925+ {1926+ int coefficient_index = coefficient_counter++;1927+ float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1928+ float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1929+ for (x = 0; x < output_w; ++x)1930+ {1931+ int in_pixel_index = x * 2;1932+ encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;1933+ encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;1934+ }1935+ }1936+ break;1937+ case 3:1938+ for (k = n0; k <= n1; k++)1939+ {1940+ int coefficient_index = coefficient_counter++;1941+ float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1942+ float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1943+ for (x = 0; x < output_w; ++x)1944+ {1945+ int in_pixel_index = x * 3;1946+ encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;1947+ encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;1948+ encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient;1949+ }1950+ }1951+ break;1952+ case 4:1953+ for (k = n0; k <= n1; k++)1954+ {1955+ int coefficient_index = coefficient_counter++;1956+ float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1957+ float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1958+ for (x = 0; x < output_w; ++x)1959+ {1960+ int in_pixel_index = x * 4;1961+ encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;1962+ encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;1963+ encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient;1964+ encode_buffer[in_pixel_index + 3] += ring_buffer_entry[in_pixel_index + 3] * coefficient;1965+ }1966+ }1967+ break;1968+ default:1969+ for (k = n0; k <= n1; k++)1970+ {1971+ int coefficient_index = coefficient_counter++;1972+ float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1973+ float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1974+ for (x = 0; x < output_w; ++x)1975+ {1976+ int in_pixel_index = x * channels;1977+ int c;1978+ for (c = 0; c < channels; c++)1979+ encode_buffer[in_pixel_index + c] += ring_buffer_entry[in_pixel_index + c] * coefficient;1980+ }1981+ }1982+ break;1983+ }1984+ stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, encode_buffer, channels, alpha_channel, decode);1985+}1986+1987+static void stbir__resample_vertical_downsample(stbir__info* stbir_info, int n)1988+{1989+ int x, k;1990+ int output_w = stbir_info->output_w;1991+ stbir__contributors* vertical_contributors = stbir_info->vertical_contributors;1992+ float* vertical_coefficients = stbir_info->vertical_coefficients;1993+ int channels = stbir_info->channels;1994+ int ring_buffer_entries = stbir_info->ring_buffer_num_entries;1995+ float* horizontal_buffer = stbir_info->horizontal_buffer;1996+ int coefficient_width = stbir_info->vertical_coefficient_width;1997+ int contributor = n + stbir_info->vertical_filter_pixel_margin;1998+1999+ float* ring_buffer = stbir_info->ring_buffer;2000+ int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index;2001+ int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline;2002+ int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);2003+ int n0,n1;2004+2005+ n0 = vertical_contributors[contributor].n0;2006+ n1 = vertical_contributors[contributor].n1;2007+2008+ STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info));2009+2010+ for (k = n0; k <= n1; k++)2011+ {2012+ int coefficient_index = k - n0;2013+ int coefficient_group = coefficient_width * contributor;2014+ float coefficient = vertical_coefficients[coefficient_group + coefficient_index];2015+2016+ float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);2017+2018+ switch (channels) {2019+ case 1:2020+ for (x = 0; x < output_w; x++)2021+ {2022+ int in_pixel_index = x * 1;2023+ ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;2024+ }2025+ break;2026+ case 2:2027+ for (x = 0; x < output_w; x++)2028+ {2029+ int in_pixel_index = x * 2;2030+ ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;2031+ ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;2032+ }2033+ break;2034+ case 3:2035+ for (x = 0; x < output_w; x++)2036+ {2037+ int in_pixel_index = x * 3;2038+ ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;2039+ ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;2040+ ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient;2041+ }2042+ break;2043+ case 4:2044+ for (x = 0; x < output_w; x++)2045+ {2046+ int in_pixel_index = x * 4;2047+ ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;2048+ ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;2049+ ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient;2050+ ring_buffer_entry[in_pixel_index + 3] += horizontal_buffer[in_pixel_index + 3] * coefficient;2051+ }2052+ break;2053+ default:2054+ for (x = 0; x < output_w; x++)2055+ {2056+ int in_pixel_index = x * channels;2057+2058+ int c;2059+ for (c = 0; c < channels; c++)2060+ ring_buffer_entry[in_pixel_index + c] += horizontal_buffer[in_pixel_index + c] * coefficient;2061+ }2062+ break;2063+ }2064+ }2065+}2066+2067+static void stbir__buffer_loop_upsample(stbir__info* stbir_info)2068+{2069+ int y;2070+ float scale_ratio = stbir_info->vertical_scale;2071+ float out_scanlines_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(1/scale_ratio) * scale_ratio;2072+2073+ STBIR_ASSERT(stbir__use_height_upsampling(stbir_info));2074+2075+ for (y = 0; y < stbir_info->output_h; y++)2076+ {2077+ float in_center_of_out = 0; // Center of the current out scanline in the in scanline space2078+ int in_first_scanline = 0, in_last_scanline = 0;2079+2080+ stbir__calculate_sample_range_upsample(y, out_scanlines_radius, scale_ratio, stbir_info->vertical_shift, &in_first_scanline, &in_last_scanline, &in_center_of_out);2081+2082+ STBIR_ASSERT(in_last_scanline - in_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);2083+2084+ if (stbir_info->ring_buffer_begin_index >= 0)2085+ {2086+ // Get rid of whatever we don't need anymore.2087+ while (in_first_scanline > stbir_info->ring_buffer_first_scanline)2088+ {2089+ if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline)2090+ {2091+ // We just popped the last scanline off the ring buffer.2092+ // Reset it to the empty state.2093+ stbir_info->ring_buffer_begin_index = -1;2094+ stbir_info->ring_buffer_first_scanline = 0;2095+ stbir_info->ring_buffer_last_scanline = 0;2096+ break;2097+ }2098+ else2099+ {2100+ stbir_info->ring_buffer_first_scanline++;2101+ stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries;2102+ }2103+ }2104+ }2105+2106+ // Load in new ones.2107+ if (stbir_info->ring_buffer_begin_index < 0)2108+ stbir__decode_and_resample_upsample(stbir_info, in_first_scanline);2109+2110+ while (in_last_scanline > stbir_info->ring_buffer_last_scanline)2111+ stbir__decode_and_resample_upsample(stbir_info, stbir_info->ring_buffer_last_scanline + 1);2112+2113+ // Now all buffers should be ready to write a row of vertical sampling.2114+ stbir__resample_vertical_upsample(stbir_info, y);2115+2116+ STBIR_PROGRESS_REPORT((float)y / stbir_info->output_h);2117+ }2118+}2119+2120+static void stbir__empty_ring_buffer(stbir__info* stbir_info, int first_necessary_scanline)2121+{2122+ int output_stride_bytes = stbir_info->output_stride_bytes;2123+ int channels = stbir_info->channels;2124+ int alpha_channel = stbir_info->alpha_channel;2125+ int type = stbir_info->type;2126+ int colorspace = stbir_info->colorspace;2127+ int output_w = stbir_info->output_w;2128+ void* output_data = stbir_info->output_data;2129+ int decode = STBIR__DECODE(type, colorspace);2130+2131+ float* ring_buffer = stbir_info->ring_buffer;2132+ int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);2133+2134+ if (stbir_info->ring_buffer_begin_index >= 0)2135+ {2136+ // Get rid of whatever we don't need anymore.2137+ while (first_necessary_scanline > stbir_info->ring_buffer_first_scanline)2138+ {2139+ if (stbir_info->ring_buffer_first_scanline >= 0 && stbir_info->ring_buffer_first_scanline < stbir_info->output_h)2140+ {2141+ int output_row_start = stbir_info->ring_buffer_first_scanline * output_stride_bytes;2142+ float* ring_buffer_entry = stbir__get_ring_buffer_entry(ring_buffer, stbir_info->ring_buffer_begin_index, ring_buffer_length);2143+ stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, ring_buffer_entry, channels, alpha_channel, decode);2144+ STBIR_PROGRESS_REPORT((float)stbir_info->ring_buffer_first_scanline / stbir_info->output_h);2145+ }2146+2147+ if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline)2148+ {2149+ // We just popped the last scanline off the ring buffer.2150+ // Reset it to the empty state.2151+ stbir_info->ring_buffer_begin_index = -1;2152+ stbir_info->ring_buffer_first_scanline = 0;2153+ stbir_info->ring_buffer_last_scanline = 0;2154+ break;2155+ }2156+ else2157+ {2158+ stbir_info->ring_buffer_first_scanline++;2159+ stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries;2160+ }2161+ }2162+ }2163+}2164+2165+static void stbir__buffer_loop_downsample(stbir__info* stbir_info)2166+{2167+ int y;2168+ float scale_ratio = stbir_info->vertical_scale;2169+ int output_h = stbir_info->output_h;2170+ float in_pixels_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(scale_ratio) / scale_ratio;2171+ int pixel_margin = stbir_info->vertical_filter_pixel_margin;2172+ int max_y = stbir_info->input_h + pixel_margin;2173+2174+ STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info));2175+2176+ for (y = -pixel_margin; y < max_y; y++)2177+ {2178+ float out_center_of_in; // Center of the current out scanline in the in scanline space2179+ int out_first_scanline, out_last_scanline;2180+2181+ stbir__calculate_sample_range_downsample(y, in_pixels_radius, scale_ratio, stbir_info->vertical_shift, &out_first_scanline, &out_last_scanline, &out_center_of_in);2182+2183+ STBIR_ASSERT(out_last_scanline - out_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);2184+2185+ if (out_last_scanline < 0 || out_first_scanline >= output_h)2186+ continue;2187+2188+ stbir__empty_ring_buffer(stbir_info, out_first_scanline);2189+2190+ stbir__decode_and_resample_downsample(stbir_info, y);2191+2192+ // Load in new ones.2193+ if (stbir_info->ring_buffer_begin_index < 0)2194+ stbir__add_empty_ring_buffer_entry(stbir_info, out_first_scanline);2195+2196+ while (out_last_scanline > stbir_info->ring_buffer_last_scanline)2197+ stbir__add_empty_ring_buffer_entry(stbir_info, stbir_info->ring_buffer_last_scanline + 1);2198+2199+ // Now the horizontal buffer is ready to write to all ring buffer rows.2200+ stbir__resample_vertical_downsample(stbir_info, y);2201+ }2202+2203+ stbir__empty_ring_buffer(stbir_info, stbir_info->output_h);2204+}2205+2206+static void stbir__setup(stbir__info *info, int input_w, int input_h, int output_w, int output_h, int channels)2207+{2208+ info->input_w = input_w;2209+ info->input_h = input_h;2210+ info->output_w = output_w;2211+ info->output_h = output_h;2212+ info->channels = channels;2213+}2214+2215+static void stbir__calculate_transform(stbir__info *info, float s0, float t0, float s1, float t1, float *transform)2216+{2217+ info->s0 = s0;2218+ info->t0 = t0;2219+ info->s1 = s1;2220+ info->t1 = t1;2221+2222+ if (transform)2223+ {2224+ info->horizontal_scale = transform[0];2225+ info->vertical_scale = transform[1];2226+ info->horizontal_shift = transform[2];2227+ info->vertical_shift = transform[3];2228+ }2229+ else2230+ {2231+ info->horizontal_scale = ((float)info->output_w / info->input_w) / (s1 - s0);2232+ info->vertical_scale = ((float)info->output_h / info->input_h) / (t1 - t0);2233+2234+ info->horizontal_shift = s0 * info->output_w / (s1 - s0);2235+ info->vertical_shift = t0 * info->output_h / (t1 - t0);2236+ }2237+}2238+2239+static void stbir__choose_filter(stbir__info *info, stbir_filter h_filter, stbir_filter v_filter)2240+{2241+ if (h_filter == 0)2242+ h_filter = stbir__use_upsampling(info->horizontal_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE;2243+ if (v_filter == 0)2244+ v_filter = stbir__use_upsampling(info->vertical_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE;2245+ info->horizontal_filter = h_filter;2246+ info->vertical_filter = v_filter;2247+}2248+2249+static stbir_uint32 stbir__calculate_memory(stbir__info *info)2250+{2251+ int pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale);2252+ int filter_height = stbir__get_filter_pixel_width(info->vertical_filter, info->vertical_scale);2253+2254+ info->horizontal_num_contributors = stbir__get_contributors(info->horizontal_scale, info->horizontal_filter, info->input_w, info->output_w);2255+ info->vertical_num_contributors = stbir__get_contributors(info->vertical_scale , info->vertical_filter , info->input_h, info->output_h);2256+2257+ // One extra entry because floating point precision problems sometimes cause an extra to be necessary.2258+ info->ring_buffer_num_entries = filter_height + 1;2259+2260+ info->horizontal_contributors_size = info->horizontal_num_contributors * sizeof(stbir__contributors);2261+ info->horizontal_coefficients_size = stbir__get_total_horizontal_coefficients(info) * sizeof(float);2262+ info->vertical_contributors_size = info->vertical_num_contributors * sizeof(stbir__contributors);2263+ info->vertical_coefficients_size = stbir__get_total_vertical_coefficients(info) * sizeof(float);2264+ info->decode_buffer_size = (info->input_w + pixel_margin * 2) * info->channels * sizeof(float);2265+ info->horizontal_buffer_size = info->output_w * info->channels * sizeof(float);2266+ info->ring_buffer_size = info->output_w * info->channels * info->ring_buffer_num_entries * sizeof(float);2267+ info->encode_buffer_size = info->output_w * info->channels * sizeof(float);2268+2269+ STBIR_ASSERT(info->horizontal_filter != 0);2270+ STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late2271+ STBIR_ASSERT(info->vertical_filter != 0);2272+ STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late2273+2274+ if (stbir__use_height_upsampling(info))2275+ // The horizontal buffer is for when we're downsampling the height and we2276+ // can't output the result of sampling the decode buffer directly into the2277+ // ring buffers.2278+ info->horizontal_buffer_size = 0;2279+ else2280+ // The encode buffer is to retain precision in the height upsampling method2281+ // and isn't used when height downsampling.2282+ info->encode_buffer_size = 0;2283+2284+ return info->horizontal_contributors_size + info->horizontal_coefficients_size2285+ + info->vertical_contributors_size + info->vertical_coefficients_size2286+ + info->decode_buffer_size + info->horizontal_buffer_size2287+ + info->ring_buffer_size + info->encode_buffer_size;2288+}2289+2290+static int stbir__resize_allocated(stbir__info *info,2291+ const void* input_data, int input_stride_in_bytes,2292+ void* output_data, int output_stride_in_bytes,2293+ int alpha_channel, stbir_uint32 flags, stbir_datatype type,2294+ stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace,2295+ void* tempmem, size_t tempmem_size_in_bytes)2296+{2297+ size_t memory_required = stbir__calculate_memory(info);2298+2299+ int width_stride_input = input_stride_in_bytes ? input_stride_in_bytes : info->channels * info->input_w * stbir__type_size[type];2300+ int width_stride_output = output_stride_in_bytes ? output_stride_in_bytes : info->channels * info->output_w * stbir__type_size[type];2301+2302+#ifdef STBIR_DEBUG_OVERWRITE_TEST2303+#define OVERWRITE_ARRAY_SIZE 82304+ unsigned char overwrite_output_before_pre[OVERWRITE_ARRAY_SIZE];2305+ unsigned char overwrite_tempmem_before_pre[OVERWRITE_ARRAY_SIZE];2306+ unsigned char overwrite_output_after_pre[OVERWRITE_ARRAY_SIZE];2307+ unsigned char overwrite_tempmem_after_pre[OVERWRITE_ARRAY_SIZE];2308+2309+ size_t begin_forbidden = width_stride_output * (info->output_h - 1) + info->output_w * info->channels * stbir__type_size[type];2310+ memcpy(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE);2311+ memcpy(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE);2312+ memcpy(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE);2313+ memcpy(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE);2314+#endif2315+2316+ STBIR_ASSERT(info->channels >= 0);2317+ STBIR_ASSERT(info->channels <= STBIR_MAX_CHANNELS);2318+2319+ if (info->channels < 0 || info->channels > STBIR_MAX_CHANNELS)2320+ return 0;2321+2322+ STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));2323+ STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));2324+2325+ if (info->horizontal_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table))2326+ return 0;2327+ if (info->vertical_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table))2328+ return 0;2329+2330+ if (alpha_channel < 0)2331+ flags |= STBIR_FLAG_ALPHA_USES_COLORSPACE | STBIR_FLAG_ALPHA_PREMULTIPLIED;2332+2333+ if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) {2334+ STBIR_ASSERT(alpha_channel >= 0 && alpha_channel < info->channels);2335+ }2336+2337+ if (alpha_channel >= info->channels)2338+ return 0;2339+2340+ STBIR_ASSERT(tempmem);2341+2342+ if (!tempmem)2343+ return 0;2344+2345+ STBIR_ASSERT(tempmem_size_in_bytes >= memory_required);2346+2347+ if (tempmem_size_in_bytes < memory_required)2348+ return 0;2349+2350+ memset(tempmem, 0, tempmem_size_in_bytes);2351+2352+ info->input_data = input_data;2353+ info->input_stride_bytes = width_stride_input;2354+2355+ info->output_data = output_data;2356+ info->output_stride_bytes = width_stride_output;2357+2358+ info->alpha_channel = alpha_channel;2359+ info->flags = flags;2360+ info->type = type;2361+ info->edge_horizontal = edge_horizontal;2362+ info->edge_vertical = edge_vertical;2363+ info->colorspace = colorspace;2364+2365+ info->horizontal_coefficient_width = stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale);2366+ info->vertical_coefficient_width = stbir__get_coefficient_width (info->vertical_filter , info->vertical_scale );2367+ info->horizontal_filter_pixel_width = stbir__get_filter_pixel_width (info->horizontal_filter, info->horizontal_scale);2368+ info->vertical_filter_pixel_width = stbir__get_filter_pixel_width (info->vertical_filter , info->vertical_scale );2369+ info->horizontal_filter_pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale);2370+ info->vertical_filter_pixel_margin = stbir__get_filter_pixel_margin(info->vertical_filter , info->vertical_scale );2371+2372+ info->ring_buffer_length_bytes = info->output_w * info->channels * sizeof(float);2373+ info->decode_buffer_pixels = info->input_w + info->horizontal_filter_pixel_margin * 2;2374+2375+#define STBIR__NEXT_MEMPTR(current, newtype) (newtype*)(((unsigned char*)current) + current##_size)2376+2377+ info->horizontal_contributors = (stbir__contributors *) tempmem;2378+ info->horizontal_coefficients = STBIR__NEXT_MEMPTR(info->horizontal_contributors, float);2379+ info->vertical_contributors = STBIR__NEXT_MEMPTR(info->horizontal_coefficients, stbir__contributors);2380+ info->vertical_coefficients = STBIR__NEXT_MEMPTR(info->vertical_contributors, float);2381+ info->decode_buffer = STBIR__NEXT_MEMPTR(info->vertical_coefficients, float);2382+2383+ if (stbir__use_height_upsampling(info))2384+ {2385+ info->horizontal_buffer = NULL;2386+ info->ring_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float);2387+ info->encode_buffer = STBIR__NEXT_MEMPTR(info->ring_buffer, float);2388+2389+ STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->encode_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes);2390+ }2391+ else2392+ {2393+ info->horizontal_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float);2394+ info->ring_buffer = STBIR__NEXT_MEMPTR(info->horizontal_buffer, float);2395+ info->encode_buffer = NULL;2396+2397+ STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->ring_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes);2398+ }2399+2400+#undef STBIR__NEXT_MEMPTR2401+2402+ // This signals that the ring buffer is empty2403+ info->ring_buffer_begin_index = -1;2404+2405+ stbir__calculate_filters(info->horizontal_contributors, info->horizontal_coefficients, info->horizontal_filter, info->horizontal_scale, info->horizontal_shift, info->input_w, info->output_w);2406+ stbir__calculate_filters(info->vertical_contributors, info->vertical_coefficients, info->vertical_filter, info->vertical_scale, info->vertical_shift, info->input_h, info->output_h);2407+2408+ STBIR_PROGRESS_REPORT(0);2409+2410+ if (stbir__use_height_upsampling(info))2411+ stbir__buffer_loop_upsample(info);2412+ else2413+ stbir__buffer_loop_downsample(info);2414+2415+ STBIR_PROGRESS_REPORT(1);2416+2417+#ifdef STBIR_DEBUG_OVERWRITE_TEST2418+ STBIR_ASSERT(memcmp(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0);2419+ STBIR_ASSERT(memcmp(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE) == 0);2420+ STBIR_ASSERT(memcmp(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0);2421+ STBIR_ASSERT(memcmp(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE) == 0);2422+#endif2423+2424+ return 1;2425+}2426+2427+2428+static int stbir__resize_arbitrary(2429+ void *alloc_context,2430+ const void* input_data, int input_w, int input_h, int input_stride_in_bytes,2431+ void* output_data, int output_w, int output_h, int output_stride_in_bytes,2432+ float s0, float t0, float s1, float t1, float *transform,2433+ int channels, int alpha_channel, stbir_uint32 flags, stbir_datatype type,2434+ stbir_filter h_filter, stbir_filter v_filter,2435+ stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace)2436+{2437+ stbir__info info;2438+ int result;2439+ size_t memory_required;2440+ void* extra_memory;2441+2442+ stbir__setup(&info, input_w, input_h, output_w, output_h, channels);2443+ stbir__calculate_transform(&info, s0,t0,s1,t1,transform);2444+ stbir__choose_filter(&info, h_filter, v_filter);2445+ memory_required = stbir__calculate_memory(&info);2446+ extra_memory = STBIR_MALLOC(memory_required, alloc_context);2447+2448+ if (!extra_memory)2449+ return 0;2450+2451+ result = stbir__resize_allocated(&info, input_data, input_stride_in_bytes,2452+ output_data, output_stride_in_bytes,2453+ alpha_channel, flags, type,2454+ edge_horizontal, edge_vertical,2455+ colorspace, extra_memory, memory_required);2456+2457+ STBIR_FREE(extra_memory, alloc_context);2458+2459+ return result;2460+}2461+2462+STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2463+ unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2464+ int num_channels)2465+{2466+ return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,2467+ output_pixels, output_w, output_h, output_stride_in_bytes,2468+ 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,2469+ STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR);2470+}2471+2472+STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2473+ float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2474+ int num_channels)2475+{2476+ return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,2477+ output_pixels, output_w, output_h, output_stride_in_bytes,2478+ 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_FLOAT, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,2479+ STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR);2480+}2481+2482+STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2483+ unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2484+ int num_channels, int alpha_channel, int flags)2485+{2486+ return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,2487+ output_pixels, output_w, output_h, output_stride_in_bytes,2488+ 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,2489+ STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB);2490+}2491+2492+STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2493+ unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2494+ int num_channels, int alpha_channel, int flags,2495+ stbir_edge edge_wrap_mode)2496+{2497+ return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,2498+ output_pixels, output_w, output_h, output_stride_in_bytes,2499+ 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,2500+ edge_wrap_mode, edge_wrap_mode, STBIR_COLORSPACE_SRGB);2501+}2502+2503+STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2504+ unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2505+ int num_channels, int alpha_channel, int flags,2506+ stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,2507+ void *alloc_context)2508+{2509+ return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2510+ output_pixels, output_w, output_h, output_stride_in_bytes,2511+ 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, filter, filter,2512+ edge_wrap_mode, edge_wrap_mode, space);2513+}2514+2515+STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2516+ stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes,2517+ int num_channels, int alpha_channel, int flags,2518+ stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,2519+ void *alloc_context)2520+{2521+ return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2522+ output_pixels, output_w, output_h, output_stride_in_bytes,2523+ 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT16, filter, filter,2524+ edge_wrap_mode, edge_wrap_mode, space);2525+}2526+2527+2528+STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2529+ float *output_pixels , int output_w, int output_h, int output_stride_in_bytes,2530+ int num_channels, int alpha_channel, int flags,2531+ stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,2532+ void *alloc_context)2533+{2534+ return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2535+ output_pixels, output_w, output_h, output_stride_in_bytes,2536+ 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_FLOAT, filter, filter,2537+ edge_wrap_mode, edge_wrap_mode, space);2538+}2539+2540+2541+STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2542+ void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2543+ stbir_datatype datatype,2544+ int num_channels, int alpha_channel, int flags,2545+ stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,2546+ stbir_filter filter_horizontal, stbir_filter filter_vertical,2547+ stbir_colorspace space, void *alloc_context)2548+{2549+ return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2550+ output_pixels, output_w, output_h, output_stride_in_bytes,2551+ 0,0,1,1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,2552+ edge_mode_horizontal, edge_mode_vertical, space);2553+}2554+2555+2556+STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2557+ void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2558+ stbir_datatype datatype,2559+ int num_channels, int alpha_channel, int flags,2560+ stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,2561+ stbir_filter filter_horizontal, stbir_filter filter_vertical,2562+ stbir_colorspace space, void *alloc_context,2563+ float x_scale, float y_scale,2564+ float x_offset, float y_offset)2565+{2566+ float transform[4];2567+ transform[0] = x_scale;2568+ transform[1] = y_scale;2569+ transform[2] = x_offset;2570+ transform[3] = y_offset;2571+ return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2572+ output_pixels, output_w, output_h, output_stride_in_bytes,2573+ 0,0,1,1,transform,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,2574+ edge_mode_horizontal, edge_mode_vertical, space);2575+}2576+2577+STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2578+ void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2579+ stbir_datatype datatype,2580+ int num_channels, int alpha_channel, int flags,2581+ stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,2582+ stbir_filter filter_horizontal, stbir_filter filter_vertical,2583+ stbir_colorspace space, void *alloc_context,2584+ float s0, float t0, float s1, float t1)2585+{2586+ return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2587+ output_pixels, output_w, output_h, output_stride_in_bytes,2588+ s0,t0,s1,t1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,2589+ edge_mode_horizontal, edge_mode_vertical, space);2590+}2591+2592+#endif // STB_IMAGE_RESIZE_IMPLEMENTATION2593+2594+/*2595+------------------------------------------------------------------------------2596+This software is available under 2 licenses -- choose whichever you prefer.2597+------------------------------------------------------------------------------2598+ALTERNATIVE A - MIT License2599+Copyright (c) 2017 Sean Barrett2600+Permission is hereby granted, free of charge, to any person obtaining a copy of2601+this software and associated documentation files (the "Software"), to deal in2602+the Software without restriction, including without limitation the rights to2603+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies2604+of the Software, and to permit persons to whom the Software is furnished to do2605+so, subject to the following conditions:2606+The above copyright notice and this permission notice shall be included in all2607+copies or substantial portions of the Software.2608+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR2609+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,2610+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE2611+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER2612+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,2613+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE2614+SOFTWARE.2615+------------------------------------------------------------------------------2616+ALTERNATIVE B - Public Domain (www.unlicense.org)2617+This is free and unencumbered software released into the public domain.2618+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this2619+software, either in source code form or as a compiled binary, for any purpose,2620+commercial or non-commercial, and by any means.2621+In jurisdictions that recognize copyright laws, the author or authors of this2622+software dedicate any and all copyright interest in the software to the public2623+domain. We make this dedication for the benefit of the public at large and to2624+the detriment of our heirs and successors. We intend this dedication to be an2625+overt act of relinquishment in perpetuity of all present and future rights to2626+this software under copyright law.2627+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR2628+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,2629+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE2630+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN2631+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION2632+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.2633+------------------------------------------------------------------------------2634+*/modified:deprecated/stb.h+14 added-1357 removed
2421 unmodified lines2422 ptrdiff_t len=0,x,y, n = (int) strlen(path), f1,f2;2423 char *s = stb_strrchr2(path, '/', '\\');2424 char *t = strrchr(path, '.');2425 if (s && t && t < s) t = NULL;2426+2427+ if (!s) {2428+ // check for drive2429+ if (isalpha(path[0]) && path[1] == ':')2430+ s = &path[1];2431+ }2432 if (s) ++s;2433 2434 if (flag == STB_EXT_NO_PERIOD)2435 flag |= STB_EXT;3701 unmodified lines6137 char **results = NULL;6138 char buffer[4096], with_slash[4096];6139 size_t n;6140 6135- #ifdef _MSC_VER6141+ #ifdef WIN326142 stb__wchar *ws;6143 struct _wfinddata_t data;6144 #ifdef _WIN646145 const intptr_t none = -1;1 unmodified line6147 #else6148 const long none = -1;6149 long z;6150 #endif6145- #else // !_MSC_VER6151+ #else // !WIN326152 const DIR *none = NULL;6153 DIR *z;6154 #endif6155 8 unmodified lines6164 buffer[n] = 0;6165 if (!stb_strscpy(with_slash,buffer,sizeof(with_slash)))6166 return NULL;6167 6162- #ifdef _MSC_VER6168+ #ifdef WIN326169 if (!stb_strscpy(buffer+n,"*.*",sizeof(buffer)-n))6170 return NULL;6171 ws = stb__from_utf8(buffer);6172 z = _wfindfirst((wchar_t *)ws, &data);2 unmodified lines6175 #endif6176 6177 if (z != none) {6178 int nonempty = STB_TRUE;6173- #ifndef _MSC_VER6179+ #ifndef WIN326180 struct dirent *data = readdir(z);6181 nonempty = (data != NULL);6182 #endif6183 6184 if (nonempty) {6185 6186 do {6187 int is_subdir;6182- #ifdef _MSC_VER6188+ #ifdef WIN326189 char *name = stb__to_utf8((stb__wchar *)data.name);6190 if (name == NULL) {6191 fprintf(stderr, "%s to convert '%S' to %s!\n", "Unable", data.name, "utf8");6192 continue;19 unmodified lines6212 }6213 }6214 }6215 }6210- #ifdef _MSC_VER6216+ #ifdef WIN326217 while (0 == _wfindnext(z, &data));6218 #else6219 while ((data = readdir(z)) != NULL);6220 #endif6221 }6216- #ifdef _MSC_VER6222+ #ifdef WIN326223 _findclose(z);6224 #else6225 closedir(z);6226 #endif3008 unmodified lines9235 int z;9236 // need to allow for non-writeable strings... assume they're small9237 if (s - last < 256) {9238 stb_strncpy(buffer, last, (int) (s-last+1));9239+ buffer[s-last] = 0;9240 z = stb__wildmatch_raw2(buffer, candidate, search, insensitive);9241 } else {9242 *s = 0;9243 z = stb__wildmatch_raw2(last, candidate, search, insensitive);3820 unmodified lines13064 13065 #endif // STB_DEFINE13066 #endif // !STB_DEBUG && !STB_ALWAYS_H13067 13061-13062-#ifdef STB_STUA13063-#error "STUA is no longer supported"13064-//////////////////////////////////////////////////////////////////////////13065-//13066-// stua: little scripting language13067-//13068-// define STB_STUA to compile it13069-//13070-// see http://nothings.org/stb/stb_stua.html for documentation13071-//13072-// basic parsing model:13073-//13074-// lexical analysis13075-// use stb_lex() to parse tokens; keywords get their own tokens13076-//13077-// parsing:13078-// recursive descent parser. too much of a hassle to make an unambiguous13079-// LR(1) grammar, and one-pass generation is clumsier (recursive descent13080-// makes it easier to e.g. compile nested functions). on the other hand,13081-// dictionary syntax required hackery to get extra lookahead.13082-//13083-// codegen:13084-// output into an evaluation tree, using array indices as 'pointers'13085-//13086-// run:13087-// traverse the tree; support for 'break/continue/return' is tricky13088-//13089-// garbage collection:13090-// stu__mark and sweep; explicit stack with non-stu__compile_global_scope roots13091-13092-typedef stb_int32 stua_obj;13093-13094-typedef stb_idict stua_dict;13095-13096-STB_EXTERN void stua_run_script(char *s);13097-STB_EXTERN void stua_uninit(void);13098-13099-extern stua_obj stua_globals;13100-13101-STB_EXTERN double stua_number(stua_obj z);13102-13103-STB_EXTERN stua_obj stua_getnil(void);13104-STB_EXTERN stua_obj stua_getfalse(void);13105-STB_EXTERN stua_obj stua_gettrue(void);13106-STB_EXTERN stua_obj stua_string(char *z);13107-STB_EXTERN stua_obj stua_make_number(double d);13108-STB_EXTERN stua_obj stua_box(int type, void *data, int size);13109-13110-enum13111-{13112- STUA_op_negate=129,13113- STUA_op_shl, STUA_op_ge,13114- STUA_op_shr, STUA_op_le,13115- STUA_op_shru,13116- STUA_op_last13117-};13118-13119-#define STUA_NO_VALUE 2 // equivalent to a tagged NULL13120-STB_EXTERN stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c);13121-13122-STB_EXTERN stua_obj stua_error(char *err, ...);13123-13124-STB_EXTERN stua_obj stua_pushroot(stua_obj o);13125-STB_EXTERN void stua_poproot ( void );13126-13127-13128-#ifdef STB_DEFINE13129-// INTERPRETER13130-13131-// 31-bit floating point implementation13132-// force the (1 << 30) bit (2nd highest bit) to be zero by re-biasing the exponent;13133-// then shift and set the bottom bit13134-13135-static stua_obj stu__floatp(float *f)13136-{13137- unsigned int n = *(unsigned int *) f;13138- unsigned int e = n & (0xff << 23);13139-13140- assert(sizeof(int) == 4 && sizeof(float) == 4);13141-13142- if (!e) // zero?13143- n = n; // no change13144- else if (e < (64 << 23)) // underflow of the packed encoding?13145- n = (n & 0x80000000); // signed 013146- else if (e > (190 << 23)) // overflow of the encoding? (or INF or NAN)13147- n = (n & 0x80000000) + (127 << 23); // new INF encoding13148- else13149- n -= 0x20000000;13150-13151- // now we need to shuffle the bits so that the spare bit is at the bottom13152- assert((n & 0x40000000) == 0);13153- return (n & 0x80000000) + (n << 1) + 1;13154-}13155-13156-static unsigned char stu__getfloat_addend[256];13157-static float stu__getfloat(stua_obj v)13158-{13159- unsigned int n;13160- unsigned int e = ((unsigned int) v) >> 24;13161-13162- n = (int) v >> 1; // preserve high bit13163- n += stu__getfloat_addend[e] << 24;13164- return *(float *) &n;13165-}13166-13167-stua_obj stua_float(float f)13168-{13169- return stu__floatp(&f);13170-}13171-13172-static void stu__float_init(void)13173-{13174- int i;13175- stu__getfloat_addend[0] = 0; // do nothing to biased exponent of 013176- for (i=1; i < 127; ++i)13177- stu__getfloat_addend[i] = 32; // undo the -0x2000000013178- stu__getfloat_addend[127] = 64; // convert packed INF to INF (0x3f -> 0x7f)13179-13180- for (i=0; i < 128; ++i) // for signed floats, remove the bit we just shifted down13181- stu__getfloat_addend[128+i] = stu__getfloat_addend[i] - 64;13182-}13183-13184-// Tagged data type implementation13185-13186- // TAGS:13187-#define stu__int_tag 0 // of 2 bits // 00 int13188-#define stu__float_tag 1 // of 1 bit // 01 float13189-#define stu__ptr_tag 2 // of 2 bits // 10 boxed13190- // 11 float13191-13192-#define stu__tag(x) ((x) & 3)13193-#define stu__number(x) (stu__tag(x) != stu__ptr_tag)13194-#define stu__isint(x) (stu__tag(x) == stu__int_tag)13195-13196-#define stu__int(x) ((x) >> 2)13197-#define stu__float(x) (stu__getfloat(x))13198-13199-#define stu__makeint(v) ((v)*4+stu__int_tag)13200-13201-// boxed data, and tag support for boxed data13202-13203-enum13204-{13205- STU___float = 1, STU___int = 2,13206- STU___number = 3, STU___string = 4,13207- STU___function = 5, STU___dict = 6,13208- STU___boolean = 7, STU___error = 8,13209-};13210-13211-// boxed data13212-#define STU__BOX short type, stua_gc13213-typedef struct stu__box { STU__BOX; } stu__box;13214-13215-stu__box stu__nil = { 0, 1 };13216-stu__box stu__true = { STU___boolean, 1, };13217-stu__box stu__false = { STU___boolean, 1, };13218-13219-#define stu__makeptr(v) ((stua_obj) (v) + stu__ptr_tag)13220-13221-#define stua_nil stu__makeptr(&stu__nil)13222-#define stua_true stu__makeptr(&stu__true)13223-#define stua_false stu__makeptr(&stu__false)13224-13225-stua_obj stua_getnil(void) { return stua_nil; }13226-stua_obj stua_getfalse(void) { return stua_false; }13227-stua_obj stua_gettrue(void) { return stua_true; }13228-13229-#define stu__ptr(x) ((stu__box *) ((x) - stu__ptr_tag))13230-13231-#define stu__checkt(t,x) ((t) == STU___float ? ((x) & 1) == stu__float_tag : \13232- (t) == STU___int ? stu__isint(x) : \13233- (t) == STU___number ? stu__number(x) : \13234- stu__tag(x) == stu__ptr_tag && stu__ptr(x)->type == (t))13235-13236-typedef struct13237-{13238- STU__BOX;13239- void *ptr;13240-} stu__wrapper;13241-13242-// implementation of a 'function' or function + closure13243-13244-typedef struct stu__func13245-{13246- STU__BOX;13247- stua_obj closure_source; // 0 - regular function; 4 - C function13248- // if closure, pointer to source function13249- union {13250- stua_obj closure_data; // partial-application data13251- void *store; // pointer to free that holds 'code'13252- stua_obj (*func)(stua_dict *context);13253- } f;13254- // closure ends here13255- short *code;13256- int num_param;13257- stua_obj *param; // list of parameter strings13258-} stu__func;13259-13260-// apply this to 'short *code' to get at data13261-#define stu__const(f) ((stua_obj *) (f))13262-13263-static void stu__free_func(stu__func *f)13264-{13265- if (f->closure_source == 0) free(f->f.store);13266- if ((stb_uint) f->closure_source <= 4) free(f->param);13267- free(f);13268-}13269-13270-#define stu__pd(x) ((stua_dict *) stu__ptr(x))13271-#define stu__pw(x) ((stu__wrapper *) stu__ptr(x))13272-#define stu__pf(x) ((stu__func *) stu__ptr(x))13273-13274-13275-// garbage-collection13276-13277-13278-static stu__box ** stu__gc_ptrlist;13279-static stua_obj * stu__gc_root_stack;13280-13281-stua_obj stua_pushroot(stua_obj o) { stb_arr_push(stu__gc_root_stack, o); return o; }13282-void stua_poproot ( void ) { stb_arr_pop(stu__gc_root_stack); }13283-13284-static stb_sdict *stu__strings;13285-static void stu__mark(stua_obj z)13286-{13287- int i;13288- stu__box *p = stu__ptr(z);13289- if (p->stua_gc == 1) return; // already marked13290- assert(p->stua_gc == 0);13291- p->stua_gc = 1;13292- switch(p->type) {13293- case STU___function: {13294- stu__func *f = (stu__func *) p;13295- if ((stb_uint) f->closure_source <= 4) {13296- if (f->closure_source == 0) {13297- for (i=1; i <= f->code[0]; ++i)13298- if (!stu__number(((stua_obj *) f->code)[-i]))13299- stu__mark(((stua_obj *) f->code)[-i]);13300- }13301- for (i=0; i < f->num_param; ++i)13302- stu__mark(f->param[i]);13303- } else {13304- stu__mark(f->closure_source);13305- stu__mark(f->f.closure_data);13306- }13307- break;13308- }13309- case STU___dict: {13310- stua_dict *e = (stua_dict *) p;13311- for (i=0; i < e->limit; ++i)13312- if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL) {13313- if (!stu__number(e->table[i].k)) stu__mark((int) e->table[i].k);13314- if (!stu__number(e->table[i].v)) stu__mark((int) e->table[i].v);13315- }13316- break;13317- }13318- }13319-}13320-13321-static int stu__num_allocs, stu__size_allocs;13322-static stua_obj stu__flow_val = stua_nil; // used for break & return13323-13324-static void stua_gc(int force)13325-{13326- int i;13327- if (!force && stu__num_allocs == 0 && stu__size_allocs == 0) return;13328- stu__num_allocs = stu__size_allocs = 0;13329- //printf("[gc]\n");13330-13331- // clear marks13332- for (i=0; i < stb_arr_len(stu__gc_ptrlist); ++i)13333- stu__gc_ptrlist[i]->stua_gc = 0;13334-13335- // stu__mark everything reachable13336- stu__nil.stua_gc = stu__true.stua_gc = stu__false.stua_gc = 1;13337- stu__mark(stua_globals);13338- if (!stu__number(stu__flow_val))13339- stu__mark(stu__flow_val);13340- for (i=0; i < stb_arr_len(stu__gc_root_stack); ++i)13341- if (!stu__number(stu__gc_root_stack[i]))13342- stu__mark(stu__gc_root_stack[i]);13343-13344- // sweep unreachables13345- for (i=0; i < stb_arr_len(stu__gc_ptrlist);) {13346- stu__box *z = stu__gc_ptrlist[i];13347- if (!z->stua_gc) {13348- switch (z->type) {13349- case STU___dict: stb_idict_destroy((stua_dict *) z); break;13350- case STU___error: free(((stu__wrapper *) z)->ptr); break;13351- case STU___string: stb_sdict_remove(stu__strings, (char*) ((stu__wrapper *) z)->ptr, NULL); free(z); break;13352- case STU___function: stu__free_func((stu__func *) z); break;13353- }13354- // swap in the last item over this, and repeat13355- z = stb_arr_pop(stu__gc_ptrlist);13356- stu__gc_ptrlist[i] = z;13357- } else13358- ++i;13359- }13360-}13361-13362-static void stu__consider_gc(stua_obj x)13363-{13364- if (stu__size_allocs < 100000) return;13365- if (stu__num_allocs < 10 && stu__size_allocs < 1000000) return;13366- stb_arr_push(stu__gc_root_stack, x);13367- stua_gc(0);13368- stb_arr_pop(stu__gc_root_stack);13369-}13370-13371-static stua_obj stu__makeobj(int type, void *data, int size, int safe_to_gc)13372-{13373- stua_obj x = stu__makeptr(data);13374- ((stu__box *) data)->type = type;13375- stb_arr_push(stu__gc_ptrlist, (stu__box *) data);13376- stu__num_allocs += 1;13377- stu__size_allocs += size;13378- if (safe_to_gc) stu__consider_gc(x);13379- return x;13380-}13381-13382-stua_obj stua_box(int type, void *data, int size)13383-{13384- stu__wrapper *p = (stu__wrapper *) malloc(sizeof(*p));13385- p->ptr = data;13386- return stu__makeobj(type, p, size, 0);13387-}13388-13389-// a stu string can be directly compared for equality, because13390-// they go into a hash table13391-stua_obj stua_string(char *z)13392-{13393- stu__wrapper *b = (stu__wrapper *) stb_sdict_get(stu__strings, z);13394- if (b == NULL) {13395- int o = stua_box(STU___string, NULL, strlen(z) + sizeof(*b));13396- b = stu__pw(o);13397- stb_sdict_add(stu__strings, z, b);13398- stb_sdict_getkey(stu__strings, z, (char **) &b->ptr);13399- }13400- return stu__makeptr(b);13401-}13402-13403-// stb_obj dictionary is just an stb_idict13404-static void stu__set(stua_dict *d, stua_obj k, stua_obj v)13405-{ if (stb_idict_set(d, k, v)) stu__size_allocs += 8; }13406-13407-static stua_obj stu__get(stua_dict *d, stua_obj k, stua_obj res)13408-{13409- stb_idict_get_flag(d, k, &res);13410- return res;13411-}13412-13413-static stua_obj make_string(char *z, int len)13414-{13415- stua_obj s;13416- char temp[256], *q = (char *) stb_temp(temp, len+1), *p = q;13417- while (len > 0) {13418- if (*z == '\\') {13419- if (z[1] == 'n') *p = '\n';13420- else if (z[1] == 'r') *p = '\r';13421- else if (z[1] == 't') *p = '\t';13422- else *p = z[1];13423- p += 1; z += 2; len -= 2;13424- } else {13425- *p++ = *z++; len -= 1;13426- }13427- }13428- *p = 0;13429- s = stua_string(q);13430- stb_tempfree(temp, q);13431- return s;13432-}13433-13434-enum token_names13435-{13436- T__none=128,13437- ST_shl = STUA_op_shl, ST_ge = STUA_op_ge,13438- ST_shr = STUA_op_shr, ST_le = STUA_op_le,13439- ST_shru = STUA_op_shru, STU__negate = STUA_op_negate,13440- ST__reset_numbering = STUA_op_last,13441- ST_white,13442- ST_id, ST_float, ST_decimal, ST_hex, ST_char,ST_string, ST_number,13443- // make sure the keywords come _AFTER_ ST_id, so stb_lex prefer them13444- ST_if, ST_while, ST_for, ST_eq, ST_nil,13445- ST_then, ST_do, ST_in, ST_ne, ST_true,13446- ST_else, ST_break, ST_let, ST_and, ST_false,13447- ST_elseif, ST_continue, ST_into, ST_or, ST_repeat,13448- ST_end, ST_as, ST_return, ST_var, ST_func,13449- ST_catch, ST__frame,13450- ST__max_terminals,13451-13452- STU__defaultparm, STU__seq,13453-};13454-13455-static stua_dict * stu__globaldict;13456- stua_obj stua_globals;13457-13458-static enum13459-{13460- FLOW_normal, FLOW_continue, FLOW_break, FLOW_return, FLOW_error,13461-} stu__flow;13462-13463-stua_obj stua_error(char *z, ...)13464-{13465- stua_obj a;13466- char temp[4096], *x;13467- va_list v; va_start(v,z); vsprintf(temp, z, v); va_end(v);13468- x = stb_p_strdup(temp);13469- a = stua_box(STU___error, x, strlen(x));13470- stu__flow = FLOW_error;13471- stu__flow_val = a;13472- return stua_nil;13473-}13474-13475-double stua_number(stua_obj z)13476-{13477- return stu__tag(z) == stu__int_tag ? stu__int(z) : stu__float(z);13478-}13479-13480-stua_obj stua_make_number(double d)13481-{13482- double e = floor(d);13483- if (e == d && e < (1 << 29) && e >= -(1 << 29))13484- return stu__makeint((int) e);13485- else13486- return stua_float((float) d);13487-}13488-13489-stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c) = NULL;13490-13491-static stua_obj stu__op(int op, stua_obj a, stua_obj b, stua_obj c)13492-{13493- stua_obj r = STUA_NO_VALUE;13494- if (op == '+') {13495- if (stu__checkt(STU___string, a) && stu__checkt(STU___string, b)) {13496- ;// @TODO: string concatenation13497- } else if (stu__checkt(STU___function, a) && stu__checkt(STU___dict, b)) {13498- stu__func *f = (stu__func *) malloc(12);13499- assert(offsetof(stu__func, code)==12);13500- f->closure_source = a;13501- f->f.closure_data = b;13502- return stu__makeobj(STU___function, f, 16, 1);13503- }13504- }13505- if (stua_overload) r = stua_overload(op,a,b,c);13506- if (stu__flow != FLOW_error && r == STUA_NO_VALUE)13507- stua_error("Typecheck for operator %d", op), r=stua_nil;13508- return r;13509-}13510-13511-#define STU__EVAL2(a,b) \13512- a = stu__eval(stu__f[n+1]); if (stu__flow) break; stua_pushroot(a); \13513- b = stu__eval(stu__f[n+2]); stua_poproot(); if (stu__flow) break;13514-13515-#define STU__FB(op) \13516- STU__EVAL2(a,b) \13517- if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \13518- return ((a) op (b)); \13519- if (stu__number(a) && stu__number(b)) \13520- return stua_make_number(stua_number(a) op stua_number(b)); \13521- return stu__op(stu__f[n], a,b, stua_nil)13522-13523-#define STU__F(op) \13524- STU__EVAL2(a,b) \13525- if (stu__number(a) && stu__number(b)) \13526- return stua_make_number(stua_number(a) op stua_number(b)); \13527- return stu__op(stu__f[n], a,b, stua_nil)13528-13529-#define STU__I(op) \13530- STU__EVAL2(a,b) \13531- if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \13532- return stu__makeint(stu__int(a) op stu__int(b)); \13533- return stu__op(stu__f[n], a,b, stua_nil)13534-13535-#define STU__C(op) \13536- STU__EVAL2(a,b) \13537- if (stu__number(a) && stu__number(b)) \13538- return (stua_number(a) op stua_number(b)) ? stua_true : stua_false; \13539- return stu__op(stu__f[n], a,b, stua_nil)13540-13541-#define STU__CE(op) \13542- STU__EVAL2(a,b) \13543- return (a op b) ? stua_true : stua_false13544-13545-static short *stu__f;13546-static stua_obj stu__f_obj;13547-static stua_dict *stu__c;13548-static stua_obj stu__funceval(stua_obj fo, stua_obj co);13549-13550-static int stu__cond(stua_obj x)13551-{13552- if (stu__flow) return 0;13553- if (!stu__checkt(STU___boolean, x))13554- x = stu__op('!', x, stua_nil, stua_nil);13555- if (x == stua_true ) return 1;13556- if (x == stua_false) return 0;13557- stu__flow = FLOW_error;13558- return 0;13559-}13560-13561-// had to manually eliminate tailcall recursion for debugging complex stuff13562-#define TAILCALL(x) n = (x); goto top;13563-static stua_obj stu__eval(int n)13564-{13565-top:13566- if (stu__flow >= FLOW_return) return stua_nil; // is this needed?13567- if (n < 0) return stu__const(stu__f)[n];13568- assert(n != 0 && n != 1);13569- switch (stu__f[n]) {13570- stua_obj a,b,c;13571- case ST_catch: a = stu__eval(stu__f[n+1]);13572- if (stu__flow == FLOW_error) { a=stu__flow_val; stu__flow = FLOW_normal; }13573- return a;13574- case ST_var: b = stu__eval(stu__f[n+2]); if (stu__flow) break;13575- stu__set(stu__c, stu__const(stu__f)[stu__f[n+1]], b);13576- return b;13577- case STU__seq: stu__eval(stu__f[n+1]); if (stu__flow) break;13578- TAILCALL(stu__f[n+2]);13579- case ST_if: if (!stu__cond(stu__eval(stu__f[n+1]))) return stua_nil;13580- TAILCALL(stu__f[n+2]);13581- case ST_else: a = stu__cond(stu__eval(stu__f[n+1]));13582- TAILCALL(stu__f[n + 2 + !a]);13583- #define STU__HANDLE_BREAK \13584- if (stu__flow >= FLOW_break) { \13585- if (stu__flow == FLOW_break) { \13586- a = stu__flow_val; \13587- stu__flow = FLOW_normal; \13588- stu__flow_val = stua_nil; \13589- return a; \13590- } \13591- return stua_nil; \13592- }13593- case ST_as: stu__eval(stu__f[n+3]);13594- STU__HANDLE_BREAK13595- // fallthrough!13596- case ST_while: a = stua_nil; stua_pushroot(a);13597- while (stu__cond(stu__eval(stu__f[n+1]))) {13598- stua_poproot();13599- a = stu__eval(stu__f[n+2]);13600- STU__HANDLE_BREAK13601- stu__flow = FLOW_normal; // clear 'continue' flag13602- stua_pushroot(a);13603- if (stu__f[n+3]) stu__eval(stu__f[n+3]);13604- STU__HANDLE_BREAK13605- stu__flow = FLOW_normal; // clear 'continue' flag13606- }13607- stua_poproot();13608- return a;13609- case ST_break: stu__flow = FLOW_break; stu__flow_val = stu__eval(stu__f[n+1]); break;13610- case ST_continue:stu__flow = FLOW_continue; break;13611- case ST_return: stu__flow = FLOW_return; stu__flow_val = stu__eval(stu__f[n+1]); break;13612- case ST__frame: return stu__f_obj;13613- case '[': STU__EVAL2(a,b);13614- if (stu__checkt(STU___dict, a))13615- return stu__get(stu__pd(a), b, stua_nil);13616- return stu__op(stu__f[n], a, b, stua_nil);13617- case '=': a = stu__eval(stu__f[n+2]); if (stu__flow) break;13618- n = stu__f[n+1];13619- if (stu__f[n] == ST_id) {13620- if (!stb_idict_update(stu__c, stu__const(stu__f)[stu__f[n+1]], a))13621- if (!stb_idict_update(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], a))13622- return stua_error("Assignment to undefined variable");13623- } else if (stu__f[n] == '[') {13624- stua_pushroot(a);13625- b = stu__eval(stu__f[n+1]); if (stu__flow) { stua_poproot(); break; }13626- stua_pushroot(b);13627- c = stu__eval(stu__f[n+2]); stua_poproot(); stua_poproot();13628- if (stu__flow) break;13629- if (!stu__checkt(STU___dict, b)) return stua_nil;13630- stu__set(stu__pd(b), c, a);13631- } else {13632- return stu__op(stu__f[n], stu__eval(n), a, stua_nil);13633- }13634- return a;13635- case STU__defaultparm:13636- a = stu__eval(stu__f[n+2]);13637- stu__flow = FLOW_normal;13638- if (stb_idict_add(stu__c, stu__const(stu__f)[stu__f[n+1]], a))13639- stu__size_allocs += 8;13640- return stua_nil;13641- case ST_id: a = stu__get(stu__c, stu__const(stu__f)[stu__f[n+1]], STUA_NO_VALUE); // try local variable13642- return a != STUA_NO_VALUE // else try stu__compile_global_scope variable13643- ? a : stu__get(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], stua_nil);13644- case STU__negate:a = stu__eval(stu__f[n+1]); if (stu__flow) break;13645- return stu__isint(a) ? -a : stu__op(stu__f[n], a, stua_nil, stua_nil);13646- case '~': a = stu__eval(stu__f[n+1]); if (stu__flow) break;13647- return stu__isint(a) ? (~a)&~3 : stu__op(stu__f[n], a, stua_nil, stua_nil);13648- case '!': a = stu__eval(stu__f[n+1]); if (stu__flow) break;13649- a = stu__cond(a); if (stu__flow) break;13650- return a ? stua_true : stua_false;13651- case ST_eq: STU__CE(==); case ST_le: STU__C(<=); case '<': STU__C(<);13652- case ST_ne: STU__CE(!=); case ST_ge: STU__C(>=); case '>': STU__C(>);13653- case '+' : STU__FB(+); case '*': STU__F(*); case '&': STU__I(&); case ST_shl: STU__I(<<);13654- case '-' : STU__FB(-); case '/': STU__F(/); case '|': STU__I(|); case ST_shr: STU__I(>>);13655- case '%': STU__I(%); case '^': STU__I(^);13656- case ST_shru: STU__EVAL2(a,b);13657- if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag)13658- return stu__makeint((unsigned) stu__int(a) >> stu__int(b));13659- return stu__op(stu__f[n], a,b, stua_nil);13660- case ST_and: a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;13661- return a ? stu__eval(stu__f[n+2]) : a;13662- case ST_or : a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;13663- return a ? b : stu__eval(stu__f[n+2]);13664- case'(':case':': STU__EVAL2(a,b);13665- if (!stu__checkt(STU___function, a))13666- return stu__op(stu__f[n], a,b, stua_nil);13667- if (!stu__checkt(STU___dict, b))13668- return stua_nil;13669- if (stu__f[n] == ':')13670- b = stu__makeobj(STU___dict, stb_idict_copy(stu__pd(b)), stb_idict_memory_usage(stu__pd(b)), 0);13671- a = stu__funceval(a,b);13672- return a;13673- case '{' : {13674- stua_dict *d;13675- d = stb_idict_new_size(stu__f[n+1] > 40 ? 64 : 16);13676- if (d == NULL)13677- return stua_nil; // breakpoint fodder13678- c = stu__makeobj(STU___dict, d, 32, 1);13679- stua_pushroot(c);13680- a = stu__f[n+1];13681- for (b=0; b < a; ++b) {13682- stua_obj x = stua_pushroot(stu__eval(stu__f[n+2 + b*2 + 0]));13683- stua_obj y = stu__eval(stu__f[n+2 + b*2 + 1]);13684- stua_poproot();13685- if (stu__flow) { stua_poproot(); return stua_nil; }13686- stu__set(d, x, y);13687- }13688- stua_poproot();13689- return c;13690- }13691- default: if (stu__f[n] < 0) return stu__const(stu__f)[stu__f[n]];13692- assert(0); /* NOTREACHED */ // internal error!13693- }13694- return stua_nil;13695-}13696-13697-int stb__stua_nesting;13698-static stua_obj stu__funceval(stua_obj fo, stua_obj co)13699-{13700- stu__func *f = stu__pf(fo);13701- stua_dict *context = stu__pd(co);13702- int i,j;13703- stua_obj p;13704- short *tf = stu__f; // save previous function13705- stua_dict *tc = stu__c;13706-13707- if (stu__flow == FLOW_error) return stua_nil;13708- assert(stu__flow == FLOW_normal);13709-13710- stua_pushroot(fo);13711- stua_pushroot(co);13712- stu__consider_gc(stua_nil);13713-13714- while ((stb_uint) f->closure_source > 4) {13715- // add data from closure to context13716- stua_dict *e = (stua_dict *) stu__pd(f->f.closure_data);13717- for (i=0; i < e->limit; ++i)13718- if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL)13719- if (stb_idict_add(context, e->table[i].k, e->table[i].v))13720- stu__size_allocs += 8;13721- // use add so if it's already defined, we don't override it; that way13722- // explicit parameters win over applied ones, and most recent applications13723- // win over previous ones13724- f = stu__pf(f->closure_source);13725- }13726-13727- for (j=0, i=0; i < f->num_param; ++i)13728- // if it doesn't already exist, add it from the numbered parameters13729- if (stb_idict_add(context, f->param[i], stu__get(context, stu__int(j), stua_nil)))13730- ++j;13731-13732- // @TODO: if (stu__get(context, stu__int(f->num_param+1)) != STUA_NO_VALUE) // error: too many parameters13733- // @TODO: ditto too few parameters13734-13735- if (f->closure_source == 4)13736- p = f->f.func(context);13737- else {13738- stu__f = f->code, stu__c = context;13739- stu__f_obj = co;13740- ++stb__stua_nesting;13741- if (stu__f[1])13742- p = stu__eval(stu__f[1]);13743- else13744- p = stua_nil;13745- --stb__stua_nesting;13746- stu__f = tf, stu__c = tc; // restore previous function13747- if (stu__flow == FLOW_return) {13748- stu__flow = FLOW_normal;13749- p = stu__flow_val;13750- stu__flow_val = stua_nil;13751- }13752- }13753-13754- stua_poproot();13755- stua_poproot();13756-13757- return p;13758-}13759-13760-// Parser13761-13762-static int stu__tok;13763-static stua_obj stu__tokval;13764-13765-static char *stu__curbuf, *stu__bufstart;13766-13767-static stb_matcher *stu__lex_matcher;13768-13769-static unsigned char stu__prec[ST__max_terminals], stu__end[ST__max_terminals];13770-13771-static void stu__nexttoken(void)13772-{13773- int len;13774-13775-retry:13776- stu__tok = stb_lex(stu__lex_matcher, stu__curbuf, &len);13777- if (stu__tok == 0)13778- return;13779- switch(stu__tok) {13780- case ST_white : stu__curbuf += len; goto retry;13781- case T__none : stu__tok = *stu__curbuf; break;13782- case ST_string: stu__tokval = make_string(stu__curbuf+1, len-2); break;13783- case ST_id : stu__tokval = make_string(stu__curbuf, len); break;13784- case ST_hex : stu__tokval = stu__makeint(strtol(stu__curbuf+2,NULL,16)); stu__tok = ST_number; break;13785- case ST_decimal: stu__tokval = stu__makeint(strtol(stu__curbuf ,NULL,10)); stu__tok = ST_number; break;13786- case ST_float : stu__tokval = stua_float((float) atof(stu__curbuf)) ; stu__tok = ST_number; break;13787- case ST_char : stu__tokval = stu__curbuf[2] == '\\' ? stu__curbuf[3] : stu__curbuf[2];13788- if (stu__curbuf[3] == 't') stu__tokval = '\t';13789- if (stu__curbuf[3] == 'n') stu__tokval = '\n';13790- if (stu__curbuf[3] == 'r') stu__tokval = '\r';13791- stu__tokval = stu__makeint(stu__tokval);13792- stu__tok = ST_number;13793- break;13794- }13795- stu__curbuf += len;13796-}13797-13798-static struct { int stu__tok; char *regex; } stu__lexemes[] =13799-{13800- ST_white , "([ \t\n\r]|/\\*(.|\n)*\\*/|//[^\r\n]*([\r\n]|$))+",13801- ST_id , "[_a-zA-Z][_a-zA-Z0-9]*",13802- ST_hex , "0x[0-9a-fA-F]+",13803- ST_decimal, "[0-9]+[0-9]*",13804- ST_float , "[0-9]+\\.?[0-9]*([eE][-+]?[0-9]+)?",13805- ST_float , "\\.[0-9]+([eE][-+]?[0-9]+)?",13806- ST_char , "c'(\\\\.|[^\\'])'",13807- ST_string , "\"(\\\\.|[^\\\"\n\r])*\"",13808- ST_string , "\'(\\\\.|[^\\\'\n\r])*\'",13809-13810- #define stua_key4(a,b,c,d) ST_##a, #a, ST_##b, #b, ST_##c, #c, ST_##d, #d,13811- stua_key4(if,then,else,elseif) stua_key4(while,do,for,in)13812- stua_key4(func,var,let,break) stua_key4(nil,true,false,end)13813- stua_key4(return,continue,as,repeat) stua_key4(_frame,catch,catch,catch)13814-13815- ST_shl, "<<", ST_and, "&&", ST_eq, "==", ST_ge, ">=",13816- ST_shr, ">>", ST_or , "||", ST_ne, "!=", ST_le, "<=",13817- ST_shru,">>>", ST_into, "=>",13818- T__none, ".",13819-};13820-13821-typedef struct13822-{13823- stua_obj *data; // constants being compiled13824- short *code; // code being compiled13825- stua_dict *locals;13826- short *non_local_refs;13827-} stu__comp_func;13828-13829-static stu__comp_func stu__pfunc;13830-static stu__comp_func *func_stack = NULL;13831-static void stu__push_func_comp(void)13832-{13833- stb_arr_push(func_stack, stu__pfunc);13834- stu__pfunc.data = NULL;13835- stu__pfunc.code = NULL;13836- stu__pfunc.locals = stb_idict_new_size(16);13837- stu__pfunc.non_local_refs = NULL;13838- stb_arr_push(stu__pfunc.code, 0); // number of data items13839- stb_arr_push(stu__pfunc.code, 1); // starting execution address13840-}13841-13842-static void stu__pop_func_comp(void)13843-{13844- stb_arr_free(stu__pfunc.code);13845- stb_arr_free(stu__pfunc.data);13846- stb_idict_destroy(stu__pfunc.locals);13847- stb_arr_free(stu__pfunc.non_local_refs);13848- stu__pfunc = stb_arr_pop(func_stack);13849-}13850-13851-// if an id is a reference to an outer lexical scope, this13852-// function returns the "name" of it, and updates the stack13853-// structures to make sure the names are propagated in.13854-static int stu__nonlocal_id(stua_obj var_obj)13855-{13856- stua_obj dummy, var = var_obj;13857- int i, n = stb_arr_len(func_stack), j,k;13858- if (stb_idict_get_flag(stu__pfunc.locals, var, &dummy)) return 0;13859- for (i=n-1; i > 1; --i) {13860- if (stb_idict_get_flag(func_stack[i].locals, var, &dummy))13861- break;13862- }13863- if (i <= 1) return 0; // stu__compile_global_scope13864- j = i; // need to access variable from j'th frame13865- for (i=0; i < stb_arr_len(stu__pfunc.non_local_refs); ++i)13866- if (stu__pfunc.non_local_refs[i] == j) return j-n;13867- stb_arr_push(stu__pfunc.non_local_refs, j-n);13868- // now make sure all the parents propagate it down13869- for (k=n-1; k > 1; --k) {13870- if (j-k >= 0) return j-n; // comes direct from this parent13871- for(i=0; i < stb_arr_len(func_stack[k].non_local_refs); ++i)13872- if (func_stack[k].non_local_refs[i] == j-k)13873- return j-n;13874- stb_arr_push(func_stack[k].non_local_refs, j-k);13875- }13876- assert (k != 1);13877-13878- return j-n;13879-}13880-13881-static int stu__off(void) { return stb_arr_len(stu__pfunc.code); }13882-static void stu__cc(int a)13883-{13884- assert(a >= -2000 && a < 5000);13885- stb_arr_push(stu__pfunc.code, a);13886-}13887-static int stu__cc1(int a) { stu__cc(a); return stu__off()-1; }13888-static int stu__cc2(int a, int b) { stu__cc(a); stu__cc(b); return stu__off()-2; }13889-static int stu__cc3(int a, int b, int c) {13890- if (a == '=') assert(c != 0);13891- stu__cc(a); stu__cc(b); stu__cc(c); return stu__off()-3; }13892-static int stu__cc4(int a, int b, int c, int d) { stu__cc(a); stu__cc(b); stu__cc(c); stu__cc(d); return stu__off()-4; }13893-13894-static int stu__cdv(stua_obj p)13895-{13896- int i;13897- assert(p != STUA_NO_VALUE);13898- for (i=0; i < stb_arr_len(stu__pfunc.data); ++i)13899- if (stu__pfunc.data[i] == p)13900- break;13901- if (i == stb_arr_len(stu__pfunc.data))13902- stb_arr_push(stu__pfunc.data, p);13903- return ~i;13904-}13905-13906-static int stu__cdt(void)13907-{13908- int z = stu__cdv(stu__tokval);13909- stu__nexttoken();13910- return z;13911-}13912-13913-static int stu__seq(int a, int b)13914-{13915- return !a ? b : !b ? a : stu__cc3(STU__seq, a,b);13916-}13917-13918-static char stu__comp_err_str[1024];13919-static int stu__comp_err_line;13920-static int stu__err(char *str, ...)13921-{13922- va_list v;13923- char *s = stu__bufstart;13924- stu__comp_err_line = 1;13925- while (s < stu__curbuf) {13926- if (s[0] == '\n' || s[0] == '\r') {13927- if (s[0]+s[1] == '\n' + '\r') ++s;13928- ++stu__comp_err_line;13929- }13930- ++s;13931- }13932- va_start(v, str);13933- vsprintf(stu__comp_err_str, str, v);13934- va_end(v);13935- return 0;13936-}13937-13938-static int stu__accept(int p)13939-{13940- if (stu__tok != p) return 0;13941- stu__nexttoken();13942- return 1;13943-}13944-13945-static int stu__demand(int p)13946-{13947- if (stu__accept(p)) return 1;13948- return stu__err("Didn't find expected stu__tok");13949-}13950-13951-static int stu__demandv(int p, stua_obj *val)13952-{13953- if (stu__tok == p || p==0) {13954- *val = stu__tokval;13955- stu__nexttoken();13956- return 1;13957- } else13958- return 0;13959-}13960-13961-static int stu__expr(int p);13962-int stu__nexpr(int p) { stu__nexttoken(); return stu__expr(p); }13963-static int stu__statements(int once, int as);13964-13965-static int stu__parse_if(void) // parse both ST_if and ST_elseif13966-{13967- int b,c,a;13968- a = stu__nexpr(1); if (!a) return 0;13969- if (!stu__demand(ST_then)) return stu__err("expecting THEN");13970- b = stu__statements(0,0); if (!b) return 0;13971- if (b == 1) b = -1;13972-13973- if (stu__tok == ST_elseif) {13974- return stu__parse_if();13975- } else if (stu__accept(ST_else)) {13976- c = stu__statements(0,0); if (!c) return 0;13977- if (!stu__demand(ST_end)) return stu__err("expecting END after else clause");13978- return stu__cc4(ST_else, a, b, c);13979- } else {13980- if (!stu__demand(ST_end)) return stu__err("expecting END in if statement");13981- return stu__cc3(ST_if, a, b);13982- }13983-}13984-13985-int stu__varinit(int z, int in_globals)13986-{13987- int a,b;13988- stu__nexttoken();13989- while (stu__demandv(ST_id, &b)) {13990- if (!stb_idict_add(stu__pfunc.locals, b, 1))13991- if (!in_globals) return stu__err("Redefined variable %s.", stu__pw(b)->ptr);13992- if (stu__accept('=')) {13993- a = stu__expr(1); if (!a) return 0;13994- } else13995- a = stu__cdv(stua_nil);13996- z = stu__seq(z, stu__cc3(ST_var, stu__cdv(b), a));13997- if (!stu__accept(',')) break;13998- }13999- return z;14000-}14001-14002-static int stu__compile_unary(int z, int outparm, int require_inparm)14003-{14004- int op = stu__tok, a, b;14005- stu__nexttoken();14006- if (outparm) {14007- if (require_inparm || (stu__tok && stu__tok != ST_end && stu__tok != ST_else && stu__tok != ST_elseif && stu__tok !=';')) {14008- a = stu__expr(1); if (!a) return 0;14009- } else14010- a = stu__cdv(stua_nil);14011- b = stu__cc2(op, a);14012- } else14013- b = stu__cc1(op);14014- return stu__seq(z,b);14015-}14016-14017-static int stu__assign(void)14018-{14019- int z;14020- stu__accept(ST_let);14021- z = stu__expr(1); if (!z) return 0;14022- if (stu__accept('=')) {14023- int y,p = (z >= 0 ? stu__pfunc.code[z] : 0);14024- if (z < 0 || (p != ST_id && p != '[')) return stu__err("Invalid lvalue in assignment");14025- y = stu__assign(); if (!y) return 0;14026- z = stu__cc3('=', z, y);14027- }14028- return z;14029-}14030-14031-static int stu__statements(int once, int stop_while)14032-{14033- int a,b, c, z=0;14034- for(;;) {14035- switch (stu__tok) {14036- case ST_if : a = stu__parse_if(); if (!a) return 0;14037- z = stu__seq(z, a);14038- break;14039- case ST_while : if (stop_while) return (z ? z:1);14040- a = stu__nexpr(1); if (!a) return 0;14041- if (stu__accept(ST_as)) c = stu__statements(0,0); else c = 0;14042- if (!stu__demand(ST_do)) return stu__err("expecting DO");14043- b = stu__statements(0,0); if (!b) return 0;14044- if (!stu__demand(ST_end)) return stu__err("expecting END");14045- if (b == 1) b = -1;14046- z = stu__seq(z, stu__cc4(ST_while, a, b, c));14047- break;14048- case ST_repeat : stu__nexttoken();14049- c = stu__statements(0,1); if (!c) return 0;14050- if (!stu__demand(ST_while)) return stu__err("expecting WHILE");14051- a = stu__expr(1); if (!a) return 0;14052- if (!stu__demand(ST_do)) return stu__err("expecting DO");14053- b = stu__statements(0,0); if (!b) return 0;14054- if (!stu__demand(ST_end)) return stu__err("expecting END");14055- if (b == 1) b = -1;14056- z = stu__seq(z, stu__cc4(ST_as, a, b, c));14057- break;14058- case ST_catch : a = stu__nexpr(1); if (!a) return 0;14059- z = stu__seq(z, stu__cc2(ST_catch, a));14060- break;14061- case ST_var : z = stu__varinit(z,0); break;14062- case ST_return : z = stu__compile_unary(z,1,1); break;14063- case ST_continue:z = stu__compile_unary(z,0,0); break;14064- case ST_break : z = stu__compile_unary(z,1,0); break;14065- case ST_into : if (z == 0 && !once) return stu__err("=> cannot be first statement in block");14066- a = stu__nexpr(99);14067- b = (a >= 0? stu__pfunc.code[a] : 0);14068- if (a < 0 || (b != ST_id && b != '[')) return stu__err("Invalid lvalue on right side of =>");14069- z = stu__cc3('=', a, z);14070- break;14071- default : if (stu__end[stu__tok]) return once ? 0 : (z ? z:1);14072- a = stu__assign(); if (!a) return 0;14073- stu__accept(';');14074- if (stu__tok && !stu__end[stu__tok]) {14075- if (a < 0)14076- return stu__err("Constant has no effect");14077- if (stu__pfunc.code[a] != '(' && stu__pfunc.code[a] != '=')14078- return stu__err("Expression has no effect");14079- }14080- z = stu__seq(z, a);14081- break;14082- }14083- if (!z) return 0;14084- stu__accept(';');14085- if (once && stu__tok != ST_into) return z;14086- }14087-}14088-14089-static int stu__postexpr(int z, int p);14090-static int stu__dictdef(int end, int *count)14091-{14092- int z,n=0,i,flags=0;14093- short *dict=NULL;14094- stu__nexttoken();14095- while (stu__tok != end) {14096- if (stu__tok == ST_id) {14097- stua_obj id = stu__tokval;14098- stu__nexttoken();14099- if (stu__tok == '=') {14100- flags |= 1;14101- stb_arr_push(dict, stu__cdv(id));14102- z = stu__nexpr(1); if (!z) return 0;14103- } else {14104- z = stu__cc2(ST_id, stu__cdv(id));14105- z = stu__postexpr(z,1); if (!z) return 0;14106- flags |= 2;14107- stb_arr_push(dict, stu__cdv(stu__makeint(n++)));14108- }14109- } else {14110- z = stu__expr(1); if (!z) return 0;14111- flags |= 2;14112- stb_arr_push(dict, stu__cdv(stu__makeint(n++)));14113- }14114- if (end != ')' && flags == 3) { z=stu__err("can't mix initialized and uninitialized defs"); goto done;}14115- stb_arr_push(dict, z);14116- if (!stu__accept(',')) break;14117- }14118- if (!stu__demand(end))14119- return stu__err(end == ')' ? "Expecting ) at end of function call"14120- : "Expecting } at end of dictionary definition");14121- z = stu__cc2('{', stb_arr_len(dict)/2);14122- for (i=0; i < stb_arr_len(dict); ++i)14123- stu__cc(dict[i]);14124- if (count) *count = n;14125-done:14126- stb_arr_free(dict);14127- return z;14128-}14129-14130-static int stu__comp_id(void)14131-{14132- int z,d;14133- d = stu__nonlocal_id(stu__tokval);14134- if (d == 0)14135- return z = stu__cc2(ST_id, stu__cdt());14136- // access a non-local frame by naming it with the appropriate int14137- assert(d < 0);14138- z = stu__cdv(d); // relative frame # is the 'variable' in our local frame14139- z = stu__cc2(ST_id, z); // now access that dictionary14140- return stu__cc3('[', z, stu__cdt()); // now access the variable from that dir14141-}14142-14143-static stua_obj stu__funcdef(stua_obj *id, stua_obj *func);14144-static int stu__expr(int p)14145-{14146- int z;14147- // unary14148- switch (stu__tok) {14149- case ST_number: z = stu__cdt(); break;14150- case ST_string: z = stu__cdt(); break; // @TODO - string concatenation like C14151- case ST_id : z = stu__comp_id(); break;14152- case ST__frame: z = stu__cc1(ST__frame); stu__nexttoken(); break;14153- case ST_func : z = stu__funcdef(NULL,NULL); break;14154- case ST_if : z = stu__parse_if(); break;14155- case ST_nil : z = stu__cdv(stua_nil); stu__nexttoken(); break;14156- case ST_true : z = stu__cdv(stua_true); stu__nexttoken(); break;14157- case ST_false : z = stu__cdv(stua_false); stu__nexttoken(); break;14158- case '-' : z = stu__nexpr(99); if (z) z=stu__cc2(STU__negate,z); else return z; break;14159- case '!' : z = stu__nexpr(99); if (z) z=stu__cc2('!',z); else return z; break;14160- case '~' : z = stu__nexpr(99); if (z) z=stu__cc2('~',z); else return z; break;14161- case '{' : z = stu__dictdef('}', NULL); break;14162- default : return stu__err("Unexpected token");14163- case '(' : stu__nexttoken(); z = stu__statements(0,0); if (!stu__demand(')')) return stu__err("Expecting )");14164- }14165- return stu__postexpr(z,p);14166-}14167-14168-static int stu__postexpr(int z, int p)14169-{14170- int q;14171- // postfix14172- while (stu__tok == '(' || stu__tok == '[' || stu__tok == '.') {14173- if (stu__accept('.')) {14174- // MUST be followed by a plain identifier! use [] for other stuff14175- if (stu__tok != ST_id) return stu__err("Must follow . with plain name; try [] instead");14176- z = stu__cc3('[', z, stu__cdv(stu__tokval));14177- stu__nexttoken();14178- } else if (stu__accept('[')) {14179- while (stu__tok != ']') {14180- int r = stu__expr(1); if (!r) return 0;14181- z = stu__cc3('[', z, r);14182- if (!stu__accept(',')) break;14183- }14184- if (!stu__demand(']')) return stu__err("Expecting ]");14185- } else {14186- int n, p = stu__dictdef(')', &n); if (!p) return 0;14187- #if 0 // this is incorrect!14188- if (z > 0 && stu__pfunc.code[z] == ST_id) {14189- stua_obj q = stu__get(stu__globaldict, stu__pfunc.data[-stu__pfunc.code[z+1]-1], stua_nil);14190- if (stu__checkt(STU___function, q))14191- if ((stu__pf(q))->num_param != n)14192- return stu__err("Incorrect number of parameters");14193- }14194- #endif14195- z = stu__cc3('(', z, p);14196- }14197- }14198- // binop - this implementation taken from lcc14199- for (q=stu__prec[stu__tok]; q >= p; --q) {14200- while (stu__prec[stu__tok] == q) {14201- int o = stu__tok, y = stu__nexpr(p+1); if (!y) return 0;14202- z = stu__cc3(o,z,y);14203- }14204- }14205- return z;14206-}14207-14208-static stua_obj stu__finish_func(stua_obj *param, int start)14209-{14210- int n, size;14211- stu__func *f = (stu__func *) malloc(sizeof(*f));14212- f->closure_source = 0;14213- f->num_param = stb_arr_len(param);14214- f->param = (int *) stb_copy(param, f->num_param * sizeof(*f->param));14215- size = stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data) + sizeof(*f) + 8;14216- f->f.store = malloc(stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data));14217- f->code = (short *) ((char *) f->f.store + stb_arr_storage(stu__pfunc.data));14218- memcpy(f->code, stu__pfunc.code, stb_arr_storage(stu__pfunc.code));14219- f->code[1] = start;14220- f->code[0] = stb_arr_len(stu__pfunc.data);14221- for (n=0; n < f->code[0]; ++n)14222- ((stua_obj *) f->code)[-1-n] = stu__pfunc.data[n];14223- return stu__makeobj(STU___function, f, size, 0);14224-}14225-14226-static int stu__funcdef(stua_obj *id, stua_obj *result)14227-{14228- int n,z=0,i,q;14229- stua_obj *param = NULL;14230- short *nonlocal;14231- stua_obj v,f=stua_nil;14232- assert(stu__tok == ST_func);14233- stu__nexttoken();14234- if (id) {14235- if (!stu__demandv(ST_id, id)) return stu__err("Expecting function name");14236- } else14237- stu__accept(ST_id);14238- if (!stu__demand('(')) return stu__err("Expecting ( for function parameter");14239- stu__push_func_comp();14240- while (stu__tok != ')') {14241- if (!stu__demandv(ST_id, &v)) { z=stu__err("Expecting parameter name"); goto done; }14242- stb_idict_add(stu__pfunc.locals, v, 1);14243- if (stu__tok == '=') {14244- n = stu__nexpr(1); if (!n) { z=0; goto done; }14245- z = stu__seq(z, stu__cc3(STU__defaultparm, stu__cdv(v), n));14246- } else14247- stb_arr_push(param, v);14248- if (!stu__accept(',')) break;14249- }14250- if (!stu__demand(')')) { z=stu__err("Expecting ) at end of parameter list"); goto done; }14251- n = stu__statements(0,0); if (!n) { z=0; goto done; }14252- if (!stu__demand(ST_end)) { z=stu__err("Expecting END at end of function"); goto done; }14253- if (n == 1) n = 0;14254- n = stu__seq(z,n);14255- f = stu__finish_func(param, n);14256- if (result) { *result = f; z=1; stu__pop_func_comp(); }14257- else {14258- nonlocal = stu__pfunc.non_local_refs;14259- stu__pfunc.non_local_refs = NULL;14260- stu__pop_func_comp();14261- z = stu__cdv(f);14262- if (nonlocal) { // build a closure with references to the needed frames14263- short *initcode = NULL;14264- for (i=0; i < stb_arr_len(nonlocal); ++i) {14265- int k = nonlocal[i], p;14266- stb_arr_push(initcode, stu__cdv(k));14267- if (k == -1) p = stu__cc1(ST__frame);14268- else { p = stu__cdv(stu__makeint(k+1)); p = stu__cc2(ST_id, p); }14269- stb_arr_push(initcode, p);14270- }14271- q = stu__cc2('{', stb_arr_len(nonlocal));14272- for (i=0; i < stb_arr_len(initcode); ++i)14273- stu__cc(initcode[i]);14274- z = stu__cc3('+', z, q);14275- stb_arr_free(initcode);14276- }14277- stb_arr_free(nonlocal);14278- }14279-done:14280- stb_arr_free(param);14281- if (!z) stu__pop_func_comp();14282- return z;14283-}14284-14285-static int stu__compile_global_scope(void)14286-{14287- stua_obj o;14288- int z=0;14289-14290- stu__push_func_comp();14291- while (stu__tok != 0) {14292- if (stu__tok == ST_func) {14293- stua_obj id, f;14294- if (!stu__funcdef(&id,&f))14295- goto error;14296- stu__set(stu__globaldict, id, f);14297- } else if (stu__tok == ST_var) {14298- z = stu__varinit(z,1); if (!z) goto error;14299- } else {14300- int y = stu__statements(1,0); if (!y) goto error;14301- z = stu__seq(z,y);14302- }14303- stu__accept(';');14304- }14305- o = stu__finish_func(NULL, z);14306- stu__pop_func_comp();14307-14308- o = stu__funceval(o, stua_globals); // initialize stu__globaldict14309- if (stu__flow == FLOW_error)14310- printf("Error: %s\n", ((stu__wrapper *) stu__ptr(stu__flow_val))->ptr);14311- return 1;14312-error:14313- stu__pop_func_comp();14314- return 0;14315-}14316-14317-stua_obj stu__myprint(stua_dict *context)14318-{14319- stua_obj x = stu__get(context, stua_string("x"), stua_nil);14320- if ((x & 1) == stu__float_tag) printf("%f", stu__getfloat(x));14321- else if (stu__tag(x) == stu__int_tag) printf("%d", stu__int(x));14322- else {14323- stu__wrapper *s = stu__pw(x);14324- if (s->type == STU___string || s->type == STU___error)14325- printf("%s", s->ptr);14326- else if (s->type == STU___dict) printf("{{dictionary}}");14327- else if (s->type == STU___function) printf("[[function]]");14328- else14329- printf("[[ERROR:%s]]", s->ptr);14330- }14331- return x;14332-}14333-14334-void stua_init(void)14335-{14336- if (!stu__globaldict) {14337- int i;14338- stua_obj s;14339- stu__func *f;14340-14341- stu__prec[ST_and] = stu__prec[ST_or] = 1;14342- stu__prec[ST_eq ] = stu__prec[ST_ne] = stu__prec[ST_le] =14343- stu__prec[ST_ge] = stu__prec['>' ] = stu__prec['<'] = 2;14344- stu__prec[':'] = 3;14345- stu__prec['&'] = stu__prec['|'] = stu__prec['^'] = 4;14346- stu__prec['+'] = stu__prec['-'] = 5;14347- stu__prec['*'] = stu__prec['/'] = stu__prec['%'] =14348- stu__prec[ST_shl]= stu__prec[ST_shr]= stu__prec[ST_shru]= 6;14349-14350- stu__end[')'] = stu__end[ST_end] = stu__end[ST_else] = 1;14351- stu__end[ST_do] = stu__end[ST_elseif] = 1;14352-14353- stu__float_init();14354- stu__lex_matcher = stb_lex_matcher();14355- for (i=0; i < sizeof(stu__lexemes)/sizeof(stu__lexemes[0]); ++i)14356- stb_lex_item(stu__lex_matcher, stu__lexemes[i].regex, stu__lexemes[i].stu__tok);14357-14358- stu__globaldict = stb_idict_new_size(64);14359- stua_globals = stu__makeobj(STU___dict, stu__globaldict, 0,0);14360- stu__strings = stb_sdict_new(0);14361-14362- stu__curbuf = stu__bufstart = "func _print(x) end\n"14363- "func print()\n var x=0 while _frame[x] != nil as x=x+1 do _print(_frame[x]) end end\n";14364- stu__nexttoken();14365- if (!stu__compile_global_scope())14366- printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);14367-14368- s = stu__get(stu__globaldict, stua_string("_print"), stua_nil);14369- if (stu__tag(s) == stu__ptr_tag && stu__ptr(s)->type == STU___function) {14370- f = stu__pf(s);14371- free(f->f.store);14372- f->closure_source = 4;14373- f->f.func = stu__myprint;14374- f->code = NULL;14375- }14376- }14377-}14378-14379-void stua_uninit(void)14380-{14381- if (stu__globaldict) {14382- stb_idict_remove_all(stu__globaldict);14383- stb_arr_setlen(stu__gc_root_stack, 0);14384- stua_gc(1);14385- stb_idict_destroy(stu__globaldict);14386- stb_sdict_delete(stu__strings);14387- stb_matcher_free(stu__lex_matcher);14388- stb_arr_free(stu__gc_ptrlist);14389- stb_arr_free(func_stack);14390- stb_arr_free(stu__gc_root_stack);14391- stu__globaldict = NULL;14392- }14393-}14394-14395-void stua_run_script(char *s)14396-{14397- stua_init();14398-14399- stu__curbuf = stu__bufstart = s;14400- stu__nexttoken();14401-14402- stu__flow = FLOW_normal;14403-14404- if (!stu__compile_global_scope())14405- printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);14406- stua_gc(1);14407-}14408-#endif // STB_DEFINE14409-#endif // STB_STUA14410-13068 #undef STB_EXTERN13069 #endif // STB_INCLUDE_STB_H13070 13071 /*40 unmodified linesadded:stb_image_resize_test/dotimings.cnot shown
Its text is not shown, added.
added:stb_image_resize_test/old_image_resize.hnot shown
Its text is not shown, added.
added:stb_image_resize_test/oldir.cnot shown
Its text is not shown, added.
added:stb_image_resize_test/stbirtest.cnot shown
Its text is not shown, added.
added:stb_image_resize_test/vf_train.cnot shown
Its text is not shown, added.
added:tests/pbm/basi0g16.pgmnot shown
Its text is not shown, added.
added:tests/pbm/basi2c16.ppmnot shown
Its text is not shown, added.
added:tests/pbm/cdfn2c08.ppmnot shown
Its text is not shown, added.
added:tests/pbm/cdun2c08.ppmnot shown
Its text is not shown, added.
added:tests/pbm/comment.pgmnot shown
Its text is not shown, added.
added:tests/pbm/ctfn0g04.pgmnot shown
Its text is not shown, added.
added:tests/pngsuite/ref_results.csvnot shown
Its text is not shown, added.
modified:tests/image_test.dspnot shown
Its text is not shown, modified.
modified:tests/ossfuzz.shnot shown
Its text is not shown, modified.
modified:tests/resample_test.cppnot shown
Its text is not shown, modified.
modified:tests/resize.dspnot shown
Its text is not shown, modified.
modified:tests/stb.dspnot shown
Its text is not shown, modified.
modified:tests/test_c_compilation.cnot shown
Its text is not shown, modified.
modified:tests/test_c_lexer.cnot shown
Its text is not shown, modified.
modified:tests/test_cpp_compilation.cppnot shown
Its text is not shown, modified.
added:tests/test_png_paeth.cnot shown
Its text is not shown, added.
added:tests/test_png_regress.cnot shown
Its text is not shown, added.
modified:tests/test_truetype.cnot shown
Its text is not shown, modified.
added:tests/truetype_test_win32.cnot shown
Its text is not shown, added.
modified:tools/make_readme.cnot shown
Its text is not shown, modified.
modified:tools/README.footer.mdnot shown
Its text is not shown, modified.
modified:tools/README.header.mdnot shown
Its text is not shown, modified.
modified:tools/README.listnot shown
Its text is not shown, modified.
added:.gitignore+3 added
1+*.o2+*.obj3+*.exemodified:.travis.yml+3 added
1 language: C2+arch:3+ - AMD644+ - ppc64le5 install: true6 script:7 - cd tests8 - make allmodified:README.md+31 added-29 removed
3 unmodified lines4 ===5 6 single-file public domain (or MIT licensed) libraries for C/C++7 8+# This project discusses security-relevant bugs in public in Github Issues and Pull Requests, and it may take significant time for security fixes to be implemented or merged. If this poses an unreasonable risk to your project, do not use stb libraries.9+10 Noteworthy:11 12 * image loader: [stb_image.h](stb_image.h)13 * image writer: [stb_image_write.h](stb_image_write.h)12-* image resizer: [stb_image_resize.h](stb_image_resize.h)14+* image resizer: [stb_image_resize2.h](stb_image_resize2.h)15 * font text rasterizer: [stb_truetype.h](stb_truetype.h)16 * typesafe containers: [stb_ds.h](stb_ds.h)17 16-Most libraries by stb, except: stb_dxt by Fabian "ryg" Giesen, stb_image_resize17-by Jorge L. "VinoBS" Rodriguez, and stb_sprintf by Jeff Roberts.18+Most libraries by stb, except: stb_dxt by Fabian "ryg" Giesen, original stb_image_resize19+by Jorge L. "VinoBS" Rodriguez, and stb_image_resize2 and stb_sprintf by Jeff Roberts.20 21 <a name="stb_libs"></a>22 23 library | lastest version | category | LoC | description24 --------------------- | ---- | -------- | --- | --------------------------------23-**[stb_vorbis.c](stb_vorbis.c)** | 1.20 | audio | 5563 | decode ogg vorbis files from file/memory to float/16-bit signed output24-**[stb_image.h](stb_image.h)** | 2.26 | graphics | 7762 | image loading/decoding from file/memory: JPG, PNG, TGA, BMP, PSD, GIF, HDR, PIC, PNM25-**[stb_truetype.h](stb_truetype.h)** | 1.24 | graphics | 5011 | parse, decode, and rasterize characters from truetype fonts26-**[stb_image_write.h](stb_image_write.h)** | 1.15 | graphics | 1690 | image writing to disk: PNG, TGA, BMP, JPG, HDR27-**[stb_image_resize.h](stb_image_resize.h)** | 0.96 | graphics | 2631 | resize images larger/smaller with good quality28-**[stb_rect_pack.h](stb_rect_pack.h)** | 1.00 | graphics | 628 | simple 2D rectangle packer with decent quality29-**[stb_ds.h](stb_ds.h)** | 0.66 | utility | 1893 | typesafe dynamic array and hash tables for C, will compile in C++30-**[stb_sprintf.h](stb_sprintf.h)** | 1.09 | utility | 1879 | fast sprintf, snprintf for C/C++31-**[stb_textedit.h](stb_textedit.h)** | 1.13 | user interface | 1404 | guts of a text editor for games etc implementing them from scratch25+**[stb_vorbis.c](stb_vorbis.c)** | 1.22 | audio | 5584 | decode ogg vorbis files from file/memory to float/16-bit signed output26+**[stb_hexwave.h](stb_hexwave.h)** | 0.5 | audio | 680 | audio waveform synthesizer27+**[stb_image.h](stb_image.h)** | 2.29 | graphics | 7985 | image loading/decoding from file/memory: JPG, PNG, TGA, BMP, PSD, GIF, HDR, PIC28+**[stb_truetype.h](stb_truetype.h)** | 1.26 | graphics | 5077 | parse, decode, and rasterize characters from truetype fonts29+**[stb_image_write.h](stb_image_write.h)** | 1.16 | graphics | 1724 | image writing to disk: PNG, TGA, BMP30+**[stb_image_resize2.h](stb_image_resize2.h)** | 2.07 | graphics | 10366 | resize images larger/smaller with good quality31+**[stb_rect_pack.h](stb_rect_pack.h)** | 1.01 | graphics | 623 | simple 2D rectangle packer with decent quality32+**[stb_perlin.h](stb_perlin.h)** | 0.5 | graphics | 428 | perlin's revised simplex noise w/ different seeds33+**[stb_ds.h](stb_ds.h)** | 0.67 | utility | 1895 | typesafe dynamic array and hash tables for C, will compile in C++34+**[stb_sprintf.h](stb_sprintf.h)** | 1.10 | utility | 1906 | fast sprintf, snprintf for C/C++35+**[stb_textedit.h](stb_textedit.h)** | 1.14 | user interface | 1429 | guts of a text editor for games etc implementing them from scratch36 **[stb_voxel_render.h](stb_voxel_render.h)** | 0.89 | 3D graphics | 3807 | Minecraft-esque voxel rendering "engine" with many more features33-**[stb_dxt.h](stb_dxt.h)** | 1.10 | 3D graphics | 753 | Fabian "ryg" Giesen's real-time DXT compressor34-**[stb_perlin.h](stb_perlin.h)** | 0.5 | 3D graphics | 428 | revised Perlin noise (3D input, 1D output)37+**[stb_dxt.h](stb_dxt.h)** | 1.12 | 3D graphics | 719 | Fabian "ryg" Giesen's real-time DXT compressor38 **[stb_easy_font.h](stb_easy_font.h)** | 1.1 | 3D graphics | 305 | quick-and-dirty easy-to-deploy bitmap font for printing frame rate, etc36-**[stb_tilemap_editor.h](stb_tilemap_editor.h)** | 0.41 | game dev | 4161 | embeddable tilemap editor39+**[stb_tilemap_editor.h](stb_tilemap_editor.h)** | 0.42 | game dev | 4187 | embeddable tilemap editor40 **[stb_herringbone_wa...](stb_herringbone_wang_tile.h)** | 0.7 | game dev | 1221 | herringbone Wang tile map generator38-**[stb_c_lexer.h](stb_c_lexer.h)** | 0.11 | parsing | 966 | simplify writing parsers for C-like languages39-**[stb_divide.h](stb_divide.h)** | 0.93 | math | 430 | more useful 32-bit modulus e.g. "euclidean divide"41+**[stb_c_lexer.h](stb_c_lexer.h)** | 0.12 | parsing | 940 | simplify writing parsers for C-like languages42+**[stb_divide.h](stb_divide.h)** | 0.94 | math | 433 | more useful 32-bit modulus e.g. "euclidean divide"43 **[stb_connected_comp...](stb_connected_components.h)** | 0.96 | misc | 1049 | incrementally compute reachability on grids41-**[stb.h](stb.h)** | 2.37 | misc | 14454 | helper functions for C, mostly redundant in C++; basically author's personal stuff44 **[stb_leakcheck.h](stb_leakcheck.h)** | 0.6 | misc | 194 | quick-and-dirty malloc/free leak-checking45 **[stb_include.h](stb_include.h)** | 0.02 | misc | 295 | implement recursive #include support, particularly for GLSL46 47 Total libraries: 2146-Total lines of C code: 5653048+Total lines of C code: 5084749 50 51 FAQ52 ---53 54+#### What's the license?55+56+These libraries are in the public domain. You can do anything you57+want with them. You have no legal obligation58+to do anything else, although I appreciate attribution.59+60+They are also licensed under the MIT open source license, if you have lawyers61+who are unhappy with public domain. Every source file includes an explicit62+dual-license for you to choose from.63+64 #### How do I use these libraries?65 66 The idea behind single-header file libraries is that they're easy to distribute and deploy67 because all the code is contained in a single file. By default, the .h files in here act as10 unmodified lines78 #include "stb_image.h"79 80 The right macro to define is pointed out right at the top of each of these libraries.81 70-#### What's the license?71-72-These libraries are in the public domain. You can do anything you73-want with them. You have no legal obligation74-to do anything else, although I appreciate attribution.75-76-They are also licensed under the MIT open source license, if you have lawyers77-who are unhappy with public domain. Every source file includes an explicit78-dual-license for you to choose from.79-82 #### <a name="other_libs"></a> Are there other single-file public-domain/open source libraries with minimal dependencies out there?83 84 [Yes.](https://github.com/nothings/single_file_libs)85 99 unmodified linesmodified:stb_c_lexer.h+49 added-75 removed
1-// stb_c_lexer.h - v0.11 - public domain Sean Barrett 20131+// stb_c_lexer.h - v0.12 - public domain Sean Barrett 20132 // lexer for making little C-like languages with recursive-descent parsers3 //4 // This file provides both the interface and the implementation.5 // To instantiate the implementation,3 unmodified lines9 // The default configuration is fairly close to a C lexer, although10 // suffixes on integer constants are not handled (you can override this).11 //12 // History:13+// 0.12 fix compilation bug for NUL support; better support separate inclusion14 // 0.11 fix clang static analysis warning15 // 0.10 fix warnings16 // 0.09 hex floats, no-stdlib fixes17 // 0.08 fix bad pointer comparison25 unmodified lines43 // LICENSE44 //45 // See end of file for license information.46 47+#ifdef STB_C_LEXER_IMPLEMENTATION48 #ifndef STB_C_LEXER_DEFINITIONS49 // to change the default parsing rules, copy the following lines50 // into your C/C++ file *before* including this, and then replace49-// the Y's with N's for the ones you don't want.51+// the Y's with N's for the ones you don't want. This needs to be52+// set to the same values for every place in your program where53+// stb_c_lexer.h is included.54 // --BEGIN--55 56+#if defined(Y) || defined(N)57+#error "Can only use stb_c_lexer in contexts where the preprocessor symbols 'Y' and 'N' are not defined"58+#endif59+60 #define STB_C_LEX_C_DECIMAL_INTS Y // "0|[1-9][0-9]*" CLEX_intlit61 #define STB_C_LEX_C_HEX_INTS Y // "0x[0-9a-fA-F]+" CLEX_intlit62 #define STB_C_LEX_C_OCTAL_INTS Y // "[0-7]+" CLEX_intlit63 #define STB_C_LEX_C_DECIMAL_FLOATS Y // "[0-9]*(.[0-9]*([eE][-+]?[0-9]+)?) CLEX_floatlit39 unmodified lines103 //#define STB_C_LEX_ISWHITE(str) ... // return length in bytes of whitespace characters if first char is whitespace104 105 #define STB_C_LEXER_DEFINITIONS // This line prevents the header file from replacing your definitions106 // --END--99-107 #endif108+#endif109 110 #ifndef INCLUDE_STB_C_LEXER_H111 #define INCLUDE_STB_C_LEXER_H112 60 unmodified lines173 #ifdef __cplusplus174 }175 #endif176 177+enum178+{179+ CLEX_eof = 256,180+ CLEX_parse_error,181+ CLEX_intlit ,182+ CLEX_floatlit ,183+ CLEX_id ,184+ CLEX_dqstring ,185+ CLEX_sqstring ,186+ CLEX_charlit ,187+ CLEX_eq ,188+ CLEX_noteq ,189+ CLEX_lesseq ,190+ CLEX_greatereq ,191+ CLEX_andand ,192+ CLEX_oror ,193+ CLEX_shl ,194+ CLEX_shr ,195+ CLEX_plusplus ,196+ CLEX_minusminus ,197+ CLEX_pluseq ,198+ CLEX_minuseq ,199+ CLEX_muleq ,200+ CLEX_diveq ,201+ CLEX_modeq ,202+ CLEX_andeq ,203+ CLEX_oreq ,204+ CLEX_xoreq ,205+ CLEX_arrow ,206+ CLEX_eqarrow ,207+ CLEX_shleq, CLEX_shreq,208+209+ CLEX_first_unused_token210+211+};212 #endif // INCLUDE_STB_C_LEXER_H213 214 #ifdef STB_C_LEXER_IMPLEMENTATION215 173- #if defined(Y) || defined(N)174- #error "Can only use stb_c_lexer in contexts where the preprocessor symbols 'Y' and 'N' are not defined"175- #endif176-177-216 // Hacky definitions so we can easily #if on them217 #define Y(x) 1218 #define N(x) 0219 12 unmodified lines232 #if STB_C_LEX_PARSE_SUFFIXES(x)233 #define STB__clex_parse_suffixes234 #endif235 198-#if STB_C_LEX_C_DECIMAL_INTS(x) || STB_C_LEX_C_HEX_INTS(x) || STB_C_LEX_DEFINE_ALL_TOKEN_NAMES(x)199-#define STB__clex_define_int200-#endif201-202-#if (STB_C_LEX_C_ARITHEQ(x) && STB_C_LEX_C_SHIFTS(x)) || STB_C_LEX_DEFINE_ALL_TOKEN_NAMES(x)203-#define STB__clex_define_shifts204-#endif205-236 #if STB_C_LEX_C99_HEX_FLOATS(x)237 #define STB__clex_hex_floats238 #endif239 21 unmodified lines261 #define STB__CLEX_use_stdlib262 #include <stdlib.h>263 #endif264 235-// Now pick a definition of Y/N that's conducive to236-// defining the enum of token names.237-#if STB_C_LEX_DEFINE_ALL_TOKEN_NAMES(x) || defined(STB_C_LEXER_SELF_TEST)238- #undef N239- #define N(a) Y(a)240-#else241- #undef N242- #define N(a)243-#endif244-245-#undef Y246-#define Y(a) a,247-248-enum249-{250- CLEX_eof = 256,251- CLEX_parse_error,252-253-#ifdef STB__clex_define_int254- CLEX_intlit,255-#endif256-257- STB_C_LEX_C_DECIMAL_FLOATS( CLEX_floatlit )258- STB_C_LEX_C_IDENTIFIERS( CLEX_id )259- STB_C_LEX_C_DQ_STRINGS( CLEX_dqstring )260- STB_C_LEX_C_SQ_STRINGS( CLEX_sqstring )261- STB_C_LEX_C_CHARS( CLEX_charlit )262- STB_C_LEX_C_COMPARISONS( CLEX_eq )263- STB_C_LEX_C_COMPARISONS( CLEX_noteq )264- STB_C_LEX_C_COMPARISONS( CLEX_lesseq )265- STB_C_LEX_C_COMPARISONS( CLEX_greatereq )266- STB_C_LEX_C_LOGICAL( CLEX_andand )267- STB_C_LEX_C_LOGICAL( CLEX_oror )268- STB_C_LEX_C_SHIFTS( CLEX_shl )269- STB_C_LEX_C_SHIFTS( CLEX_shr )270- STB_C_LEX_C_INCREMENTS( CLEX_plusplus )271- STB_C_LEX_C_INCREMENTS( CLEX_minusminus )272- STB_C_LEX_C_ARITHEQ( CLEX_pluseq )273- STB_C_LEX_C_ARITHEQ( CLEX_minuseq )274- STB_C_LEX_C_ARITHEQ( CLEX_muleq )275- STB_C_LEX_C_ARITHEQ( CLEX_diveq )276- STB_C_LEX_C_ARITHEQ( CLEX_modeq )277- STB_C_LEX_C_BITWISEEQ( CLEX_andeq )278- STB_C_LEX_C_BITWISEEQ( CLEX_oreq )279- STB_C_LEX_C_BITWISEEQ( CLEX_xoreq )280- STB_C_LEX_C_ARROW( CLEX_arrow )281- STB_C_LEX_EQUAL_ARROW( CLEX_eqarrow )282-283-#ifdef STB__clex_define_shifts284- CLEX_shleq, CLEX_shreq,285-#endif286-287- CLEX_first_unused_token288-289-#undef Y290-#define Y(a) a291-};292-265 // Now for the rest of the file we'll use the basic definition where266 // where Y expands to its contents and N expands to nothing267+#undef Y268+#define Y(a) a269 #undef N270 #define N(a)271 272 // API function309 unmodified lines582 583 // check for EOF584 STB_C_LEX_0_IS_EOF(585 if (*p == 0)612- return stb__clex_eof(tok);586+ return stb__clex_eof(lexer);587 )588 589 single_char:590 // not an identifier, return the character as itself351 unmodified linesmodified:stb_divide.h+12 added-9 removed
1-// stb_divide.h - v0.93 - public domain - Sean Barrett, Feb 20101+// stb_divide.h - v0.94 - public domain - Sean Barrett, Feb 20102 // Three kinds of divide/modulus of signed integers.3 //4 // HISTORY5 //6+// v0.94 Fix integer overflow issues7 // v0.93 2020-02-02 Write useful exit() value from main()8 // v0.92 2019-02-25 Fix warning9 // v0.91 2010-02-27 Fix euclidean division by INT_MIN for non-truncating C10 // Check result with 64-bit math to catch such cases155 unmodified lines166 #ifdef C_INTEGER_DIVISION_FLOORS167 return v1/v2;168 #else169 if (v1 >= 0 && v2 < 0) {169- if ((-v1)+v2+1 < 0) // check if increasing v1's magnitude overflows170- return -stb__div(-v1+v2+1,v2); // nope, so just compute it170+ if (v2 + 1 >= INT_MIN + v1) // check if increasing v1's magnitude overflows171+ return -stb__div((v2+1)-v1,v2); // nope, so just compute it172 else173 return -stb__div(-v1,v2) + ((-v1)%v2 ? -1 : 0);174 }175 if (v1 < 0 && v2 >= 0) {176 if (v1 != INT_MIN) {176- if (v1-v2+1 < 0) // check if increasing v1's magnitude overflows177- return -stb__div(v1-v2+1,-v2); // nope, so just compute it177+ if (v1 + 1 >= INT_MIN + v2) // check if increasing v1's magnitude overflows178+ return -stb__div((v1+1)-v2,-v2); // nope, so just compute it179 else180 return -stb__div(-v1,v2) + (stb__mod(v1,-v2) ? -1 : 0);181 } else // it must be possible to compute -(v1+v2) without overflowing182 return -stb__div(-(v1+v2),v2) + (stb__mod(-(v1+v2),v2) ? -2 : -1);26 unmodified lines209 q = 1, r = v1-q*v2;210 else // if v1 is INT_MIN, we have to move away from overflow place211 if (v2 >= 0)212 q = -stb__div(-(v1+v2),v2)-1, r = -stb__mod(-(v1+v2),v2);212- else213+ else if (v2 != INT_MIN)214 q = stb__div(-(v1-v2),-v2)+1, r = -stb__mod(-(v1-v2),-v2);215+ else // for INT_MIN / INT_MIN, we need to be extra-careful to avoid overflow216+ q = 1, r = 0;217 #endif218 if (r >= 0)219 return q;220 else9 unmodified lines230 int r = stb__mod(v1,v2);231 if (r >= 0)232 return r;233 else231- return r + (v2 > 0 ? v2 : -v2);234+ return r - (v2 < 0 ? v2 : -v2);235 } else { // modulus result should always be negative236 int r = stb__mod(v1,v2);237 if (r <= 0)238 return r;239 else237- return r - (v2 > 0 ? v2 : -v2);240+ return r + (v2 < 0 ? v2 : -v2);241 }242 #endif243 }244 24 unmodified lines269 270 if (r >= 0)271 return r;272 else270- return r + (v2 > 0 ? v2 : -v2); // abs()273+ return r - (v2 < 0 ? v2 : -v2); // negative abs() [to avoid overflow]274 }275 276 #ifdef STB_DIVIDE_TEST277 #include <stdio.h>156 unmodified linesmodified:stb_ds.h+23 added-21 removed
1-/* stb_ds.h - v0.66 - public domain data structures - Sean Barrett 20191+/* stb_ds.h - v0.67 - public domain data structures - Sean Barrett 20192 3 This is a single-header-file library that provides easy-to-use4 dynamic arrays and hash tables for C (also works in C++).5 97 unmodified lines103 Inserts the item b into the middle of array a, into a[p],104 moving the rest of the array over. Returns b.105 106 arrinsn:107- void arrins(T* a, int p, int n);107+ void arrinsn(T* a, int p, int n);108 Inserts n uninitialized items into array a starting at a[p],109 moving the rest of the array over.110 111 arraddnptr:10 unmodified lines122 void arrdel(T* a, int p);123 Deletes the element at a[p], moving the rest of the array over.124 125 arrdeln:126- void arrdel(T* a, int p, int n);126+ void arrdeln(T* a, int p, int n);127 Deletes n elements starting at a[p], moving the rest of the array over.128 129 arrdelswap:130 void arrdelswap(T* a, int p);249 unmodified lines380 github:hashitaku381 github:srdjanstipic382 Macoy Madson383 Andreas Vennstrom384+ Tobias Mansfield-Williams385 */386 387 #ifdef STBDS_UNIT_TESTS388 #define _CRT_SECURE_NO_WARNINGS145 unmodified lines534 #define stbds_header(t) ((stbds_array_header *) (t) - 1)535 #define stbds_temp(t) stbds_header(t)->temp536 #define stbds_temp_key(t) (*(char **) stbds_header(t)->hash_table)537 537-#define stbds_arrsetcap(a,n) (stbds_arrgrow(a,0,n))538-#define stbds_arrsetlen(a,n) ((stbds_arrcap(a) < (size_t) (n) ? stbds_arrsetcap((a),(size_t)(n)),0 : 0), (a) ? stbds_header(a)->length = (size_t) (n) : 0)539-#define stbds_arrcap(a) ((a) ? stbds_header(a)->capacity : 0)540-#define stbds_arrlen(a) ((a) ? (ptrdiff_t) stbds_header(a)->length : 0)541-#define stbds_arrlenu(a) ((a) ? stbds_header(a)->length : 0)542-#define stbds_arrput(a,v) (stbds_arrmaybegrow(a,1), (a)[stbds_header(a)->length++] = (v))543-#define stbds_arrpush stbds_arrput // synonym544-#define stbds_arrpop(a) (stbds_header(a)->length--, (a)[stbds_header(a)->length])545-#define stbds_arraddn(a,n) ((void)(stbds_arraddnoff(a, n))) // deprecated, use one of the following instead:546-#define stbds_arraddnptr(a,n) (stbds_arrmaybegrow(a,n), stbds_header(a)->length += (n), &(a)[stbds_header(a)->length-(n)])547-#define stbds_arraddnoff(a,n) (stbds_arrmaybegrow(a,n), stbds_header(a)->length += (n), stbds_header(a)->length-(n))548-#define stbds_arrlast(a) ((a)[stbds_header(a)->length-1])549-#define stbds_arrfree(a) ((void) ((a) ? stbds_arrfreef(a) : (void)0), (a)=NULL)550-#define stbds_arrdel(a,i) stbds_arrdeln(a,i,1)551-#define stbds_arrdeln(a,i,n) (memmove(&(a)[i], &(a)[(i)+(n)], sizeof *(a) * (stbds_header(a)->length-(n)-(i))), stbds_header(a)->length -= (n))552-#define stbds_arrdelswap(a,i) ((a)[i] = stbds_arrlast(a), stbds_header(a)->length -= 1)553-#define stbds_arrinsn(a,i,n) ((a)?stbds_temp(a)=(i):0,stbds_arraddn((a),(n)), memmove(&(a)[stbds_temp(a)+(n)], &(a)[stbds_temp(a)], sizeof *(a) * (stbds_header(a)->length-(n)-stbds_temp(a))))554-#define stbds_arrins(a,i,v) (stbds_arrinsn((a),(i),1), (a)[i]=(v))538+#define stbds_arrsetcap(a,n) (stbds_arrgrow(a,0,n))539+#define stbds_arrsetlen(a,n) ((stbds_arrcap(a) < (size_t) (n) ? stbds_arrsetcap((a),(size_t)(n)),0 : 0), (a) ? stbds_header(a)->length = (size_t) (n) : 0)540+#define stbds_arrcap(a) ((a) ? stbds_header(a)->capacity : 0)541+#define stbds_arrlen(a) ((a) ? (ptrdiff_t) stbds_header(a)->length : 0)542+#define stbds_arrlenu(a) ((a) ? stbds_header(a)->length : 0)543+#define stbds_arrput(a,v) (stbds_arrmaybegrow(a,1), (a)[stbds_header(a)->length++] = (v))544+#define stbds_arrpush stbds_arrput // synonym545+#define stbds_arrpop(a) (stbds_header(a)->length--, (a)[stbds_header(a)->length])546+#define stbds_arraddn(a,n) ((void)(stbds_arraddnindex(a, n))) // deprecated, use one of the following instead:547+#define stbds_arraddnptr(a,n) (stbds_arrmaybegrow(a,n), (n) ? (stbds_header(a)->length += (n), &(a)[stbds_header(a)->length-(n)]) : (a))548+#define stbds_arraddnindex(a,n)(stbds_arrmaybegrow(a,n), (n) ? (stbds_header(a)->length += (n), stbds_header(a)->length-(n)) : stbds_arrlen(a))549+#define stbds_arraddnoff stbds_arraddnindex550+#define stbds_arrlast(a) ((a)[stbds_header(a)->length-1])551+#define stbds_arrfree(a) ((void) ((a) ? STBDS_FREE(NULL,stbds_header(a)) : (void)0), (a)=NULL)552+#define stbds_arrdel(a,i) stbds_arrdeln(a,i,1)553+#define stbds_arrdeln(a,i,n) (memmove(&(a)[i], &(a)[(i)+(n)], sizeof *(a) * (stbds_header(a)->length-(n)-(i))), stbds_header(a)->length -= (n))554+#define stbds_arrdelswap(a,i) ((a)[i] = stbds_arrlast(a), stbds_header(a)->length -= 1)555+#define stbds_arrinsn(a,i,n) (stbds_arraddn((a),(n)), memmove(&(a)[(i)+(n)], &(a)[i], sizeof *(a) * (stbds_header(a)->length-(n)-(i))))556+#define stbds_arrins(a,i,v) (stbds_arrinsn((a),(i),1), (a)[i]=(v))557 558 #define stbds_arrmaybegrow(a,n) ((!(a) || stbds_header(a)->length + (n) > stbds_header(a)->capacity) \559 ? (stbds_arrgrow(a,n,0),0) : 0)560 1335 unmodified linesmodified:stb_dxt.h+67 added-66 removed
1-// stb_dxt.h - v1.11 - DXT1/DXT5 compressor - public domain1+// stb_dxt.h - v1.12 - DXT1/DXT5 compressor - public domain2 // original by fabian "ryg" giesen - ported to C by stb3 // use '#define STB_DXT_IMPLEMENTATION' before including to create the implementation4 //5 // USAGE:3 unmodified lines9 // must supply some constant alpha in the alpha channel).10 // You can turn on dithering and "high quality" using mode.11 //12 // version history:13+// v1.12 - (ryg) fix bug in single-color table generator14 // v1.11 - (ryg) avoid racy global init, better single-color tables, remove dither15 // v1.10 - (i.c) various small quality improvements16 // v1.09 - (stb) update documentation re: surprising alpha channel requirement17 // v1.08 - (stb) fix bug in dxt-with-alpha block74 unmodified lines92 #define STBD_FABS(x) fabs(x)93 #endif94 95 static const unsigned char stb__OMatch5[256][2] = {95- { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 1, 1 }, { 1, 1 }, { 1, 1 },96- { 1, 1 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 2, 2 }, { 2, 2 }, { 2, 2 },97- { 2, 2 }, { 2, 2 }, { 2, 2 }, { 2, 2 }, { 2, 2 }, { 3, 3 }, { 3, 3 }, { 3, 3 },98- { 3, 3 }, { 3, 3 }, { 3, 3 }, { 3, 3 }, { 3, 3 }, { 4, 4 }, { 4, 4 }, { 4, 4 },99- { 4, 4 }, { 4, 4 }, { 4, 4 }, { 4, 4 }, { 4, 4 }, { 4, 4 }, { 5, 5 }, { 5, 5 },100- { 5, 5 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 6, 6 }, { 6, 6 },101- { 6, 6 }, { 6, 6 }, { 6, 6 }, { 6, 6 }, { 6, 6 }, { 6, 6 }, { 7, 7 }, { 7, 7 },102- { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 8, 8 }, { 8, 8 },103- { 8, 8 }, { 8, 8 }, { 8, 8 }, { 8, 8 }, { 8, 8 }, { 8, 8 }, { 8, 8 }, { 9, 9 },104- { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 10, 10 },105- { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 11, 11 },106- { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 12, 12 },107- { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 },108- { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 },109- { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 },110- { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 },111- { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 },112- { 16, 16 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 },113- { 17, 17 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 },114- { 18, 18 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 },115- { 19, 19 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 },116- { 20, 20 }, { 20, 20 }, { 21, 21 }, { 21, 21 }, { 21, 21 }, { 21, 21 }, { 21, 21 }, { 21, 21 },117- { 21, 21 }, { 21, 21 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 22 },118- { 22, 22 }, { 22, 22 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 23 },119- { 23, 23 }, { 23, 23 }, { 24, 24 }, { 24, 24 }, { 24, 24 }, { 24, 24 }, { 24, 24 }, { 24, 24 },120- { 24, 24 }, { 24, 24 }, { 24, 24 }, { 25, 25 }, { 25, 25 }, { 25, 25 }, { 25, 25 }, { 25, 25 },121- { 25, 25 }, { 25, 25 }, { 25, 25 }, { 26, 26 }, { 26, 26 }, { 26, 26 }, { 26, 26 }, { 26, 26 },122- { 26, 26 }, { 26, 26 }, { 26, 26 }, { 27, 27 }, { 27, 27 }, { 27, 27 }, { 27, 27 }, { 27, 27 },123- { 27, 27 }, { 27, 27 }, { 27, 27 }, { 28, 28 }, { 28, 28 }, { 28, 28 }, { 28, 28 }, { 28, 28 },124- { 28, 28 }, { 28, 28 }, { 28, 28 }, { 28, 28 }, { 29, 29 }, { 29, 29 }, { 29, 29 }, { 29, 29 },125- { 29, 29 }, { 29, 29 }, { 29, 29 }, { 29, 29 }, { 30, 30 }, { 30, 30 }, { 30, 30 }, { 30, 30 },126- { 30, 30 }, { 30, 30 }, { 30, 30 }, { 30, 30 }, { 31, 31 }, { 31, 31 }, { 31, 31 }, { 31, 31 },96+ { 0, 0 }, { 0, 0 }, { 0, 1 }, { 0, 1 }, { 1, 0 }, { 1, 0 }, { 1, 0 }, { 1, 1 },97+ { 1, 1 }, { 1, 1 }, { 1, 2 }, { 0, 4 }, { 2, 1 }, { 2, 1 }, { 2, 1 }, { 2, 2 },98+ { 2, 2 }, { 2, 2 }, { 2, 3 }, { 1, 5 }, { 3, 2 }, { 3, 2 }, { 4, 0 }, { 3, 3 },99+ { 3, 3 }, { 3, 3 }, { 3, 4 }, { 3, 4 }, { 3, 4 }, { 3, 5 }, { 4, 3 }, { 4, 3 },100+ { 5, 2 }, { 4, 4 }, { 4, 4 }, { 4, 5 }, { 4, 5 }, { 5, 4 }, { 5, 4 }, { 5, 4 },101+ { 6, 3 }, { 5, 5 }, { 5, 5 }, { 5, 6 }, { 4, 8 }, { 6, 5 }, { 6, 5 }, { 6, 5 },102+ { 6, 6 }, { 6, 6 }, { 6, 6 }, { 6, 7 }, { 5, 9 }, { 7, 6 }, { 7, 6 }, { 8, 4 },103+ { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 8 }, { 7, 8 }, { 7, 8 }, { 7, 9 }, { 8, 7 },104+ { 8, 7 }, { 9, 6 }, { 8, 8 }, { 8, 8 }, { 8, 9 }, { 8, 9 }, { 9, 8 }, { 9, 8 },105+ { 9, 8 }, { 10, 7 }, { 9, 9 }, { 9, 9 }, { 9, 10 }, { 8, 12 }, { 10, 9 }, { 10, 9 },106+ { 10, 9 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 11 }, { 9, 13 }, { 11, 10 }, { 11, 10 },107+ { 12, 8 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 12 }, { 11, 12 }, { 11, 12 }, { 11, 13 },108+ { 12, 11 }, { 12, 11 }, { 13, 10 }, { 12, 12 }, { 12, 12 }, { 12, 13 }, { 12, 13 }, { 13, 12 },109+ { 13, 12 }, { 13, 12 }, { 14, 11 }, { 13, 13 }, { 13, 13 }, { 13, 14 }, { 12, 16 }, { 14, 13 },110+ { 14, 13 }, { 14, 13 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 15 }, { 13, 17 }, { 15, 14 },111+ { 15, 14 }, { 16, 12 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 16 }, { 15, 16 }, { 15, 16 },112+ { 15, 17 }, { 16, 15 }, { 16, 15 }, { 17, 14 }, { 16, 16 }, { 16, 16 }, { 16, 17 }, { 16, 17 },113+ { 17, 16 }, { 17, 16 }, { 17, 16 }, { 18, 15 }, { 17, 17 }, { 17, 17 }, { 17, 18 }, { 16, 20 },114+ { 18, 17 }, { 18, 17 }, { 18, 17 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 19 }, { 17, 21 },115+ { 19, 18 }, { 19, 18 }, { 20, 16 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 20 }, { 19, 20 },116+ { 19, 20 }, { 19, 21 }, { 20, 19 }, { 20, 19 }, { 21, 18 }, { 20, 20 }, { 20, 20 }, { 20, 21 },117+ { 20, 21 }, { 21, 20 }, { 21, 20 }, { 21, 20 }, { 22, 19 }, { 21, 21 }, { 21, 21 }, { 21, 22 },118+ { 20, 24 }, { 22, 21 }, { 22, 21 }, { 22, 21 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 23 },119+ { 21, 25 }, { 23, 22 }, { 23, 22 }, { 24, 20 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 24 },120+ { 23, 24 }, { 23, 24 }, { 23, 25 }, { 24, 23 }, { 24, 23 }, { 25, 22 }, { 24, 24 }, { 24, 24 },121+ { 24, 25 }, { 24, 25 }, { 25, 24 }, { 25, 24 }, { 25, 24 }, { 26, 23 }, { 25, 25 }, { 25, 25 },122+ { 25, 26 }, { 24, 28 }, { 26, 25 }, { 26, 25 }, { 26, 25 }, { 26, 26 }, { 26, 26 }, { 26, 26 },123+ { 26, 27 }, { 25, 29 }, { 27, 26 }, { 27, 26 }, { 28, 24 }, { 27, 27 }, { 27, 27 }, { 27, 27 },124+ { 27, 28 }, { 27, 28 }, { 27, 28 }, { 27, 29 }, { 28, 27 }, { 28, 27 }, { 29, 26 }, { 28, 28 },125+ { 28, 28 }, { 28, 29 }, { 28, 29 }, { 29, 28 }, { 29, 28 }, { 29, 28 }, { 30, 27 }, { 29, 29 },126+ { 29, 29 }, { 29, 30 }, { 29, 30 }, { 30, 29 }, { 30, 29 }, { 30, 29 }, { 30, 30 }, { 30, 30 },127+ { 30, 30 }, { 30, 31 }, { 30, 31 }, { 31, 30 }, { 31, 30 }, { 31, 30 }, { 31, 31 }, { 31, 31 },128 };129 static const unsigned char stb__OMatch6[256][2] = {129- { 0, 0 }, { 0, 0 }, { 0, 0 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 2, 2 },130- { 2, 2 }, { 2, 2 }, { 2, 2 }, { 3, 3 }, { 3, 3 }, { 3, 3 }, { 3, 3 }, { 4, 4 },131- { 4, 4 }, { 4, 4 }, { 4, 4 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 6, 6 },132- { 6, 6 }, { 6, 6 }, { 6, 6 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 8, 8 },133- { 8, 8 }, { 8, 8 }, { 8, 8 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 10, 10 },134- { 10, 10 }, { 10, 10 }, { 10, 10 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 12, 12 },135- { 12, 12 }, { 12, 12 }, { 12, 12 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 14, 14 },136- { 14, 14 }, { 14, 14 }, { 14, 14 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 16, 16 },137- { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 },138- { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 },139- { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 21, 21 }, { 21, 21 }, { 21, 21 }, { 21, 21 },140- { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 23 },141- { 24, 24 }, { 24, 24 }, { 24, 24 }, { 24, 24 }, { 25, 25 }, { 25, 25 }, { 25, 25 }, { 25, 25 },142- { 26, 26 }, { 26, 26 }, { 26, 26 }, { 26, 26 }, { 27, 27 }, { 27, 27 }, { 27, 27 }, { 27, 27 },143- { 28, 28 }, { 28, 28 }, { 28, 28 }, { 28, 28 }, { 29, 29 }, { 29, 29 }, { 29, 29 }, { 29, 29 },144- { 30, 30 }, { 30, 30 }, { 30, 30 }, { 30, 30 }, { 31, 31 }, { 31, 31 }, { 31, 31 }, { 31, 31 },145- { 32, 32 }, { 32, 32 }, { 32, 32 }, { 32, 32 }, { 32, 32 }, { 33, 33 }, { 33, 33 }, { 33, 33 },146- { 33, 33 }, { 34, 34 }, { 34, 34 }, { 34, 34 }, { 34, 34 }, { 35, 35 }, { 35, 35 }, { 35, 35 },147- { 35, 35 }, { 36, 36 }, { 36, 36 }, { 36, 36 }, { 36, 36 }, { 37, 37 }, { 37, 37 }, { 37, 37 },148- { 37, 37 }, { 38, 38 }, { 38, 38 }, { 38, 38 }, { 38, 38 }, { 39, 39 }, { 39, 39 }, { 39, 39 },149- { 39, 39 }, { 40, 40 }, { 40, 40 }, { 40, 40 }, { 40, 40 }, { 41, 41 }, { 41, 41 }, { 41, 41 },150- { 41, 41 }, { 42, 42 }, { 42, 42 }, { 42, 42 }, { 42, 42 }, { 43, 43 }, { 43, 43 }, { 43, 43 },151- { 43, 43 }, { 44, 44 }, { 44, 44 }, { 44, 44 }, { 44, 44 }, { 45, 45 }, { 45, 45 }, { 45, 45 },152- { 45, 45 }, { 46, 46 }, { 46, 46 }, { 46, 46 }, { 46, 46 }, { 47, 47 }, { 47, 47 }, { 47, 47 },153- { 47, 47 }, { 48, 48 }, { 48, 48 }, { 48, 48 }, { 48, 48 }, { 48, 48 }, { 49, 49 }, { 49, 49 },154- { 49, 49 }, { 49, 49 }, { 50, 50 }, { 50, 50 }, { 50, 50 }, { 50, 50 }, { 51, 51 }, { 51, 51 },155- { 51, 51 }, { 51, 51 }, { 52, 52 }, { 52, 52 }, { 52, 52 }, { 52, 52 }, { 53, 53 }, { 53, 53 },156- { 53, 53 }, { 53, 53 }, { 54, 54 }, { 54, 54 }, { 54, 54 }, { 54, 54 }, { 55, 55 }, { 55, 55 },157- { 55, 55 }, { 55, 55 }, { 56, 56 }, { 56, 56 }, { 56, 56 }, { 56, 56 }, { 57, 57 }, { 57, 57 },158- { 57, 57 }, { 57, 57 }, { 58, 58 }, { 58, 58 }, { 58, 58 }, { 58, 58 }, { 59, 59 }, { 59, 59 },159- { 59, 59 }, { 59, 59 }, { 60, 60 }, { 60, 60 }, { 60, 60 }, { 60, 60 }, { 61, 61 }, { 61, 61 },160- { 61, 61 }, { 61, 61 }, { 62, 62 }, { 62, 62 }, { 62, 62 }, { 62, 62 }, { 63, 63 }, { 63, 63 },130+ { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 }, { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 },131+ { 2, 2 }, { 2, 3 }, { 3, 2 }, { 3, 3 }, { 3, 3 }, { 3, 4 }, { 4, 3 }, { 4, 4 },132+ { 4, 4 }, { 4, 5 }, { 5, 4 }, { 5, 5 }, { 5, 5 }, { 5, 6 }, { 6, 5 }, { 6, 6 },133+ { 6, 6 }, { 6, 7 }, { 7, 6 }, { 7, 7 }, { 7, 7 }, { 7, 8 }, { 8, 7 }, { 8, 8 },134+ { 8, 8 }, { 8, 9 }, { 9, 8 }, { 9, 9 }, { 9, 9 }, { 9, 10 }, { 10, 9 }, { 10, 10 },135+ { 10, 10 }, { 10, 11 }, { 11, 10 }, { 8, 16 }, { 11, 11 }, { 11, 12 }, { 12, 11 }, { 9, 17 },136+ { 12, 12 }, { 12, 13 }, { 13, 12 }, { 11, 16 }, { 13, 13 }, { 13, 14 }, { 14, 13 }, { 12, 17 },137+ { 14, 14 }, { 14, 15 }, { 15, 14 }, { 14, 16 }, { 15, 15 }, { 15, 16 }, { 16, 14 }, { 16, 15 },138+ { 17, 14 }, { 16, 16 }, { 16, 17 }, { 17, 16 }, { 18, 15 }, { 17, 17 }, { 17, 18 }, { 18, 17 },139+ { 20, 14 }, { 18, 18 }, { 18, 19 }, { 19, 18 }, { 21, 15 }, { 19, 19 }, { 19, 20 }, { 20, 19 },140+ { 20, 20 }, { 20, 20 }, { 20, 21 }, { 21, 20 }, { 21, 21 }, { 21, 21 }, { 21, 22 }, { 22, 21 },141+ { 22, 22 }, { 22, 22 }, { 22, 23 }, { 23, 22 }, { 23, 23 }, { 23, 23 }, { 23, 24 }, { 24, 23 },142+ { 24, 24 }, { 24, 24 }, { 24, 25 }, { 25, 24 }, { 25, 25 }, { 25, 25 }, { 25, 26 }, { 26, 25 },143+ { 26, 26 }, { 26, 26 }, { 26, 27 }, { 27, 26 }, { 24, 32 }, { 27, 27 }, { 27, 28 }, { 28, 27 },144+ { 25, 33 }, { 28, 28 }, { 28, 29 }, { 29, 28 }, { 27, 32 }, { 29, 29 }, { 29, 30 }, { 30, 29 },145+ { 28, 33 }, { 30, 30 }, { 30, 31 }, { 31, 30 }, { 30, 32 }, { 31, 31 }, { 31, 32 }, { 32, 30 },146+ { 32, 31 }, { 33, 30 }, { 32, 32 }, { 32, 33 }, { 33, 32 }, { 34, 31 }, { 33, 33 }, { 33, 34 },147+ { 34, 33 }, { 36, 30 }, { 34, 34 }, { 34, 35 }, { 35, 34 }, { 37, 31 }, { 35, 35 }, { 35, 36 },148+ { 36, 35 }, { 36, 36 }, { 36, 36 }, { 36, 37 }, { 37, 36 }, { 37, 37 }, { 37, 37 }, { 37, 38 },149+ { 38, 37 }, { 38, 38 }, { 38, 38 }, { 38, 39 }, { 39, 38 }, { 39, 39 }, { 39, 39 }, { 39, 40 },150+ { 40, 39 }, { 40, 40 }, { 40, 40 }, { 40, 41 }, { 41, 40 }, { 41, 41 }, { 41, 41 }, { 41, 42 },151+ { 42, 41 }, { 42, 42 }, { 42, 42 }, { 42, 43 }, { 43, 42 }, { 40, 48 }, { 43, 43 }, { 43, 44 },152+ { 44, 43 }, { 41, 49 }, { 44, 44 }, { 44, 45 }, { 45, 44 }, { 43, 48 }, { 45, 45 }, { 45, 46 },153+ { 46, 45 }, { 44, 49 }, { 46, 46 }, { 46, 47 }, { 47, 46 }, { 46, 48 }, { 47, 47 }, { 47, 48 },154+ { 48, 46 }, { 48, 47 }, { 49, 46 }, { 48, 48 }, { 48, 49 }, { 49, 48 }, { 50, 47 }, { 49, 49 },155+ { 49, 50 }, { 50, 49 }, { 52, 46 }, { 50, 50 }, { 50, 51 }, { 51, 50 }, { 53, 47 }, { 51, 51 },156+ { 51, 52 }, { 52, 51 }, { 52, 52 }, { 52, 52 }, { 52, 53 }, { 53, 52 }, { 53, 53 }, { 53, 53 },157+ { 53, 54 }, { 54, 53 }, { 54, 54 }, { 54, 54 }, { 54, 55 }, { 55, 54 }, { 55, 55 }, { 55, 55 },158+ { 55, 56 }, { 56, 55 }, { 56, 56 }, { 56, 56 }, { 56, 57 }, { 57, 56 }, { 57, 57 }, { 57, 57 },159+ { 57, 58 }, { 58, 57 }, { 58, 58 }, { 58, 58 }, { 58, 59 }, { 59, 58 }, { 59, 59 }, { 59, 59 },160+ { 59, 60 }, { 60, 59 }, { 60, 60 }, { 60, 60 }, { 60, 61 }, { 61, 60 }, { 61, 61 }, { 61, 61 },161+ { 61, 62 }, { 62, 61 }, { 62, 62 }, { 62, 62 }, { 62, 63 }, { 63, 62 }, { 63, 63 }, { 63, 63 },162 };163 164 static int stb__Mul8Bit(int a, int b)165 {483 unmodified lines649 for (mn=0;mn<size;mn++) {650 for (mx=0;mx<size;mx++) {651 int mine = (mn * dequant) >> 4;652 int maxe = (mx * dequant) >> 4;652- int err = abs(stb__Lerp13(maxe, mine) - j);653+ int err = abs(stb__Lerp13(maxe, mine) - j) * 100;654 655 // DX10 spec says that interpolation must be within 3% of "correct" result,656 // add this as error term. Normally we'd expect a random distribution of657 // +-1.5% error, but nowhere in the spec does it say that the error has to be62 unmodified linesdeleted:stb_image_resize.h-2631 removed
1-/* stb_image_resize - v0.96 - public domain image resizing2- by Jorge L Rodriguez (@VinoBS) - 20143- http://github.com/nothings/stb4-5- Written with emphasis on usability, portability, and efficiency. (No6- SIMD or threads, so it be easily outperformed by libs that use those.)7- Only scaling and translation is supported, no rotations or shears.8- Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation.9-10- COMPILING & LINKING11- In one C/C++ file that #includes this file, do this:12- #define STB_IMAGE_RESIZE_IMPLEMENTATION13- before the #include. That will create the implementation in that file.14-15- QUICKSTART16- stbir_resize_uint8( input_pixels , in_w , in_h , 0,17- output_pixels, out_w, out_h, 0, num_channels)18- stbir_resize_float(...)19- stbir_resize_uint8_srgb( input_pixels , in_w , in_h , 0,20- output_pixels, out_w, out_h, 0,21- num_channels , alpha_chan , 0)22- stbir_resize_uint8_srgb_edgemode(23- input_pixels , in_w , in_h , 0,24- output_pixels, out_w, out_h, 0,25- num_channels , alpha_chan , 0, STBIR_EDGE_CLAMP)26- // WRAP/REFLECT/ZERO27-28- FULL API29- See the "header file" section of the source for API documentation.30-31- ADDITIONAL DOCUMENTATION32-33- SRGB & FLOATING POINT REPRESENTATION34- The sRGB functions presume IEEE floating point. If you do not have35- IEEE floating point, define STBIR_NON_IEEE_FLOAT. This will use36- a slower implementation.37-38- MEMORY ALLOCATION39- The resize functions here perform a single memory allocation using40- malloc. To control the memory allocation, before the #include that41- triggers the implementation, do:42-43- #define STBIR_MALLOC(size,context) ...44- #define STBIR_FREE(ptr,context) ...45-46- Each resize function makes exactly one call to malloc/free, so to use47- temp memory, store the temp memory in the context and return that.48-49- ASSERT50- Define STBIR_ASSERT(boolval) to override assert() and not use assert.h51-52- OPTIMIZATION53- Define STBIR_SATURATE_INT to compute clamp values in-range using54- integer operations instead of float operations. This may be faster55- on some platforms.56-57- DEFAULT FILTERS58- For functions which don't provide explicit control over what filters59- to use, you can change the compile-time defaults with60-61- #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_something62- #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_something63-64- See stbir_filter in the header-file section for the list of filters.65-66- NEW FILTERS67- A number of 1D filter kernels are used. For a list of68- supported filters see the stbir_filter enum. To add a new filter,69- write a filter function and add it to stbir__filter_info_table.70-71- PROGRESS72- For interactive use with slow resize operations, you can install73- a progress-report callback:74-75- #define STBIR_PROGRESS_REPORT(val) some_func(val)76-77- The parameter val is a float which goes from 0 to 1 as progress is made.78-79- For example:80-81- static void my_progress_report(float progress);82- #define STBIR_PROGRESS_REPORT(val) my_progress_report(val)83-84- #define STB_IMAGE_RESIZE_IMPLEMENTATION85- #include "stb_image_resize.h"86-87- static void my_progress_report(float progress)88- {89- printf("Progress: %f%%\n", progress*100);90- }91-92- MAX CHANNELS93- If your image has more than 64 channels, define STBIR_MAX_CHANNELS94- to the max you'll have.95-96- ALPHA CHANNEL97- Most of the resizing functions provide the ability to control how98- the alpha channel of an image is processed. The important things99- to know about this:100-101- 1. The best mathematically-behaved version of alpha to use is102- called "premultiplied alpha", in which the other color channels103- have had the alpha value multiplied in. If you use premultiplied104- alpha, linear filtering (such as image resampling done by this105- library, or performed in texture units on GPUs) does the "right106- thing". While premultiplied alpha is standard in the movie CGI107- industry, it is still uncommon in the videogame/real-time world.108-109- If you linearly filter non-premultiplied alpha, strange effects110- occur. (For example, the 50/50 average of 99% transparent bright green111- and 1% transparent black produces 50% transparent dark green when112- non-premultiplied, whereas premultiplied it produces 50%113- transparent near-black. The former introduces green energy114- that doesn't exist in the source image.)115-116- 2. Artists should not edit premultiplied-alpha images; artists117- want non-premultiplied alpha images. Thus, art tools generally output118- non-premultiplied alpha images.119-120- 3. You will get best results in most cases by converting images121- to premultiplied alpha before processing them mathematically.122-123- 4. If you pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, the124- resizer does not do anything special for the alpha channel;125- it is resampled identically to other channels. This produces126- the correct results for premultiplied-alpha images, but produces127- less-than-ideal results for non-premultiplied-alpha images.128-129- 5. If you do not pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED,130- then the resizer weights the contribution of input pixels131- based on their alpha values, or, equivalently, it multiplies132- the alpha value into the color channels, resamples, then divides133- by the resultant alpha value. Input pixels which have alpha=0 do134- not contribute at all to output pixels unless _all_ of the input135- pixels affecting that output pixel have alpha=0, in which case136- the result for that pixel is the same as it would be without137- STBIR_FLAG_ALPHA_PREMULTIPLIED. However, this is only true for138- input images in integer formats. For input images in float format,139- input pixels with alpha=0 have no effect, and output pixels140- which have alpha=0 will be 0 in all channels. (For float images,141- you can manually achieve the same result by adding a tiny epsilon142- value to the alpha channel of every image, and then subtracting143- or clamping it at the end.)144-145- 6. You can suppress the behavior described in #5 and make146- all-0-alpha pixels have 0 in all channels by #defining147- STBIR_NO_ALPHA_EPSILON.148-149- 7. You can separately control whether the alpha channel is150- interpreted as linear or affected by the colorspace. By default151- it is linear; you almost never want to apply the colorspace.152- (For example, graphics hardware does not apply sRGB conversion153- to the alpha channel.)154-155- CONTRIBUTORS156- Jorge L Rodriguez: Implementation157- Sean Barrett: API design, optimizations158- Aras Pranckevicius: bugfix159- Nathan Reed: warning fixes160-161- REVISIONS162- 0.97 (2020-02-02) fixed warning163- 0.96 (2019-03-04) fixed warnings164- 0.95 (2017-07-23) fixed warnings165- 0.94 (2017-03-18) fixed warnings166- 0.93 (2017-03-03) fixed bug with certain combinations of heights167- 0.92 (2017-01-02) fix integer overflow on large (>2GB) images168- 0.91 (2016-04-02) fix warnings; fix handling of subpixel regions169- 0.90 (2014-09-17) first released version170-171- LICENSE172- See end of file for license information.173-174- TODO175- Don't decode all of the image data when only processing a partial tile176- Don't use full-width decode buffers when only processing a partial tile177- When processing wide images, break processing into tiles so data fits in L1 cache178- Installable filters?179- Resize that respects alpha test coverage180- (Reference code: FloatImage::alphaTestCoverage and FloatImage::scaleAlphaToCoverage:181- https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvimage/FloatImage.cpp )182-*/183-184-#ifndef STBIR_INCLUDE_STB_IMAGE_RESIZE_H185-#define STBIR_INCLUDE_STB_IMAGE_RESIZE_H186-187-#ifdef _MSC_VER188-typedef unsigned char stbir_uint8;189-typedef unsigned short stbir_uint16;190-typedef unsigned int stbir_uint32;191-#else192-#include <stdint.h>193-typedef uint8_t stbir_uint8;194-typedef uint16_t stbir_uint16;195-typedef uint32_t stbir_uint32;196-#endif197-198-#ifndef STBIRDEF199-#ifdef STB_IMAGE_RESIZE_STATIC200-#define STBIRDEF static201-#else202-#ifdef __cplusplus203-#define STBIRDEF extern "C"204-#else205-#define STBIRDEF extern206-#endif207-#endif208-#endif209-210-//////////////////////////////////////////////////////////////////////////////211-//212-// Easy-to-use API:213-//214-// * "input pixels" points to an array of image data with 'num_channels' channels (e.g. RGB=3, RGBA=4)215-// * input_w is input image width (x-axis), input_h is input image height (y-axis)216-// * stride is the offset between successive rows of image data in memory, in bytes. you can217-// specify 0 to mean packed continuously in memory218-// * alpha channel is treated identically to other channels.219-// * colorspace is linear or sRGB as specified by function name220-// * returned result is 1 for success or 0 in case of an error.221-// #define STBIR_ASSERT() to trigger an assert on parameter validation errors.222-// * Memory required grows approximately linearly with input and output size, but with223-// discontinuities at input_w == output_w and input_h == output_h.224-// * These functions use a "default" resampling filter defined at compile time. To change the filter,225-// you can change the compile-time defaults by #defining STBIR_DEFAULT_FILTER_UPSAMPLE226-// and STBIR_DEFAULT_FILTER_DOWNSAMPLE, or you can use the medium-complexity API.227-228-STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,229- unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,230- int num_channels);231-232-STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,233- float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,234- int num_channels);235-236-237-// The following functions interpret image data as gamma-corrected sRGB.238-// Specify STBIR_ALPHA_CHANNEL_NONE if you have no alpha channel,239-// or otherwise provide the index of the alpha channel. Flags value240-// of 0 will probably do the right thing if you're not sure what241-// the flags mean.242-243-#define STBIR_ALPHA_CHANNEL_NONE -1244-245-// Set this flag if your texture has premultiplied alpha. Otherwise, stbir will246-// use alpha-weighted resampling (effectively premultiplying, resampling,247-// then unpremultiplying).248-#define STBIR_FLAG_ALPHA_PREMULTIPLIED (1 << 0)249-// The specified alpha channel should be handled as gamma-corrected value even250-// when doing sRGB operations.251-#define STBIR_FLAG_ALPHA_USES_COLORSPACE (1 << 1)252-253-STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,254- unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,255- int num_channels, int alpha_channel, int flags);256-257-258-typedef enum259-{260- STBIR_EDGE_CLAMP = 1,261- STBIR_EDGE_REFLECT = 2,262- STBIR_EDGE_WRAP = 3,263- STBIR_EDGE_ZERO = 4,264-} stbir_edge;265-266-// This function adds the ability to specify how requests to sample off the edge of the image are handled.267-STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,268- unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,269- int num_channels, int alpha_channel, int flags,270- stbir_edge edge_wrap_mode);271-272-//////////////////////////////////////////////////////////////////////////////273-//274-// Medium-complexity API275-//276-// This extends the easy-to-use API as follows:277-//278-// * Alpha-channel can be processed separately279-// * If alpha_channel is not STBIR_ALPHA_CHANNEL_NONE280-// * Alpha channel will not be gamma corrected (unless flags&STBIR_FLAG_GAMMA_CORRECT)281-// * Filters will be weighted by alpha channel (unless flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)282-// * Filter can be selected explicitly283-// * uint16 image type284-// * sRGB colorspace available for all types285-// * context parameter for passing to STBIR_MALLOC286-287-typedef enum288-{289- STBIR_FILTER_DEFAULT = 0, // use same filter type that easy-to-use API chooses290- STBIR_FILTER_BOX = 1, // A trapezoid w/1-pixel wide ramps, same result as box for integer scale ratios291- STBIR_FILTER_TRIANGLE = 2, // On upsampling, produces same results as bilinear texture filtering292- STBIR_FILTER_CUBICBSPLINE = 3, // The cubic b-spline (aka Mitchell-Netrevalli with B=1,C=0), gaussian-esque293- STBIR_FILTER_CATMULLROM = 4, // An interpolating cubic spline294- STBIR_FILTER_MITCHELL = 5, // Mitchell-Netrevalli filter with B=1/3, C=1/3295-} stbir_filter;296-297-typedef enum298-{299- STBIR_COLORSPACE_LINEAR,300- STBIR_COLORSPACE_SRGB,301-302- STBIR_MAX_COLORSPACES,303-} stbir_colorspace;304-305-// The following functions are all identical except for the type of the image data306-307-STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,308- unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,309- int num_channels, int alpha_channel, int flags,310- stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,311- void *alloc_context);312-313-STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes,314- stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes,315- int num_channels, int alpha_channel, int flags,316- stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,317- void *alloc_context);318-319-STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,320- float *output_pixels , int output_w, int output_h, int output_stride_in_bytes,321- int num_channels, int alpha_channel, int flags,322- stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,323- void *alloc_context);324-325-326-327-//////////////////////////////////////////////////////////////////////////////328-//329-// Full-complexity API330-//331-// This extends the medium API as follows:332-//333-// * uint32 image type334-// * not typesafe335-// * separate filter types for each axis336-// * separate edge modes for each axis337-// * can specify scale explicitly for subpixel correctness338-// * can specify image source tile using texture coordinates339-340-typedef enum341-{342- STBIR_TYPE_UINT8 ,343- STBIR_TYPE_UINT16,344- STBIR_TYPE_UINT32,345- STBIR_TYPE_FLOAT ,346-347- STBIR_MAX_TYPES348-} stbir_datatype;349-350-STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,351- void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,352- stbir_datatype datatype,353- int num_channels, int alpha_channel, int flags,354- stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,355- stbir_filter filter_horizontal, stbir_filter filter_vertical,356- stbir_colorspace space, void *alloc_context);357-358-STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,359- void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,360- stbir_datatype datatype,361- int num_channels, int alpha_channel, int flags,362- stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,363- stbir_filter filter_horizontal, stbir_filter filter_vertical,364- stbir_colorspace space, void *alloc_context,365- float x_scale, float y_scale,366- float x_offset, float y_offset);367-368-STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,369- void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,370- stbir_datatype datatype,371- int num_channels, int alpha_channel, int flags,372- stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,373- stbir_filter filter_horizontal, stbir_filter filter_vertical,374- stbir_colorspace space, void *alloc_context,375- float s0, float t0, float s1, float t1);376-// (s0, t0) & (s1, t1) are the top-left and bottom right corner (uv addressing style: [0, 1]x[0, 1]) of a region of the input image to use.377-378-//379-//380-//// end header file /////////////////////////////////////////////////////381-#endif // STBIR_INCLUDE_STB_IMAGE_RESIZE_H382-383-384-385-386-387-#ifdef STB_IMAGE_RESIZE_IMPLEMENTATION388-389-#ifndef STBIR_ASSERT390-#include <assert.h>391-#define STBIR_ASSERT(x) assert(x)392-#endif393-394-// For memset395-#include <string.h>396-397-#include <math.h>398-399-#ifndef STBIR_MALLOC400-#include <stdlib.h>401-// use comma operator to evaluate c, to avoid "unused parameter" warnings402-#define STBIR_MALLOC(size,c) ((void)(c), malloc(size))403-#define STBIR_FREE(ptr,c) ((void)(c), free(ptr))404-#endif405-406-#ifndef _MSC_VER407-#ifdef __cplusplus408-#define stbir__inline inline409-#else410-#define stbir__inline411-#endif412-#else413-#define stbir__inline __forceinline414-#endif415-416-417-// should produce compiler error if size is wrong418-typedef unsigned char stbir__validate_uint32[sizeof(stbir_uint32) == 4 ? 1 : -1];419-420-#ifdef _MSC_VER421-#define STBIR__NOTUSED(v) (void)(v)422-#else423-#define STBIR__NOTUSED(v) (void)sizeof(v)424-#endif425-426-#define STBIR__ARRAY_SIZE(a) (sizeof((a))/sizeof((a)[0]))427-428-#ifndef STBIR_DEFAULT_FILTER_UPSAMPLE429-#define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_CATMULLROM430-#endif431-432-#ifndef STBIR_DEFAULT_FILTER_DOWNSAMPLE433-#define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_MITCHELL434-#endif435-436-#ifndef STBIR_PROGRESS_REPORT437-#define STBIR_PROGRESS_REPORT(float_0_to_1)438-#endif439-440-#ifndef STBIR_MAX_CHANNELS441-#define STBIR_MAX_CHANNELS 64442-#endif443-444-#if STBIR_MAX_CHANNELS > 65536445-#error "Too many channels; STBIR_MAX_CHANNELS must be no more than 65536."446-// because we store the indices in 16-bit variables447-#endif448-449-// This value is added to alpha just before premultiplication to avoid450-// zeroing out color values. It is equivalent to 2^-80. If you don't want451-// that behavior (it may interfere if you have floating point images with452-// very small alpha values) then you can define STBIR_NO_ALPHA_EPSILON to453-// disable it.454-#ifndef STBIR_ALPHA_EPSILON455-#define STBIR_ALPHA_EPSILON ((float)1 / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20))456-#endif457-458-459-460-#ifdef _MSC_VER461-#define STBIR__UNUSED_PARAM(v) (void)(v)462-#else463-#define STBIR__UNUSED_PARAM(v) (void)sizeof(v)464-#endif465-466-// must match stbir_datatype467-static unsigned char stbir__type_size[] = {468- 1, // STBIR_TYPE_UINT8469- 2, // STBIR_TYPE_UINT16470- 4, // STBIR_TYPE_UINT32471- 4, // STBIR_TYPE_FLOAT472-};473-474-// Kernel function centered at 0475-typedef float (stbir__kernel_fn)(float x, float scale);476-typedef float (stbir__support_fn)(float scale);477-478-typedef struct479-{480- stbir__kernel_fn* kernel;481- stbir__support_fn* support;482-} stbir__filter_info;483-484-// When upsampling, the contributors are which source pixels contribute.485-// When downsampling, the contributors are which destination pixels are contributed to.486-typedef struct487-{488- int n0; // First contributing pixel489- int n1; // Last contributing pixel490-} stbir__contributors;491-492-typedef struct493-{494- const void* input_data;495- int input_w;496- int input_h;497- int input_stride_bytes;498-499- void* output_data;500- int output_w;501- int output_h;502- int output_stride_bytes;503-504- float s0, t0, s1, t1;505-506- float horizontal_shift; // Units: output pixels507- float vertical_shift; // Units: output pixels508- float horizontal_scale;509- float vertical_scale;510-511- int channels;512- int alpha_channel;513- stbir_uint32 flags;514- stbir_datatype type;515- stbir_filter horizontal_filter;516- stbir_filter vertical_filter;517- stbir_edge edge_horizontal;518- stbir_edge edge_vertical;519- stbir_colorspace colorspace;520-521- stbir__contributors* horizontal_contributors;522- float* horizontal_coefficients;523-524- stbir__contributors* vertical_contributors;525- float* vertical_coefficients;526-527- int decode_buffer_pixels;528- float* decode_buffer;529-530- float* horizontal_buffer;531-532- // cache these because ceil/floor are inexplicably showing up in profile533- int horizontal_coefficient_width;534- int vertical_coefficient_width;535- int horizontal_filter_pixel_width;536- int vertical_filter_pixel_width;537- int horizontal_filter_pixel_margin;538- int vertical_filter_pixel_margin;539- int horizontal_num_contributors;540- int vertical_num_contributors;541-542- int ring_buffer_length_bytes; // The length of an individual entry in the ring buffer. The total number of ring buffers is stbir__get_filter_pixel_width(filter)543- int ring_buffer_num_entries; // Total number of entries in the ring buffer.544- int ring_buffer_first_scanline;545- int ring_buffer_last_scanline;546- int ring_buffer_begin_index; // first_scanline is at this index in the ring buffer547- float* ring_buffer;548-549- float* encode_buffer; // A temporary buffer to store floats so we don't lose precision while we do multiply-adds.550-551- int horizontal_contributors_size;552- int horizontal_coefficients_size;553- int vertical_contributors_size;554- int vertical_coefficients_size;555- int decode_buffer_size;556- int horizontal_buffer_size;557- int ring_buffer_size;558- int encode_buffer_size;559-} stbir__info;560-561-562-static const float stbir__max_uint8_as_float = 255.0f;563-static const float stbir__max_uint16_as_float = 65535.0f;564-static const double stbir__max_uint32_as_float = 4294967295.0;565-566-567-static stbir__inline int stbir__min(int a, int b)568-{569- return a < b ? a : b;570-}571-572-static stbir__inline float stbir__saturate(float x)573-{574- if (x < 0)575- return 0;576-577- if (x > 1)578- return 1;579-580- return x;581-}582-583-#ifdef STBIR_SATURATE_INT584-static stbir__inline stbir_uint8 stbir__saturate8(int x)585-{586- if ((unsigned int) x <= 255)587- return x;588-589- if (x < 0)590- return 0;591-592- return 255;593-}594-595-static stbir__inline stbir_uint16 stbir__saturate16(int x)596-{597- if ((unsigned int) x <= 65535)598- return x;599-600- if (x < 0)601- return 0;602-603- return 65535;604-}605-#endif606-607-static float stbir__srgb_uchar_to_linear_float[256] = {608- 0.000000f, 0.000304f, 0.000607f, 0.000911f, 0.001214f, 0.001518f, 0.001821f, 0.002125f, 0.002428f, 0.002732f, 0.003035f,609- 0.003347f, 0.003677f, 0.004025f, 0.004391f, 0.004777f, 0.005182f, 0.005605f, 0.006049f, 0.006512f, 0.006995f, 0.007499f,610- 0.008023f, 0.008568f, 0.009134f, 0.009721f, 0.010330f, 0.010960f, 0.011612f, 0.012286f, 0.012983f, 0.013702f, 0.014444f,611- 0.015209f, 0.015996f, 0.016807f, 0.017642f, 0.018500f, 0.019382f, 0.020289f, 0.021219f, 0.022174f, 0.023153f, 0.024158f,612- 0.025187f, 0.026241f, 0.027321f, 0.028426f, 0.029557f, 0.030713f, 0.031896f, 0.033105f, 0.034340f, 0.035601f, 0.036889f,613- 0.038204f, 0.039546f, 0.040915f, 0.042311f, 0.043735f, 0.045186f, 0.046665f, 0.048172f, 0.049707f, 0.051269f, 0.052861f,614- 0.054480f, 0.056128f, 0.057805f, 0.059511f, 0.061246f, 0.063010f, 0.064803f, 0.066626f, 0.068478f, 0.070360f, 0.072272f,615- 0.074214f, 0.076185f, 0.078187f, 0.080220f, 0.082283f, 0.084376f, 0.086500f, 0.088656f, 0.090842f, 0.093059f, 0.095307f,616- 0.097587f, 0.099899f, 0.102242f, 0.104616f, 0.107023f, 0.109462f, 0.111932f, 0.114435f, 0.116971f, 0.119538f, 0.122139f,617- 0.124772f, 0.127438f, 0.130136f, 0.132868f, 0.135633f, 0.138432f, 0.141263f, 0.144128f, 0.147027f, 0.149960f, 0.152926f,618- 0.155926f, 0.158961f, 0.162029f, 0.165132f, 0.168269f, 0.171441f, 0.174647f, 0.177888f, 0.181164f, 0.184475f, 0.187821f,619- 0.191202f, 0.194618f, 0.198069f, 0.201556f, 0.205079f, 0.208637f, 0.212231f, 0.215861f, 0.219526f, 0.223228f, 0.226966f,620- 0.230740f, 0.234551f, 0.238398f, 0.242281f, 0.246201f, 0.250158f, 0.254152f, 0.258183f, 0.262251f, 0.266356f, 0.270498f,621- 0.274677f, 0.278894f, 0.283149f, 0.287441f, 0.291771f, 0.296138f, 0.300544f, 0.304987f, 0.309469f, 0.313989f, 0.318547f,622- 0.323143f, 0.327778f, 0.332452f, 0.337164f, 0.341914f, 0.346704f, 0.351533f, 0.356400f, 0.361307f, 0.366253f, 0.371238f,623- 0.376262f, 0.381326f, 0.386430f, 0.391573f, 0.396755f, 0.401978f, 0.407240f, 0.412543f, 0.417885f, 0.423268f, 0.428691f,624- 0.434154f, 0.439657f, 0.445201f, 0.450786f, 0.456411f, 0.462077f, 0.467784f, 0.473532f, 0.479320f, 0.485150f, 0.491021f,625- 0.496933f, 0.502887f, 0.508881f, 0.514918f, 0.520996f, 0.527115f, 0.533276f, 0.539480f, 0.545725f, 0.552011f, 0.558340f,626- 0.564712f, 0.571125f, 0.577581f, 0.584078f, 0.590619f, 0.597202f, 0.603827f, 0.610496f, 0.617207f, 0.623960f, 0.630757f,627- 0.637597f, 0.644480f, 0.651406f, 0.658375f, 0.665387f, 0.672443f, 0.679543f, 0.686685f, 0.693872f, 0.701102f, 0.708376f,628- 0.715694f, 0.723055f, 0.730461f, 0.737911f, 0.745404f, 0.752942f, 0.760525f, 0.768151f, 0.775822f, 0.783538f, 0.791298f,629- 0.799103f, 0.806952f, 0.814847f, 0.822786f, 0.830770f, 0.838799f, 0.846873f, 0.854993f, 0.863157f, 0.871367f, 0.879622f,630- 0.887923f, 0.896269f, 0.904661f, 0.913099f, 0.921582f, 0.930111f, 0.938686f, 0.947307f, 0.955974f, 0.964686f, 0.973445f,631- 0.982251f, 0.991102f, 1.0f632-};633-634-static float stbir__srgb_to_linear(float f)635-{636- if (f <= 0.04045f)637- return f / 12.92f;638- else639- return (float)pow((f + 0.055f) / 1.055f, 2.4f);640-}641-642-static float stbir__linear_to_srgb(float f)643-{644- if (f <= 0.0031308f)645- return f * 12.92f;646- else647- return 1.055f * (float)pow(f, 1 / 2.4f) - 0.055f;648-}649-650-#ifndef STBIR_NON_IEEE_FLOAT651-// From https://gist.github.com/rygorous/2203834652-653-typedef union654-{655- stbir_uint32 u;656- float f;657-} stbir__FP32;658-659-static const stbir_uint32 fp32_to_srgb8_tab4[104] = {660- 0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d,661- 0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a,662- 0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033,663- 0x01dc0067, 0x020f0067, 0x02430067, 0x02760067, 0x02aa0067, 0x02dd0067, 0x03110067, 0x03440067,664- 0x037800ce, 0x03df00ce, 0x044600ce, 0x04ad00ce, 0x051400ce, 0x057b00c5, 0x05dd00bc, 0x063b00b5,665- 0x06970158, 0x07420142, 0x07e30130, 0x087b0120, 0x090b0112, 0x09940106, 0x0a1700fc, 0x0a9500f2,666- 0x0b0f01cb, 0x0bf401ae, 0x0ccb0195, 0x0d950180, 0x0e56016e, 0x0f0d015e, 0x0fbc0150, 0x10630143,667- 0x11070264, 0x1238023e, 0x1357021d, 0x14660201, 0x156601e9, 0x165a01d3, 0x174401c0, 0x182401af,668- 0x18fe0331, 0x1a9602fe, 0x1c1502d2, 0x1d7e02ad, 0x1ed4028d, 0x201a0270, 0x21520256, 0x227d0240,669- 0x239f0443, 0x25c003fe, 0x27bf03c4, 0x29a10392, 0x2b6a0367, 0x2d1d0341, 0x2ebe031f, 0x304d0300,670- 0x31d105b0, 0x34a80555, 0x37520507, 0x39d504c5, 0x3c37048b, 0x3e7c0458, 0x40a8042a, 0x42bd0401,671- 0x44c20798, 0x488e071e, 0x4c1c06b6, 0x4f76065d, 0x52a50610, 0x55ac05cc, 0x5892058f, 0x5b590559,672- 0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723,673-};674-675-static stbir_uint8 stbir__linear_to_srgb_uchar(float in)676-{677- static const stbir__FP32 almostone = { 0x3f7fffff }; // 1-eps678- static const stbir__FP32 minval = { (127-13) << 23 };679- stbir_uint32 tab,bias,scale,t;680- stbir__FP32 f;681-682- // Clamp to [2^(-13), 1-eps]; these two values map to 0 and 1, respectively.683- // The tests are carefully written so that NaNs map to 0, same as in the reference684- // implementation.685- if (!(in > minval.f)) // written this way to catch NaNs686- in = minval.f;687- if (in > almostone.f)688- in = almostone.f;689-690- // Do the table lookup and unpack bias, scale691- f.f = in;692- tab = fp32_to_srgb8_tab4[(f.u - minval.u) >> 20];693- bias = (tab >> 16) << 9;694- scale = tab & 0xffff;695-696- // Grab next-highest mantissa bits and perform linear interpolation697- t = (f.u >> 12) & 0xff;698- return (unsigned char) ((bias + scale*t) >> 16);699-}700-701-#else702-// sRGB transition values, scaled by 1<<28703-static int stbir__srgb_offset_to_linear_scaled[256] =704-{705- 0, 40738, 122216, 203693, 285170, 366648, 448125, 529603,706- 611080, 692557, 774035, 855852, 942009, 1033024, 1128971, 1229926,707- 1335959, 1447142, 1563542, 1685229, 1812268, 1944725, 2082664, 2226148,708- 2375238, 2529996, 2690481, 2856753, 3028870, 3206888, 3390865, 3580856,709- 3776916, 3979100, 4187460, 4402049, 4622919, 4850123, 5083710, 5323731,710- 5570236, 5823273, 6082892, 6349140, 6622065, 6901714, 7188133, 7481369,711- 7781466, 8088471, 8402427, 8723380, 9051372, 9386448, 9728650, 10078021,712- 10434603, 10798439, 11169569, 11548036, 11933879, 12327139, 12727857, 13136073,713- 13551826, 13975156, 14406100, 14844697, 15290987, 15745007, 16206795, 16676389,714- 17153826, 17639142, 18132374, 18633560, 19142734, 19659934, 20185196, 20718552,715- 21260042, 21809696, 22367554, 22933648, 23508010, 24090680, 24681686, 25281066,716- 25888850, 26505076, 27129772, 27762974, 28404716, 29055026, 29713942, 30381490,717- 31057708, 31742624, 32436272, 33138682, 33849884, 34569912, 35298800, 36036568,718- 36783260, 37538896, 38303512, 39077136, 39859796, 40651528, 41452360, 42262316,719- 43081432, 43909732, 44747252, 45594016, 46450052, 47315392, 48190064, 49074096,720- 49967516, 50870356, 51782636, 52704392, 53635648, 54576432, 55526772, 56486700,721- 57456236, 58435408, 59424248, 60422780, 61431036, 62449032, 63476804, 64514376,722- 65561776, 66619028, 67686160, 68763192, 69850160, 70947088, 72053992, 73170912,723- 74297864, 75434880, 76581976, 77739184, 78906536, 80084040, 81271736, 82469648,724- 83677792, 84896192, 86124888, 87363888, 88613232, 89872928, 91143016, 92423512,725- 93714432, 95015816, 96327688, 97650056, 98982952, 100326408, 101680440, 103045072,726- 104420320, 105806224, 107202800, 108610064, 110028048, 111456776, 112896264, 114346544,727- 115807632, 117279552, 118762328, 120255976, 121760536, 123276016, 124802440, 126339832,728- 127888216, 129447616, 131018048, 132599544, 134192112, 135795792, 137410592, 139036528,729- 140673648, 142321952, 143981456, 145652208, 147334208, 149027488, 150732064, 152447968,730- 154175200, 155913792, 157663776, 159425168, 161197984, 162982240, 164777968, 166585184,731- 168403904, 170234160, 172075968, 173929344, 175794320, 177670896, 179559120, 181458992,732- 183370528, 185293776, 187228736, 189175424, 191133888, 193104112, 195086128, 197079968,733- 199085648, 201103184, 203132592, 205173888, 207227120, 209292272, 211369392, 213458480,734- 215559568, 217672656, 219797792, 221934976, 224084240, 226245600, 228419056, 230604656,735- 232802400, 235012320, 237234432, 239468736, 241715280, 243974080, 246245120, 248528464,736- 250824112, 253132064, 255452368, 257785040, 260130080, 262487520, 264857376, 267239664,737-};738-739-static stbir_uint8 stbir__linear_to_srgb_uchar(float f)740-{741- int x = (int) (f * (1 << 28)); // has headroom so you don't need to clamp742- int v = 0;743- int i;744-745- // Refine the guess with a short binary search.746- i = v + 128; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;747- i = v + 64; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;748- i = v + 32; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;749- i = v + 16; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;750- i = v + 8; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;751- i = v + 4; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;752- i = v + 2; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;753- i = v + 1; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i;754-755- return (stbir_uint8) v;756-}757-#endif758-759-static float stbir__filter_trapezoid(float x, float scale)760-{761- float halfscale = scale / 2;762- float t = 0.5f + halfscale;763- STBIR_ASSERT(scale <= 1);764-765- x = (float)fabs(x);766-767- if (x >= t)768- return 0;769- else770- {771- float r = 0.5f - halfscale;772- if (x <= r)773- return 1;774- else775- return (t - x) / scale;776- }777-}778-779-static float stbir__support_trapezoid(float scale)780-{781- STBIR_ASSERT(scale <= 1);782- return 0.5f + scale / 2;783-}784-785-static float stbir__filter_triangle(float x, float s)786-{787- STBIR__UNUSED_PARAM(s);788-789- x = (float)fabs(x);790-791- if (x <= 1.0f)792- return 1 - x;793- else794- return 0;795-}796-797-static float stbir__filter_cubic(float x, float s)798-{799- STBIR__UNUSED_PARAM(s);800-801- x = (float)fabs(x);802-803- if (x < 1.0f)804- return (4 + x*x*(3*x - 6))/6;805- else if (x < 2.0f)806- return (8 + x*(-12 + x*(6 - x)))/6;807-808- return (0.0f);809-}810-811-static float stbir__filter_catmullrom(float x, float s)812-{813- STBIR__UNUSED_PARAM(s);814-815- x = (float)fabs(x);816-817- if (x < 1.0f)818- return 1 - x*x*(2.5f - 1.5f*x);819- else if (x < 2.0f)820- return 2 - x*(4 + x*(0.5f*x - 2.5f));821-822- return (0.0f);823-}824-825-static float stbir__filter_mitchell(float x, float s)826-{827- STBIR__UNUSED_PARAM(s);828-829- x = (float)fabs(x);830-831- if (x < 1.0f)832- return (16 + x*x*(21 * x - 36))/18;833- else if (x < 2.0f)834- return (32 + x*(-60 + x*(36 - 7*x)))/18;835-836- return (0.0f);837-}838-839-static float stbir__support_zero(float s)840-{841- STBIR__UNUSED_PARAM(s);842- return 0;843-}844-845-static float stbir__support_one(float s)846-{847- STBIR__UNUSED_PARAM(s);848- return 1;849-}850-851-static float stbir__support_two(float s)852-{853- STBIR__UNUSED_PARAM(s);854- return 2;855-}856-857-static stbir__filter_info stbir__filter_info_table[] = {858- { NULL, stbir__support_zero },859- { stbir__filter_trapezoid, stbir__support_trapezoid },860- { stbir__filter_triangle, stbir__support_one },861- { stbir__filter_cubic, stbir__support_two },862- { stbir__filter_catmullrom, stbir__support_two },863- { stbir__filter_mitchell, stbir__support_two },864-};865-866-stbir__inline static int stbir__use_upsampling(float ratio)867-{868- return ratio > 1;869-}870-871-stbir__inline static int stbir__use_width_upsampling(stbir__info* stbir_info)872-{873- return stbir__use_upsampling(stbir_info->horizontal_scale);874-}875-876-stbir__inline static int stbir__use_height_upsampling(stbir__info* stbir_info)877-{878- return stbir__use_upsampling(stbir_info->vertical_scale);879-}880-881-// This is the maximum number of input samples that can affect an output sample882-// with the given filter883-static int stbir__get_filter_pixel_width(stbir_filter filter, float scale)884-{885- STBIR_ASSERT(filter != 0);886- STBIR_ASSERT(filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));887-888- if (stbir__use_upsampling(scale))889- return (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2);890- else891- return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2 / scale);892-}893-894-// This is how much to expand buffers to account for filters seeking outside895-// the image boundaries.896-static int stbir__get_filter_pixel_margin(stbir_filter filter, float scale)897-{898- return stbir__get_filter_pixel_width(filter, scale) / 2;899-}900-901-static int stbir__get_coefficient_width(stbir_filter filter, float scale)902-{903- if (stbir__use_upsampling(scale))904- return (int)ceil(stbir__filter_info_table[filter].support(1 / scale) * 2);905- else906- return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2);907-}908-909-static int stbir__get_contributors(float scale, stbir_filter filter, int input_size, int output_size)910-{911- if (stbir__use_upsampling(scale))912- return output_size;913- else914- return (input_size + stbir__get_filter_pixel_margin(filter, scale) * 2);915-}916-917-static int stbir__get_total_horizontal_coefficients(stbir__info* info)918-{919- return info->horizontal_num_contributors920- * stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale);921-}922-923-static int stbir__get_total_vertical_coefficients(stbir__info* info)924-{925- return info->vertical_num_contributors926- * stbir__get_coefficient_width (info->vertical_filter, info->vertical_scale);927-}928-929-static stbir__contributors* stbir__get_contributor(stbir__contributors* contributors, int n)930-{931- return &contributors[n];932-}933-934-// For perf reasons this code is duplicated in stbir__resample_horizontal_upsample/downsample,935-// if you change it here change it there too.936-static float* stbir__get_coefficient(float* coefficients, stbir_filter filter, float scale, int n, int c)937-{938- int width = stbir__get_coefficient_width(filter, scale);939- return &coefficients[width*n + c];940-}941-942-static int stbir__edge_wrap_slow(stbir_edge edge, int n, int max)943-{944- switch (edge)945- {946- case STBIR_EDGE_ZERO:947- return 0; // we'll decode the wrong pixel here, and then overwrite with 0s later948-949- case STBIR_EDGE_CLAMP:950- if (n < 0)951- return 0;952-953- if (n >= max)954- return max - 1;955-956- return n; // NOTREACHED957-958- case STBIR_EDGE_REFLECT:959- {960- if (n < 0)961- {962- if (n < max)963- return -n;964- else965- return max - 1;966- }967-968- if (n >= max)969- {970- int max2 = max * 2;971- if (n >= max2)972- return 0;973- else974- return max2 - n - 1;975- }976-977- return n; // NOTREACHED978- }979-980- case STBIR_EDGE_WRAP:981- if (n >= 0)982- return (n % max);983- else984- {985- int m = (-n) % max;986-987- if (m != 0)988- m = max - m;989-990- return (m);991- }992- // NOTREACHED993-994- default:995- STBIR_ASSERT(!"Unimplemented edge type");996- return 0;997- }998-}999-1000-stbir__inline static int stbir__edge_wrap(stbir_edge edge, int n, int max)1001-{1002- // avoid per-pixel switch1003- if (n >= 0 && n < max)1004- return n;1005- return stbir__edge_wrap_slow(edge, n, max);1006-}1007-1008-// What input pixels contribute to this output pixel?1009-static void stbir__calculate_sample_range_upsample(int n, float out_filter_radius, float scale_ratio, float out_shift, int* in_first_pixel, int* in_last_pixel, float* in_center_of_out)1010-{1011- float out_pixel_center = (float)n + 0.5f;1012- float out_pixel_influence_lowerbound = out_pixel_center - out_filter_radius;1013- float out_pixel_influence_upperbound = out_pixel_center + out_filter_radius;1014-1015- float in_pixel_influence_lowerbound = (out_pixel_influence_lowerbound + out_shift) / scale_ratio;1016- float in_pixel_influence_upperbound = (out_pixel_influence_upperbound + out_shift) / scale_ratio;1017-1018- *in_center_of_out = (out_pixel_center + out_shift) / scale_ratio;1019- *in_first_pixel = (int)(floor(in_pixel_influence_lowerbound + 0.5));1020- *in_last_pixel = (int)(floor(in_pixel_influence_upperbound - 0.5));1021-}1022-1023-// What output pixels does this input pixel contribute to?1024-static void stbir__calculate_sample_range_downsample(int n, float in_pixels_radius, float scale_ratio, float out_shift, int* out_first_pixel, int* out_last_pixel, float* out_center_of_in)1025-{1026- float in_pixel_center = (float)n + 0.5f;1027- float in_pixel_influence_lowerbound = in_pixel_center - in_pixels_radius;1028- float in_pixel_influence_upperbound = in_pixel_center + in_pixels_radius;1029-1030- float out_pixel_influence_lowerbound = in_pixel_influence_lowerbound * scale_ratio - out_shift;1031- float out_pixel_influence_upperbound = in_pixel_influence_upperbound * scale_ratio - out_shift;1032-1033- *out_center_of_in = in_pixel_center * scale_ratio - out_shift;1034- *out_first_pixel = (int)(floor(out_pixel_influence_lowerbound + 0.5));1035- *out_last_pixel = (int)(floor(out_pixel_influence_upperbound - 0.5));1036-}1037-1038-static void stbir__calculate_coefficients_upsample(stbir_filter filter, float scale, int in_first_pixel, int in_last_pixel, float in_center_of_out, stbir__contributors* contributor, float* coefficient_group)1039-{1040- int i;1041- float total_filter = 0;1042- float filter_scale;1043-1044- STBIR_ASSERT(in_last_pixel - in_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical.1045-1046- contributor->n0 = in_first_pixel;1047- contributor->n1 = in_last_pixel;1048-1049- STBIR_ASSERT(contributor->n1 >= contributor->n0);1050-1051- for (i = 0; i <= in_last_pixel - in_first_pixel; i++)1052- {1053- float in_pixel_center = (float)(i + in_first_pixel) + 0.5f;1054- coefficient_group[i] = stbir__filter_info_table[filter].kernel(in_center_of_out - in_pixel_center, 1 / scale);1055-1056- // If the coefficient is zero, skip it. (Don't do the <0 check here, we want the influence of those outside pixels.)1057- if (i == 0 && !coefficient_group[i])1058- {1059- contributor->n0 = ++in_first_pixel;1060- i--;1061- continue;1062- }1063-1064- total_filter += coefficient_group[i];1065- }1066-1067- STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(in_last_pixel + 1) + 0.5f - in_center_of_out, 1/scale) == 0);1068-1069- STBIR_ASSERT(total_filter > 0.9);1070- STBIR_ASSERT(total_filter < 1.1f); // Make sure it's not way off.1071-1072- // Make sure the sum of all coefficients is 1.1073- filter_scale = 1 / total_filter;1074-1075- for (i = 0; i <= in_last_pixel - in_first_pixel; i++)1076- coefficient_group[i] *= filter_scale;1077-1078- for (i = in_last_pixel - in_first_pixel; i >= 0; i--)1079- {1080- if (coefficient_group[i])1081- break;1082-1083- // This line has no weight. We can skip it.1084- contributor->n1 = contributor->n0 + i - 1;1085- }1086-}1087-1088-static void stbir__calculate_coefficients_downsample(stbir_filter filter, float scale_ratio, int out_first_pixel, int out_last_pixel, float out_center_of_in, stbir__contributors* contributor, float* coefficient_group)1089-{1090- int i;1091-1092- STBIR_ASSERT(out_last_pixel - out_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(scale_ratio) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical.1093-1094- contributor->n0 = out_first_pixel;1095- contributor->n1 = out_last_pixel;1096-1097- STBIR_ASSERT(contributor->n1 >= contributor->n0);1098-1099- for (i = 0; i <= out_last_pixel - out_first_pixel; i++)1100- {1101- float out_pixel_center = (float)(i + out_first_pixel) + 0.5f;1102- float x = out_pixel_center - out_center_of_in;1103- coefficient_group[i] = stbir__filter_info_table[filter].kernel(x, scale_ratio) * scale_ratio;1104- }1105-1106- STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(out_last_pixel + 1) + 0.5f - out_center_of_in, scale_ratio) == 0);1107-1108- for (i = out_last_pixel - out_first_pixel; i >= 0; i--)1109- {1110- if (coefficient_group[i])1111- break;1112-1113- // This line has no weight. We can skip it.1114- contributor->n1 = contributor->n0 + i - 1;1115- }1116-}1117-1118-static void stbir__normalize_downsample_coefficients(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, int input_size, int output_size)1119-{1120- int num_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size);1121- int num_coefficients = stbir__get_coefficient_width(filter, scale_ratio);1122- int i, j;1123- int skip;1124-1125- for (i = 0; i < output_size; i++)1126- {1127- float scale;1128- float total = 0;1129-1130- for (j = 0; j < num_contributors; j++)1131- {1132- if (i >= contributors[j].n0 && i <= contributors[j].n1)1133- {1134- float coefficient = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0);1135- total += coefficient;1136- }1137- else if (i < contributors[j].n0)1138- break;1139- }1140-1141- STBIR_ASSERT(total > 0.9f);1142- STBIR_ASSERT(total < 1.1f);1143-1144- scale = 1 / total;1145-1146- for (j = 0; j < num_contributors; j++)1147- {1148- if (i >= contributors[j].n0 && i <= contributors[j].n1)1149- *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0) *= scale;1150- else if (i < contributors[j].n0)1151- break;1152- }1153- }1154-1155- // Optimize: Skip zero coefficients and contributions outside of image bounds.1156- // Do this after normalizing because normalization depends on the n0/n1 values.1157- for (j = 0; j < num_contributors; j++)1158- {1159- int range, max, width;1160-1161- skip = 0;1162- while (*stbir__get_coefficient(coefficients, filter, scale_ratio, j, skip) == 0)1163- skip++;1164-1165- contributors[j].n0 += skip;1166-1167- while (contributors[j].n0 < 0)1168- {1169- contributors[j].n0++;1170- skip++;1171- }1172-1173- range = contributors[j].n1 - contributors[j].n0 + 1;1174- max = stbir__min(num_coefficients, range);1175-1176- width = stbir__get_coefficient_width(filter, scale_ratio);1177- for (i = 0; i < max; i++)1178- {1179- if (i + skip >= width)1180- break;1181-1182- *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i) = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i + skip);1183- }1184-1185- continue;1186- }1187-1188- // Using min to avoid writing into invalid pixels.1189- for (i = 0; i < num_contributors; i++)1190- contributors[i].n1 = stbir__min(contributors[i].n1, output_size - 1);1191-}1192-1193-// Each scan line uses the same kernel values so we should calculate the kernel1194-// values once and then we can use them for every scan line.1195-static void stbir__calculate_filters(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, float shift, int input_size, int output_size)1196-{1197- int n;1198- int total_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size);1199-1200- if (stbir__use_upsampling(scale_ratio))1201- {1202- float out_pixels_radius = stbir__filter_info_table[filter].support(1 / scale_ratio) * scale_ratio;1203-1204- // Looping through out pixels1205- for (n = 0; n < total_contributors; n++)1206- {1207- float in_center_of_out; // Center of the current out pixel in the in pixel space1208- int in_first_pixel, in_last_pixel;1209-1210- stbir__calculate_sample_range_upsample(n, out_pixels_radius, scale_ratio, shift, &in_first_pixel, &in_last_pixel, &in_center_of_out);1211-1212- stbir__calculate_coefficients_upsample(filter, scale_ratio, in_first_pixel, in_last_pixel, in_center_of_out, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0));1213- }1214- }1215- else1216- {1217- float in_pixels_radius = stbir__filter_info_table[filter].support(scale_ratio) / scale_ratio;1218-1219- // Looping through in pixels1220- for (n = 0; n < total_contributors; n++)1221- {1222- float out_center_of_in; // Center of the current out pixel in the in pixel space1223- int out_first_pixel, out_last_pixel;1224- int n_adjusted = n - stbir__get_filter_pixel_margin(filter, scale_ratio);1225-1226- stbir__calculate_sample_range_downsample(n_adjusted, in_pixels_radius, scale_ratio, shift, &out_first_pixel, &out_last_pixel, &out_center_of_in);1227-1228- stbir__calculate_coefficients_downsample(filter, scale_ratio, out_first_pixel, out_last_pixel, out_center_of_in, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0));1229- }1230-1231- stbir__normalize_downsample_coefficients(contributors, coefficients, filter, scale_ratio, input_size, output_size);1232- }1233-}1234-1235-static float* stbir__get_decode_buffer(stbir__info* stbir_info)1236-{1237- // The 0 index of the decode buffer starts after the margin. This makes1238- // it okay to use negative indexes on the decode buffer.1239- return &stbir_info->decode_buffer[stbir_info->horizontal_filter_pixel_margin * stbir_info->channels];1240-}1241-1242-#define STBIR__DECODE(type, colorspace) ((int)(type) * (STBIR_MAX_COLORSPACES) + (int)(colorspace))1243-1244-static void stbir__decode_scanline(stbir__info* stbir_info, int n)1245-{1246- int c;1247- int channels = stbir_info->channels;1248- int alpha_channel = stbir_info->alpha_channel;1249- int type = stbir_info->type;1250- int colorspace = stbir_info->colorspace;1251- int input_w = stbir_info->input_w;1252- size_t input_stride_bytes = stbir_info->input_stride_bytes;1253- float* decode_buffer = stbir__get_decode_buffer(stbir_info);1254- stbir_edge edge_horizontal = stbir_info->edge_horizontal;1255- stbir_edge edge_vertical = stbir_info->edge_vertical;1256- size_t in_buffer_row_offset = stbir__edge_wrap(edge_vertical, n, stbir_info->input_h) * input_stride_bytes;1257- const void* input_data = (char *) stbir_info->input_data + in_buffer_row_offset;1258- int max_x = input_w + stbir_info->horizontal_filter_pixel_margin;1259- int decode = STBIR__DECODE(type, colorspace);1260-1261- int x = -stbir_info->horizontal_filter_pixel_margin;1262-1263- // special handling for STBIR_EDGE_ZERO because it needs to return an item that doesn't appear in the input,1264- // and we want to avoid paying overhead on every pixel if not STBIR_EDGE_ZERO1265- if (edge_vertical == STBIR_EDGE_ZERO && (n < 0 || n >= stbir_info->input_h))1266- {1267- for (; x < max_x; x++)1268- for (c = 0; c < channels; c++)1269- decode_buffer[x*channels + c] = 0;1270- return;1271- }1272-1273- switch (decode)1274- {1275- case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR):1276- for (; x < max_x; x++)1277- {1278- int decode_pixel_index = x * channels;1279- int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1280- for (c = 0; c < channels; c++)1281- decode_buffer[decode_pixel_index + c] = ((float)((const unsigned char*)input_data)[input_pixel_index + c]) / stbir__max_uint8_as_float;1282- }1283- break;1284-1285- case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB):1286- for (; x < max_x; x++)1287- {1288- int decode_pixel_index = x * channels;1289- int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1290- for (c = 0; c < channels; c++)1291- decode_buffer[decode_pixel_index + c] = stbir__srgb_uchar_to_linear_float[((const unsigned char*)input_data)[input_pixel_index + c]];1292-1293- if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1294- decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned char*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint8_as_float;1295- }1296- break;1297-1298- case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR):1299- for (; x < max_x; x++)1300- {1301- int decode_pixel_index = x * channels;1302- int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1303- for (c = 0; c < channels; c++)1304- decode_buffer[decode_pixel_index + c] = ((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float;1305- }1306- break;1307-1308- case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB):1309- for (; x < max_x; x++)1310- {1311- int decode_pixel_index = x * channels;1312- int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1313- for (c = 0; c < channels; c++)1314- decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float);1315-1316- if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1317- decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned short*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint16_as_float;1318- }1319- break;1320-1321- case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR):1322- for (; x < max_x; x++)1323- {1324- int decode_pixel_index = x * channels;1325- int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1326- for (c = 0; c < channels; c++)1327- decode_buffer[decode_pixel_index + c] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float);1328- }1329- break;1330-1331- case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB):1332- for (; x < max_x; x++)1333- {1334- int decode_pixel_index = x * channels;1335- int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1336- for (c = 0; c < channels; c++)1337- decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear((float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float));1338-1339- if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1340- decode_buffer[decode_pixel_index + alpha_channel] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint32_as_float);1341- }1342- break;1343-1344- case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR):1345- for (; x < max_x; x++)1346- {1347- int decode_pixel_index = x * channels;1348- int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1349- for (c = 0; c < channels; c++)1350- decode_buffer[decode_pixel_index + c] = ((const float*)input_data)[input_pixel_index + c];1351- }1352- break;1353-1354- case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB):1355- for (; x < max_x; x++)1356- {1357- int decode_pixel_index = x * channels;1358- int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels;1359- for (c = 0; c < channels; c++)1360- decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((const float*)input_data)[input_pixel_index + c]);1361-1362- if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1363- decode_buffer[decode_pixel_index + alpha_channel] = ((const float*)input_data)[input_pixel_index + alpha_channel];1364- }1365-1366- break;1367-1368- default:1369- STBIR_ASSERT(!"Unknown type/colorspace/channels combination.");1370- break;1371- }1372-1373- if (!(stbir_info->flags & STBIR_FLAG_ALPHA_PREMULTIPLIED))1374- {1375- for (x = -stbir_info->horizontal_filter_pixel_margin; x < max_x; x++)1376- {1377- int decode_pixel_index = x * channels;1378-1379- // If the alpha value is 0 it will clobber the color values. Make sure it's not.1380- float alpha = decode_buffer[decode_pixel_index + alpha_channel];1381-#ifndef STBIR_NO_ALPHA_EPSILON1382- if (stbir_info->type != STBIR_TYPE_FLOAT) {1383- alpha += STBIR_ALPHA_EPSILON;1384- decode_buffer[decode_pixel_index + alpha_channel] = alpha;1385- }1386-#endif1387- for (c = 0; c < channels; c++)1388- {1389- if (c == alpha_channel)1390- continue;1391-1392- decode_buffer[decode_pixel_index + c] *= alpha;1393- }1394- }1395- }1396-1397- if (edge_horizontal == STBIR_EDGE_ZERO)1398- {1399- for (x = -stbir_info->horizontal_filter_pixel_margin; x < 0; x++)1400- {1401- for (c = 0; c < channels; c++)1402- decode_buffer[x*channels + c] = 0;1403- }1404- for (x = input_w; x < max_x; x++)1405- {1406- for (c = 0; c < channels; c++)1407- decode_buffer[x*channels + c] = 0;1408- }1409- }1410-}1411-1412-static float* stbir__get_ring_buffer_entry(float* ring_buffer, int index, int ring_buffer_length)1413-{1414- return &ring_buffer[index * ring_buffer_length];1415-}1416-1417-static float* stbir__add_empty_ring_buffer_entry(stbir__info* stbir_info, int n)1418-{1419- int ring_buffer_index;1420- float* ring_buffer;1421-1422- stbir_info->ring_buffer_last_scanline = n;1423-1424- if (stbir_info->ring_buffer_begin_index < 0)1425- {1426- ring_buffer_index = stbir_info->ring_buffer_begin_index = 0;1427- stbir_info->ring_buffer_first_scanline = n;1428- }1429- else1430- {1431- ring_buffer_index = (stbir_info->ring_buffer_begin_index + (stbir_info->ring_buffer_last_scanline - stbir_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries;1432- STBIR_ASSERT(ring_buffer_index != stbir_info->ring_buffer_begin_index);1433- }1434-1435- ring_buffer = stbir__get_ring_buffer_entry(stbir_info->ring_buffer, ring_buffer_index, stbir_info->ring_buffer_length_bytes / sizeof(float));1436- memset(ring_buffer, 0, stbir_info->ring_buffer_length_bytes);1437-1438- return ring_buffer;1439-}1440-1441-1442-static void stbir__resample_horizontal_upsample(stbir__info* stbir_info, float* output_buffer)1443-{1444- int x, k;1445- int output_w = stbir_info->output_w;1446- int channels = stbir_info->channels;1447- float* decode_buffer = stbir__get_decode_buffer(stbir_info);1448- stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors;1449- float* horizontal_coefficients = stbir_info->horizontal_coefficients;1450- int coefficient_width = stbir_info->horizontal_coefficient_width;1451-1452- for (x = 0; x < output_w; x++)1453- {1454- int n0 = horizontal_contributors[x].n0;1455- int n1 = horizontal_contributors[x].n1;1456-1457- int out_pixel_index = x * channels;1458- int coefficient_group = coefficient_width * x;1459- int coefficient_counter = 0;1460-1461- STBIR_ASSERT(n1 >= n0);1462- STBIR_ASSERT(n0 >= -stbir_info->horizontal_filter_pixel_margin);1463- STBIR_ASSERT(n1 >= -stbir_info->horizontal_filter_pixel_margin);1464- STBIR_ASSERT(n0 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin);1465- STBIR_ASSERT(n1 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin);1466-1467- switch (channels) {1468- case 1:1469- for (k = n0; k <= n1; k++)1470- {1471- int in_pixel_index = k * 1;1472- float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1473- STBIR_ASSERT(coefficient != 0);1474- output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1475- }1476- break;1477- case 2:1478- for (k = n0; k <= n1; k++)1479- {1480- int in_pixel_index = k * 2;1481- float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1482- STBIR_ASSERT(coefficient != 0);1483- output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1484- output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1485- }1486- break;1487- case 3:1488- for (k = n0; k <= n1; k++)1489- {1490- int in_pixel_index = k * 3;1491- float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1492- STBIR_ASSERT(coefficient != 0);1493- output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1494- output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1495- output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;1496- }1497- break;1498- case 4:1499- for (k = n0; k <= n1; k++)1500- {1501- int in_pixel_index = k * 4;1502- float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1503- STBIR_ASSERT(coefficient != 0);1504- output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1505- output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1506- output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;1507- output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient;1508- }1509- break;1510- default:1511- for (k = n0; k <= n1; k++)1512- {1513- int in_pixel_index = k * channels;1514- float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++];1515- int c;1516- STBIR_ASSERT(coefficient != 0);1517- for (c = 0; c < channels; c++)1518- output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient;1519- }1520- break;1521- }1522- }1523-}1524-1525-static void stbir__resample_horizontal_downsample(stbir__info* stbir_info, float* output_buffer)1526-{1527- int x, k;1528- int input_w = stbir_info->input_w;1529- int channels = stbir_info->channels;1530- float* decode_buffer = stbir__get_decode_buffer(stbir_info);1531- stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors;1532- float* horizontal_coefficients = stbir_info->horizontal_coefficients;1533- int coefficient_width = stbir_info->horizontal_coefficient_width;1534- int filter_pixel_margin = stbir_info->horizontal_filter_pixel_margin;1535- int max_x = input_w + filter_pixel_margin * 2;1536-1537- STBIR_ASSERT(!stbir__use_width_upsampling(stbir_info));1538-1539- switch (channels) {1540- case 1:1541- for (x = 0; x < max_x; x++)1542- {1543- int n0 = horizontal_contributors[x].n0;1544- int n1 = horizontal_contributors[x].n1;1545-1546- int in_x = x - filter_pixel_margin;1547- int in_pixel_index = in_x * 1;1548- int max_n = n1;1549- int coefficient_group = coefficient_width * x;1550-1551- for (k = n0; k <= max_n; k++)1552- {1553- int out_pixel_index = k * 1;1554- float coefficient = horizontal_coefficients[coefficient_group + k - n0];1555- STBIR_ASSERT(coefficient != 0);1556- output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1557- }1558- }1559- break;1560-1561- case 2:1562- for (x = 0; x < max_x; x++)1563- {1564- int n0 = horizontal_contributors[x].n0;1565- int n1 = horizontal_contributors[x].n1;1566-1567- int in_x = x - filter_pixel_margin;1568- int in_pixel_index = in_x * 2;1569- int max_n = n1;1570- int coefficient_group = coefficient_width * x;1571-1572- for (k = n0; k <= max_n; k++)1573- {1574- int out_pixel_index = k * 2;1575- float coefficient = horizontal_coefficients[coefficient_group + k - n0];1576- STBIR_ASSERT(coefficient != 0);1577- output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1578- output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1579- }1580- }1581- break;1582-1583- case 3:1584- for (x = 0; x < max_x; x++)1585- {1586- int n0 = horizontal_contributors[x].n0;1587- int n1 = horizontal_contributors[x].n1;1588-1589- int in_x = x - filter_pixel_margin;1590- int in_pixel_index = in_x * 3;1591- int max_n = n1;1592- int coefficient_group = coefficient_width * x;1593-1594- for (k = n0; k <= max_n; k++)1595- {1596- int out_pixel_index = k * 3;1597- float coefficient = horizontal_coefficients[coefficient_group + k - n0];1598- STBIR_ASSERT(coefficient != 0);1599- output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1600- output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1601- output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;1602- }1603- }1604- break;1605-1606- case 4:1607- for (x = 0; x < max_x; x++)1608- {1609- int n0 = horizontal_contributors[x].n0;1610- int n1 = horizontal_contributors[x].n1;1611-1612- int in_x = x - filter_pixel_margin;1613- int in_pixel_index = in_x * 4;1614- int max_n = n1;1615- int coefficient_group = coefficient_width * x;1616-1617- for (k = n0; k <= max_n; k++)1618- {1619- int out_pixel_index = k * 4;1620- float coefficient = horizontal_coefficients[coefficient_group + k - n0];1621- STBIR_ASSERT(coefficient != 0);1622- output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient;1623- output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient;1624- output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient;1625- output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient;1626- }1627- }1628- break;1629-1630- default:1631- for (x = 0; x < max_x; x++)1632- {1633- int n0 = horizontal_contributors[x].n0;1634- int n1 = horizontal_contributors[x].n1;1635-1636- int in_x = x - filter_pixel_margin;1637- int in_pixel_index = in_x * channels;1638- int max_n = n1;1639- int coefficient_group = coefficient_width * x;1640-1641- for (k = n0; k <= max_n; k++)1642- {1643- int c;1644- int out_pixel_index = k * channels;1645- float coefficient = horizontal_coefficients[coefficient_group + k - n0];1646- STBIR_ASSERT(coefficient != 0);1647- for (c = 0; c < channels; c++)1648- output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient;1649- }1650- }1651- break;1652- }1653-}1654-1655-static void stbir__decode_and_resample_upsample(stbir__info* stbir_info, int n)1656-{1657- // Decode the nth scanline from the source image into the decode buffer.1658- stbir__decode_scanline(stbir_info, n);1659-1660- // Now resample it into the ring buffer.1661- if (stbir__use_width_upsampling(stbir_info))1662- stbir__resample_horizontal_upsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n));1663- else1664- stbir__resample_horizontal_downsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n));1665-1666- // Now it's sitting in the ring buffer ready to be used as source for the vertical sampling.1667-}1668-1669-static void stbir__decode_and_resample_downsample(stbir__info* stbir_info, int n)1670-{1671- // Decode the nth scanline from the source image into the decode buffer.1672- stbir__decode_scanline(stbir_info, n);1673-1674- memset(stbir_info->horizontal_buffer, 0, stbir_info->output_w * stbir_info->channels * sizeof(float));1675-1676- // Now resample it into the horizontal buffer.1677- if (stbir__use_width_upsampling(stbir_info))1678- stbir__resample_horizontal_upsample(stbir_info, stbir_info->horizontal_buffer);1679- else1680- stbir__resample_horizontal_downsample(stbir_info, stbir_info->horizontal_buffer);1681-1682- // Now it's sitting in the horizontal buffer ready to be distributed into the ring buffers.1683-}1684-1685-// Get the specified scan line from the ring buffer.1686-static float* stbir__get_ring_buffer_scanline(int get_scanline, float* ring_buffer, int begin_index, int first_scanline, int ring_buffer_num_entries, int ring_buffer_length)1687-{1688- int ring_buffer_index = (begin_index + (get_scanline - first_scanline)) % ring_buffer_num_entries;1689- return stbir__get_ring_buffer_entry(ring_buffer, ring_buffer_index, ring_buffer_length);1690-}1691-1692-1693-static void stbir__encode_scanline(stbir__info* stbir_info, int num_pixels, void *output_buffer, float *encode_buffer, int channels, int alpha_channel, int decode)1694-{1695- int x;1696- int n;1697- int num_nonalpha;1698- stbir_uint16 nonalpha[STBIR_MAX_CHANNELS];1699-1700- if (!(stbir_info->flags&STBIR_FLAG_ALPHA_PREMULTIPLIED))1701- {1702- for (x=0; x < num_pixels; ++x)1703- {1704- int pixel_index = x*channels;1705-1706- float alpha = encode_buffer[pixel_index + alpha_channel];1707- float reciprocal_alpha = alpha ? 1.0f / alpha : 0;1708-1709- // unrolling this produced a 1% slowdown upscaling a large RGBA linear-space image on my machine - stb1710- for (n = 0; n < channels; n++)1711- if (n != alpha_channel)1712- encode_buffer[pixel_index + n] *= reciprocal_alpha;1713-1714- // We added in a small epsilon to prevent the color channel from being deleted with zero alpha.1715- // Because we only add it for integer types, it will automatically be discarded on integer1716- // conversion, so we don't need to subtract it back out (which would be problematic for1717- // numeric precision reasons).1718- }1719- }1720-1721- // build a table of all channels that need colorspace correction, so1722- // we don't perform colorspace correction on channels that don't need it.1723- for (x = 0, num_nonalpha = 0; x < channels; ++x)1724- {1725- if (x != alpha_channel || (stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE))1726- {1727- nonalpha[num_nonalpha++] = (stbir_uint16)x;1728- }1729- }1730-1731- #define STBIR__ROUND_INT(f) ((int) ((f)+0.5))1732- #define STBIR__ROUND_UINT(f) ((stbir_uint32) ((f)+0.5))1733-1734- #ifdef STBIR__SATURATE_INT1735- #define STBIR__ENCODE_LINEAR8(f) stbir__saturate8 (STBIR__ROUND_INT((f) * stbir__max_uint8_as_float ))1736- #define STBIR__ENCODE_LINEAR16(f) stbir__saturate16(STBIR__ROUND_INT((f) * stbir__max_uint16_as_float))1737- #else1738- #define STBIR__ENCODE_LINEAR8(f) (unsigned char ) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint8_as_float )1739- #define STBIR__ENCODE_LINEAR16(f) (unsigned short) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint16_as_float)1740- #endif1741-1742- switch (decode)1743- {1744- case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR):1745- for (x=0; x < num_pixels; ++x)1746- {1747- int pixel_index = x*channels;1748-1749- for (n = 0; n < channels; n++)1750- {1751- int index = pixel_index + n;1752- ((unsigned char*)output_buffer)[index] = STBIR__ENCODE_LINEAR8(encode_buffer[index]);1753- }1754- }1755- break;1756-1757- case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB):1758- for (x=0; x < num_pixels; ++x)1759- {1760- int pixel_index = x*channels;1761-1762- for (n = 0; n < num_nonalpha; n++)1763- {1764- int index = pixel_index + nonalpha[n];1765- ((unsigned char*)output_buffer)[index] = stbir__linear_to_srgb_uchar(encode_buffer[index]);1766- }1767-1768- if (!(stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE))1769- ((unsigned char *)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR8(encode_buffer[pixel_index+alpha_channel]);1770- }1771- break;1772-1773- case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR):1774- for (x=0; x < num_pixels; ++x)1775- {1776- int pixel_index = x*channels;1777-1778- for (n = 0; n < channels; n++)1779- {1780- int index = pixel_index + n;1781- ((unsigned short*)output_buffer)[index] = STBIR__ENCODE_LINEAR16(encode_buffer[index]);1782- }1783- }1784- break;1785-1786- case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB):1787- for (x=0; x < num_pixels; ++x)1788- {1789- int pixel_index = x*channels;1790-1791- for (n = 0; n < num_nonalpha; n++)1792- {1793- int index = pixel_index + nonalpha[n];1794- ((unsigned short*)output_buffer)[index] = (unsigned short)STBIR__ROUND_INT(stbir__linear_to_srgb(stbir__saturate(encode_buffer[index])) * stbir__max_uint16_as_float);1795- }1796-1797- if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1798- ((unsigned short*)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR16(encode_buffer[pixel_index + alpha_channel]);1799- }1800-1801- break;1802-1803- case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR):1804- for (x=0; x < num_pixels; ++x)1805- {1806- int pixel_index = x*channels;1807-1808- for (n = 0; n < channels; n++)1809- {1810- int index = pixel_index + n;1811- ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__saturate(encode_buffer[index])) * stbir__max_uint32_as_float);1812- }1813- }1814- break;1815-1816- case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB):1817- for (x=0; x < num_pixels; ++x)1818- {1819- int pixel_index = x*channels;1820-1821- for (n = 0; n < num_nonalpha; n++)1822- {1823- int index = pixel_index + nonalpha[n];1824- ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__linear_to_srgb(stbir__saturate(encode_buffer[index]))) * stbir__max_uint32_as_float);1825- }1826-1827- if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1828- ((unsigned int*)output_buffer)[pixel_index + alpha_channel] = (unsigned int)STBIR__ROUND_INT(((double)stbir__saturate(encode_buffer[pixel_index + alpha_channel])) * stbir__max_uint32_as_float);1829- }1830- break;1831-1832- case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR):1833- for (x=0; x < num_pixels; ++x)1834- {1835- int pixel_index = x*channels;1836-1837- for (n = 0; n < channels; n++)1838- {1839- int index = pixel_index + n;1840- ((float*)output_buffer)[index] = encode_buffer[index];1841- }1842- }1843- break;1844-1845- case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB):1846- for (x=0; x < num_pixels; ++x)1847- {1848- int pixel_index = x*channels;1849-1850- for (n = 0; n < num_nonalpha; n++)1851- {1852- int index = pixel_index + nonalpha[n];1853- ((float*)output_buffer)[index] = stbir__linear_to_srgb(encode_buffer[index]);1854- }1855-1856- if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE))1857- ((float*)output_buffer)[pixel_index + alpha_channel] = encode_buffer[pixel_index + alpha_channel];1858- }1859- break;1860-1861- default:1862- STBIR_ASSERT(!"Unknown type/colorspace/channels combination.");1863- break;1864- }1865-}1866-1867-static void stbir__resample_vertical_upsample(stbir__info* stbir_info, int n)1868-{1869- int x, k;1870- int output_w = stbir_info->output_w;1871- stbir__contributors* vertical_contributors = stbir_info->vertical_contributors;1872- float* vertical_coefficients = stbir_info->vertical_coefficients;1873- int channels = stbir_info->channels;1874- int alpha_channel = stbir_info->alpha_channel;1875- int type = stbir_info->type;1876- int colorspace = stbir_info->colorspace;1877- int ring_buffer_entries = stbir_info->ring_buffer_num_entries;1878- void* output_data = stbir_info->output_data;1879- float* encode_buffer = stbir_info->encode_buffer;1880- int decode = STBIR__DECODE(type, colorspace);1881- int coefficient_width = stbir_info->vertical_coefficient_width;1882- int coefficient_counter;1883- int contributor = n;1884-1885- float* ring_buffer = stbir_info->ring_buffer;1886- int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index;1887- int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline;1888- int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);1889-1890- int n0,n1, output_row_start;1891- int coefficient_group = coefficient_width * contributor;1892-1893- n0 = vertical_contributors[contributor].n0;1894- n1 = vertical_contributors[contributor].n1;1895-1896- output_row_start = n * stbir_info->output_stride_bytes;1897-1898- STBIR_ASSERT(stbir__use_height_upsampling(stbir_info));1899-1900- memset(encode_buffer, 0, output_w * sizeof(float) * channels);1901-1902- // I tried reblocking this for better cache usage of encode_buffer1903- // (using x_outer, k, x_inner), but it lost speed. -- stb1904-1905- coefficient_counter = 0;1906- switch (channels) {1907- case 1:1908- for (k = n0; k <= n1; k++)1909- {1910- int coefficient_index = coefficient_counter++;1911- float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1912- float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1913- for (x = 0; x < output_w; ++x)1914- {1915- int in_pixel_index = x * 1;1916- encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;1917- }1918- }1919- break;1920- case 2:1921- for (k = n0; k <= n1; k++)1922- {1923- int coefficient_index = coefficient_counter++;1924- float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1925- float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1926- for (x = 0; x < output_w; ++x)1927- {1928- int in_pixel_index = x * 2;1929- encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;1930- encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;1931- }1932- }1933- break;1934- case 3:1935- for (k = n0; k <= n1; k++)1936- {1937- int coefficient_index = coefficient_counter++;1938- float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1939- float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1940- for (x = 0; x < output_w; ++x)1941- {1942- int in_pixel_index = x * 3;1943- encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;1944- encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;1945- encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient;1946- }1947- }1948- break;1949- case 4:1950- for (k = n0; k <= n1; k++)1951- {1952- int coefficient_index = coefficient_counter++;1953- float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1954- float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1955- for (x = 0; x < output_w; ++x)1956- {1957- int in_pixel_index = x * 4;1958- encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient;1959- encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient;1960- encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient;1961- encode_buffer[in_pixel_index + 3] += ring_buffer_entry[in_pixel_index + 3] * coefficient;1962- }1963- }1964- break;1965- default:1966- for (k = n0; k <= n1; k++)1967- {1968- int coefficient_index = coefficient_counter++;1969- float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);1970- float coefficient = vertical_coefficients[coefficient_group + coefficient_index];1971- for (x = 0; x < output_w; ++x)1972- {1973- int in_pixel_index = x * channels;1974- int c;1975- for (c = 0; c < channels; c++)1976- encode_buffer[in_pixel_index + c] += ring_buffer_entry[in_pixel_index + c] * coefficient;1977- }1978- }1979- break;1980- }1981- stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, encode_buffer, channels, alpha_channel, decode);1982-}1983-1984-static void stbir__resample_vertical_downsample(stbir__info* stbir_info, int n)1985-{1986- int x, k;1987- int output_w = stbir_info->output_w;1988- stbir__contributors* vertical_contributors = stbir_info->vertical_contributors;1989- float* vertical_coefficients = stbir_info->vertical_coefficients;1990- int channels = stbir_info->channels;1991- int ring_buffer_entries = stbir_info->ring_buffer_num_entries;1992- float* horizontal_buffer = stbir_info->horizontal_buffer;1993- int coefficient_width = stbir_info->vertical_coefficient_width;1994- int contributor = n + stbir_info->vertical_filter_pixel_margin;1995-1996- float* ring_buffer = stbir_info->ring_buffer;1997- int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index;1998- int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline;1999- int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);2000- int n0,n1;2001-2002- n0 = vertical_contributors[contributor].n0;2003- n1 = vertical_contributors[contributor].n1;2004-2005- STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info));2006-2007- for (k = n0; k <= n1; k++)2008- {2009- int coefficient_index = k - n0;2010- int coefficient_group = coefficient_width * contributor;2011- float coefficient = vertical_coefficients[coefficient_group + coefficient_index];2012-2013- float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length);2014-2015- switch (channels) {2016- case 1:2017- for (x = 0; x < output_w; x++)2018- {2019- int in_pixel_index = x * 1;2020- ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;2021- }2022- break;2023- case 2:2024- for (x = 0; x < output_w; x++)2025- {2026- int in_pixel_index = x * 2;2027- ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;2028- ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;2029- }2030- break;2031- case 3:2032- for (x = 0; x < output_w; x++)2033- {2034- int in_pixel_index = x * 3;2035- ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;2036- ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;2037- ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient;2038- }2039- break;2040- case 4:2041- for (x = 0; x < output_w; x++)2042- {2043- int in_pixel_index = x * 4;2044- ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient;2045- ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient;2046- ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient;2047- ring_buffer_entry[in_pixel_index + 3] += horizontal_buffer[in_pixel_index + 3] * coefficient;2048- }2049- break;2050- default:2051- for (x = 0; x < output_w; x++)2052- {2053- int in_pixel_index = x * channels;2054-2055- int c;2056- for (c = 0; c < channels; c++)2057- ring_buffer_entry[in_pixel_index + c] += horizontal_buffer[in_pixel_index + c] * coefficient;2058- }2059- break;2060- }2061- }2062-}2063-2064-static void stbir__buffer_loop_upsample(stbir__info* stbir_info)2065-{2066- int y;2067- float scale_ratio = stbir_info->vertical_scale;2068- float out_scanlines_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(1/scale_ratio) * scale_ratio;2069-2070- STBIR_ASSERT(stbir__use_height_upsampling(stbir_info));2071-2072- for (y = 0; y < stbir_info->output_h; y++)2073- {2074- float in_center_of_out = 0; // Center of the current out scanline in the in scanline space2075- int in_first_scanline = 0, in_last_scanline = 0;2076-2077- stbir__calculate_sample_range_upsample(y, out_scanlines_radius, scale_ratio, stbir_info->vertical_shift, &in_first_scanline, &in_last_scanline, &in_center_of_out);2078-2079- STBIR_ASSERT(in_last_scanline - in_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);2080-2081- if (stbir_info->ring_buffer_begin_index >= 0)2082- {2083- // Get rid of whatever we don't need anymore.2084- while (in_first_scanline > stbir_info->ring_buffer_first_scanline)2085- {2086- if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline)2087- {2088- // We just popped the last scanline off the ring buffer.2089- // Reset it to the empty state.2090- stbir_info->ring_buffer_begin_index = -1;2091- stbir_info->ring_buffer_first_scanline = 0;2092- stbir_info->ring_buffer_last_scanline = 0;2093- break;2094- }2095- else2096- {2097- stbir_info->ring_buffer_first_scanline++;2098- stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries;2099- }2100- }2101- }2102-2103- // Load in new ones.2104- if (stbir_info->ring_buffer_begin_index < 0)2105- stbir__decode_and_resample_upsample(stbir_info, in_first_scanline);2106-2107- while (in_last_scanline > stbir_info->ring_buffer_last_scanline)2108- stbir__decode_and_resample_upsample(stbir_info, stbir_info->ring_buffer_last_scanline + 1);2109-2110- // Now all buffers should be ready to write a row of vertical sampling.2111- stbir__resample_vertical_upsample(stbir_info, y);2112-2113- STBIR_PROGRESS_REPORT((float)y / stbir_info->output_h);2114- }2115-}2116-2117-static void stbir__empty_ring_buffer(stbir__info* stbir_info, int first_necessary_scanline)2118-{2119- int output_stride_bytes = stbir_info->output_stride_bytes;2120- int channels = stbir_info->channels;2121- int alpha_channel = stbir_info->alpha_channel;2122- int type = stbir_info->type;2123- int colorspace = stbir_info->colorspace;2124- int output_w = stbir_info->output_w;2125- void* output_data = stbir_info->output_data;2126- int decode = STBIR__DECODE(type, colorspace);2127-2128- float* ring_buffer = stbir_info->ring_buffer;2129- int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float);2130-2131- if (stbir_info->ring_buffer_begin_index >= 0)2132- {2133- // Get rid of whatever we don't need anymore.2134- while (first_necessary_scanline > stbir_info->ring_buffer_first_scanline)2135- {2136- if (stbir_info->ring_buffer_first_scanline >= 0 && stbir_info->ring_buffer_first_scanline < stbir_info->output_h)2137- {2138- int output_row_start = stbir_info->ring_buffer_first_scanline * output_stride_bytes;2139- float* ring_buffer_entry = stbir__get_ring_buffer_entry(ring_buffer, stbir_info->ring_buffer_begin_index, ring_buffer_length);2140- stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, ring_buffer_entry, channels, alpha_channel, decode);2141- STBIR_PROGRESS_REPORT((float)stbir_info->ring_buffer_first_scanline / stbir_info->output_h);2142- }2143-2144- if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline)2145- {2146- // We just popped the last scanline off the ring buffer.2147- // Reset it to the empty state.2148- stbir_info->ring_buffer_begin_index = -1;2149- stbir_info->ring_buffer_first_scanline = 0;2150- stbir_info->ring_buffer_last_scanline = 0;2151- break;2152- }2153- else2154- {2155- stbir_info->ring_buffer_first_scanline++;2156- stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries;2157- }2158- }2159- }2160-}2161-2162-static void stbir__buffer_loop_downsample(stbir__info* stbir_info)2163-{2164- int y;2165- float scale_ratio = stbir_info->vertical_scale;2166- int output_h = stbir_info->output_h;2167- float in_pixels_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(scale_ratio) / scale_ratio;2168- int pixel_margin = stbir_info->vertical_filter_pixel_margin;2169- int max_y = stbir_info->input_h + pixel_margin;2170-2171- STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info));2172-2173- for (y = -pixel_margin; y < max_y; y++)2174- {2175- float out_center_of_in; // Center of the current out scanline in the in scanline space2176- int out_first_scanline, out_last_scanline;2177-2178- stbir__calculate_sample_range_downsample(y, in_pixels_radius, scale_ratio, stbir_info->vertical_shift, &out_first_scanline, &out_last_scanline, &out_center_of_in);2179-2180- STBIR_ASSERT(out_last_scanline - out_first_scanline + 1 <= stbir_info->ring_buffer_num_entries);2181-2182- if (out_last_scanline < 0 || out_first_scanline >= output_h)2183- continue;2184-2185- stbir__empty_ring_buffer(stbir_info, out_first_scanline);2186-2187- stbir__decode_and_resample_downsample(stbir_info, y);2188-2189- // Load in new ones.2190- if (stbir_info->ring_buffer_begin_index < 0)2191- stbir__add_empty_ring_buffer_entry(stbir_info, out_first_scanline);2192-2193- while (out_last_scanline > stbir_info->ring_buffer_last_scanline)2194- stbir__add_empty_ring_buffer_entry(stbir_info, stbir_info->ring_buffer_last_scanline + 1);2195-2196- // Now the horizontal buffer is ready to write to all ring buffer rows.2197- stbir__resample_vertical_downsample(stbir_info, y);2198- }2199-2200- stbir__empty_ring_buffer(stbir_info, stbir_info->output_h);2201-}2202-2203-static void stbir__setup(stbir__info *info, int input_w, int input_h, int output_w, int output_h, int channels)2204-{2205- info->input_w = input_w;2206- info->input_h = input_h;2207- info->output_w = output_w;2208- info->output_h = output_h;2209- info->channels = channels;2210-}2211-2212-static void stbir__calculate_transform(stbir__info *info, float s0, float t0, float s1, float t1, float *transform)2213-{2214- info->s0 = s0;2215- info->t0 = t0;2216- info->s1 = s1;2217- info->t1 = t1;2218-2219- if (transform)2220- {2221- info->horizontal_scale = transform[0];2222- info->vertical_scale = transform[1];2223- info->horizontal_shift = transform[2];2224- info->vertical_shift = transform[3];2225- }2226- else2227- {2228- info->horizontal_scale = ((float)info->output_w / info->input_w) / (s1 - s0);2229- info->vertical_scale = ((float)info->output_h / info->input_h) / (t1 - t0);2230-2231- info->horizontal_shift = s0 * info->output_w / (s1 - s0);2232- info->vertical_shift = t0 * info->output_h / (t1 - t0);2233- }2234-}2235-2236-static void stbir__choose_filter(stbir__info *info, stbir_filter h_filter, stbir_filter v_filter)2237-{2238- if (h_filter == 0)2239- h_filter = stbir__use_upsampling(info->horizontal_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE;2240- if (v_filter == 0)2241- v_filter = stbir__use_upsampling(info->vertical_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE;2242- info->horizontal_filter = h_filter;2243- info->vertical_filter = v_filter;2244-}2245-2246-static stbir_uint32 stbir__calculate_memory(stbir__info *info)2247-{2248- int pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale);2249- int filter_height = stbir__get_filter_pixel_width(info->vertical_filter, info->vertical_scale);2250-2251- info->horizontal_num_contributors = stbir__get_contributors(info->horizontal_scale, info->horizontal_filter, info->input_w, info->output_w);2252- info->vertical_num_contributors = stbir__get_contributors(info->vertical_scale , info->vertical_filter , info->input_h, info->output_h);2253-2254- // One extra entry because floating point precision problems sometimes cause an extra to be necessary.2255- info->ring_buffer_num_entries = filter_height + 1;2256-2257- info->horizontal_contributors_size = info->horizontal_num_contributors * sizeof(stbir__contributors);2258- info->horizontal_coefficients_size = stbir__get_total_horizontal_coefficients(info) * sizeof(float);2259- info->vertical_contributors_size = info->vertical_num_contributors * sizeof(stbir__contributors);2260- info->vertical_coefficients_size = stbir__get_total_vertical_coefficients(info) * sizeof(float);2261- info->decode_buffer_size = (info->input_w + pixel_margin * 2) * info->channels * sizeof(float);2262- info->horizontal_buffer_size = info->output_w * info->channels * sizeof(float);2263- info->ring_buffer_size = info->output_w * info->channels * info->ring_buffer_num_entries * sizeof(float);2264- info->encode_buffer_size = info->output_w * info->channels * sizeof(float);2265-2266- STBIR_ASSERT(info->horizontal_filter != 0);2267- STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late2268- STBIR_ASSERT(info->vertical_filter != 0);2269- STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late2270-2271- if (stbir__use_height_upsampling(info))2272- // The horizontal buffer is for when we're downsampling the height and we2273- // can't output the result of sampling the decode buffer directly into the2274- // ring buffers.2275- info->horizontal_buffer_size = 0;2276- else2277- // The encode buffer is to retain precision in the height upsampling method2278- // and isn't used when height downsampling.2279- info->encode_buffer_size = 0;2280-2281- return info->horizontal_contributors_size + info->horizontal_coefficients_size2282- + info->vertical_contributors_size + info->vertical_coefficients_size2283- + info->decode_buffer_size + info->horizontal_buffer_size2284- + info->ring_buffer_size + info->encode_buffer_size;2285-}2286-2287-static int stbir__resize_allocated(stbir__info *info,2288- const void* input_data, int input_stride_in_bytes,2289- void* output_data, int output_stride_in_bytes,2290- int alpha_channel, stbir_uint32 flags, stbir_datatype type,2291- stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace,2292- void* tempmem, size_t tempmem_size_in_bytes)2293-{2294- size_t memory_required = stbir__calculate_memory(info);2295-2296- int width_stride_input = input_stride_in_bytes ? input_stride_in_bytes : info->channels * info->input_w * stbir__type_size[type];2297- int width_stride_output = output_stride_in_bytes ? output_stride_in_bytes : info->channels * info->output_w * stbir__type_size[type];2298-2299-#ifdef STBIR_DEBUG_OVERWRITE_TEST2300-#define OVERWRITE_ARRAY_SIZE 82301- unsigned char overwrite_output_before_pre[OVERWRITE_ARRAY_SIZE];2302- unsigned char overwrite_tempmem_before_pre[OVERWRITE_ARRAY_SIZE];2303- unsigned char overwrite_output_after_pre[OVERWRITE_ARRAY_SIZE];2304- unsigned char overwrite_tempmem_after_pre[OVERWRITE_ARRAY_SIZE];2305-2306- size_t begin_forbidden = width_stride_output * (info->output_h - 1) + info->output_w * info->channels * stbir__type_size[type];2307- memcpy(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE);2308- memcpy(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE);2309- memcpy(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE);2310- memcpy(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE);2311-#endif2312-2313- STBIR_ASSERT(info->channels >= 0);2314- STBIR_ASSERT(info->channels <= STBIR_MAX_CHANNELS);2315-2316- if (info->channels < 0 || info->channels > STBIR_MAX_CHANNELS)2317- return 0;2318-2319- STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));2320- STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table));2321-2322- if (info->horizontal_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table))2323- return 0;2324- if (info->vertical_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table))2325- return 0;2326-2327- if (alpha_channel < 0)2328- flags |= STBIR_FLAG_ALPHA_USES_COLORSPACE | STBIR_FLAG_ALPHA_PREMULTIPLIED;2329-2330- if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) {2331- STBIR_ASSERT(alpha_channel >= 0 && alpha_channel < info->channels);2332- }2333-2334- if (alpha_channel >= info->channels)2335- return 0;2336-2337- STBIR_ASSERT(tempmem);2338-2339- if (!tempmem)2340- return 0;2341-2342- STBIR_ASSERT(tempmem_size_in_bytes >= memory_required);2343-2344- if (tempmem_size_in_bytes < memory_required)2345- return 0;2346-2347- memset(tempmem, 0, tempmem_size_in_bytes);2348-2349- info->input_data = input_data;2350- info->input_stride_bytes = width_stride_input;2351-2352- info->output_data = output_data;2353- info->output_stride_bytes = width_stride_output;2354-2355- info->alpha_channel = alpha_channel;2356- info->flags = flags;2357- info->type = type;2358- info->edge_horizontal = edge_horizontal;2359- info->edge_vertical = edge_vertical;2360- info->colorspace = colorspace;2361-2362- info->horizontal_coefficient_width = stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale);2363- info->vertical_coefficient_width = stbir__get_coefficient_width (info->vertical_filter , info->vertical_scale );2364- info->horizontal_filter_pixel_width = stbir__get_filter_pixel_width (info->horizontal_filter, info->horizontal_scale);2365- info->vertical_filter_pixel_width = stbir__get_filter_pixel_width (info->vertical_filter , info->vertical_scale );2366- info->horizontal_filter_pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale);2367- info->vertical_filter_pixel_margin = stbir__get_filter_pixel_margin(info->vertical_filter , info->vertical_scale );2368-2369- info->ring_buffer_length_bytes = info->output_w * info->channels * sizeof(float);2370- info->decode_buffer_pixels = info->input_w + info->horizontal_filter_pixel_margin * 2;2371-2372-#define STBIR__NEXT_MEMPTR(current, newtype) (newtype*)(((unsigned char*)current) + current##_size)2373-2374- info->horizontal_contributors = (stbir__contributors *) tempmem;2375- info->horizontal_coefficients = STBIR__NEXT_MEMPTR(info->horizontal_contributors, float);2376- info->vertical_contributors = STBIR__NEXT_MEMPTR(info->horizontal_coefficients, stbir__contributors);2377- info->vertical_coefficients = STBIR__NEXT_MEMPTR(info->vertical_contributors, float);2378- info->decode_buffer = STBIR__NEXT_MEMPTR(info->vertical_coefficients, float);2379-2380- if (stbir__use_height_upsampling(info))2381- {2382- info->horizontal_buffer = NULL;2383- info->ring_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float);2384- info->encode_buffer = STBIR__NEXT_MEMPTR(info->ring_buffer, float);2385-2386- STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->encode_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes);2387- }2388- else2389- {2390- info->horizontal_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float);2391- info->ring_buffer = STBIR__NEXT_MEMPTR(info->horizontal_buffer, float);2392- info->encode_buffer = NULL;2393-2394- STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->ring_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes);2395- }2396-2397-#undef STBIR__NEXT_MEMPTR2398-2399- // This signals that the ring buffer is empty2400- info->ring_buffer_begin_index = -1;2401-2402- stbir__calculate_filters(info->horizontal_contributors, info->horizontal_coefficients, info->horizontal_filter, info->horizontal_scale, info->horizontal_shift, info->input_w, info->output_w);2403- stbir__calculate_filters(info->vertical_contributors, info->vertical_coefficients, info->vertical_filter, info->vertical_scale, info->vertical_shift, info->input_h, info->output_h);2404-2405- STBIR_PROGRESS_REPORT(0);2406-2407- if (stbir__use_height_upsampling(info))2408- stbir__buffer_loop_upsample(info);2409- else2410- stbir__buffer_loop_downsample(info);2411-2412- STBIR_PROGRESS_REPORT(1);2413-2414-#ifdef STBIR_DEBUG_OVERWRITE_TEST2415- STBIR_ASSERT(memcmp(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0);2416- STBIR_ASSERT(memcmp(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE) == 0);2417- STBIR_ASSERT(memcmp(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0);2418- STBIR_ASSERT(memcmp(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE) == 0);2419-#endif2420-2421- return 1;2422-}2423-2424-2425-static int stbir__resize_arbitrary(2426- void *alloc_context,2427- const void* input_data, int input_w, int input_h, int input_stride_in_bytes,2428- void* output_data, int output_w, int output_h, int output_stride_in_bytes,2429- float s0, float t0, float s1, float t1, float *transform,2430- int channels, int alpha_channel, stbir_uint32 flags, stbir_datatype type,2431- stbir_filter h_filter, stbir_filter v_filter,2432- stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace)2433-{2434- stbir__info info;2435- int result;2436- size_t memory_required;2437- void* extra_memory;2438-2439- stbir__setup(&info, input_w, input_h, output_w, output_h, channels);2440- stbir__calculate_transform(&info, s0,t0,s1,t1,transform);2441- stbir__choose_filter(&info, h_filter, v_filter);2442- memory_required = stbir__calculate_memory(&info);2443- extra_memory = STBIR_MALLOC(memory_required, alloc_context);2444-2445- if (!extra_memory)2446- return 0;2447-2448- result = stbir__resize_allocated(&info, input_data, input_stride_in_bytes,2449- output_data, output_stride_in_bytes,2450- alpha_channel, flags, type,2451- edge_horizontal, edge_vertical,2452- colorspace, extra_memory, memory_required);2453-2454- STBIR_FREE(extra_memory, alloc_context);2455-2456- return result;2457-}2458-2459-STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2460- unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2461- int num_channels)2462-{2463- return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,2464- output_pixels, output_w, output_h, output_stride_in_bytes,2465- 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,2466- STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR);2467-}2468-2469-STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2470- float *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2471- int num_channels)2472-{2473- return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,2474- output_pixels, output_w, output_h, output_stride_in_bytes,2475- 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_FLOAT, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,2476- STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR);2477-}2478-2479-STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2480- unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2481- int num_channels, int alpha_channel, int flags)2482-{2483- return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,2484- output_pixels, output_w, output_h, output_stride_in_bytes,2485- 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,2486- STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB);2487-}2488-2489-STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2490- unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2491- int num_channels, int alpha_channel, int flags,2492- stbir_edge edge_wrap_mode)2493-{2494- return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes,2495- output_pixels, output_w, output_h, output_stride_in_bytes,2496- 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT,2497- edge_wrap_mode, edge_wrap_mode, STBIR_COLORSPACE_SRGB);2498-}2499-2500-STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2501- unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2502- int num_channels, int alpha_channel, int flags,2503- stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,2504- void *alloc_context)2505-{2506- return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2507- output_pixels, output_w, output_h, output_stride_in_bytes,2508- 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, filter, filter,2509- edge_wrap_mode, edge_wrap_mode, space);2510-}2511-2512-STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2513- stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes,2514- int num_channels, int alpha_channel, int flags,2515- stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,2516- void *alloc_context)2517-{2518- return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2519- output_pixels, output_w, output_h, output_stride_in_bytes,2520- 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT16, filter, filter,2521- edge_wrap_mode, edge_wrap_mode, space);2522-}2523-2524-2525-STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2526- float *output_pixels , int output_w, int output_h, int output_stride_in_bytes,2527- int num_channels, int alpha_channel, int flags,2528- stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space,2529- void *alloc_context)2530-{2531- return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2532- output_pixels, output_w, output_h, output_stride_in_bytes,2533- 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_FLOAT, filter, filter,2534- edge_wrap_mode, edge_wrap_mode, space);2535-}2536-2537-2538-STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2539- void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2540- stbir_datatype datatype,2541- int num_channels, int alpha_channel, int flags,2542- stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,2543- stbir_filter filter_horizontal, stbir_filter filter_vertical,2544- stbir_colorspace space, void *alloc_context)2545-{2546- return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2547- output_pixels, output_w, output_h, output_stride_in_bytes,2548- 0,0,1,1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,2549- edge_mode_horizontal, edge_mode_vertical, space);2550-}2551-2552-2553-STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2554- void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2555- stbir_datatype datatype,2556- int num_channels, int alpha_channel, int flags,2557- stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,2558- stbir_filter filter_horizontal, stbir_filter filter_vertical,2559- stbir_colorspace space, void *alloc_context,2560- float x_scale, float y_scale,2561- float x_offset, float y_offset)2562-{2563- float transform[4];2564- transform[0] = x_scale;2565- transform[1] = y_scale;2566- transform[2] = x_offset;2567- transform[3] = y_offset;2568- return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2569- output_pixels, output_w, output_h, output_stride_in_bytes,2570- 0,0,1,1,transform,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,2571- edge_mode_horizontal, edge_mode_vertical, space);2572-}2573-2574-STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes,2575- void *output_pixels, int output_w, int output_h, int output_stride_in_bytes,2576- stbir_datatype datatype,2577- int num_channels, int alpha_channel, int flags,2578- stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical,2579- stbir_filter filter_horizontal, stbir_filter filter_vertical,2580- stbir_colorspace space, void *alloc_context,2581- float s0, float t0, float s1, float t1)2582-{2583- return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes,2584- output_pixels, output_w, output_h, output_stride_in_bytes,2585- s0,t0,s1,t1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical,2586- edge_mode_horizontal, edge_mode_vertical, space);2587-}2588-2589-#endif // STB_IMAGE_RESIZE_IMPLEMENTATION2590-2591-/*2592-------------------------------------------------------------------------------2593-This software is available under 2 licenses -- choose whichever you prefer.2594-------------------------------------------------------------------------------2595-ALTERNATIVE A - MIT License2596-Copyright (c) 2017 Sean Barrett2597-Permission is hereby granted, free of charge, to any person obtaining a copy of2598-this software and associated documentation files (the "Software"), to deal in2599-the Software without restriction, including without limitation the rights to2600-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies2601-of the Software, and to permit persons to whom the Software is furnished to do2602-so, subject to the following conditions:2603-The above copyright notice and this permission notice shall be included in all2604-copies or substantial portions of the Software.2605-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR2606-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,2607-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE2608-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER2609-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,2610-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE2611-SOFTWARE.2612-------------------------------------------------------------------------------2613-ALTERNATIVE B - Public Domain (www.unlicense.org)2614-This is free and unencumbered software released into the public domain.2615-Anyone is free to copy, modify, publish, use, compile, sell, or distribute this2616-software, either in source code form or as a compiled binary, for any purpose,2617-commercial or non-commercial, and by any means.2618-In jurisdictions that recognize copyright laws, the author or authors of this2619-software dedicate any and all copyright interest in the software to the public2620-domain. We make this dedication for the benefit of the public at large and to2621-the detriment of our heirs and successors. We intend this dedication to be an2622-overt act of relinquishment in perpetuity of all present and future rights to2623-this software under copyright law.2624-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR2625-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,2626-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE2627-AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN2628-ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION2629-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.2630-------------------------------------------------------------------------------2631-*/added:stb_image_resize2.hnot shown
Its text is not shown, added.
modified:stb_image_write.hnot shown
Its text is not shown, modified.
modified:stb_image.h+373 added-224 removed
1-/* stb_image - v2.27 - public domain image loader - http://nothings.org/stb1+/* stb_image - v2.29 - public domain image loader - http://nothings.org/stb2 no warranty implied; use at your own risk3 4 Do this:5 #define STB_IMAGE_IMPLEMENTATION41 unmodified lines47 See end of file for license information.48 49 RECENT REVISION HISTORY:50 51+ 2.29 (2023-05-xx) optimizations52+ 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff51- 2.27 ( ) document stbi_info better, 16-bit PNM support, bug fixes53+ 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes54 2.26 (2020-07-13) many minor fixes55 2.25 (2020-02-02) fix warnings56 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically57 2.23 (2019-08-11) fix clang static analysis warning51 unmodified lines109 Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex110 Cass Everitt Ryamond Barbiero github:grim210111 Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw112 Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus111- Josh Tobin Matthew Gregan github:poppolopoppo113+ Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo114 Julian Raschke Gregory Mullen Christian Floisand github:darealshinji115 Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007114- Brad Weinberger Matvey Cherevko [reserved]116+ Brad Weinberger Matvey Cherevko github:mosra117 Luca Sas Alexander Veselov Zack Middleton [reserved]118 Ryan C. Gordon [reserved] [reserved]119 DO NOT ADD YOUR NAME HERE120 20 unmodified lines141 // // ... process data if not NULL ...142 // // ... x = width, y = height, n = # 8-bit components per pixel ...143 // // ... replace '0' with '1'..'4' to force that many components per pixel144 // // ... but 'n' will always be the number that it would have been if you said 0143-// stbi_image_free(data)145+// stbi_image_free(data);146 //147 // Standard parameters:148 // int *x -- outputs image width in pixels149 // int *y -- outputs image height in pixels161 unmodified lines311 // ===========================================================================312 //313 // iPhone PNG support:314 //313-// By default we convert iphone-formatted PNGs back to RGB, even though314-// they are internally encoded differently. You can disable this conversion315-// by calling stbi_convert_iphone_png_to_rgb(0), in which case316-// you will always just get the native iphone "format" through (which317-// is BGR stored in RGB).315+// We optionally support converting iPhone-formatted PNGs (which store316+// premultiplied BGRA) back to RGB, even though they're internally encoded317+// differently. To enable this conversion, call318+// stbi_convert_iphone_png_to_rgb(1).319 //320 // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per321 // pixel to remove any premultiplied alpha *only* if the image file explicitly322 // says there's premultiplied data (currently only happens in iPhone images,195 unmodified lines518 519 // as above, but only applies to images loaded on the thread that calls the function520 // this function is only available if your compiler supports thread-local variables;521 // calling it will fail to link if your compiler doesn't522+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);523+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);524 STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);525 526 // ZLIB client - used by PNG, available for other purposes527 108 unmodified lines636 #endif637 #endif638 #endif639 637-#ifdef _MSC_VER640+#if defined(_MSC_VER) || defined(__SYMBIAN32__)641 typedef unsigned short stbi__uint16;642 typedef signed short stbi__int16;643 typedef unsigned int stbi__uint32;644 typedef signed int stbi__int32;388 unmodified lines1033 stbi__addsizes_valid(a*b*c, add);1034 }1035 1036 // returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow1034-#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)1037+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)1038 static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)1039 {1040 return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&1041 stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add);14 unmodified lines1056 if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL;1057 return stbi__malloc(a*b*c + add);1058 }1059 1057-#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)1060+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)1061 static void *stbi__malloc_mad4(int a, int b, int c, int d, int add)1062 {1063 if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL;1064 return stbi__malloc(a*b*c*d + add);1065 }1066 #endif1067 1068+// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow.1069+static int stbi__addints_valid(int a, int b)1070+{1071+ if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow1072+ if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0.1073+ return a <= INT_MAX - b;1074+}1075+1076+// returns 1 if the product of two ints fits in a signed short, 0 on overflow.1077+static int stbi__mul2shorts_valid(int a, int b)1078+{1079+ if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow1080+ if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid1081+ if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN1082+ return a >= SHRT_MIN / b;1083+}1084+1085 // stbi__err - error1086 // stbi__errpf - error returning pointer to float1087 // stbi__errpuc - error returning pointer to unsigned char1088 914 unmodified lines2003 {2004 int i,j,k=0;2005 unsigned int code;2006 // build size list for each symbol (from JPEG spec)1987- for (i=0; i < 16; ++i)1988- for (j=0; j < count[i]; ++j)2007+ for (i=0; i < 16; ++i) {2008+ for (j=0; j < count[i]; ++j) {2009 h->size[k++] = (stbi_uc) (i+1);2010+ if(k >= 257) return stbi__err("bad size list","Corrupt JPEG");2011+ }2012+ }2013 h->size[k] = 0;2014 2015 // compute actual symbols (from jpeg spec)2016 code = 0;116 unmodified lines2133 return -1;2134 2135 // convert the huffman code to the symbol id2136 c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];2137+ if(c < 0 || c >= 256) // symbol id out of bounds!2138+ return -1;2139 STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);2140 2141 // convert the id to a symbol2142 j->code_bits -= k;10 unmodified lines2153 {2154 unsigned int k;2155 int sgn;2156 if (j->code_bits < n) stbi__grow_buffer_unsafe(j);2157+ if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing2158 2159 sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative)2160 k = stbi_lrot(j->code_buffer, n);2161 j->code_buffer = k & ~stbi__bmask[n];6 unmodified lines2168 stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)2169 {2170 unsigned int k;2171 if (j->code_bits < n) stbi__grow_buffer_unsafe(j);2172+ if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing2173 k = stbi_lrot(j->code_buffer, n);2174 j->code_buffer = k & ~stbi__bmask[n];2175 k &= stbi__bmask[n];2176 j->code_bits -= n;3 unmodified lines2180 stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j)2181 {2182 unsigned int k;2183 if (j->code_bits < 1) stbi__grow_buffer_unsafe(j);2184+ if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing2185 k = j->code_buffer;2186 j->code_buffer <<= 1;2187 --j->code_bits;2188 return k & 0x80000000;29 unmodified lines2218 // 0 all the ac values now so we can do it 32-bits at a time2219 memset(data,0,64*sizeof(data[0]));2220 2221 diff = t ? stbi__extend_receive(j, t) : 0;2222+ if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG");2223 dc = j->img_comp[b].dc_pred + diff;2224 j->img_comp[b].dc_pred = dc;2225+ if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG");2226 data[0] = (short) (dc * dequant[0]);2227 2228 // decode AC components, see JPEG spec2229 k = 1;5 unmodified lines2235 r = fac[c];2236 if (r) { // fast-AC path2237 k += (r >> 4) & 15; // run2238 s = r & 15; // combined length2239+ if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available");2240 j->code_buffer <<= s;2241 j->code_bits -= s;2242 // decode into unzigzag'd location2243 zig = stbi__jpeg_dezigzag[k++];31 unmodified lines2275 t = stbi__jpeg_huff_decode(j, hdc);2276 if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG");2277 diff = t ? stbi__extend_receive(j, t) : 0;2278 2279+ if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG");2280 dc = j->img_comp[b].dc_pred + diff;2281 j->img_comp[b].dc_pred = dc;2282+ if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG");2283 data[0] = (short) (dc * (1 << j->succ_low));2284 } else {2285 // refinement scan for DC coefficient2286 if (stbi__jpeg_get_bit(j))26 unmodified lines2313 r = fac[c];2314 if (r) { // fast-AC path2315 k += (r >> 4) & 15; // run2316 s = r & 15; // combined length2317+ if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available");2318 j->code_buffer <<= s;2319 j->code_bits -= s;2320 zig = stbi__jpeg_dezigzag[k++];2321 data[zig] = (short) ((r >> 8) * (1 << shift));812 unmodified lines3134 for (i=0; i < 16; ++i) {3135 sizes[i] = stbi__get8(z->s);3136 n += sizes[i];3137 }3138+ if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values!3139 L -= 17;3140 if (tc == 0) {3141 if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;3142 v = z->huff_dc[th].values;157 unmodified lines3300 if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;3301 if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;3302 }3303 3304+ // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios3305+ // and I've never seen a non-corrupted JPEG file actually use them3306+ for (i=0; i < s->img_n; ++i) {3307+ if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG");3308+ if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG");3309+ }3310+3311 // compute interleaved mcu info3312 z->img_h_max = h_max;3313 z->img_v_max = v_max;3314 z->img_mcu_w = h_max * 8;69 unmodified lines3384 if (!stbi__process_frame_header(z, scan)) return 0;3385 return 1;3386 }3387 3388+static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j)3389+{3390+ // some JPEGs have junk at end, skip over it but if we find what looks3391+ // like a valid marker, resume there3392+ while (!stbi__at_eof(j->s)) {3393+ stbi_uc x = stbi__get8(j->s);3394+ while (x == 0xff) { // might be a marker3395+ if (stbi__at_eof(j->s)) return STBI__MARKER_none;3396+ x = stbi__get8(j->s);3397+ if (x != 0x00 && x != 0xff) {3398+ // not a stuffed zero or lead-in to another marker, looks3399+ // like an actual marker, return it3400+ return x;3401+ }3402+ // stuffed zero has x=0 now which ends the loop, meaning we go3403+ // back to regular scan loop.3404+ // repeated 0xff keeps trying to read the next byte of the marker.3405+ }3406+ }3407+ return STBI__MARKER_none;3408+}3409+3410 // decode image to YCbCr format3411 static int stbi__decode_jpeg_image(stbi__jpeg *j)3412 {3413 int m;8 unmodified lines3422 if (stbi__SOS(m)) {3423 if (!stbi__process_scan_header(j)) return 0;3424 if (!stbi__parse_entropy_coded_data(j)) return 0;3425 if (j->marker == STBI__MARKER_none ) {3362- // handle 0s at the end of image data from IP Kamera 90603363- while (!stbi__at_eof(j->s)) {3364- int x = stbi__get8(j->s);3365- if (x == 255) {3366- j->marker = stbi__get8(j->s);3367- break;3368- }3369- }3426+ j->marker = stbi__skip_jpeg_junk_at_end(j);3427 // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 03428 }3429+ m = stbi__get_marker(j);3430+ if (STBI__RESTART(m))3431+ m = stbi__get_marker(j);3432 } else if (stbi__DNL(m)) {3433 int Ld = stbi__get16be(j->s);3434 stbi__uint32 NL = stbi__get16be(j->s);3435 if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG");3436 if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG");3437+ m = stbi__get_marker(j);3438 } else {3378- if (!stbi__process_marker(j, m)) return 0;3439+ if (!stbi__process_marker(j, m)) return 1;3440+ m = stbi__get_marker(j);3441 }3380- m = stbi__get_marker(j);3442 }3443 if (j->progressive)3444 stbi__jpeg_finish(j);3445 return 1;435 unmodified lines3881 decode_n = 1;3882 else3883 decode_n = z->s->img_n;3884 3885+ // nothing to do if no components requested; check this now to avoid3886+ // accessing uninitialized coutput[0] later3887+ if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; }3888+3889 // resample and color-convert3890 {3891 int k;3892 unsigned int i,j;135 unmodified lines4028 {4029 unsigned char* result;4030 stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));4031 if (!j) return stbi__errpuc("outofmem", "Out of memory");4032+ memset(j, 0, sizeof(stbi__jpeg));4033 STBI_NOTUSED(ri);4034 j->s = s;4035 stbi__setup_jpeg(j);4036 result = load_jpeg_image(j, x,y,comp,req_comp);5 unmodified lines4042 {4043 int r;4044 stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));4045 if (!j) return stbi__err("outofmem", "Out of memory");4046+ memset(j, 0, sizeof(stbi__jpeg));4047 j->s = s;4048 stbi__setup_jpeg(j);4049 r = stbi__decode_jpeg_header(j, STBI__SCAN_type);4050 stbi__rewind(s);17 unmodified lines4068 {4069 int result;4070 stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg)));4071 if (!j) return stbi__err("outofmem", "Out of memory");4072+ memset(j, 0, sizeof(stbi__jpeg));4073 j->s = s;4074 result = stbi__jpeg_info_raw(j, x, y, comp);4075 STBI_FREE(j);4076 return result;99 unmodified lines4176 typedef struct4177 {4178 stbi_uc *zbuffer, *zbuffer_end;4179 int num_bits;4180+ int hit_zeof_once;4181 stbi__uint32 code_buffer;4182 4183 char *zout;4184 char *zout_start;58 unmodified lines4243 {4244 int b,s;4245 if (a->num_bits < 16) {4246 if (stbi__zeof(a)) {4178- return -1; /* report error for unexpected end of data. */4247+ if (!a->hit_zeof_once) {4248+ // This is the first time we hit eof, insert 16 extra padding btis4249+ // to allow us to keep going; if we actually consume any of them4250+ // though, that is invalid data. This is caught later.4251+ a->hit_zeof_once = 1;4252+ a->num_bits += 16; // add 16 implicit zero bits4253+ } else {4254+ // We already inserted our extra 16 padding bits and are again4255+ // out, this stream is actually prematurely terminated.4256+ return -1;4257+ }4258+ } else {4259+ stbi__fill_bits(a);4260 }4180- stbi__fill_bits(a);4261 }4262 b = z->fast[a->code_buffer & STBI__ZFAST_MASK];4263 if (b) {4264 s = b >> 9;56 unmodified lines4321 stbi_uc *p;4322 int len,dist;4323 if (z == 256) {4324 a->zout = zout;4325+ if (a->hit_zeof_once && a->num_bits < 16) {4326+ // The first time we hit zeof, we inserted 16 extra zero bits into our bit4327+ // buffer so the decoder can just do its speculative decoding. But if we4328+ // actually consumed any of those bits (which is the case when num_bits < 16),4329+ // the stream actually read past the end so it is malformed.4330+ return stbi__err("unexpected end","Corrupt PNG");4331+ }4332 return 1;4333 }4334+ if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data4335 z -= 257;4336 len = stbi__zlength_base[z];4337 if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);4338 z = stbi__zhuffman_decode(a, &a->z_distance);4251- if (z < 0) return stbi__err("bad huffman code","Corrupt PNG");4339+ if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data4340 dist = stbi__zdist_base[z];4341 if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);4342 if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");4255- if (zout + len > a->zout_end) {4343+ if (len > a->zout_end - zout) {4344 if (!stbi__zexpand(a, zout, len)) return 0;4345 zout = a->zout;4346 }4347 p = (stbi_uc *) (zout - dist);135 unmodified lines4483 if (parse_header)4484 if (!stbi__parse_zlib_header(a)) return 0;4485 a->num_bits = 0;4486 a->code_buffer = 0;4487+ a->hit_zeof_once = 0;4488 do {4489 final = stbi__zreceive(a,1);4490 type = stbi__zreceive(a,2);4491 if (type == 0) {147 unmodified lines4639 STBI__F_sub=1,4640 STBI__F_up=2,4641 STBI__F_avg=3,4642 STBI__F_paeth=4,4554- // synthetic filters used for first scanline to avoid needing a dummy row of 0s4555- STBI__F_avg_first,4556- STBI__F_paeth_first4643+ // synthetic filter used for first scanline to avoid needing a dummy row of 0s4644+ STBI__F_avg_first4645 };4646 4647 static stbi_uc first_row_filter[5] =4648 {4649 STBI__F_none,4650 STBI__F_sub,4651 STBI__F_none,4652 STBI__F_avg_first,4565- STBI__F_paeth_first4653+ STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub4654 };4655 4656 static int stbi__paeth(int a, int b, int c)4657 {4570- int p = a + b - c;4571- int pa = abs(p-a);4572- int pb = abs(p-b);4573- int pc = abs(p-c);4574- if (pa <= pb && pa <= pc) return a;4575- if (pb <= pc) return b;4576- return c;4658+ // This formulation looks very different from the reference in the PNG spec, but is4659+ // actually equivalent and has favorable data dependencies and admits straightforward4660+ // generation of branch-free code, which helps performance significantly.4661+ int thresh = c*3 - (a + b);4662+ int lo = a < b ? a : b;4663+ int hi = a < b ? b : a;4664+ int t0 = (hi <= thresh) ? lo : c;4665+ int t1 = (thresh <= lo) ? hi : t0;4666+ return t1;4667 }4668 4669 static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 };4670 4671+// adds an extra all-255 alpha channel4672+// dest == src is legal4673+// img_n must be 1 or 34674+static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n)4675+{4676+ int i;4677+ // must process data backwards since we allow dest==src4678+ if (img_n == 1) {4679+ for (i=x-1; i >= 0; --i) {4680+ dest[i*2+1] = 255;4681+ dest[i*2+0] = src[i];4682+ }4683+ } else {4684+ STBI_ASSERT(img_n == 3);4685+ for (i=x-1; i >= 0; --i) {4686+ dest[i*4+3] = 255;4687+ dest[i*4+2] = src[i*3+2];4688+ dest[i*4+1] = src[i*3+1];4689+ dest[i*4+0] = src[i*3+0];4690+ }4691+ }4692+}4693+4694 // create the png data from post-deflated data4695 static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)4696 {4584- int bytes = (depth == 16? 2 : 1);4697+ int bytes = (depth == 16 ? 2 : 1);4698 stbi__context *s = a->s;4699 stbi__uint32 i,j,stride = x*out_n*bytes;4700 stbi__uint32 img_len, img_width_bytes;4701+ stbi_uc *filter_buf;4702+ int all_ok = 1;4703 int k;4704 int img_n = s->img_n; // copy it into a local for later4705 4706 int output_bytes = out_n*bytes;3 unmodified lines4710 STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);4711 a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into4712 if (!a->out) return stbi__err("outofmem", "Out of memory");4713 4714+ // note: error exits here don't need to clean up a->out individually,4715+ // stbi__do_png always does on error.4716 if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG");4717 img_width_bytes = (((img_n * x * depth) + 7) >> 3);4718+ if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG");4719 img_len = (img_width_bytes + 1) * y;4720 4721 // we used to check for exact match between raw_len and img_len on non-interlaced PNGs,4722 // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros),4723 // so just check for raw_len < img_len always.4724 if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG");4725 4726+ // Allocate two scan lines worth of filter workspace buffer.4727+ filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0);4728+ if (!filter_buf) return stbi__err("outofmem", "Out of memory");4729+4730+ // Filtering for low-bit-depth images4731+ if (depth < 8) {4732+ filter_bytes = 1;4733+ width = img_width_bytes;4734+ }4735+4736 for (j=0; j < y; ++j) {4609- stbi_uc *cur = a->out + stride*j;4610- stbi_uc *prior;4737+ // cur/prior filter buffers alternate4738+ stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes;4739+ stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes;4740+ stbi_uc *dest = a->out + stride*j;4741+ int nk = width * filter_bytes;4742 int filter = *raw++;4743 4613- if (filter > 4)4614- return stbi__err("invalid filter","Corrupt PNG");4615-4616- if (depth < 8) {4617- if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG");4618- cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place4619- filter_bytes = 1;4620- width = img_width_bytes;4744+ // check filter type4745+ if (filter > 4) {4746+ all_ok = stbi__err("invalid filter","Corrupt PNG");4747+ break;4748 }4622- prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above4749 4750 // if first row, use special filter that doesn't sample previous row4751 if (j == 0) filter = first_row_filter[filter];4752 4627- // handle first byte explicitly4628- for (k=0; k < filter_bytes; ++k) {4629- switch (filter) {4630- case STBI__F_none : cur[k] = raw[k]; break;4631- case STBI__F_sub : cur[k] = raw[k]; break;4632- case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;4633- case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break;4634- case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break;4635- case STBI__F_avg_first : cur[k] = raw[k]; break;4636- case STBI__F_paeth_first: cur[k] = raw[k]; break;4637- }4753+ // perform actual filtering4754+ switch (filter) {4755+ case STBI__F_none:4756+ memcpy(cur, raw, nk);4757+ break;4758+ case STBI__F_sub:4759+ memcpy(cur, raw, filter_bytes);4760+ for (k = filter_bytes; k < nk; ++k)4761+ cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]);4762+ break;4763+ case STBI__F_up:4764+ for (k = 0; k < nk; ++k)4765+ cur[k] = STBI__BYTECAST(raw[k] + prior[k]);4766+ break;4767+ case STBI__F_avg:4768+ for (k = 0; k < filter_bytes; ++k)4769+ cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1));4770+ for (k = filter_bytes; k < nk; ++k)4771+ cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1));4772+ break;4773+ case STBI__F_paeth:4774+ for (k = 0; k < filter_bytes; ++k)4775+ cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0)4776+ for (k = filter_bytes; k < nk; ++k)4777+ cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes]));4778+ break;4779+ case STBI__F_avg_first:4780+ memcpy(cur, raw, filter_bytes);4781+ for (k = filter_bytes; k < nk; ++k)4782+ cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1));4783+ break;4784 }4785 4640- if (depth == 8) {4641- if (img_n != out_n)4642- cur[img_n] = 255; // first pixel4643- raw += img_n;4644- cur += out_n;4645- prior += out_n;4646- } else if (depth == 16) {4647- if (img_n != out_n) {4648- cur[filter_bytes] = 255; // first pixel top byte4649- cur[filter_bytes+1] = 255; // first pixel bottom byte4650- }4651- raw += filter_bytes;4652- cur += output_bytes;4653- prior += output_bytes;4654- } else {4655- raw += 1;4786+ raw += nk;4656- cur += 1;4657- prior += 1;4658- }4787 4660- // this is a little gross, so that we don't switch per-pixel or per-component4661- if (depth < 8 || img_n == out_n) {4662- int nk = (width - 1)*filter_bytes;4663- #define STBI__CASE(f) \4664- case f: \4665- for (k=0; k < nk; ++k)4666- switch (filter) {4667- // "none" filter turns into a memcpy here; make that explicit.4668- case STBI__F_none: memcpy(cur, raw, nk); break;4669- STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break;4670- STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break;4671- STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break;4672- STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break;4673- STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break;4674- STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break;4675- }4676- #undef STBI__CASE4677- raw += nk;4678- } else {4679- STBI_ASSERT(img_n+1 == out_n);4680- #define STBI__CASE(f) \4681- case f: \4682- for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \4683- for (k=0; k < filter_bytes; ++k)4684- switch (filter) {4685- STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break;4686- STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break;4687- STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break;4688- STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break;4689- STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break;4690- STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break;4691- STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break;4692- }4693- #undef STBI__CASE4694-4695- // the loop above sets the high byte of the pixels' alpha, but for4696- // 16 bit png files we also need the low byte set. we'll do that here.4697- if (depth == 16) {4698- cur = a->out + stride*j; // start at the beginning of the row again4699- for (i=0; i < x; ++i,cur+=output_bytes) {4700- cur[filter_bytes+1] = 255;4701- }4702- }4703- }4704- }4705-4706- // we make a separate pass to expand bits to pixels; for performance,4707- // this could run two scanlines behind the above code, so it won't4708- // intefere with filtering but will still be in the cache.4709- if (depth < 8) {4710- for (j=0; j < y; ++j) {4711- stbi_uc *cur = a->out + stride*j;4712- stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes;4713- // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit4714- // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop4788+ // expand decoded bits in cur to dest, also adding an extra alpha channel if desired4789+ if (depth < 8) {4790 stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range4791+ stbi_uc *in = cur;4792+ stbi_uc *out = dest;4793+ stbi_uc inb = 0;4794+ stbi__uint32 nsmp = x*img_n;4795 4717- // note that the final byte might overshoot and write more data than desired.4718- // we can allocate enough data that this never writes out of memory, but it4719- // could also overwrite the next scanline. can it overwrite non-empty data4720- // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel.4721- // so we need to explicitly clamp the final ones4722-4796+ // expand bits to bytes first4797 if (depth == 4) {4724- for (k=x*img_n; k >= 2; k-=2, ++in) {4725- *cur++ = scale * ((*in >> 4) );4726- *cur++ = scale * ((*in ) & 0x0f);4798+ for (i=0; i < nsmp; ++i) {4799+ if ((i & 1) == 0) inb = *in++;4800+ *out++ = scale * (inb >> 4);4801+ inb <<= 4;4802 }4728- if (k > 0) *cur++ = scale * ((*in >> 4) );4803 } else if (depth == 2) {4730- for (k=x*img_n; k >= 4; k-=4, ++in) {4731- *cur++ = scale * ((*in >> 6) );4732- *cur++ = scale * ((*in >> 4) & 0x03);4733- *cur++ = scale * ((*in >> 2) & 0x03);4734- *cur++ = scale * ((*in ) & 0x03);4804+ for (i=0; i < nsmp; ++i) {4805+ if ((i & 3) == 0) inb = *in++;4806+ *out++ = scale * (inb >> 6);4807+ inb <<= 2;4808 }4736- if (k > 0) *cur++ = scale * ((*in >> 6) );4737- if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03);4738- if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03);4739- } else if (depth == 1) {4740- for (k=x*img_n; k >= 8; k-=8, ++in) {4741- *cur++ = scale * ((*in >> 7) );4742- *cur++ = scale * ((*in >> 6) & 0x01);4743- *cur++ = scale * ((*in >> 5) & 0x01);4744- *cur++ = scale * ((*in >> 4) & 0x01);4745- *cur++ = scale * ((*in >> 3) & 0x01);4746- *cur++ = scale * ((*in >> 2) & 0x01);4747- *cur++ = scale * ((*in >> 1) & 0x01);4748- *cur++ = scale * ((*in ) & 0x01);4809+ } else {4810+ STBI_ASSERT(depth == 1);4811+ for (i=0; i < nsmp; ++i) {4812+ if ((i & 7) == 0) inb = *in++;4813+ *out++ = scale * (inb >> 7);4814+ inb <<= 1;4815 }4750- if (k > 0) *cur++ = scale * ((*in >> 7) );4751- if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01);4752- if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01);4753- if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01);4754- if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01);4755- if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01);4756- if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01);4816 }4758- if (img_n != out_n) {4759- int q;4760- // insert alpha = 2554761- cur = a->out + stride*j;4817+4818+ // insert alpha=255 values if desired4819+ if (img_n != out_n)4820+ stbi__create_png_alpha_expand8(dest, dest, x, img_n);4821+ } else if (depth == 8) {4822+ if (img_n == out_n)4823+ memcpy(dest, cur, x*img_n);4824+ else4825+ stbi__create_png_alpha_expand8(dest, cur, x, img_n);4826+ } else if (depth == 16) {4827+ // convert the image data from big-endian to platform-native4828+ stbi__uint16 *dest16 = (stbi__uint16*)dest;4829+ stbi__uint32 nsmp = x*img_n;4830+4831+ if (img_n == out_n) {4832+ for (i = 0; i < nsmp; ++i, ++dest16, cur += 2)4833+ *dest16 = (cur[0] << 8) | cur[1];4834+ } else {4835+ STBI_ASSERT(img_n+1 == out_n);4836 if (img_n == 1) {4763- for (q=x-1; q >= 0; --q) {4764- cur[q*2+1] = 255;4765- cur[q*2+0] = cur[q];4837+ for (i = 0; i < x; ++i, dest16 += 2, cur += 2) {4838+ dest16[0] = (cur[0] << 8) | cur[1];4839+ dest16[1] = 0xffff;4840 }4841 } else {4842 STBI_ASSERT(img_n == 3);4769- for (q=x-1; q >= 0; --q) {4770- cur[q*4+3] = 255;4771- cur[q*4+2] = cur[q*3+2];4772- cur[q*4+1] = cur[q*3+1];4773- cur[q*4+0] = cur[q*3+0];4843+ for (i = 0; i < x; ++i, dest16 += 4, cur += 6) {4844+ dest16[0] = (cur[0] << 8) | cur[1];4845+ dest16[1] = (cur[2] << 8) | cur[3];4846+ dest16[2] = (cur[4] << 8) | cur[5];4847+ dest16[3] = 0xffff;4848 }4849 }4850 }4851 }4778- } else if (depth == 16) {4779- // force the image data from big-endian to platform-native.4780- // this is done in a separate pass due to the decoding relying4781- // on the data being untouched, but could probably be done4782- // per-line during decode if care is taken.4783- stbi_uc *cur = a->out;4784- stbi__uint16 *cur16 = (stbi__uint16*)cur;4785-4786- for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) {4787- *cur16 = (cur[0] << 8) | cur[1];4788- }4852 }4853 4854+ STBI_FREE(filter_buf);4855+ if (!all_ok) return 0;4856+4857 return 1;4858 }4859 4860 static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)127 unmodified lines4988 4989 return 1;4990 }4991 4926-static int stbi__unpremultiply_on_load = 0;4927-static int stbi__de_iphone_flag = 0;4992+static int stbi__unpremultiply_on_load_global = 0;4993+static int stbi__de_iphone_flag_global = 0;4994 4995 STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)4996 {4931- stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply;4997+ stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;4998 }4999 5000 STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)5001 {4936- stbi__de_iphone_flag = flag_true_if_should_convert;5002+ stbi__de_iphone_flag_global = flag_true_if_should_convert;5003 }5004 5005+#ifndef STBI_THREAD_LOCAL5006+#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global5007+#define stbi__de_iphone_flag stbi__de_iphone_flag_global5008+#else5009+static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set;5010+static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;5011+5012+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply)5013+{5014+ stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;5015+ stbi__unpremultiply_on_load_set = 1;5016+}5017+5018+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert)5019+{5020+ stbi__de_iphone_flag_local = flag_true_if_should_convert;5021+ stbi__de_iphone_flag_set = 1;5022+}5023+5024+#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \5025+ ? stbi__unpremultiply_on_load_local \5026+ : stbi__unpremultiply_on_load_global)5027+#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \5028+ ? stbi__de_iphone_flag_local \5029+ : stbi__de_iphone_flag_global)5030+#endif // STBI_THREAD_LOCAL5031+5032 static void stbi__de_iphone(stbi__png *z)5033 {5034 stbi__context *s = z->s;5035 stbi__uint32 i, pixel_count = s->img_x * s->img_y;81 unmodified lines5117 if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");5118 if (!pal_img_n) {5119 s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);5120 if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");5028- if (scan == STBI__SCAN_header) return 1;5121 } else {5122 // if paletted, then pal_n is our final components, and5123 // img_n is # components to decompress/filter.5124 s->img_n = 1;5125 if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");5034- // if SCAN_header, have to scan to see if we have a tRNS5126 }5127+ // even with SCAN_header, have to scan to see if we have a tRNS5128 break;5129 }5130 5131 case STBI__PNG_TYPE('P','L','T','E'): {23 unmodified lines5155 } else {5156 if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");5157 if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");5158 has_trans = 1;5159+ // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now.5160+ if (scan == STBI__SCAN_header) { ++s->img_n; return 1; }5161 if (z->depth == 16) {5162 for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is5163 } else {5164 for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger4 unmodified lines5169 5170 case STBI__PNG_TYPE('I','D','A','T'): {5171 if (first) return stbi__err("first not IHDR", "Corrupt PNG");5172 if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");5079- if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; }5173+ if (scan == STBI__SCAN_header) {5174+ // header scan definitely stops at first IDAT5175+ if (pal_img_n)5176+ s->img_n = pal_img_n;5177+ return 1;5178+ }5179+ if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes");5180 if ((int)(ioff + c.length) < (int)ioff) return 0;5181 if (ioff + c.length > idata_limit) {5182 stbi__uint32 idata_limit_old = idata_limit;5183 stbi_uc *p;231 unmodified lines5415 unsigned int mr,mg,mb,ma, all_a;5416 int extra_read;5417 } stbi__bmp_data;5418 5419+static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress)5420+{5421+ // BI_BITFIELDS specifies masks explicitly, don't override5422+ if (compress == 3)5423+ return 1;5424+5425+ if (compress == 0) {5426+ if (info->bpp == 16) {5427+ info->mr = 31u << 10;5428+ info->mg = 31u << 5;5429+ info->mb = 31u << 0;5430+ } else if (info->bpp == 32) {5431+ info->mr = 0xffu << 16;5432+ info->mg = 0xffu << 8;5433+ info->mb = 0xffu << 0;5434+ info->ma = 0xffu << 24;5435+ info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 05436+ } else {5437+ // otherwise, use defaults, which is all-05438+ info->mr = info->mg = info->mb = info->ma = 0;5439+ }5440+ return 1;5441+ }5442+ return 0; // error5443+}5444+5445 static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)5446 {5447 int hsz;5448 if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");19 unmodified lines5468 info->bpp = stbi__get16le(s);5469 if (hsz != 12) {5470 int compress = stbi__get32le(s);5471 if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");5472+ if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes5473+ if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel5474 stbi__get32le(s); // discard sizeof5475 stbi__get32le(s); // discard hres5476 stbi__get32le(s); // discard vres5477 stbi__get32le(s); // discard colorsused6 unmodified lines5484 stbi__get32le(s);5485 }5486 if (info->bpp == 16 || info->bpp == 32) {5487 if (compress == 0) {5360- if (info->bpp == 32) {5361- info->mr = 0xffu << 16;5362- info->mg = 0xffu << 8;5363- info->mb = 0xffu << 0;5364- info->ma = 0xffu << 24;5365- info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 05366- } else {5367- info->mr = 31u << 10;5368- info->mg = 31u << 5;5369- info->mb = 31u << 0;5370- }5488+ stbi__bmp_set_mask_defaults(info, compress);5489 } else if (compress == 3) {5490 info->mr = stbi__get32le(s);5491 info->mg = stbi__get32le(s);5492 info->mb = stbi__get32le(s);6 unmodified lines5499 } else5500 return stbi__errpuc("bad BMP", "bad BMP");5501 }5502 } else {5503+ // V4/V5 header5504 int i;5505 if (hsz != 108 && hsz != 124)5506 return stbi__errpuc("bad BMP", "bad BMP");5507 info->mr = stbi__get32le(s);5508 info->mg = stbi__get32le(s);5509 info->mb = stbi__get32le(s);5510 info->ma = stbi__get32le(s);5511+ if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs5512+ stbi__bmp_set_mask_defaults(info, compress);5513 stbi__get32le(s); // discard color space5514 for (i=0; i < 12; ++i)5515 stbi__get32le(s); // discard color space parameters5516 if (hsz == 124) {41 unmodified lines5558 if (info.bpp < 16)5559 psize = (info.offset - info.extra_read - info.hsz) >> 2;5560 }5561 if (psize == 0) {5441- if (info.offset != s->callback_already_read + (s->img_buffer - s->img_buffer_original)) {5442- return stbi__errpuc("bad offset", "Corrupt BMP");5562+ // accept some number of extra bytes after the header, but if the offset points either to before5563+ // the header ends or implies a large amount of extra data, reject the file as malformed5564+ int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original);5565+ int header_limit = 1024; // max we actually read is below 256 bytes currently.5566+ int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size.5567+ if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) {5568+ return stbi__errpuc("bad header", "Corrupt BMP");5569 }5570+ // we established that bytes_read_so_far is positive and sensible.5571+ // the first half of this test rejects offsets that are either too small positives, or5572+ // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn5573+ // ensures the number computed in the second half of the test can't overflow.5574+ if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) {5575+ return stbi__errpuc("bad offset", "Corrupt BMP");5576+ } else {5577+ stbi__skip(s, info.offset - bytes_read_so_far);5578+ }5579 }5580 5581 if (info.bpp == 24 && ma == 0xff000000)5582 s->img_n = 3;1413 unmodified lines6996 out_size = layers * stride;6997 }6998 6999 if (delays) {6865- *delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers );6866- if (!*delays)7000+ int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers );7001+ if (!new_delays)7002 return stbi__load_gif_main_outofmem(&g, out, delays);7003+ *delays = new_delays;7004 delays_size = layers * sizeof(int);7005 }7006 } else {7007 out = (stbi_uc*)stbi__malloc( layers * stride );253 unmodified lines7261 if (count > 128) {7262 // Run7263 value = stbi__get8(s);7264 count -= 128;7129- if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }7265+ if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }7266 for (z = 0; z < count; ++z)7267 scanline[i++ * 4 + k] = value;7268 } else {7269 // Dump7134- if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }7270+ if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }7271 for (z = 0; z < count; ++z)7272 scanline[i++ * 4 + k] = stbi__get8(s);7273 }7274 }60 unmodified lines7335 stbi__bmp_data info;7336 7337 info.all_a = 255;7338 p = stbi__bmp_parse_header(s, &info);7203- stbi__rewind( s );7204- if (p == NULL)7339+ if (p == NULL) {7340+ stbi__rewind( s );7341 return 0;7342+ }7343 if (x) *x = s->img_x;7344 if (y) *y = s->img_y;7345 if (comp) {7346 if (info.bpp == 24 && info.ma == 0xff000000)173 unmodified lines7520 return stbi__errpuc("too large", "PNM too large");7521 7522 out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0);7523 if (!out) return stbi__errpuc("outofmem", "Out of memory");7387- stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8));7524+ if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) {7525+ STBI_FREE(out);7526+ return stbi__errpuc("bad PNM", "PNM file truncated");7527+ }7528 7529 if (req_comp && req_comp != s->img_n) {7530+ if (ri->bits_per_channel == 16) {7531+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y);7532+ } else {7390- out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);7533+ out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);7534+ }7535 if (out == NULL) return out; // stbi__convert_format frees input on failure7536 }7537 return out;7538 }28 unmodified lines7567 7568 while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) {7569 value = value*10 + (*c - '0');7570 *c = (char) stbi__get8(s);7571+ if((value > 214748364) || (value == 214748364 && *c > '7'))7572+ return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int");7573 }7574 7575 return value;7576 }22 unmodified lines7599 c = (char) stbi__get8(s);7600 stbi__pnm_skip_whitespace(s, &c);7601 7602 *x = stbi__pnm_getinteger(s, &c); // read width7603+ if(*x == 0)7604+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");7605 stbi__pnm_skip_whitespace(s, &c);7606 7607 *y = stbi__pnm_getinteger(s, &c); // read height7608+ if (*y == 0)7609+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");7610 stbi__pnm_skip_whitespace(s, &c);7611 7612 maxv = stbi__pnm_getinteger(s, &c); // read max value7613 if (maxv > 65535)9 unmodified lines7623 if (stbi__pnm_info(s, NULL, NULL, NULL) == 16)7624 return 1;7625 return 0;7626 }7477-7627 #endif7628 7629 static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)7630 {355 unmodified linesmodified:stb_rect_pack.hnot shown
Its text is not shown, modified.
modified:stb_sprintf.hnot shown
Its text is not shown, modified.
modified:stb_textedit.hnot shown
Its text is not shown, modified.
modified:stb_tilemap_editor.hnot shown
Its text is not shown, modified.
modified:stb_truetype.hnot shown
Its text is not shown, modified.
modified:stb_vorbis.cnot shown
Its text is not shown, modified.