aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


tools/client/png_benchmark/decoder.c (2322B)


      1 #include <png.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 #include <emscripten.h>
      5 
      6 struct input { const unsigned char *data; size_t size; };
      7 static void read_data(png_structp png, png_bytep output, png_size_t size) {
      8     struct input *input = png_get_io_ptr(png);
      9     if (size > input->size) png_error(png, "truncated PNG");
     10     memcpy(output, input->data, size);
     11     input->data += size;
     12     input->size -= size;
     13 }
     14 static unsigned result[4];
     15 EMSCRIPTEN_KEEPALIVE unsigned *decode(const unsigned char *data, unsigned size) {
     16     png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
     17     png_infop info = png_create_info_struct(png);
     18     struct input input = {data, size};
     19     if (setjmp(png_jmpbuf(png))) { png_destroy_read_struct(&png, &info, NULL); return NULL; }
     20     png_set_read_fn(png, &input, read_data);
     21     png_read_info(png, info);
     22     int depth = png_get_bit_depth(png, info);
     23     int color = png_get_color_type(png, info);
     24     if (depth < 8) png_set_packing(png);
     25     if (color == PNG_COLOR_TYPE_GRAY && depth < 8) png_set_expand(png);
     26     if (depth == 16) png_set_strip_16(png);
     27     png_set_bgr(png);
     28     png_set_interlace_handling(png);
     29     png_read_update_info(png, info);
     30     unsigned width = png_get_image_width(png, info), height = png_get_image_height(png, info);
     31     unsigned rowbytes = png_get_rowbytes(png, info);
     32     unsigned char *pixels = malloc(rowbytes * height);
     33     png_bytep *rows = malloc(height * sizeof(*rows));
     34     for (unsigned y = 0; y < height; ++y) rows[y] = pixels + y * rowbytes;
     35     png_read_image(png, rows);
     36     png_read_end(png, NULL);
     37     result[0] = width; result[1] = height; result[2] = rowbytes * 8 / width;
     38     result[3] = (unsigned)pixels;
     39     free(rows);
     40     png_destroy_read_struct(&png, &info, NULL);
     41     return result;
     42 }
     43 
     44 /* Browser readback is RGBA; the guest expects packed BGR or BGRA. */
     45 EMSCRIPTEN_KEEPALIVE void pack_pixels(unsigned char *pixels, unsigned count, unsigned channels) {
     46     for (unsigned i = 0; i < count; ++i) {
     47         unsigned char r = pixels[i * 4], g = pixels[i * 4 + 1];
     48         unsigned char b = pixels[i * 4 + 2], a = pixels[i * 4 + 3];
     49         pixels[i * channels] = b;
     50         pixels[i * channels + 1] = g;
     51         pixels[i * channels + 2] = r;
     52         if (channels == 4) pixels[i * channels + 3] = a;
     53     }
     54 }