AtlatestRepositorysigil-image
sigil-image / tree / nativeimage.c
1
/* Memory-only STB codec. No windowing, GPU or filesystem dependencies. */2
#include "sigil-internal.h"3
#include <stdlib.h>4
#include <string.h>5
#define STBI_ONLY_PNG6
#define STBI_ONLY_JPEG7
#define STBI_NO_STDIO8
#define STBI_MAX_DIMENSIONS 81929
#define STB_IMAGE_STATIC10
#define STB_IMAGE_IMPLEMENTATION11
#include "stb_image.h"12
#define STBI_WRITE_NO_STDIO13
#define STB_IMAGE_WRITE_STATIC14
#define STB_IMAGE_WRITE_IMPLEMENTATION15
#include "stb_image_write.h"17
static Value raster_png(SigilVM *vm, int argc, Value *args) {18
(void)argc;19
if (!sigil_is_fixnum(args[1]) || !sigil_is_fixnum(args[2]) || !sigil_is_fixnum(args[3])) return SIGIL_FALSE;20
int side = (int)sigil_as_fixnum(args[1]);21
int pixels_limit = (int)sigil_as_fixnum(args[2]);22
int input_limit = (int)sigil_as_fixnum(args[3]);23
if (side < 1 || side > 8192 || pixels_limit < 1 || pixels_limit > 16777216 || input_limit < 1 || input_limit > 16777216) return SIGIL_FALSE;24
if (!sigil_is_bytevector(args[0])) return SIGIL_FALSE;25
SigilBytevector *input = (SigilBytevector *)sigil_as_ptr(args[0]);26
if (input->length == 0 || input->length > (size_t)input_limit) return SIGIL_FALSE;27
int width, height, channels;28
if (!stbi_info_from_memory(input->data, (int)input->length, &width, &height, &channels)29
|| width <= 0 || height <= 0 || width > side || height > side30
|| (size_t)width * (size_t)height > (size_t)pixels_limit) return SIGIL_FALSE;31
unsigned char *pixels = stbi_load_from_memory(input->data, (int)input->length,32
&width, &height, &channels, 4);33
if (!pixels) return SIGIL_FALSE;34
int size = 0;35
unsigned char *png = stbi_write_png_to_mem(pixels, width * 4, width, height, 4, &size);36
stbi_image_free(pixels);37
if (!png) return SIGIL_FALSE;38
if (size <= 0 || size > 80 * 1024 * 1024) { STBIW_FREE(png); return SIGIL_FALSE; }39
Value result = sigil_make_bytevector(vm, (size_t)size);40
if (sigil_is_bytevector(result)) memcpy(sigil_bytevector_data(result), png, (size_t)size);41
STBIW_FREE(png);42
return result;43
}45
void sigil__init_sigil_image_module(SigilVM *vm) {46
SigilModule *module = sigil_begin_module(vm, "(sigil image native)");47
if (!module) return;48
sigil_module_register_native(vm, "normalize-png-bytes", raster_png, SIGIL_ARITY_EXACT(4),49
"Decode bounded PNG/JPEG bytes and encode a metadata-free PNG.");50
sigil_module_export(vm, "normalize-png-bytes");51
sigil_end_module(vm);52
}