Compare commits

...

38 Commits

Author SHA1 Message Date
Paul Kinlan
f77cd9b61f Fixes #766 - Spacial -> Spatial 2020-07-02 10:37:18 +01:00
Surma
6ad28c0b5c Merge pull request #765 from petele/dimension 2020-06-24 16:15:16 +01:00
Surma
c76dabf063 Merge branch 'dev' into dimension 2020-06-24 16:12:59 +01:00
Surma
e6d8bac9c5 Merge pull request #764 from petele/install-prompt 2020-06-24 16:12:48 +01:00
Jake Archibald
42e43730c8 Naming changes 2020-06-24 15:16:38 +01:00
Jake Archibald
5c17fba349 Minor tweaks 2020-06-24 15:12:48 +01:00
Pete LePage
85eb94b725 Set the dimension value 2020-06-24 09:54:54 -04:00
Pete LePage
4fa73be842 Apply suggestions from code review
Co-authored-by: Surma <surma@surma.dev>
2020-06-24 09:40:56 -04:00
Surma
7c89d09139 Add missing prop to navigator 2020-06-24 14:08:52 +01:00
Pete LePage
079e56f1e1 Use a dimension to note how the user opened squoosh 2020-06-23 16:34:47 -04:00
Pete LePage
6065ceabfe update readme 2020-06-23 16:16:32 -04:00
Pete LePage
265e6db2bd Adds install button to Squoosh 2020-06-23 16:10:40 -04:00
Surma
3a5c0aa30c Merge pull request #757 from GoogleChromeLabs/fixup-clang-format 2020-05-14 17:02:50 +01:00
Ingvar Stepanyan
f0c3ec9d51 Fixup clang-format
I've actually comitted files formatted with column limit of 100, but forgot to include updated .clang-format 🤦🏻‍♂️
2020-05-14 16:30:12 +01:00
Ingvar Stepanyan
1ae93b527c Revert docker run --rm change 2020-05-13 19:39:27 +01:00
Ingvar Stepanyan
a95cb740bf Format C / C++ with Chromium style 2020-05-13 19:39:27 +01:00
Ingvar Stepanyan
de543b3206 Further speed improvements
- Store Emscripten cache inside node_modules/.em_cache. Docker image ships without LTO libs, so Emscripten has to rebuild stdlibs on every build otherwise.
 - Merge webp_enc + webp_dec build scripts. Core libwebp library is same in both cases, so there's no point in storing and building two copies of it.
2020-05-13 19:39:27 +01:00
Ingvar Stepanyan
1542bfb7fd Tweak up compile flags
- Remove unnecessary `-x c++`.
 - Improve rebuild speed by caching:
   - Remove `-f` from `autoreconf` to reuse generated configure scripts.
   - Remove `--rm` from `docker run` to avoid rebuilding Emscripten stdlib.
   - Add `-C` to `./configure` to reuse stored information about `emcc`.
   - Remove `rm -rf build` from WebP encoder/decoder.
2020-05-13 19:39:27 +01:00
Ingvar Stepanyan
bc8d75128f Remove libpng-dev dependency from WebP (#752)
It's unnecessary as we disable PNG support via ./configure anyway.

Co-authored-by: Surma <surma@surma.dev>
2020-05-05 13:23:12 +01:00
Ingvar Stepanyan
d3252bb1bb Add LTO for C++ builds (#755)
* Add LTO for C++ builds

This didn't have much effect on fastcomp builds, but provides further size savings with new LLVM backend we switched to in #750 (and fixes the MozJPEG size regression from the same PR).

In the future we won't need to pass `--llvm-lto 1` explicitly, but latest Emscripten Docker image doesn't contain the Emscripten version with the necessary fixes for this.

* Delete build.log

Co-authored-by: Jake Archibald <jaffathecake@gmail.com>
2020-05-05 11:54:28 +01:00
Surma
83d9d2c764 Disable renovate 2020-05-05 11:19:40 +01:00
Surma
476268fe19 Merge pull request #748 from GoogleChromeLabs/cleanup 2020-05-01 17:21:37 +01:00
Ingvar Stepanyan
74492af675 Merge branch 'master' into cleanup 2020-05-01 17:08:08 +01:00
Surma
bd4179aff2 Merge pull request #751 from GoogleChromeLabs/make-j 2020-05-01 16:48:45 +01:00
Ingvar Stepanyan
27ae47117e Leverage make -j to parallelise C++ builds
We've been running each Make command in a single thread, resulting in fairly slow builds for C++ codecs.

This change instead runs all `make` invocations with `-j` defaulting to number of cores (retrieved via `nproc`).

On my machine Docker uses a VM configured to 4 cores out of 8 available. This change brings total build time for C++ codecs down from 10m28s to 7m5s (~3.5 minutes difference).

Note (1): I've converted imagequant builds to use built-in `make` as well to leverage this parallelisation and future-proof build script.
Note (2): we don't need to do the same for Rust, since Cargo parallelises builds by default.
2020-05-01 16:42:41 +01:00
Ingvar Stepanyan
7da3f07333 Switch to Emscripten upstream
Looks like we've been stuck on Emscripten fastcomp backend, misssing out on all new optimisations between LLVM 6 and LLVM 11 and going via slow asm.js pipeline when building.

This changes Docker images for Emscripten projects to point to emscripten-upstream instead and commits the updated artifacts.
2020-05-01 15:00:10 +01:00
Surma
ed666dd381 Merge pull request #749 from GoogleChromeLabs/oxipng-update
Limit OxiPNG levels
2020-04-21 00:21:28 +01:00
Ingvar Stepanyan
6f18f08a8e Disable logging statically in OxiPNG
This was a no-op in Wasm anyway. Now that I've added ability to control logging upstream, let's use it to disable it from compiled unit altogether for a slight win in size and perf.
2020-04-20 13:54:21 +01:00
Ingvar Stepanyan
eae808cb6f Limit max level
With libdeflate, any OxiPNG level above 3 is equivalent to 3, so don't show them anymore.
2020-04-20 13:48:56 +01:00
Ingvar Stepanyan
0ae99c9228 Remove obsolete worker termination
I switched build process to proper ES modules back in #672, so, if the TODO is correct, this is no longer necessary.
2020-04-17 14:41:04 +01:00
Surma
ae7782031d Merge pull request #746 from GoogleChromeLabs/fix-oxipng-free
Fix and document allocation shim for OxiPNG
2020-04-16 20:06:46 +01:00
Ingvar Stepanyan
7cd6487a28 Fix and document allocation shim for OxiPNG 2020-04-16 19:34:28 +01:00
Surma
f3dfcae3f0 Merge pull request #730 from kripken/closure2
Closure all the things
2020-04-16 11:11:15 +01:00
Alon Zakai
3f7274a6ac update builds using docker 2020-04-15 13:38:09 -07:00
Alon Zakai
f5bc715bc0 Merge remote-tracking branch 'upstream/master' into closure2 2020-04-15 13:25:00 -07:00
Alon Zakai
d7fb0d9b40 Remove unneeded compile flags from imagequant 2020-02-28 13:03:51 -08:00
Alon Zakai
309947a08f Merge branch 'master' into closure2 2020-02-27 09:45:46 -08:00
Alon Zakai
6aeaae6160 Closure all the things 2020-02-27 09:44:28 -08:00
50 changed files with 713 additions and 1577 deletions

2
.clang-format Normal file
View File

@@ -0,0 +1,2 @@
BasedOnStyle: Chromium
ColumnLimit: 100

View File

@@ -10,6 +10,7 @@ Google Analytics is used to record the following:
* [Basic visit data](https://support.google.com/analytics/answer/6004245?ref_topic=2919631).
* Before and after image size once an image is downloaded. These values are rounded to the nearest
kilobyte.
* If install is available, when Squoosh is installed, and what method was used to install Squoosh.
Image compression is handled locally; no additional data is sent to the server.

View File

@@ -2,7 +2,8 @@
set -e
export OPTIMIZE="-Os"
export EM_CACHE="${PWD}/node_modules/.em_cache"
export OPTIMIZE="-Os -flto --llvm-lto 1"
export LDFLAGS="${OPTIMIZE}"
export CFLAGS="${OPTIMIZE}"
export CPPFLAGS="${OPTIMIZE}"
@@ -11,16 +12,9 @@ echo "============================================="
echo "Compiling libimagequant"
echo "============================================="
(
emcc \
--bind \
${OPTIMIZE} \
-s ALLOW_MEMORY_GROWTH=1 \
-s MODULARIZE=1 \
-s 'EXPORT_NAME="imagequant"' \
-I node_modules/libimagequant \
--std=c99 \
-c \
node_modules/libimagequant/{libimagequant,pam,mediancut,blur,mempool,kmeans,nearest}.c
cd node_modules/libimagequant
emconfigure ./configure --disable-sse
emmake make static -j`nproc`
)
echo "============================================="
echo "Compiling wasm module"
@@ -29,14 +23,15 @@ echo "============================================="
emcc \
--bind \
${OPTIMIZE} \
--closure 1 \
-s ALLOW_MEMORY_GROWTH=1 \
-s MODULARIZE=1 \
-s 'EXPORT_NAME="imagequant"' \
-I node_modules/libimagequant \
-o ./imagequant.js \
--std=c++11 *.o \
-x c++ \
imagequant.cpp
--std=c++11 \
imagequant.cpp \
node_modules/libimagequant/libimagequant.a
)
echo "============================================="
echo "Compiling wasm module done"
@@ -44,5 +39,5 @@ echo "============================================="
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "Did you update your docker image?"
echo "Run \`docker pull trzeci/emscripten\`"
echo "Run \`docker pull trzeci/emscripten-upstream\`"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

View File

@@ -1,36 +1,37 @@
#include "emscripten/bind.h"
#include "emscripten/val.h"
#include <stdlib.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include "libimagequant.h"
using namespace emscripten;
int version() {
return (((LIQ_VERSION/10000) % 100) << 16) |
(((LIQ_VERSION/100 ) % 100) << 8) |
(((LIQ_VERSION/1 ) % 100) << 0);
return (((LIQ_VERSION / 10000) % 100) << 16) | (((LIQ_VERSION / 100) % 100) << 8) |
(((LIQ_VERSION / 1) % 100) << 0);
}
class RawImage {
public:
public:
val buffer;
int width;
int height;
RawImage(val b, int w, int h)
: buffer(b), width(w), height(h) {}
RawImage(val b, int w, int h) : buffer(b), width(w), height(h) {}
};
liq_attr *attr;
liq_image *image;
liq_result *res;
liq_attr* attr;
liq_image* image;
liq_result* res;
uint8_t* result;
RawImage quantize(std::string rawimage, int image_width, int image_height, int num_colors, float dithering) {
RawImage quantize(std::string rawimage,
int image_width,
int image_height,
int num_colors,
float dithering) {
const uint8_t* image_buffer = (uint8_t*)rawimage.c_str();
int size = image_width * image_height;
attr = liq_attr_create();
@@ -38,12 +39,12 @@ RawImage quantize(std::string rawimage, int image_width, int image_height, int n
liq_set_max_colors(attr, num_colors);
liq_image_quantize(image, attr, &res);
liq_set_dithering_level(res, dithering);
uint8_t* image8bit = (uint8_t*) malloc(size);
result = (uint8_t*) malloc(size * 4);
uint8_t* image8bit = (uint8_t*)malloc(size);
result = (uint8_t*)malloc(size * 4);
liq_write_remapped_image(res, image, image8bit, size);
const liq_palette *pal = liq_get_palette(res);
const liq_palette* pal = liq_get_palette(res);
// Turn palletted image back into an RGBA image
for(int i = 0; i < size; i++) {
for (int i = 0; i < size; i++) {
result[i * 4 + 0] = pal->entries[image8bit[i]].r;
result[i * 4 + 1] = pal->entries[image8bit[i]].g;
result[i * 4 + 2] = pal->entries[image8bit[i]].b;
@@ -53,43 +54,41 @@ RawImage quantize(std::string rawimage, int image_width, int image_height, int n
liq_result_destroy(res);
liq_image_destroy(image);
liq_attr_destroy(attr);
return {
val(typed_memory_view(image_width*image_height*4, result)),
image_width,
image_height
};
return {val(typed_memory_view(image_width * image_height * 4, result)), image_width,
image_height};
}
const liq_color zx_colors[] = {
{.a = 255, .r = 0, .g = 0, .b = 0}, // regular black
{.a = 255, .r = 0, .g = 0, .b = 215}, // regular blue
{.a = 255, .r = 215, .g = 0, .b = 0}, // regular red
{.a = 255, .r = 215, .g = 0, .b = 215}, // regular magenta
{.a = 255, .r = 0, .g = 215, .b = 0}, // regular green
{.a = 255, .r = 0, .g = 215, .b = 215}, // regular cyan
{.a = 255, .r = 215, .g = 215, .b = 0}, // regular yellow
{.a = 255, .r = 215, .g = 215, .b = 215}, // regular white
{.a = 255, .r = 0, .g = 0, .b = 255}, // bright blue
{.a = 255, .r = 255, .g = 0, .b = 0}, // bright red
{.a = 255, .r = 255, .g = 0, .b = 255}, // bright magenta
{.a = 255, .r = 0, .g = 255, .b = 0}, // bright green
{.a = 255, .r = 0, .g = 255, .b = 255}, // bright cyan
{.a = 255, .r = 255, .g = 255, .b = 0}, // bright yellow
{.a = 255, .r = 255, .g = 255, .b = 255} // bright white
{.r = 0, .g = 0, .b = 0, .a = 255}, // regular black
{.r = 0, .g = 0, .b = 215, .a = 255}, // regular blue
{.r = 215, .g = 0, .b = 0, .a = 255}, // regular red
{.r = 215, .g = 0, .b = 215, .a = 255}, // regular magenta
{.r = 0, .g = 215, .b = 0, .a = 255}, // regular green
{.r = 0, .g = 215, .b = 215, .a = 255}, // regular cyan
{.r = 215, .g = 215, .b = 0, .a = 255}, // regular yellow
{.r = 215, .g = 215, .b = 215, .a = 255}, // regular white
{.r = 0, .g = 0, .b = 255, .a = 255}, // bright blue
{.r = 255, .g = 0, .b = 0, .a = 255}, // bright red
{.r = 255, .g = 0, .b = 255, .a = 255}, // bright magenta
{.r = 0, .g = 255, .b = 0, .a = 255}, // bright green
{.r = 0, .g = 255, .b = 255, .a = 255}, // bright cyan
{.r = 255, .g = 255, .b = 0, .a = 255}, // bright yellow
{.r = 255, .g = 255, .b = 255, .a = 255} // bright white
};
uint8_t block[8 * 8 * 4];
/**
* The ZX has one bit per pixel, but can assign two colours to an 8x8 block. The two colours must
* both be 'regular' or 'bright'. Black exists as both regular and bright.
* The ZX has one bit per pixel, but can assign two colours to an 8x8 block. The
* two colours must both be 'regular' or 'bright'. Black exists as both regular
* and bright.
*/
RawImage zx_quantize(std::string rawimage, int image_width, int image_height, float dithering) {
const uint8_t* image_buffer = (uint8_t*) rawimage.c_str();
const uint8_t* image_buffer = (uint8_t*)rawimage.c_str();
int size = image_width * image_height;
int bytes_per_pixel = 4;
result = (uint8_t*) malloc(size * bytes_per_pixel);
uint8_t* image8bit = (uint8_t*) malloc(8 * 8);
result = (uint8_t*)malloc(size * bytes_per_pixel);
uint8_t* image8bit = (uint8_t*)malloc(8 * 8);
// For each 8x8 grid
for (int block_start_y = 0; block_start_y < image_height; block_start_y += 8) {
@@ -99,7 +98,8 @@ RawImage zx_quantize(std::string rawimage, int image_width, int image_height, fl
int block_width = 8;
int block_height = 8;
// If the block hangs off the right/bottom of the image dimensions, make it smaller to fit.
// If the block hangs off the right/bottom of the image dimensions, make
// it smaller to fit.
if (block_start_y + block_height > image_height) {
block_height = image_height - block_start_y;
}
@@ -125,12 +125,11 @@ RawImage zx_quantize(std::string rawimage, int image_width, int image_height, fl
for (int color_index = 0; color_index < 15; color_index++) {
liq_color color = zx_colors[color_index];
// Using Euclidean distance. LibQuant has better methods, but it requires conversion to
// LAB, so I don't think it's worth it.
int distance =
pow(color.r - image_buffer[pixel_start + 0], 2) +
pow(color.g - image_buffer[pixel_start + 1], 2) +
pow(color.b - image_buffer[pixel_start + 2], 2);
// Using Euclidean distance. LibQuant has better methods, but it
// requires conversion to LAB, so I don't think it's worth it.
int distance = pow(color.r - image_buffer[pixel_start + 0], 2) +
pow(color.g - image_buffer[pixel_start + 1], 2) +
pow(color.b - image_buffer[pixel_start + 2], 2);
if (distance < smallest_distance) {
winning_index = color_index;
@@ -151,7 +150,8 @@ RawImage zx_quantize(std::string rawimage, int image_width, int image_height, fl
for (int color_index = 0; color_index < 15; color_index++) {
if (color_popularity[color_index] > highest_popularity) {
// Store this as the most popular pixel, and demote the current values:
// Store this as the most popular pixel, and demote the current
// values:
third_color_index = second_color_index;
third_highest_popularity = second_highest_popularity;
second_color_index = first_color_index;
@@ -169,8 +169,8 @@ RawImage zx_quantize(std::string rawimage, int image_width, int image_height, fl
}
}
// ZX images can't mix bright and regular colours, except black which appears in both.
// Resolve any conflict:
// ZX images can't mix bright and regular colours, except black which
// appears in both. Resolve any conflict:
while (1) {
// If either colour is black, there's no conflict to resolve.
if (first_color_index != 0 && second_color_index != 0) {
@@ -183,12 +183,13 @@ RawImage zx_quantize(std::string rawimage, int image_width, int image_height, fl
}
}
// If, during conflict resolving, we now have two of the same colour (because we initially
// selected the bright & regular version of the same colour), retry again with the third
// most popular colour.
// If, during conflict resolving, we now have two of the same colour
// (because we initially selected the bright & regular version of the
// same colour), retry again with the third most popular colour.
if (first_color_index == second_color_index) {
second_color_index = third_color_index;
} else break;
} else
break;
}
// Quantize
@@ -200,13 +201,15 @@ RawImage zx_quantize(std::string rawimage, int image_width, int image_height, fl
liq_image_quantize(image, attr, &res);
liq_set_dithering_level(res, dithering);
liq_write_remapped_image(res, image, image8bit, size);
const liq_palette *pal = liq_get_palette(res);
const liq_palette* pal = liq_get_palette(res);
// Turn palletted image back into an RGBA image, and write it into the full size result image.
for(int y = 0; y < block_height; y++) {
for(int x = 0; x < block_width; x++) {
// Turn palletted image back into an RGBA image, and write it into the
// full size result image.
for (int y = 0; y < block_height; y++) {
for (int x = 0; x < block_width; x++) {
int image8BitPos = y * block_width + x;
int resultStartPos = ((block_start_y + y) * bytes_per_pixel * image_width) + ((block_start_x + x) * bytes_per_pixel);
int resultStartPos = ((block_start_y + y) * bytes_per_pixel * image_width) +
((block_start_x + x) * bytes_per_pixel);
result[resultStartPos + 0] = pal->entries[image8bit[image8BitPos]].r;
result[resultStartPos + 1] = pal->entries[image8bit[image8BitPos]].g;
result[resultStartPos + 2] = pal->entries[image8bit[image8BitPos]].b;
@@ -221,11 +224,8 @@ RawImage zx_quantize(std::string rawimage, int image_width, int image_height, fl
}
free(image8bit);
return {
val(typed_memory_view(image_width*image_height*4, result)),
image_width,
image_height
};
return {val(typed_memory_view(image_width * image_height * 4, result)), image_width,
image_height};
}
void free_result() {
@@ -234,9 +234,9 @@ void free_result() {
EMSCRIPTEN_BINDINGS(my_module) {
class_<RawImage>("RawImage")
.property("buffer", &RawImage::buffer)
.property("width", &RawImage::width)
.property("height", &RawImage::height);
.property("buffer", &RawImage::buffer)
.property("width", &RawImage::width)
.property("height", &RawImage::height);
function("quantize", &quantize);
function("zx_quantize", &zx_quantize);

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -2,7 +2,7 @@
"name": "imagequant",
"scripts": {
"install": "napa",
"build": "docker run --rm -v $(pwd):/src trzeci/emscripten ./build.sh"
"build": "docker run --rm -v $(pwd):/src trzeci/emscripten-upstream ./build.sh"
},
"napa": {
"libimagequant": "ImageOptim/libimagequant#2.12.1"

View File

@@ -2,7 +2,8 @@
set -e
export OPTIMIZE="-Os"
export EM_CACHE="${PWD}/node_modules/.em_cache"
export OPTIMIZE="-Os -flto --llvm-lto 1"
export LDFLAGS="${OPTIMIZE}"
export CFLAGS="${OPTIMIZE}"
export CPPFLAGS="${OPTIMIZE}"
@@ -15,9 +16,9 @@ echo "Compiling mozjpeg"
echo "============================================="
(
cd node_modules/mozjpeg
autoreconf -fiv
emconfigure ./configure --without-simd
emmake make libjpeg.la
autoreconf -iv
emconfigure ./configure -C --without-simd
emmake make libjpeg.la rdswitch.o -j`nproc`
)
echo "============================================="
echo "Compiling mozjpeg done"
@@ -30,18 +31,16 @@ echo "============================================="
emcc \
--bind \
${OPTIMIZE} \
-s WASM=1 \
--closure 1 \
-s ALLOW_MEMORY_GROWTH=1 \
-s MODULARIZE=1 \
-s 'EXPORT_NAME="mozjpeg_enc"' \
-I node_modules/mozjpeg \
-o ./mozjpeg_enc.js \
-Wno-deprecated-register \
-Wno-writable-strings \
node_modules/mozjpeg/rdswitch.c \
-x c++ -std=c++11 \
-std=c++11 \
mozjpeg_enc.cpp \
node_modules/mozjpeg/.libs/libjpeg.a
node_modules/mozjpeg/.libs/libjpeg.a \
node_modules/mozjpeg/rdswitch.o
)
echo "============================================="
echo "Compiling wasm bindings done"
@@ -49,5 +48,5 @@ echo "============================================="
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "Did you update your docker image?"
echo "Run \`docker pull trzeci/emscripten\`"
echo "Run \`docker pull trzeci/emscripten-upstream\`"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

View File

@@ -1,18 +1,22 @@
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdio.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "jpeglib.h"
extern "C" {
#include "cdjpeg.h"
}
using namespace emscripten;
// MozJPEG doesnt expose a numeric version, so I have to do some fun C macro hackery to turn it
// into a string. More details here: https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html
// MozJPEG doesnt expose a numeric version, so I have to do some fun C macro
// hackery to turn it into a string. More details here:
// https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html
#define xstr(s) str(s)
#define str(s) #s
@@ -39,8 +43,8 @@ int version() {
char buffer[] = xstr(MOZJPEG_VERSION);
int version = 0;
int last_index = 0;
for(int i = 0; i < strlen(buffer); i++) {
if(buffer[i] == '.') {
for (int i = 0; i < strlen(buffer); i++) {
if (buffer[i] == '.') {
buffer[i] = '\0';
version = version << 8 | atoi(&buffer[last_index]);
buffer[i] = '.';
@@ -55,13 +59,12 @@ uint8_t* last_result;
struct jpeg_compress_struct cinfo;
val encode(std::string image_in, int image_width, int image_height, MozJpegOptions opts) {
uint8_t* image_buffer = (uint8_t*) image_in.c_str();
uint8_t* image_buffer = (uint8_t*)image_in.c_str();
// The code below is basically the `write_JPEG_file` function from
// https://github.com/mozilla/mozjpeg/blob/master/example.c
// I just write to memory instead of a file.
/* This struct contains the JPEG compression parameters and pointers to
* working space (which is allocated as needed by the JPEG library).
* It is possible to have several such structures, representing multiple
@@ -78,8 +81,8 @@ val encode(std::string image_in, int image_width, int image_height, MozJpegOptio
*/
struct jpeg_error_mgr jerr;
/* More stuff */
JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
int row_stride; /* physical row width in image buffer */
JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
int row_stride; /* physical row width in image buffer */
uint8_t* output;
unsigned long size;
@@ -113,17 +116,17 @@ val encode(std::string image_in, int image_width, int image_height, MozJpegOptio
/* First we supply a description of the input image.
* Four fields of the cinfo struct must be filled in:
*/
cinfo.image_width = image_width; /* image width and height, in pixels */
cinfo.image_width = image_width; /* image width and height, in pixels */
cinfo.image_height = image_height;
cinfo.input_components = 4; /* # of color components per pixel */
cinfo.in_color_space = JCS_EXT_RGBA; /* colorspace of input image */
cinfo.input_components = 4; /* # of color components per pixel */
cinfo.in_color_space = JCS_EXT_RGBA; /* colorspace of input image */
/* Now use the library's routine to set default compression parameters.
* (You must set at least cinfo.in_color_space before calling this,
* since the defaults depend on the source color space.)
*/
jpeg_set_defaults(&cinfo);
jpeg_set_colorspace(&cinfo, (J_COLOR_SPACE) opts.color_space);
jpeg_set_colorspace(&cinfo, (J_COLOR_SPACE)opts.color_space);
if (opts.quant_table != -1) {
jpeg_c_set_int_param(&cinfo, JINT_BASE_QUANT_TBL_IDX, opts.quant_table);
@@ -143,17 +146,17 @@ val encode(std::string image_in, int image_width, int image_height, MozJpegOptio
jpeg_c_set_bool_param(&cinfo, JBOOLEAN_TRELLIS_Q_OPT, opts.trellis_opt_table);
jpeg_c_set_int_param(&cinfo, JINT_TRELLIS_NUM_LOOPS, opts.trellis_loops);
// A little hacky to build a string for this, but it means we can use set_quality_ratings which
// does some useful heuristic stuff.
// A little hacky to build a string for this, but it means we can use
// set_quality_ratings which does some useful heuristic stuff.
std::string quality_str = std::to_string(opts.quality);
if (opts.separate_chroma_quality && opts.color_space == JCS_YCbCr) {
quality_str += "," + std::to_string(opts.chroma_quality);
}
char const *pqual = quality_str.c_str();
char const* pqual = quality_str.c_str();
set_quality_ratings(&cinfo, (char*) pqual, opts.baseline);
set_quality_ratings(&cinfo, (char*)pqual, opts.baseline);
if (!opts.auto_subsample && opts.color_space == JCS_YCbCr) {
cinfo.comp_info[0].h_samp_factor = opts.chroma_subsample;
@@ -188,8 +191,8 @@ val encode(std::string image_in, int image_width, int image_height, MozJpegOptio
* Here the array is only one element long, but you could pass
* more than one scanline at a time if that's more convenient.
*/
row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
row_pointer[0] = &image_buffer[cinfo.next_scanline * row_stride];
(void)jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
/* Step 6: Finish compression */
@@ -210,23 +213,22 @@ void free_result() {
EMSCRIPTEN_BINDINGS(my_module) {
value_object<MozJpegOptions>("MozJpegOptions")
.field("quality", &MozJpegOptions::quality)
.field("baseline", &MozJpegOptions::baseline)
.field("arithmetic", &MozJpegOptions::arithmetic)
.field("progressive", &MozJpegOptions::progressive)
.field("optimize_coding", &MozJpegOptions::optimize_coding)
.field("smoothing", &MozJpegOptions::smoothing)
.field("color_space", &MozJpegOptions::color_space)
.field("quant_table", &MozJpegOptions::quant_table)
.field("trellis_multipass", &MozJpegOptions::trellis_multipass)
.field("trellis_opt_zero", &MozJpegOptions::trellis_opt_zero)
.field("trellis_opt_table", &MozJpegOptions::trellis_opt_table)
.field("trellis_loops", &MozJpegOptions::trellis_loops)
.field("chroma_subsample", &MozJpegOptions::chroma_subsample)
.field("auto_subsample", &MozJpegOptions::auto_subsample)
.field("separate_chroma_quality", &MozJpegOptions::separate_chroma_quality)
.field("chroma_quality", &MozJpegOptions::chroma_quality)
;
.field("quality", &MozJpegOptions::quality)
.field("baseline", &MozJpegOptions::baseline)
.field("arithmetic", &MozJpegOptions::arithmetic)
.field("progressive", &MozJpegOptions::progressive)
.field("optimize_coding", &MozJpegOptions::optimize_coding)
.field("smoothing", &MozJpegOptions::smoothing)
.field("color_space", &MozJpegOptions::color_space)
.field("quant_table", &MozJpegOptions::quant_table)
.field("trellis_multipass", &MozJpegOptions::trellis_multipass)
.field("trellis_opt_zero", &MozJpegOptions::trellis_opt_zero)
.field("trellis_opt_table", &MozJpegOptions::trellis_opt_table)
.field("trellis_loops", &MozJpegOptions::trellis_loops)
.field("chroma_subsample", &MozJpegOptions::chroma_subsample)
.field("auto_subsample", &MozJpegOptions::auto_subsample)
.field("separate_chroma_quality", &MozJpegOptions::separate_chroma_quality)
.field("chroma_quality", &MozJpegOptions::chroma_quality);
function("version", &version);
function("encode", &encode);

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -2,7 +2,7 @@
"name": "mozjpeg_enc",
"scripts": {
"install": "napa",
"build": "docker run --rm -v $(pwd):/src trzeci/emscripten ./build.sh"
"build": "docker run --rm -v $(pwd):/src trzeci/emscripten-upstream ./build.sh"
},
"napa": {
"mozjpeg": "mozilla/mozjpeg#v3.3.1"

View File

@@ -282,6 +282,7 @@ dependencies = [
name = "oxipng"
version = "0.1.0"
dependencies = [
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"oxipng 2.3.0 (git+https://github.com/shssoichiro/oxipng.git)",
"wasm-bindgen 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -289,7 +290,7 @@ dependencies = [
[[package]]
name = "oxipng"
version = "2.3.0"
source = "git+https://github.com/shssoichiro/oxipng.git#f74726915131ec7ff1df0514436aac34bc603cff"
source = "git+https://github.com/shssoichiro/oxipng.git#ec8ecf5a800dfb41359d9cf41eed8a730062b9a8"
dependencies = [
"bit-vec 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
"byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -299,9 +300,9 @@ dependencies = [
"indexmap 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"itertools 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
"libdeflater 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"miniz_oxide 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
"num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rgb 0.8.16 (registry+https://github.com/rust-lang/crates.io-index)",
"rgb 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)",
"zopfli 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -356,7 +357,7 @@ dependencies = [
[[package]]
name = "rgb"
version = "0.8.16"
version = "0.8.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
@@ -488,7 +489,7 @@ dependencies = [
"checksum quote 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2bdc6c187c65bca4260c9011c9e3132efe4909da44726bad24cf7572ae338d7f"
"checksum rayon 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "db6ce3297f9c85e16621bb8cca38a06779ffc31bb8184e1be4bed2be4678a098"
"checksum rayon-core 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "08a89b46efaf957e52b18062fb2f4660f8b8a4dde1807ca002690868ef2c85a9"
"checksum rgb 0.8.16 (registry+https://github.com/rust-lang/crates.io-index)" = "5ec4ab2cf0b27e111e266e161cf7f9efd20125a161190da1c0945c4a4408fef3"
"checksum rgb 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)" = "a85b83fd629b0ce765f45316774fa6aaa95947fd74c8e4bbf3c6d1e349701d95"
"checksum scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
"checksum syn 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)" = "0df0eb663f387145cab623dea85b09c2c5b4b0aef44e945d928e682fce71bb03"
"checksum typed-arena 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a9b2228007eba4120145f785df0f6c92ea538f5a3635a612ecf4e334c8c1446d"

View File

@@ -11,6 +11,7 @@ crate-type = ["cdylib"]
[dependencies]
oxipng = { version = "2.3.0", default-features = false }
wasm-bindgen = "0.2.48"
log = { version = "0.4", features = ["release_max_level_off"] }
[profile.release]
lto = true

Binary file not shown.

View File

@@ -2,6 +2,26 @@
//! These implementations are compatible with the standard signatures
//! but use Rust allocator instead of including libc one as well.
//!
//! Rust allocator APIs requires passing size and alignment to the
//! `dealloc` function. This is different from C API, which only
//! expects a pointer in `free` and expects allocators to take care of
//! storing any necessary information elsewhere.
//!
//! In order to simulate C API, we allocate a `size_and_data_ptr`
//! of size `sizeof(usize) + size` where `size` is the requested number
//! of bytes. Then, we store `size` at the beginning of the allocated
//! chunk (within those `sizeof(usize)` bytes) and return
//! `data_ptr = size_and_data_ptr + sizeof(usize)` to the calleer:
//!
//! [`size`][...actual data]
//! -^------------------ `size_and_data_ptr`
//! ---------^---------- `data_ptr`
//!
//! Then, in `free`, the caller gives us `data_ptr`. We can subtract
//! `sizeof(usize)` back and get the original `size_and_data_ptr`.
//! At this point we can read `size` back and call the Rust `dealloc`
//! for the whole allocated chunk.
//!
//! I've raised an upstream issue to hopefully make this easier in
//! future: https://github.com/ebiggers/libdeflate/issues/62
@@ -20,8 +40,8 @@ pub unsafe extern "C" fn malloc(size: usize) -> *mut u8 {
}
#[no_mangle]
pub unsafe extern "C" fn free(ptr: *mut u8) {
let size_and_data_ptr = ptr.sub(size_of::<usize>());
pub unsafe extern "C" fn free(data_ptr: *mut u8) {
let size_and_data_ptr = data_ptr.sub(size_of::<usize>());
let size = *(size_and_data_ptr as *const usize);
dealloc(ptr, layout_for(size))
dealloc(size_and_data_ptr, layout_for(size))
}

37
codecs/webp_dec/build.sh → codecs/webp/build.sh Executable file → Normal file
View File

@@ -2,22 +2,21 @@
set -e
export OPTIMIZE="-Os"
export EM_CACHE="${PWD}/node_modules/.em_cache"
export OPTIMIZE="-Os -flto --llvm-lto 1"
export LDFLAGS="${OPTIMIZE}"
export CFLAGS="${OPTIMIZE}"
export CPPFLAGS="${OPTIMIZE}"
apt-get update
apt-get install -qqy autoconf libtool libpng-dev pkg-config
apt-get install -qqy autoconf libtool pkg-config
echo "============================================="
echo "Compiling libwebp"
echo "============================================="
test -n "$SKIP_LIBWEBP" || (
cd node_modules/libwebp
autoreconf -fiv
rm -rf build || true
mkdir -p build && cd build
emconfigure ../configure \
autoreconf -iv
emconfigure ./configure -C \
--disable-libwebpdemux \
--disable-wic \
--disable-gif \
@@ -31,7 +30,7 @@ test -n "$SKIP_LIBWEBP" || (
--disable-neon \
--disable-sse2 \
--disable-sse4.1
emmake make
emmake make -j`nproc`
)
echo "============================================="
echo "Compiling wasm bindings"
@@ -39,16 +38,28 @@ echo "============================================="
(
emcc \
${OPTIMIZE} \
--closure 1 \
--bind \
-s ALLOW_MEMORY_GROWTH=1 \
-s MODULARIZE=1 \
-s 'EXPORT_NAME="webp_dec"' \
--std=c++11 \
-I node_modules/libwebp \
-o ./webp_dec.js \
-x c++ \
webp_dec.cpp \
node_modules/libwebp/build/src/.libs/libwebp.a
-o dec/webp_dec.js \
dec/webp_dec.cpp \
node_modules/libwebp/src/.libs/libwebp.a
)
(
emcc \
${OPTIMIZE} \
--closure 1 \
--bind \
-s ALLOW_MEMORY_GROWTH=1 \
-s MODULARIZE=1 \
-s 'EXPORT_NAME="webp_enc"' \
-I node_modules/libwebp \
-o enc/webp_enc.js \
enc/webp_enc.cpp \
node_modules/libwebp/src/.libs/libwebp.a
)
echo "============================================="
echo "Compiling wasm bindings done"
@@ -56,5 +67,5 @@ echo "============================================="
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "Did you update your docker image?"
echo "Run \`docker pull trzeci/emscripten\`"
echo "Run \`docker pull trzeci/emscripten-upstream\`"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

View File

@@ -10,7 +10,7 @@
Module.onRuntimeInitialized = async _ => {
console.log('Version:', Module.version().toString(16));
const image = await loadFile('../example.webp');
const image = await loadFile('../../example.webp');
const result = Module.decode(image);
const imageData = new ImageData(new Uint8ClampedArray(result.buffer), result.width, result.height);
Module.free_result();

View File

@@ -1,8 +1,8 @@
#include <string>
#include "emscripten/bind.h"
#include "emscripten/val.h"
#include "src/webp/decode.h"
#include "src/webp/demux.h"
#include <string>
using namespace emscripten;
@@ -11,24 +11,19 @@ int version() {
}
class RawImage {
public:
public:
val buffer;
int width;
int height;
RawImage(val b, int w, int h)
: buffer(b), width(w), height(h) {}
RawImage(val b, int w, int h) : buffer(b), width(w), height(h) {}
};
uint8_t* last_result;
RawImage decode(std::string buffer) {
int width, height;
last_result = WebPDecodeRGBA((const uint8_t*)buffer.c_str(), buffer.size(), &width, &height);
return RawImage(
val(typed_memory_view(width*height*4, last_result)),
width,
height
);
return RawImage(val(typed_memory_view(width * height * 4, last_result)), width, height);
}
void free_result() {
@@ -37,9 +32,9 @@ void free_result() {
EMSCRIPTEN_BINDINGS(my_module) {
class_<RawImage>("RawImage")
.property("buffer", &RawImage::buffer)
.property("width", &RawImage::width)
.property("height", &RawImage::height);
.property("buffer", &RawImage::buffer)
.property("width", &RawImage::width)
.property("height", &RawImage::height);
function("decode", &decode);
function("version", &version);

View File

@@ -0,0 +1,79 @@
var webp_dec = (function() {
var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;
return (
function(webp_dec) {
webp_dec = webp_dec || {};
var e;e||(e=typeof webp_dec !== 'undefined' ? webp_dec : {});var r={},w;for(w in e)e.hasOwnProperty(w)&&(r[w]=e[w]);var aa=!1,z=!1,ba=!1,ca=!1;aa="object"===typeof window;z="function"===typeof importScripts;ba="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node;ca=!aa&&!ba&&!z;var A="",da,B,ea,ha;
if(ba)A=z?require("path").dirname(A)+"/":__dirname+"/",da=function(a,b){ea||(ea=require("fs"));ha||(ha=require("path"));a=ha.normalize(a);return ea.readFileSync(a,b?null:"utf8")},B=function(a){a=da(a,!0);a.buffer||(a=new Uint8Array(a));a.buffer||D("Assertion failed: undefined");return a},1<process.argv.length&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(a){throw a;}),process.on("unhandledRejection",D),e.inspect=function(){return"[Emscripten Module object]"};
else if(ca)"undefined"!=typeof read&&(da=function(a){return read(a)}),B=function(a){if("function"===typeof readbuffer)return new Uint8Array(readbuffer(a));a=read(a,"binary");"object"===typeof a||D("Assertion failed: undefined");return a},"undefined"!==typeof print&&("undefined"===typeof console&&(console={}),console.log=print,console.warn=console.error="undefined"!==typeof printErr?printErr:print);else if(aa||z)z?A=self.location.href:document.currentScript&&(A=document.currentScript.src),_scriptDir&&
(A=_scriptDir),0!==A.indexOf("blob:")?A=A.substr(0,A.lastIndexOf("/")+1):A="",da=function(a){var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);return b.responseText},z&&(B=function(a){var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)});var ia=e.print||console.log.bind(console),E=e.printErr||console.warn.bind(console);for(w in r)r.hasOwnProperty(w)&&(e[w]=r[w]);r=null;var F;e.wasmBinary&&(F=e.wasmBinary);var noExitRuntime;
e.noExitRuntime&&(noExitRuntime=e.noExitRuntime);"object"!==typeof WebAssembly&&E("no native wasm support detected");var G,ja=new WebAssembly.Table({initial:138,maximum:138,element:"anyfunc"}),ka=!1,la="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0;
function ma(a,b,c){var d=H;if(0<c){c=b+c-1;for(var f=0;f<a.length;++f){var g=a.charCodeAt(f);if(55296<=g&&57343>=g){var q=a.charCodeAt(++f);g=65536+((g&1023)<<10)|q&1023}if(127>=g){if(b>=c)break;d[b++]=g}else{if(2047>=g){if(b+1>=c)break;d[b++]=192|g>>6}else{if(65535>=g){if(b+2>=c)break;d[b++]=224|g>>12}else{if(b+3>=c)break;d[b++]=240|g>>18;d[b++]=128|g>>12&63}d[b++]=128|g>>6&63}d[b++]=128|g&63}}d[b]=0}}var na="undefined"!==typeof TextDecoder?new TextDecoder("utf-16le"):void 0;
function oa(a){var b;for(b=a>>1;I[b];)++b;b<<=1;if(32<b-a&&na)return na.decode(H.subarray(a,b));b=0;for(var c="";;){var d=I[a+2*b>>1];if(0==d)return c;++b;c+=String.fromCharCode(d)}}function pa(a,b,c){void 0===c&&(c=2147483647);if(2>c)return 0;c-=2;var d=b;c=c<2*a.length?c/2:a.length;for(var f=0;f<c;++f)I[b>>1]=a.charCodeAt(f),b+=2;I[b>>1]=0;return b-d}function qa(a){return 2*a.length}
function ra(a){for(var b=0,c="";;){var d=J[a+4*b>>2];if(0==d)return c;++b;65536<=d?(d-=65536,c+=String.fromCharCode(55296|d>>10,56320|d&1023)):c+=String.fromCharCode(d)}}function sa(a,b,c){void 0===c&&(c=2147483647);if(4>c)return 0;var d=b;c=d+c-4;for(var f=0;f<a.length;++f){var g=a.charCodeAt(f);if(55296<=g&&57343>=g){var q=a.charCodeAt(++f);g=65536+((g&1023)<<10)|q&1023}J[b>>2]=g;b+=4;if(b+4>c)break}J[b>>2]=0;return b-d}
function ta(a){for(var b=0,c=0;c<a.length;++c){var d=a.charCodeAt(c);55296<=d&&57343>=d&&++c;b+=4}return b}var K,ua,H,I,va,J,L,wa,xa;function ya(a){K=a;e.HEAP8=ua=new Int8Array(a);e.HEAP16=I=new Int16Array(a);e.HEAP32=J=new Int32Array(a);e.HEAPU8=H=new Uint8Array(a);e.HEAPU16=va=new Uint16Array(a);e.HEAPU32=L=new Uint32Array(a);e.HEAPF32=wa=new Float32Array(a);e.HEAPF64=xa=new Float64Array(a)}var za=e.INITIAL_MEMORY||16777216;e.wasmMemory?G=e.wasmMemory:G=new WebAssembly.Memory({initial:za/65536});
G&&(K=G.buffer);za=K.byteLength;ya(K);J[3336]=5256384;function Aa(a){for(;0<a.length;){var b=a.shift();if("function"==typeof b)b();else{var c=b.ka;"number"===typeof c?void 0===b.ba?e.dynCall_v(c):e.dynCall_vi(c,b.ba):c(void 0===b.ba?null:b.ba)}}}var Ba=[],Ca=[],Da=[],Ea=[];function Fa(){var a=e.preRun.shift();Ba.unshift(a)}var M=0,Ga=null,N=null;e.preloadedImages={};e.preloadedAudios={};
function D(a){if(e.onAbort)e.onAbort(a);ia(a);E(a);ka=!0;throw new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");}function Ha(){var a=O;return String.prototype.startsWith?a.startsWith("data:application/octet-stream;base64,"):0===a.indexOf("data:application/octet-stream;base64,")}var O="webp_dec.wasm";if(!Ha()){var Ia=O;O=e.locateFile?e.locateFile(Ia,A):A+Ia}
function Ja(){try{if(F)return new Uint8Array(F);if(B)return B(O);throw"both async and sync fetching of the wasm failed";}catch(a){D(a)}}function Ka(){return F||!aa&&!z||"function"!==typeof fetch?new Promise(function(a){a(Ja())}):fetch(O,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+O+"'";return a.arrayBuffer()}).catch(function(){return Ja()})}Ca.push({ka:function(){La()}});function Ma(){return 0<Ma.X}
function Na(a){switch(a){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+a);}}var Oa=void 0;function P(a){for(var b="";H[a];)b+=Oa[H[a++]];return b}var Q={},R={},Pa={};function Qa(a){if(void 0===a)return"_unknown";a=a.replace(/[^a-zA-Z0-9_]/g,"$");var b=a.charCodeAt(0);return 48<=b&&57>=b?"_"+a:a}
function Ra(a,b){a=Qa(a);return(new Function("body","return function "+a+'() {\n "use strict"; return body.apply(this, arguments);\n};\n'))(b)}function Sa(a){var b=Error,c=Ra(a,function(d){this.name=a;this.message=d;d=Error(d).stack;void 0!==d&&(this.stack=this.toString()+"\n"+d.replace(/^Error(:[^\n]*)?\n/,""))});c.prototype=Object.create(b.prototype);c.prototype.constructor=c;c.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message};return c}
var Ta=void 0;function S(a){throw new Ta(a);}var Ua=void 0;function Va(a){throw new Ua(a);}function Wa(a,b,c){function d(h){h=c(h);h.length!==a.length&&Va("Mismatched type converter count");for(var l=0;l<a.length;++l)T(a[l],h[l])}a.forEach(function(h){Pa[h]=b});var f=Array(b.length),g=[],q=0;b.forEach(function(h,l){R.hasOwnProperty(h)?f[l]=R[h]:(g.push(h),Q.hasOwnProperty(h)||(Q[h]=[]),Q[h].push(function(){f[l]=R[h];++q;q===g.length&&d(f)}))});0===g.length&&d(f)}
function T(a,b,c){c=c||{};if(!("argPackAdvance"in b))throw new TypeError("registerType registeredInstance requires argPackAdvance");var d=b.name;a||S('type "'+d+'" must have a positive integer typeid pointer');if(R.hasOwnProperty(a)){if(c.na)return;S("Cannot register type '"+d+"' twice")}R[a]=b;delete Pa[a];Q.hasOwnProperty(a)&&(b=Q[a],delete Q[a],b.forEach(function(f){f()}))}function Xa(a){return{count:a.count,W:a.W,Y:a.Y,L:a.L,N:a.N,O:a.O,P:a.P}}
function Ya(a){S(a.K.N.M.name+" instance already deleted")}var Za=!1;function $a(){}function ab(a){--a.count.value;0===a.count.value&&(a.O?a.P.V(a.O):a.N.M.V(a.L))}function bb(a){if("undefined"===typeof FinalizationGroup)return bb=function(b){return b},a;Za=new FinalizationGroup(function(b){for(var c=b.next();!c.done;c=b.next())c=c.value,c.L?ab(c):console.warn("object already deleted: "+c.L)});bb=function(b){Za.register(b,b.K,b.K);return b};$a=function(b){Za.unregister(b.K)};return bb(a)}
var cb=void 0,db=[];function eb(){for(;db.length;){var a=db.pop();a.K.W=!1;a["delete"]()}}function U(){}var fb={};function gb(a,b){var c=e;if(void 0===c[a].S){var d=c[a];c[a]=function(){c[a].S.hasOwnProperty(arguments.length)||S("Function '"+b+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+c[a].S+")!");return c[a].S[arguments.length].apply(this,arguments)};c[a].S=[];c[a].S[d.ha]=d}}
function hb(a,b,c){e.hasOwnProperty(a)?((void 0===c||void 0!==e[a].S&&void 0!==e[a].S[c])&&S("Cannot register public name '"+a+"' twice"),gb(a,a),e.hasOwnProperty(c)&&S("Cannot register multiple overloads of a function with the same number of arguments ("+c+")!"),e[a].S[c]=b):(e[a]=b,void 0!==c&&(e[a].ta=c))}function ib(a,b,c,d,f,g,q,h){this.name=a;this.constructor=b;this.U=c;this.V=d;this.R=f;this.la=g;this.Z=q;this.ja=h}
function jb(a,b,c){for(;b!==c;)b.Z||S("Expected null or instance of "+c.name+", got an instance of "+b.name),a=b.Z(a),b=b.R;return a}function kb(a,b){if(null===b)return this.da&&S("null is not a valid "+this.name),0;b.K||S('Cannot pass "'+V(b)+'" as a '+this.name);b.K.L||S("Cannot pass deleted object as a pointer of type "+this.name);return jb(b.K.L,b.K.N.M,this.M)}
function lb(a,b){if(null===b){this.da&&S("null is not a valid "+this.name);if(this.aa){var c=this.pa();null!==a&&a.push(this.V,c);return c}return 0}b.K||S('Cannot pass "'+V(b)+'" as a '+this.name);b.K.L||S("Cannot pass deleted object as a pointer of type "+this.name);!this.$&&b.K.N.$&&S("Cannot convert argument of type "+(b.K.P?b.K.P.name:b.K.N.name)+" to parameter type "+this.name);c=jb(b.K.L,b.K.N.M,this.M);if(this.aa)switch(void 0===b.K.O&&S("Passing raw pointer to smart pointer is illegal"),this.ra){case 0:b.K.P===
this?c=b.K.O:S("Cannot convert argument of type "+(b.K.P?b.K.P.name:b.K.N.name)+" to parameter type "+this.name);break;case 1:c=b.K.O;break;case 2:if(b.K.P===this)c=b.K.O;else{var d=b.clone();c=this.qa(c,mb(function(){d["delete"]()}));null!==a&&a.push(this.V,c)}break;default:S("Unsupporting sharing policy")}return c}
function nb(a,b){if(null===b)return this.da&&S("null is not a valid "+this.name),0;b.K||S('Cannot pass "'+V(b)+'" as a '+this.name);b.K.L||S("Cannot pass deleted object as a pointer of type "+this.name);b.K.N.$&&S("Cannot convert argument of type "+b.K.N.name+" to parameter type "+this.name);return jb(b.K.L,b.K.N.M,this.M)}function pb(a){return this.fromWireType(L[a>>2])}function qb(a,b,c){if(b===c)return a;if(void 0===c.R)return null;a=qb(a,b,c.R);return null===a?null:c.ja(a)}var rb={};
function sb(a,b){for(void 0===b&&S("ptr should not be undefined");a.R;)b=a.Z(b),a=a.R;return rb[b]}function tb(a,b){b.N&&b.L||Va("makeClassHandle requires ptr and ptrType");!!b.P!==!!b.O&&Va("Both smartPtrType and smartPtr must be specified");b.count={value:1};return bb(Object.create(a,{K:{value:b}}))}function W(a,b,c,d){this.name=a;this.M=b;this.da=c;this.$=d;this.aa=!1;this.V=this.qa=this.pa=this.ga=this.ra=this.oa=void 0;void 0!==b.R?this.toWireType=lb:(this.toWireType=d?kb:nb,this.T=null)}
function ub(a,b,c){e.hasOwnProperty(a)||Va("Replacing nonexistant public symbol");void 0!==e[a].S&&void 0!==c?e[a].S[c]=b:(e[a]=b,e[a].ha=c)}
function X(a,b){a=P(a);var c=e["dynCall_"+a];for(var d=[],f=1;f<a.length;++f)d.push("a"+f);f="return function dynCall_"+(a+"_"+b)+"("+d.join(", ")+") {\n";f+=" return dynCall(rawFunction"+(d.length?", ":"")+d.join(", ")+");\n";c=(new Function("dynCall","rawFunction",f+"};\n"))(c,b);"function"!==typeof c&&S("unknown function pointer with signature "+a+": "+b);return c}var vb=void 0;function wb(a){a=xb(a);var b=P(a);Y(a);return b}
function yb(a,b){function c(g){f[g]||R[g]||(Pa[g]?Pa[g].forEach(c):(d.push(g),f[g]=!0))}var d=[],f={};b.forEach(c);throw new vb(a+": "+d.map(wb).join([", "]));}function zb(a){for(;a.length;){var b=a.pop();a.pop()(b)}}function Ab(a,b,c){a instanceof Object||S(c+' with invalid "this": '+a);a instanceof b.M.constructor||S(c+' incompatible with "this" of type '+a.constructor.name);a.K.L||S("cannot call emscripten binding method "+c+" on deleted object");return jb(a.K.L,a.K.N.M,b.M)}
var Bb=[],Z=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function Cb(a){4<a&&0===--Z[a].ea&&(Z[a]=void 0,Bb.push(a))}function mb(a){switch(a){case void 0:return 1;case null:return 2;case !0:return 3;case !1:return 4;default:var b=Bb.length?Bb.pop():Z.length;Z[b]={ea:1,value:a};return b}}function V(a){if(null===a)return"null";var b=typeof a;return"object"===b||"array"===b||"function"===b?a.toString():""+a}
function Db(a,b){switch(b){case 2:return function(c){return this.fromWireType(wa[c>>2])};case 3:return function(c){return this.fromWireType(xa[c>>3])};default:throw new TypeError("Unknown float type: "+a);}}function Eb(a){var b=Function;if(!(b instanceof Function))throw new TypeError("new_ called with constructor type "+typeof b+" which is not a function");var c=Ra(b.name||"unknownFunctionName",function(){});c.prototype=b.prototype;c=new c;a=b.apply(c,a);return a instanceof Object?a:c}
function Fb(a,b){for(var c=[],d=0;d<a;d++)c.push(J[(b>>2)+d]);return c}function Gb(a,b,c){switch(b){case 0:return c?function(d){return ua[d]}:function(d){return H[d]};case 1:return c?function(d){return I[d>>1]}:function(d){return va[d>>1]};case 2:return c?function(d){return J[d>>2]}:function(d){return L[d>>2]};default:throw new TypeError("Unknown integer type: "+a);}}for(var Hb=Array(256),Ib=0;256>Ib;++Ib)Hb[Ib]=String.fromCharCode(Ib);Oa=Hb;Ta=e.BindingError=Sa("BindingError");
Ua=e.InternalError=Sa("InternalError");U.prototype.isAliasOf=function(a){if(!(this instanceof U&&a instanceof U))return!1;var b=this.K.N.M,c=this.K.L,d=a.K.N.M;for(a=a.K.L;b.R;)c=b.Z(c),b=b.R;for(;d.R;)a=d.Z(a),d=d.R;return b===d&&c===a};U.prototype.clone=function(){this.K.L||Ya(this);if(this.K.Y)return this.K.count.value+=1,this;var a=bb(Object.create(Object.getPrototypeOf(this),{K:{value:Xa(this.K)}}));a.K.count.value+=1;a.K.W=!1;return a};
U.prototype["delete"]=function(){this.K.L||Ya(this);this.K.W&&!this.K.Y&&S("Object already scheduled for deletion");$a(this);ab(this.K);this.K.Y||(this.K.O=void 0,this.K.L=void 0)};U.prototype.isDeleted=function(){return!this.K.L};U.prototype.deleteLater=function(){this.K.L||Ya(this);this.K.W&&!this.K.Y&&S("Object already scheduled for deletion");db.push(this);1===db.length&&cb&&cb(eb);this.K.W=!0;return this};W.prototype.ma=function(a){this.ga&&(a=this.ga(a));return a};
W.prototype.fa=function(a){this.V&&this.V(a)};W.prototype.argPackAdvance=8;W.prototype.readValueFromPointer=pb;W.prototype.deleteObject=function(a){if(null!==a)a["delete"]()};
W.prototype.fromWireType=function(a){function b(){return this.aa?tb(this.M.U,{N:this.oa,L:c,P:this,O:a}):tb(this.M.U,{N:this,L:a})}var c=this.ma(a);if(!c)return this.fa(a),null;var d=sb(this.M,c);if(void 0!==d){if(0===d.K.count.value)return d.K.L=c,d.K.O=a,d.clone();d=d.clone();this.fa(a);return d}d=this.M.la(c);d=fb[d];if(!d)return b.call(this);d=this.$?d.ia:d.pointerType;var f=qb(c,this.M,d.M);return null===f?b.call(this):this.aa?tb(d.M.U,{N:d,L:f,P:this,O:a}):tb(d.M.U,{N:d,L:f})};
e.getInheritedInstanceCount=function(){return Object.keys(rb).length};e.getLiveInheritedInstances=function(){var a=[],b;for(b in rb)rb.hasOwnProperty(b)&&a.push(rb[b]);return a};e.flushPendingDeletes=eb;e.setDelayFunction=function(a){cb=a;db.length&&cb&&cb(eb)};vb=e.UnboundTypeError=Sa("UnboundTypeError");e.count_emval_handles=function(){for(var a=0,b=5;b<Z.length;++b)void 0!==Z[b]&&++a;return a};e.get_first_emval=function(){for(var a=5;a<Z.length;++a)if(void 0!==Z[a])return Z[a];return null};
var Kb={n:function(a){return Jb(a)},m:function(a){"uncaught_exception"in Ma?Ma.X++:Ma.X=1;throw a;},k:function(a,b,c,d,f){var g=Na(c);b=P(b);T(a,{name:b,fromWireType:function(q){return!!q},toWireType:function(q,h){return h?d:f},argPackAdvance:8,readValueFromPointer:function(q){if(1===c)var h=ua;else if(2===c)h=I;else if(4===c)h=J;else throw new TypeError("Unknown boolean type size: "+b);return this.fromWireType(h[q>>g])},T:null})},o:function(a,b,c,d,f,g,q,h,l,m,k,p,t){k=P(k);g=X(f,g);h&&(h=X(q,h));
m&&(m=X(l,m));t=X(p,t);var v=Qa(k);hb(v,function(){yb("Cannot construct "+k+" due to unbound types",[d])});Wa([a,b,c],d?[d]:[],function(n){n=n[0];if(d){var u=n.M;var x=u.U}else x=U.prototype;n=Ra(v,function(){if(Object.getPrototypeOf(this)!==y)throw new Ta("Use 'new' to construct "+k);if(void 0===C.X)throw new Ta(k+" has no accessible constructor");var ob=C.X[arguments.length];if(void 0===ob)throw new Ta("Tried to invoke ctor of "+k+" with invalid number of parameters ("+arguments.length+") - expected ("+
Object.keys(C.X).toString()+") parameters instead!");return ob.apply(this,arguments)});var y=Object.create(x,{constructor:{value:n}});n.prototype=y;var C=new ib(k,n,y,t,u,g,h,m);u=new W(k,C,!0,!1);x=new W(k+"*",C,!1,!1);var fa=new W(k+" const*",C,!1,!0);fb[a]={pointerType:x,ia:fa};ub(v,n);return[u,x,fa]})},e:function(a,b,c,d,f,g,q,h,l,m){b=P(b);f=X(d,f);Wa([],[a],function(k){k=k[0];var p=k.name+"."+b,t={get:function(){yb("Cannot access "+p+" due to unbound types",[c,q])},enumerable:!0,configurable:!0};
l?t.set=function(){yb("Cannot access "+p+" due to unbound types",[c,q])}:t.set=function(){S(p+" is a read-only property")};Object.defineProperty(k.M.U,b,t);Wa([],l?[c,q]:[c],function(v){var n=v[0],u={get:function(){var y=Ab(this,k,p+" getter");return n.fromWireType(f(g,y))},enumerable:!0};if(l){l=X(h,l);var x=v[1];u.set=function(y){var C=Ab(this,k,p+" setter"),fa=[];l(m,C,x.toWireType(fa,y));zb(fa)}}Object.defineProperty(k.M.U,b,u);return[]});return[]})},q:function(a,b){b=P(b);T(a,{name:b,fromWireType:function(c){var d=
Z[c].value;Cb(c);return d},toWireType:function(c,d){return mb(d)},argPackAdvance:8,readValueFromPointer:pb,T:null})},h:function(a,b,c){c=Na(c);b=P(b);T(a,{name:b,fromWireType:function(d){return d},toWireType:function(d,f){if("number"!==typeof f&&"boolean"!==typeof f)throw new TypeError('Cannot convert "'+V(f)+'" to '+this.name);return f},argPackAdvance:8,readValueFromPointer:Db(b,c),T:null})},d:function(a,b,c,d,f,g){var q=Fb(b,c);a=P(a);f=X(d,f);hb(a,function(){yb("Cannot call "+a+" due to unbound types",
q)},b-1);Wa([],q,function(h){var l=[h[0],null].concat(h.slice(1)),m=h=a,k=f,p=l.length;2>p&&S("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var t=null!==l[1]&&!1,v=!1,n=1;n<l.length;++n)if(null!==l[n]&&void 0===l[n].T){v=!0;break}var u="void"!==l[0].name,x="",y="";for(n=0;n<p-2;++n)x+=(0!==n?", ":"")+"arg"+n,y+=(0!==n?", ":"")+"arg"+n+"Wired";m="return function "+Qa(m)+"("+x+") {\nif (arguments.length !== "+(p-2)+") {\nthrowBindingError('function "+m+" called with ' + arguments.length + ' arguments, expected "+
(p-2)+" args!');\n}\n";v&&(m+="var destructors = [];\n");var C=v?"destructors":"null";x="throwBindingError invoker fn runDestructors retType classParam".split(" ");k=[S,k,g,zb,l[0],l[1]];t&&(m+="var thisWired = classParam.toWireType("+C+", this);\n");for(n=0;n<p-2;++n)m+="var arg"+n+"Wired = argType"+n+".toWireType("+C+", arg"+n+"); // "+l[n+2].name+"\n",x.push("argType"+n),k.push(l[n+2]);t&&(y="thisWired"+(0<y.length?", ":"")+y);m+=(u?"var rv = ":"")+"invoker(fn"+(0<y.length?", ":"")+y+");\n";if(v)m+=
"runDestructors(destructors);\n";else for(n=t?1:2;n<l.length;++n)p=1===n?"thisWired":"arg"+(n-2)+"Wired",null!==l[n].T&&(m+=p+"_dtor("+p+"); // "+l[n].name+"\n",x.push(p+"_dtor"),k.push(l[n].T));u&&(m+="var ret = retType.fromWireType(rv);\nreturn ret;\n");x.push(m+"}\n");l=Eb(x).apply(null,k);ub(h,l,b-1);return[]})},b:function(a,b,c,d,f){function g(m){return m}b=P(b);-1===f&&(f=4294967295);var q=Na(c);if(0===d){var h=32-8*c;g=function(m){return m<<h>>>h}}var l=-1!=b.indexOf("unsigned");T(a,{name:b,
fromWireType:g,toWireType:function(m,k){if("number"!==typeof k&&"boolean"!==typeof k)throw new TypeError('Cannot convert "'+V(k)+'" to '+this.name);if(k<d||k>f)throw new TypeError('Passing a number "'+V(k)+'" from JS side to C/C++ side to an argument of type "'+b+'", which is outside the valid range ['+d+", "+f+"]!");return l?k>>>0:k|0},argPackAdvance:8,readValueFromPointer:Gb(b,q,0!==d),T:null})},a:function(a,b,c){function d(g){g>>=2;var q=L;return new f(K,q[g+1],q[g])}var f=[Int8Array,Uint8Array,
Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][b];c=P(c);T(a,{name:c,fromWireType:d,argPackAdvance:8,readValueFromPointer:d},{na:!0})},i:function(a,b){b=P(b);var c="std::string"===b;T(a,{name:b,fromWireType:function(d){var f=L[d>>2];if(c){var g=H[d+4+f],q=0;0!=g&&(q=g,H[d+4+f]=0);var h=d+4;for(g=0;g<=f;++g){var l=d+4+g;if(0==H[l]){if(h){for(var m=H,k=h+NaN,p=h;m[p]&&!(p>=k);)++p;if(16<p-h&&m.subarray&&la)h=la.decode(m.subarray(h,p));else{for(k="";h<p;){var t=m[h++];if(t&
128){var v=m[h++]&63;if(192==(t&224))k+=String.fromCharCode((t&31)<<6|v);else{var n=m[h++]&63;t=224==(t&240)?(t&15)<<12|v<<6|n:(t&7)<<18|v<<12|n<<6|m[h++]&63;65536>t?k+=String.fromCharCode(t):(t-=65536,k+=String.fromCharCode(55296|t>>10,56320|t&1023))}}else k+=String.fromCharCode(t)}h=k}}else h="";if(void 0===u)var u=h;else u+=String.fromCharCode(0),u+=h;h=l+1}}0!=q&&(H[d+4+f]=q)}else{u=Array(f);for(g=0;g<f;++g)u[g]=String.fromCharCode(H[d+4+g]);u=u.join("")}Y(d);return u},toWireType:function(d,f){f instanceof
ArrayBuffer&&(f=new Uint8Array(f));var g="string"===typeof f;g||f instanceof Uint8Array||f instanceof Uint8ClampedArray||f instanceof Int8Array||S("Cannot pass non-string to std::string");var q=(c&&g?function(){for(var m=0,k=0;k<f.length;++k){var p=f.charCodeAt(k);55296<=p&&57343>=p&&(p=65536+((p&1023)<<10)|f.charCodeAt(++k)&1023);127>=p?++m:m=2047>=p?m+2:65535>=p?m+3:m+4}return m}:function(){return f.length})(),h=Jb(4+q+1);L[h>>2]=q;if(c&&g)ma(f,h+4,q+1);else if(g)for(g=0;g<q;++g){var l=f.charCodeAt(g);
255<l&&(Y(h),S("String has UTF-16 code units that do not fit in 8 bits"));H[h+4+g]=l}else for(g=0;g<q;++g)H[h+4+g]=f[g];null!==d&&d.push(Y,h);return h},argPackAdvance:8,readValueFromPointer:pb,T:function(d){Y(d)}})},f:function(a,b,c){c=P(c);if(2===b){var d=oa;var f=pa;var g=qa;var q=function(){return va};var h=1}else 4===b&&(d=ra,f=sa,g=ta,q=function(){return L},h=2);T(a,{name:c,fromWireType:function(l){var m=L[l>>2],k=q(),p=k[l+4+m*b>>h],t=0;0!=p&&(t=p,k[l+4+m*b>>h]=0);var v=l+4;for(p=0;p<=m;++p){var n=
l+4+p*b;if(0==k[n>>h]){v=d(v);if(void 0===u)var u=v;else u+=String.fromCharCode(0),u+=v;v=n+b}}0!=t&&(k[l+4+m*b>>h]=t);Y(l);return u},toWireType:function(l,m){"string"!==typeof m&&S("Cannot pass non-string to C++ string type "+c);var k=g(m),p=Jb(4+k+b);L[p>>2]=k>>h;f(m,p+4,k+b);null!==l&&l.push(Y,p);return p},argPackAdvance:8,readValueFromPointer:pb,T:function(l){Y(l)}})},l:function(a,b){b=P(b);T(a,{sa:!0,name:b,argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},g:Cb,r:function(a){4<
a&&(Z[a].ea+=1)},j:function(a,b){var c=R[a];void 0===c&&S("_emval_take_value has unknown type "+wb(a));a=c.readValueFromPointer(b);return mb(a)},p:function(a,b,c){H.copyWithin(a,b,b+c)},c:function(a){var b=H.length;if(2147418112<a)return!1;for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);d=Math.max(16777216,a,d);0<d%65536&&(d+=65536-d%65536);a:{try{G.grow(Math.min(2147418112,d)-K.byteLength+65535>>16);ya(G.buffer);var f=1;break a}catch(g){}f=void 0}if(f)return!0}return!1},memory:G,
table:ja},Lb=function(){function a(f){e.asm=f.exports;M--;e.monitorRunDependencies&&e.monitorRunDependencies(M);0==M&&(null!==Ga&&(clearInterval(Ga),Ga=null),N&&(f=N,N=null,f()))}function b(f){a(f.instance)}function c(f){return Ka().then(function(g){return WebAssembly.instantiate(g,d)}).then(f,function(g){E("failed to asynchronously prepare wasm: "+g);D(g)})}var d={a:Kb};M++;e.monitorRunDependencies&&e.monitorRunDependencies(M);if(e.instantiateWasm)try{return e.instantiateWasm(d,a)}catch(f){return E("Module.instantiateWasm callback failed with error: "+
f),!1}(function(){if(F||"function"!==typeof WebAssembly.instantiateStreaming||Ha()||"function"!==typeof fetch)return c(b);fetch(O,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,d).then(b,function(g){E("wasm streaming compile failed: "+g);E("falling back to ArrayBuffer instantiation");c(b)})})})();return{}}();e.asm=Lb;
var La=e.___wasm_call_ctors=function(){return(La=e.___wasm_call_ctors=e.asm.s).apply(null,arguments)},Y=e._free=function(){return(Y=e._free=e.asm.t).apply(null,arguments)},Jb=e._malloc=function(){return(Jb=e._malloc=e.asm.u).apply(null,arguments)},xb=e.___getTypeName=function(){return(xb=e.___getTypeName=e.asm.v).apply(null,arguments)};e.___embind_register_native_and_builtin_types=function(){return(e.___embind_register_native_and_builtin_types=e.asm.w).apply(null,arguments)};
e.dynCall_ii=function(){return(e.dynCall_ii=e.asm.x).apply(null,arguments)};e.dynCall_vi=function(){return(e.dynCall_vi=e.asm.y).apply(null,arguments)};e.dynCall_iii=function(){return(e.dynCall_iii=e.asm.z).apply(null,arguments)};e.dynCall_viii=function(){return(e.dynCall_viii=e.asm.A).apply(null,arguments)};e.dynCall_vii=function(){return(e.dynCall_vii=e.asm.B).apply(null,arguments)};e.dynCall_i=function(){return(e.dynCall_i=e.asm.C).apply(null,arguments)};
e.dynCall_v=function(){return(e.dynCall_v=e.asm.D).apply(null,arguments)};e.dynCall_iiii=function(){return(e.dynCall_iiii=e.asm.E).apply(null,arguments)};e.dynCall_iiiiiii=function(){return(e.dynCall_iiiiiii=e.asm.F).apply(null,arguments)};e.dynCall_viiii=function(){return(e.dynCall_viiii=e.asm.G).apply(null,arguments)};e.dynCall_viiiii=function(){return(e.dynCall_viiiii=e.asm.H).apply(null,arguments)};e.dynCall_viiiiiiiii=function(){return(e.dynCall_viiiiiiiii=e.asm.I).apply(null,arguments)};
e.dynCall_viiiiii=function(){return(e.dynCall_viiiiii=e.asm.J).apply(null,arguments)};e.asm=Lb;var Mb;e.then=function(a){if(Mb)a(e);else{var b=e.onRuntimeInitialized;e.onRuntimeInitialized=function(){b&&b();a(e)}}return e};N=function Nb(){Mb||Ob();Mb||(N=Nb)};
function Ob(){function a(){if(!Mb&&(Mb=!0,e.calledRun=!0,!ka)){Aa(Ca);Aa(Da);if(e.onRuntimeInitialized)e.onRuntimeInitialized();if(e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var b=e.postRun.shift();Ea.unshift(b)}Aa(Ea)}}if(!(0<M)){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)Fa();Aa(Ba);0<M||(e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1);a()},1)):a())}}
e.run=Ob;if(e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.pop()();noExitRuntime=!0;Ob();
return webp_dec
}
);
})();
if (typeof exports === 'object' && typeof module === 'object')
module.exports = webp_dec;
else if (typeof define === 'function' && define['amd'])
define([], function() { return webp_dec; });
else if (typeof exports === 'object')
exports["webp_dec"] = webp_dec;

Binary file not shown.

View File

@@ -19,7 +19,7 @@
module.onRuntimeInitialized = async _ => {
console.log('Version:', module.version().toString(16));
const image = await loadImage('../example.png');
const image = await loadImage('../../example.png');
const result = module.encode(image.data, image.width, image.height, {
quality: 75,
target_size: 0,

View File

@@ -0,0 +1,93 @@
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include <stdlib.h>
#include <string.h>
#include <stdexcept>
#include "src/webp/encode.h"
using namespace emscripten;
int version() {
return WebPGetEncoderVersion();
}
uint8_t* last_result;
val encode(std::string img, int width, int height, WebPConfig config) {
uint8_t* img_in = (uint8_t*)img.c_str();
// A lot of this is duplicated from Encode in picture_enc.c
WebPPicture pic;
WebPMemoryWriter wrt;
int ok;
if (!WebPPictureInit(&pic)) {
// shouldn't happen, except if system installation is broken
throw std::runtime_error("Unexpected error");
}
// Only use use_argb if we really need it, as it's slower.
pic.use_argb = config.lossless || config.use_sharp_yuv || config.preprocessing > 0;
pic.width = width;
pic.height = height;
pic.writer = WebPMemoryWrite;
pic.custom_ptr = &wrt;
WebPMemoryWriterInit(&wrt);
ok = WebPPictureImportRGBA(&pic, (uint8_t*)img_in, width * 4) && WebPEncode(&config, &pic);
WebPPictureFree(&pic);
if (!ok) {
WebPMemoryWriterClear(&wrt);
throw std::runtime_error("Encode failed");
}
last_result = wrt.mem;
return val(typed_memory_view(wrt.size, wrt.mem));
}
void free_result() {
WebPFree(last_result);
}
EMSCRIPTEN_BINDINGS(my_module) {
enum_<WebPImageHint>("WebPImageHint")
.value("WEBP_HINT_DEFAULT", WebPImageHint::WEBP_HINT_DEFAULT)
.value("WEBP_HINT_PICTURE", WebPImageHint::WEBP_HINT_PICTURE)
.value("WEBP_HINT_PHOTO", WebPImageHint::WEBP_HINT_PHOTO)
.value("WEBP_HINT_GRAPH", WebPImageHint::WEBP_HINT_GRAPH);
value_object<WebPConfig>("WebPConfig")
.field("lossless", &WebPConfig::lossless)
.field("quality", &WebPConfig::quality)
.field("method", &WebPConfig::method)
.field("image_hint", &WebPConfig::image_hint)
.field("target_size", &WebPConfig::target_size)
.field("target_PSNR", &WebPConfig::target_PSNR)
.field("segments", &WebPConfig::segments)
.field("sns_strength", &WebPConfig::sns_strength)
.field("filter_strength", &WebPConfig::filter_strength)
.field("filter_sharpness", &WebPConfig::filter_sharpness)
.field("filter_type", &WebPConfig::filter_type)
.field("autofilter", &WebPConfig::autofilter)
.field("alpha_compression", &WebPConfig::alpha_compression)
.field("alpha_filtering", &WebPConfig::alpha_filtering)
.field("alpha_quality", &WebPConfig::alpha_quality)
.field("pass", &WebPConfig::pass)
.field("show_compressed", &WebPConfig::show_compressed)
.field("preprocessing", &WebPConfig::preprocessing)
.field("partitions", &WebPConfig::partitions)
.field("partition_limit", &WebPConfig::partition_limit)
.field("emulate_jpeg_size", &WebPConfig::emulate_jpeg_size)
.field("thread_level", &WebPConfig::thread_level)
.field("low_memory", &WebPConfig::low_memory)
.field("near_lossless", &WebPConfig::near_lossless)
.field("exact", &WebPConfig::exact)
.field("use_delta_palette", &WebPConfig::use_delta_palette)
.field("use_sharp_yuv", &WebPConfig::use_sharp_yuv);
function("version", &version);
function("encode", &encode);
function("free_result", &free_result);
}

View File

@@ -0,0 +1,70 @@
var webp_enc = (function() {
var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;
return (
function(webp_enc) {
webp_enc = webp_enc || {};
var d;d||(d=typeof webp_enc !== 'undefined' ? webp_enc : {});var u={},w;for(w in d)d.hasOwnProperty(w)&&(u[w]=d[w]);var x=!1,y=!1,aa=!1,ba=!1;x="object"===typeof window;y="function"===typeof importScripts;aa="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node;ba=!x&&!aa&&!y;var z="",B,C,ca,da;
if(aa)z=y?require("path").dirname(z)+"/":__dirname+"/",B=function(a,b){ca||(ca=require("fs"));da||(da=require("path"));a=da.normalize(a);return ca.readFileSync(a,b?null:"utf8")},C=function(a){a=B(a,!0);a.buffer||(a=new Uint8Array(a));a.buffer||D("Assertion failed: undefined");return a},1<process.argv.length&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(a){throw a;}),process.on("unhandledRejection",D),d.inspect=function(){return"[Emscripten Module object]"};
else if(ba)"undefined"!=typeof read&&(B=function(a){return read(a)}),C=function(a){if("function"===typeof readbuffer)return new Uint8Array(readbuffer(a));a=read(a,"binary");"object"===typeof a||D("Assertion failed: undefined");return a},"undefined"!==typeof print&&("undefined"===typeof console&&(console={}),console.log=print,console.warn=console.error="undefined"!==typeof printErr?printErr:print);else if(x||y)y?z=self.location.href:document.currentScript&&(z=document.currentScript.src),_scriptDir&&
(z=_scriptDir),0!==z.indexOf("blob:")?z=z.substr(0,z.lastIndexOf("/")+1):z="",B=function(a){var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);return b.responseText},y&&(C=function(a){var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)});var ea=d.print||console.log.bind(console),E=d.printErr||console.warn.bind(console);for(w in u)u.hasOwnProperty(w)&&(d[w]=u[w]);u=null;var F;d.wasmBinary&&(F=d.wasmBinary);var noExitRuntime;
d.noExitRuntime&&(noExitRuntime=d.noExitRuntime);"object"!==typeof WebAssembly&&E("no native wasm support detected");var G,fa=new WebAssembly.Table({initial:129,maximum:129,element:"anyfunc"}),ha=!1,ia="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0;
function ja(a,b,c){var e=I;if(0<c){c=b+c-1;for(var f=0;f<a.length;++f){var g=a.charCodeAt(f);if(55296<=g&&57343>=g){var n=a.charCodeAt(++f);g=65536+((g&1023)<<10)|n&1023}if(127>=g){if(b>=c)break;e[b++]=g}else{if(2047>=g){if(b+1>=c)break;e[b++]=192|g>>6}else{if(65535>=g){if(b+2>=c)break;e[b++]=224|g>>12}else{if(b+3>=c)break;e[b++]=240|g>>18;e[b++]=128|g>>12&63}e[b++]=128|g>>6&63}e[b++]=128|g&63}}e[b]=0}}var ka="undefined"!==typeof TextDecoder?new TextDecoder("utf-16le"):void 0;
function la(a){var b;for(b=a>>1;J[b];)++b;b<<=1;if(32<b-a&&ka)return ka.decode(I.subarray(a,b));b=0;for(var c="";;){var e=J[a+2*b>>1];if(0==e)return c;++b;c+=String.fromCharCode(e)}}function ma(a,b,c){void 0===c&&(c=2147483647);if(2>c)return 0;c-=2;var e=b;c=c<2*a.length?c/2:a.length;for(var f=0;f<c;++f)J[b>>1]=a.charCodeAt(f),b+=2;J[b>>1]=0;return b-e}function na(a){return 2*a.length}
function oa(a){for(var b=0,c="";;){var e=K[a+4*b>>2];if(0==e)return c;++b;65536<=e?(e-=65536,c+=String.fromCharCode(55296|e>>10,56320|e&1023)):c+=String.fromCharCode(e)}}function pa(a,b,c){void 0===c&&(c=2147483647);if(4>c)return 0;var e=b;c=e+c-4;for(var f=0;f<a.length;++f){var g=a.charCodeAt(f);if(55296<=g&&57343>=g){var n=a.charCodeAt(++f);g=65536+((g&1023)<<10)|n&1023}K[b>>2]=g;b+=4;if(b+4>c)break}K[b>>2]=0;return b-e}
function qa(a){for(var b=0,c=0;c<a.length;++c){var e=a.charCodeAt(c);55296<=e&&57343>=e&&++c;b+=4}return b}var L,ra,I,J,sa,K,M,ta,ua;function va(a){L=a;d.HEAP8=ra=new Int8Array(a);d.HEAP16=J=new Int16Array(a);d.HEAP32=K=new Int32Array(a);d.HEAPU8=I=new Uint8Array(a);d.HEAPU16=sa=new Uint16Array(a);d.HEAPU32=M=new Uint32Array(a);d.HEAPF32=ta=new Float32Array(a);d.HEAPF64=ua=new Float64Array(a)}var wa=d.INITIAL_MEMORY||16777216;d.wasmMemory?G=d.wasmMemory:G=new WebAssembly.Memory({initial:wa/65536});
G&&(L=G.buffer);wa=L.byteLength;va(L);K[8664]=5277696;function xa(a){for(;0<a.length;){var b=a.shift();if("function"==typeof b)b();else{var c=b.X;"number"===typeof c?void 0===b.R?d.dynCall_v(c):d.dynCall_vi(c,b.R):c(void 0===b.R?null:b.R)}}}var ya=[],za=[],Aa=[],Ba=[];function Ca(){var a=d.preRun.shift();ya.unshift(a)}var N=0,Da=null,O=null;d.preloadedImages={};d.preloadedAudios={};
function D(a){if(d.onAbort)d.onAbort(a);ea(a);E(a);ha=!0;throw new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");}function Ea(){var a=P;return String.prototype.startsWith?a.startsWith("data:application/octet-stream;base64,"):0===a.indexOf("data:application/octet-stream;base64,")}var P="webp_enc.wasm";if(!Ea()){var Fa=P;P=d.locateFile?d.locateFile(Fa,z):z+Fa}
function Ga(){try{if(F)return new Uint8Array(F);if(C)return C(P);throw"both async and sync fetching of the wasm failed";}catch(a){D(a)}}function Ha(){return F||!x&&!y||"function"!==typeof fetch?new Promise(function(a){a(Ga())}):fetch(P,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+P+"'";return a.arrayBuffer()}).catch(function(){return Ga()})}za.push({X:function(){Ia()}});function Ja(){return 0<Ja.T}var Ka={};
function La(a){for(;a.length;){var b=a.pop();a.pop()(b)}}function Ma(a){return this.fromWireType(M[a>>2])}var Q={},R={},Na={};function Oa(a){if(void 0===a)return"_unknown";a=a.replace(/[^a-zA-Z0-9_]/g,"$");var b=a.charCodeAt(0);return 48<=b&&57>=b?"_"+a:a}function Pa(a,b){a=Oa(a);return(new Function("body","return function "+a+'() {\n "use strict"; return body.apply(this, arguments);\n};\n'))(b)}
function Qa(a){var b=Error,c=Pa(a,function(e){this.name=a;this.message=e;e=Error(e).stack;void 0!==e&&(this.stack=this.toString()+"\n"+e.replace(/^Error(:[^\n]*)?\n/,""))});c.prototype=Object.create(b.prototype);c.prototype.constructor=c;c.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message};return c}var Ra=void 0;
function Sa(a,b,c){function e(h){h=c(h);if(h.length!==a.length)throw new Ra("Mismatched type converter count");for(var k=0;k<a.length;++k)S(a[k],h[k])}a.forEach(function(h){Na[h]=b});var f=Array(b.length),g=[],n=0;b.forEach(function(h,k){R.hasOwnProperty(h)?f[k]=R[h]:(g.push(h),Q.hasOwnProperty(h)||(Q[h]=[]),Q[h].push(function(){f[k]=R[h];++n;n===g.length&&e(f)}))});0===g.length&&e(f)}
function Ta(a){switch(a){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+a);}}var Ua=void 0;function T(a){for(var b="";I[a];)b+=Ua[I[a++]];return b}var Va=void 0;function U(a){throw new Va(a);}
function S(a,b,c){c=c||{};if(!("argPackAdvance"in b))throw new TypeError("registerType registeredInstance requires argPackAdvance");var e=b.name;a||U('type "'+e+'" must have a positive integer typeid pointer');if(R.hasOwnProperty(a)){if(c.aa)return;U("Cannot register type '"+e+"' twice")}R[a]=b;delete Na[a];Q.hasOwnProperty(a)&&(b=Q[a],delete Q[a],b.forEach(function(f){f()}))}var Wa=[],V=[{},{value:void 0},{value:null},{value:!0},{value:!1}];
function Xa(a){4<a&&0===--V[a].S&&(V[a]=void 0,Wa.push(a))}function Ya(a){switch(a){case void 0:return 1;case null:return 2;case !0:return 3;case !1:return 4;default:var b=Wa.length?Wa.pop():V.length;V[b]={S:1,value:a};return b}}
function Za(a,b){var c=d;if(void 0===c[a].P){var e=c[a];c[a]=function(){c[a].P.hasOwnProperty(arguments.length)||U("Function '"+b+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+c[a].P+")!");return c[a].P[arguments.length].apply(this,arguments)};c[a].P=[];c[a].P[e.V]=e}}
function $a(a,b,c){d.hasOwnProperty(a)?((void 0===c||void 0!==d[a].P&&void 0!==d[a].P[c])&&U("Cannot register public name '"+a+"' twice"),Za(a,a),d.hasOwnProperty(c)&&U("Cannot register multiple overloads of a function with the same number of arguments ("+c+")!"),d[a].P[c]=b):(d[a]=b,void 0!==c&&(d[a].ia=c))}
function ab(a,b,c){switch(b){case 0:return function(e){return this.fromWireType((c?ra:I)[e])};case 1:return function(e){return this.fromWireType((c?J:sa)[e>>1])};case 2:return function(e){return this.fromWireType((c?K:M)[e>>2])};default:throw new TypeError("Unknown integer type: "+a);}}function bb(a){a=cb(a);var b=T(a);X(a);return b}function db(a,b){var c=R[a];void 0===c&&U(b+" has unknown type "+bb(a));return c}
function eb(a){if(null===a)return"null";var b=typeof a;return"object"===b||"array"===b||"function"===b?a.toString():""+a}function fb(a,b){switch(b){case 2:return function(c){return this.fromWireType(ta[c>>2])};case 3:return function(c){return this.fromWireType(ua[c>>3])};default:throw new TypeError("Unknown float type: "+a);}}
function gb(a){var b=Function;if(!(b instanceof Function))throw new TypeError("new_ called with constructor type "+typeof b+" which is not a function");var c=Pa(b.name||"unknownFunctionName",function(){});c.prototype=b.prototype;c=new c;a=b.apply(c,a);return a instanceof Object?a:c}function hb(a,b){for(var c=[],e=0;e<a;e++)c.push(K[(b>>2)+e]);return c}
function Y(a,b){a=T(a);var c=d["dynCall_"+a];for(var e=[],f=1;f<a.length;++f)e.push("a"+f);f="return function dynCall_"+(a+"_"+b)+"("+e.join(", ")+") {\n";f+=" return dynCall(rawFunction"+(e.length?", ":"")+e.join(", ")+");\n";c=(new Function("dynCall","rawFunction",f+"};\n"))(c,b);"function"!==typeof c&&U("unknown function pointer with signature "+a+": "+b);return c}var ib=void 0;
function jb(a,b){function c(g){f[g]||R[g]||(Na[g]?Na[g].forEach(c):(e.push(g),f[g]=!0))}var e=[],f={};b.forEach(c);throw new ib(a+": "+e.map(bb).join([", "]));}function kb(a,b,c){switch(b){case 0:return c?function(e){return ra[e]}:function(e){return I[e]};case 1:return c?function(e){return J[e>>1]}:function(e){return sa[e>>1]};case 2:return c?function(e){return K[e>>2]}:function(e){return M[e>>2]};default:throw new TypeError("Unknown integer type: "+a);}}Ra=d.InternalError=Qa("InternalError");
for(var lb=Array(256),mb=0;256>mb;++mb)lb[mb]=String.fromCharCode(mb);Ua=lb;Va=d.BindingError=Qa("BindingError");d.count_emval_handles=function(){for(var a=0,b=5;b<V.length;++b)void 0!==V[b]&&++a;return a};d.get_first_emval=function(){for(var a=5;a<V.length;++a)if(void 0!==V[a])return V[a];return null};ib=d.UnboundTypeError=Qa("UnboundTypeError");
var ob={j:function(a){return nb(a)},i:function(a){"uncaught_exception"in Ja?Ja.T++:Ja.T=1;throw a;},l:function(a){var b=Ka[a];delete Ka[a];var c=b.ba,e=b.da,f=b.U,g=f.map(function(n){return n.$}).concat(f.map(function(n){return n.fa}));Sa([a],g,function(n){var h={};f.forEach(function(k,l){var m=n[l],p=k.Y,r=k.Z,v=n[l+f.length],q=k.ea,t=k.ga;h[k.W]={read:function(A){return m.fromWireType(p(r,A))},write:function(A,H){var W=[];q(t,A,v.toWireType(W,H));La(W)}}});return[{name:b.name,fromWireType:function(k){var l=
{},m;for(m in h)l[m]=h[m].read(k);e(k);return l},toWireType:function(k,l){for(var m in h)if(!(m in l))throw new TypeError("Missing field");var p=c();for(m in h)h[m].write(p,l[m]);null!==k&&k.push(e,p);return p},argPackAdvance:8,readValueFromPointer:Ma,O:e}]})},s:function(a,b,c,e,f){var g=Ta(c);b=T(b);S(a,{name:b,fromWireType:function(n){return!!n},toWireType:function(n,h){return h?e:f},argPackAdvance:8,readValueFromPointer:function(n){if(1===c)var h=ra;else if(2===c)h=J;else if(4===c)h=K;else throw new TypeError("Unknown boolean type size: "+
b);return this.fromWireType(h[n>>g])},O:null})},r:function(a,b){b=T(b);S(a,{name:b,fromWireType:function(c){var e=V[c].value;Xa(c);return e},toWireType:function(c,e){return Ya(e)},argPackAdvance:8,readValueFromPointer:Ma,O:null})},o:function(a,b,c,e){function f(){}c=Ta(c);b=T(b);f.values={};S(a,{name:b,constructor:f,fromWireType:function(g){return this.constructor.values[g]},toWireType:function(g,n){return n.value},argPackAdvance:8,readValueFromPointer:ab(b,c,e),O:null});$a(b,f)},n:function(a,b,c){var e=
db(a,"enum");b=T(b);a=e.constructor;e=Object.create(e.constructor.prototype,{value:{value:c},constructor:{value:Pa(e.name+"_"+b,function(){})}});a.values[c]=e;a[b]=e},g:function(a,b,c){c=Ta(c);b=T(b);S(a,{name:b,fromWireType:function(e){return e},toWireType:function(e,f){if("number"!==typeof f&&"boolean"!==typeof f)throw new TypeError('Cannot convert "'+eb(f)+'" to '+this.name);return f},argPackAdvance:8,readValueFromPointer:fb(b,c),O:null})},d:function(a,b,c,e,f,g){var n=hb(b,c);a=T(a);f=Y(e,f);
$a(a,function(){jb("Cannot call "+a+" due to unbound types",n)},b-1);Sa([],n,function(h){var k=[h[0],null].concat(h.slice(1)),l=h=a,m=f,p=k.length;2>p&&U("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var r=null!==k[1]&&!1,v=!1,q=1;q<k.length;++q)if(null!==k[q]&&void 0===k[q].O){v=!0;break}var t="void"!==k[0].name,A="",H="";for(q=0;q<p-2;++q)A+=(0!==q?", ":"")+"arg"+q,H+=(0!==q?", ":"")+"arg"+q+"Wired";l="return function "+Oa(l)+"("+A+") {\nif (arguments.length !== "+
(p-2)+") {\nthrowBindingError('function "+l+" called with ' + arguments.length + ' arguments, expected "+(p-2)+" args!');\n}\n";v&&(l+="var destructors = [];\n");var W=v?"destructors":"null";A="throwBindingError invoker fn runDestructors retType classParam".split(" ");m=[U,m,g,La,k[0],k[1]];r&&(l+="var thisWired = classParam.toWireType("+W+", this);\n");for(q=0;q<p-2;++q)l+="var arg"+q+"Wired = argType"+q+".toWireType("+W+", arg"+q+"); // "+k[q+2].name+"\n",A.push("argType"+q),m.push(k[q+2]);r&&(H=
"thisWired"+(0<H.length?", ":"")+H);l+=(t?"var rv = ":"")+"invoker(fn"+(0<H.length?", ":"")+H+");\n";if(v)l+="runDestructors(destructors);\n";else for(q=r?1:2;q<k.length;++q)p=1===q?"thisWired":"arg"+(q-2)+"Wired",null!==k[q].O&&(l+=p+"_dtor("+p+"); // "+k[q].name+"\n",A.push(p+"_dtor"),m.push(k[q].O));t&&(l+="var ret = retType.fromWireType(rv);\nreturn ret;\n");A.push(l+"}\n");k=gb(A).apply(null,m);q=b-1;if(!d.hasOwnProperty(h))throw new Ra("Replacing nonexistant public symbol");void 0!==d[h].P&&
void 0!==q?d[h].P[q]=k:(d[h]=k,d[h].V=q);return[]})},b:function(a,b,c,e,f){function g(l){return l}b=T(b);-1===f&&(f=4294967295);var n=Ta(c);if(0===e){var h=32-8*c;g=function(l){return l<<h>>>h}}var k=-1!=b.indexOf("unsigned");S(a,{name:b,fromWireType:g,toWireType:function(l,m){if("number"!==typeof m&&"boolean"!==typeof m)throw new TypeError('Cannot convert "'+eb(m)+'" to '+this.name);if(m<e||m>f)throw new TypeError('Passing a number "'+eb(m)+'" from JS side to C/C++ side to an argument of type "'+
b+'", which is outside the valid range ['+e+", "+f+"]!");return k?m>>>0:m|0},argPackAdvance:8,readValueFromPointer:kb(b,n,0!==e),O:null})},a:function(a,b,c){function e(g){g>>=2;var n=M;return new f(L,n[g+1],n[g])}var f=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][b];c=T(c);S(a,{name:c,fromWireType:e,argPackAdvance:8,readValueFromPointer:e},{aa:!0})},h:function(a,b){b=T(b);var c="std::string"===b;S(a,{name:b,fromWireType:function(e){var f=M[e>>2];if(c){var g=
I[e+4+f],n=0;0!=g&&(n=g,I[e+4+f]=0);var h=e+4;for(g=0;g<=f;++g){var k=e+4+g;if(0==I[k]){if(h){for(var l=I,m=h+NaN,p=h;l[p]&&!(p>=m);)++p;if(16<p-h&&l.subarray&&ia)h=ia.decode(l.subarray(h,p));else{for(m="";h<p;){var r=l[h++];if(r&128){var v=l[h++]&63;if(192==(r&224))m+=String.fromCharCode((r&31)<<6|v);else{var q=l[h++]&63;r=224==(r&240)?(r&15)<<12|v<<6|q:(r&7)<<18|v<<12|q<<6|l[h++]&63;65536>r?m+=String.fromCharCode(r):(r-=65536,m+=String.fromCharCode(55296|r>>10,56320|r&1023))}}else m+=String.fromCharCode(r)}h=
m}}else h="";if(void 0===t)var t=h;else t+=String.fromCharCode(0),t+=h;h=k+1}}0!=n&&(I[e+4+f]=n)}else{t=Array(f);for(g=0;g<f;++g)t[g]=String.fromCharCode(I[e+4+g]);t=t.join("")}X(e);return t},toWireType:function(e,f){f instanceof ArrayBuffer&&(f=new Uint8Array(f));var g="string"===typeof f;g||f instanceof Uint8Array||f instanceof Uint8ClampedArray||f instanceof Int8Array||U("Cannot pass non-string to std::string");var n=(c&&g?function(){for(var l=0,m=0;m<f.length;++m){var p=f.charCodeAt(m);55296<=
p&&57343>=p&&(p=65536+((p&1023)<<10)|f.charCodeAt(++m)&1023);127>=p?++l:l=2047>=p?l+2:65535>=p?l+3:l+4}return l}:function(){return f.length})(),h=nb(4+n+1);M[h>>2]=n;if(c&&g)ja(f,h+4,n+1);else if(g)for(g=0;g<n;++g){var k=f.charCodeAt(g);255<k&&(X(h),U("String has UTF-16 code units that do not fit in 8 bits"));I[h+4+g]=k}else for(g=0;g<n;++g)I[h+4+g]=f[g];null!==e&&e.push(X,h);return h},argPackAdvance:8,readValueFromPointer:Ma,O:function(e){X(e)}})},f:function(a,b,c){c=T(c);if(2===b){var e=la;var f=
ma;var g=na;var n=function(){return sa};var h=1}else 4===b&&(e=oa,f=pa,g=qa,n=function(){return M},h=2);S(a,{name:c,fromWireType:function(k){var l=M[k>>2],m=n(),p=m[k+4+l*b>>h],r=0;0!=p&&(r=p,m[k+4+l*b>>h]=0);var v=k+4;for(p=0;p<=l;++p){var q=k+4+p*b;if(0==m[q>>h]){v=e(v);if(void 0===t)var t=v;else t+=String.fromCharCode(0),t+=v;v=q+b}}0!=r&&(m[k+4+l*b>>h]=r);X(k);return t},toWireType:function(k,l){"string"!==typeof l&&U("Cannot pass non-string to C++ string type "+c);var m=g(l),p=nb(4+m+b);M[p>>
2]=m>>h;f(l,p+4,m+b);null!==k&&k.push(X,p);return p},argPackAdvance:8,readValueFromPointer:Ma,O:function(k){X(k)}})},m:function(a,b,c,e,f,g){Ka[a]={name:T(b),ba:Y(c,e),da:Y(f,g),U:[]}},e:function(a,b,c,e,f,g,n,h,k,l){Ka[a].U.push({W:T(b),$:c,Y:Y(e,f),Z:g,fa:n,ea:Y(h,k),ga:l})},t:function(a,b){b=T(b);S(a,{ha:!0,name:b,argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},u:Xa,k:function(a){4<a&&(V[a].S+=1)},q:function(a,b){a=db(a,"_emval_take_value");a=a.readValueFromPointer(b);return Ya(a)},
p:function(a,b,c){I.copyWithin(a,b,b+c)},c:function(a){var b=I.length;if(2147418112<a)return!1;for(var c=1;4>=c;c*=2){var e=b*(1+.2/c);e=Math.min(e,a+100663296);e=Math.max(16777216,a,e);0<e%65536&&(e+=65536-e%65536);a:{try{G.grow(Math.min(2147418112,e)-L.byteLength+65535>>16);va(G.buffer);var f=1;break a}catch(g){}f=void 0}if(f)return!0}return!1},memory:G,table:fa},pb=function(){function a(f){d.asm=f.exports;N--;d.monitorRunDependencies&&d.monitorRunDependencies(N);0==N&&(null!==Da&&(clearInterval(Da),
Da=null),O&&(f=O,O=null,f()))}function b(f){a(f.instance)}function c(f){return Ha().then(function(g){return WebAssembly.instantiate(g,e)}).then(f,function(g){E("failed to asynchronously prepare wasm: "+g);D(g)})}var e={a:ob};N++;d.monitorRunDependencies&&d.monitorRunDependencies(N);if(d.instantiateWasm)try{return d.instantiateWasm(e,a)}catch(f){return E("Module.instantiateWasm callback failed with error: "+f),!1}(function(){if(F||"function"!==typeof WebAssembly.instantiateStreaming||Ea()||"function"!==
typeof fetch)return c(b);fetch(P,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(b,function(g){E("wasm streaming compile failed: "+g);E("falling back to ArrayBuffer instantiation");c(b)})})})();return{}}();d.asm=pb;
var Ia=d.___wasm_call_ctors=function(){return(Ia=d.___wasm_call_ctors=d.asm.v).apply(null,arguments)},nb=d._malloc=function(){return(nb=d._malloc=d.asm.w).apply(null,arguments)},X=d._free=function(){return(X=d._free=d.asm.x).apply(null,arguments)},cb=d.___getTypeName=function(){return(cb=d.___getTypeName=d.asm.y).apply(null,arguments)};d.___embind_register_native_and_builtin_types=function(){return(d.___embind_register_native_and_builtin_types=d.asm.z).apply(null,arguments)};
d.dynCall_i=function(){return(d.dynCall_i=d.asm.A).apply(null,arguments)};d.dynCall_vi=function(){return(d.dynCall_vi=d.asm.B).apply(null,arguments)};d.dynCall_iii=function(){return(d.dynCall_iii=d.asm.C).apply(null,arguments)};d.dynCall_viii=function(){return(d.dynCall_viii=d.asm.D).apply(null,arguments)};d.dynCall_fii=function(){return(d.dynCall_fii=d.asm.E).apply(null,arguments)};d.dynCall_viif=function(){return(d.dynCall_viif=d.asm.F).apply(null,arguments)};
d.dynCall_ii=function(){return(d.dynCall_ii=d.asm.G).apply(null,arguments)};d.dynCall_iiiiii=function(){return(d.dynCall_iiiiii=d.asm.H).apply(null,arguments)};d.dynCall_viiiii=function(){return(d.dynCall_viiiii=d.asm.I).apply(null,arguments)};d.dynCall_v=function(){return(d.dynCall_v=d.asm.J).apply(null,arguments)};d.dynCall_iiii=function(){return(d.dynCall_iiii=d.asm.K).apply(null,arguments)};d.dynCall_viiiiiiiii=function(){return(d.dynCall_viiiiiiiii=d.asm.L).apply(null,arguments)};
d.dynCall_viiii=function(){return(d.dynCall_viiii=d.asm.M).apply(null,arguments)};d.dynCall_viiiiii=function(){return(d.dynCall_viiiiii=d.asm.N).apply(null,arguments)};d.asm=pb;var Z;d.then=function(a){if(Z)a(d);else{var b=d.onRuntimeInitialized;d.onRuntimeInitialized=function(){b&&b();a(d)}}return d};O=function qb(){Z||rb();Z||(O=qb)};
function rb(){function a(){if(!Z&&(Z=!0,d.calledRun=!0,!ha)){xa(za);xa(Aa);if(d.onRuntimeInitialized)d.onRuntimeInitialized();if(d.postRun)for("function"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;){var b=d.postRun.shift();Ba.unshift(b)}xa(Ba)}}if(!(0<N)){if(d.preRun)for("function"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)Ca();xa(ya);0<N||(d.setStatus?(d.setStatus("Running..."),setTimeout(function(){setTimeout(function(){d.setStatus("")},1);a()},1)):a())}}d.run=rb;
if(d.preInit)for("function"==typeof d.preInit&&(d.preInit=[d.preInit]);0<d.preInit.length;)d.preInit.pop()();noExitRuntime=!0;rb();
return webp_enc
}
);
})();
if (typeof exports === 'object' && typeof module === 'object')
module.exports = webp_enc;
else if (typeof define === 'function' && define['amd'])
define([], function() { return webp_enc; });
else if (typeof exports === 'object')
exports["webp_enc"] = webp_enc;

Binary file not shown.

View File

@@ -1,5 +1,5 @@
{
"name": "webp_enc",
"name": "webp",
"requires": true,
"lockfileVersion": 1,
"dependencies": {

View File

@@ -1,8 +1,8 @@
{
"name": "webp_enc",
"name": "webp",
"scripts": {
"install": "napa",
"build": "docker run --rm -v $(pwd):/src trzeci/emscripten ./build.sh"
"build": "docker run --rm -v $(pwd):/src trzeci/emscripten-upstream ./build.sh"
},
"napa": {
"libwebp": "webmproject/libwebp#v1.0.2"

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +0,0 @@
{
"name": "webp_dec",
"scripts": {
"install": "napa",
"build": "docker run --rm -v $(pwd):/src trzeci/emscripten ./build.sh"
},
"napa": {
"libwebp": "webmproject/libwebp#v1.0.2"
},
"devDependencies": {
"napa": "3.0.0"
}
}

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -1,61 +0,0 @@
#!/bin/bash
set -e
export OPTIMIZE="-Os"
export LDFLAGS="${OPTIMIZE}"
export CFLAGS="${OPTIMIZE}"
export CPPFLAGS="${OPTIMIZE}"
apt-get update
apt-get install -qqy autoconf libtool libpng-dev pkg-config
echo "============================================="
echo "Compiling libwebp"
echo "============================================="
test -n "$SKIP_LIBWEBP" || (
cd node_modules/libwebp
autoreconf -fiv
rm -rf build || true
mkdir -p build && cd build
emconfigure ../configure \
--disable-libwebpdemux \
--disable-wic \
--disable-gif \
--disable-tiff \
--disable-jpeg \
--disable-png \
--disable-sdl \
--disable-gl \
--disable-threading \
--disable-neon-rtcd \
--disable-neon \
--disable-sse2 \
--disable-sse4.1
emmake make
)
echo "============================================="
echo "Compiling wasm bindings"
echo "============================================="
(
emcc \
${OPTIMIZE} \
--bind \
-s ALLOW_MEMORY_GROWTH=1 \
-s MODULARIZE=1 \
-s 'EXPORT_NAME="webp_enc"' \
--std=c++11 \
-I node_modules/libwebp \
-o ./webp_enc.js \
-x c++ \
webp_enc.cpp \
node_modules/libwebp/build/src/.libs/libwebp.a
)
echo "============================================="
echo "Compiling wasm bindings done"
echo "============================================="
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "Did you update your docker image?"
echo "Run \`docker pull trzeci/emscripten\`"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

View File

@@ -1,96 +0,0 @@
#include <emscripten/bind.h>
#include <emscripten/val.h>
#include "src/webp/encode.h"
#include <stdlib.h>
#include <string.h>
#include <stdexcept>
using namespace emscripten;
int version() {
return WebPGetEncoderVersion();
}
uint8_t* last_result;
val encode(std::string img, int width, int height, WebPConfig config) {
uint8_t* img_in = (uint8_t*) img.c_str();
// A lot of this is duplicated from Encode in picture_enc.c
WebPPicture pic;
WebPMemoryWriter wrt;
int ok;
if (!WebPPictureInit(&pic)) {
// shouldn't happen, except if system installation is broken
throw std::runtime_error("Unexpected error");
}
// Only use use_argb if we really need it, as it's slower.
pic.use_argb = config.lossless || config.use_sharp_yuv || config.preprocessing > 0;
pic.width = width;
pic.height = height;
pic.writer = WebPMemoryWrite;
pic.custom_ptr = &wrt;
WebPMemoryWriterInit(&wrt);
ok = WebPPictureImportRGBA(&pic, (uint8_t*) img_in, width * 4) && WebPEncode(&config, &pic);
WebPPictureFree(&pic);
if (!ok) {
WebPMemoryWriterClear(&wrt);
throw std::runtime_error("Encode failed");
}
last_result = wrt.mem;
return val(typed_memory_view(wrt.size, wrt.mem));
}
void free_result() {
WebPFree(last_result);
}
EMSCRIPTEN_BINDINGS(my_module) {
enum_<WebPImageHint>("WebPImageHint")
.value("WEBP_HINT_DEFAULT", WebPImageHint::WEBP_HINT_DEFAULT)
.value("WEBP_HINT_PICTURE", WebPImageHint::WEBP_HINT_PICTURE)
.value("WEBP_HINT_PHOTO", WebPImageHint::WEBP_HINT_PHOTO)
.value("WEBP_HINT_GRAPH", WebPImageHint::WEBP_HINT_GRAPH)
;
value_object<WebPConfig>("WebPConfig")
.field("lossless", &WebPConfig::lossless)
.field("quality", &WebPConfig::quality)
.field("method", &WebPConfig::method)
.field("image_hint", &WebPConfig::image_hint)
.field("target_size", &WebPConfig::target_size)
.field("target_PSNR", &WebPConfig::target_PSNR)
.field("segments", &WebPConfig::segments)
.field("sns_strength", &WebPConfig::sns_strength)
.field("filter_strength", &WebPConfig::filter_strength)
.field("filter_sharpness", &WebPConfig::filter_sharpness)
.field("filter_type", &WebPConfig::filter_type)
.field("autofilter", &WebPConfig::autofilter)
.field("alpha_compression", &WebPConfig::alpha_compression)
.field("alpha_filtering", &WebPConfig::alpha_filtering)
.field("alpha_quality", &WebPConfig::alpha_quality)
.field("pass", &WebPConfig::pass)
.field("show_compressed", &WebPConfig::show_compressed)
.field("preprocessing", &WebPConfig::preprocessing)
.field("partitions", &WebPConfig::partitions)
.field("partition_limit", &WebPConfig::partition_limit)
.field("emulate_jpeg_size", &WebPConfig::emulate_jpeg_size)
.field("thread_level", &WebPConfig::thread_level)
.field("low_memory", &WebPConfig::low_memory)
.field("near_lossless", &WebPConfig::near_lossless)
.field("exact", &WebPConfig::exact)
.field("use_delta_palette", &WebPConfig::use_delta_palette)
.field("use_sharp_yuv", &WebPConfig::use_sharp_yuv)
;
function("version", &version);
function("encode", &encode);
function("free_result", &free_result);
}

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -1,5 +1,3 @@
{
"extends": [
"config:base"
]
"enabled": false
}

View File

@@ -28,7 +28,7 @@ export default class OxiPNGEncoderOptions extends Component<Props, {}> {
<Range
name="level"
min="0"
max="6"
max="3"
step="1"
value={options.level}
onInput={this.onChange}

View File

@@ -1,5 +1,5 @@
import webp_dec, { WebPModule } from '../../../codecs/webp_dec/webp_dec';
import wasmUrl from '../../../codecs/webp_dec/webp_dec.wasm';
import webp_dec, { WebPModule } from '../../../codecs/webp/dec/webp_dec';
import wasmUrl from '../../../codecs/webp/dec/webp_dec.wasm';
import { initEmscriptenModule } from '../util';
let emscriptenModule: Promise<WebPModule>;

View File

@@ -1,5 +1,5 @@
import webp_enc, { WebPModule } from '../../../codecs/webp_enc/webp_enc';
import wasmUrl from '../../../codecs/webp_enc/webp_enc.wasm';
import webp_enc, { WebPModule } from '../../../codecs/webp/enc/webp_enc';
import wasmUrl from '../../../codecs/webp/enc/webp_enc.wasm';
import { EncodeOptions } from './encoder-meta';
import { initEmscriptenModule } from '../util';

View File

@@ -270,7 +270,7 @@ export default class WebPEncoderOptions extends Component<Props, State> {
value={options.sns_strength}
onInput={this.onChange}
>
Spacial noise shaping:
Spatial noise shaping:
</Range>
</div>
<label class={style.optionTextFirst}>

View File

@@ -109,11 +109,6 @@ async function preprocessImage(
} else if (isHqx(preprocessData.resize)) {
// Hqx can only do x2, x3 or x4.
result = await processor.workerResize(result, preprocessData.resize);
// Seems like the globals from Rust from hqx and resize are conflicting.
// For now we can fix that by terminating the worker.
// TODO: Use wasm-bindgens new --web target to create a proper ES6 module
// and remove this.
processor.terminateWorker();
// If the target size is not a clean x2, x3 or x4, use Catmull-Rom
// for the remaining scaling.
const pixelOpts = { ...preprocessData.resize, method: 'catrom' };

View File

@@ -41,17 +41,31 @@ const demos = [
},
];
const installButtonSource = 'introInstallButton';
interface Props {
onFile: (file: File | Fileish) => void;
showSnack: SnackBarElement['showSnackbar'];
}
interface State {
fetchingDemoIndex?: number;
beforeInstallEvent?: BeforeInstallPromptEvent;
}
export default class Intro extends Component<Props, State> {
state: State = {};
private fileInput?: HTMLInputElement;
private installingViaButton = false;
constructor() {
super();
// Listen for beforeinstallprompt events, indicating Squoosh is installable.
window.addEventListener('beforeinstallprompt', this.onBeforeInstallPromptEvent);
// Listen for the appinstalled event, indicating Squoosh has been installed.
window.addEventListener('appinstalled', this.onAppInstalled);
}
@bind
private resetFileInput() {
@@ -90,7 +104,52 @@ export default class Intro extends Component<Props, State> {
}
}
render({ }: Props, { fetchingDemoIndex }: State) {
@bind
private onBeforeInstallPromptEvent(event: BeforeInstallPromptEvent) {
// Don't show the mini-infobar on mobile
event.preventDefault();
// Save the beforeinstallprompt event so it can be called later.
this.setState({ beforeInstallEvent: event });
// Log the event.
ga('send', 'event', 'pwa-install', 'available');
}
@bind
private async onInstallClick(event: Event) {
// Get the deferred beforeinstallprompt event
const beforeInstallEvent = this.state.beforeInstallEvent;
// If there's no deferred prompt, bail.
if (!beforeInstallEvent) return;
this.installingViaButton = true;
// Show the browser install prompt
beforeInstallEvent.prompt();
// Wait for the user to accept or dismiss the install prompt
const { outcome } = await beforeInstallEvent.userChoice;
ga('send', 'event', 'pwa-install', installButtonSource, outcome);
// If the prompt was dismissed, we aren't going to install via the button.
if (outcome === 'dismissed') {
this.installingViaButton = false;
}
}
@bind
private onAppInstalled() {
// Try to get the install, if it's not set, use 'browser'
const source = this.installingViaButton ? installButtonSource : 'browser';
ga('send', 'event', 'pwa-install', 'installed', source);
this.installingViaButton = false;
// We don't need the install button, if it's shown
this.setState({ beforeInstallEvent: undefined });
}
render({ }: Props, { fetchingDemoIndex, beforeInstallEvent }: State) {
return (
<div class={style.intro}>
<div>
@@ -120,7 +179,7 @@ export default class Intro extends Component<Props, State> {
<img class={style.demoIcon} src={demo.iconUrl} alt="" decoding="async" />
{fetchingDemoIndex === i &&
<div class={style.demoLoading}>
<loading-spinner class={style.demoLoadingSpinner}/>
<loading-spinner class={style.demoLoadingSpinner} />
</div>
}
</div>
@@ -132,6 +191,15 @@ export default class Intro extends Component<Props, State> {
)}
</ul>
</div>
{beforeInstallEvent &&
<button
type="button"
class={style.installButton}
onClick={this.onInstallClick}
>
Install
</button>
}
<ul class={style.relatedLinks}>
<li><a href="https://github.com/GoogleChromeLabs/squoosh/">View the code</a></li>
<li><a href="https://github.com/GoogleChromeLabs/squoosh/issues">Report a bug</a></li>

32
src/components/intro/missing-types.d.ts vendored Normal file
View File

@@ -0,0 +1,32 @@
/**
* The BeforeInstallPromptEvent is fired at the Window.onbeforeinstallprompt handler
* before a user is prompted to "install" a web site to a home screen on mobile.
*/
interface BeforeInstallPromptEvent extends Event {
/**
* Returns an array of DOMString items containing the platforms on which the event was dispatched.
* This is provided for user agents that want to present a choice of versions to the user such as,
* for example, "web" or "play" which would allow the user to chose between a web version or
* an Android version.
*/
readonly platforms: Array<string>;
/**
* Returns a Promise that resolves to a DOMString containing either "accepted" or "dismissed".
*/
readonly userChoice: Promise<{
outcome: 'accepted' | 'dismissed',
platform: string
}>;
/**
* Allows a developer to show the install prompt at a time of their own choosing.
* This method returns a Promise.
*/
prompt(): Promise<void>;
}
interface WindowEventMap {
"beforeinstallprompt": BeforeInstallPromptEvent;
}

View File

@@ -170,6 +170,30 @@
--color: #fff;
}
.install-button {
composes: unbutton from '../../lib/util.scss';
&:hover,
&:focus {
background: #f5f5f5;
}
background: #fff;
border: 1px solid #e8e8e8;
padding: 14px;
font-size: 1.3rem;
position: absolute;
top: 1rem;
right: 1rem;
animation: fade-in .3s ease-in-out;
}
@keyframes fade-in {
from { opacity: 0; }
}
.related-links {
display: flex;
padding: 0;

View File

@@ -13,11 +13,19 @@ if (!('customElements' in self)) {
}
if (typeof PRERENDER === 'undefined') {
// Determine the current display mode.
let displayMode = 'browser';
const mqStandAlone = '(display-mode: standalone)';
if (navigator.standalone || window.matchMedia(mqStandAlone).matches) {
displayMode = 'standalone';
}
// Setup analytics
window.ga = window.ga || ((...args) => (ga.q = ga.q || []).push(args));
ga('create', 'UA-128752250-1', 'auto');
ga('set', 'transport', 'beacon');
ga('set', 'dimension1', displayMode);
ga('send', 'pageview');
// Load the GA script
// Load the GA script
const s = document.createElement('script');
s.src = 'https://www.google-analytics.com/analytics.js';
document.head!.appendChild(s);

View File

@@ -39,3 +39,7 @@ declare var ga: {
(...args: any[]): void;
q: any[];
};
interface Navigator {
readonly standalone: boolean;
}