Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optipng #156

Merged
merged 10 commits into from
Sep 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added codecs/example_palette.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions codecs/optipng/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
build/
*.o
26 changes: 26 additions & 0 deletions codecs/optipng/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# OptiPNG

- Source: <https://sourceforge.net/project/optipng>
- Version: v0.7.7

## Dependencies

- Docker

## Example

See `example.html`

## API

### `int version()`

Returns the version of optipng as a number. va.b.c is encoded as 0x0a0b0c

### `ArrayBuffer compress(std::string buffer, {level})`;

`compress` will re-compress the given PNG image via `buffer`. `level` is a number between 0 and 7.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lazy question: are there other options to expose, or is that all it offers?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is some more options, just wanted to get this off my table, honestly:

Synopsis:
    optipng [options] files ...
Files:
    Image files of type: PNG, BMP, GIF, PNM or TIFF
Basic options:
    -?, -h, -help	show this help
    -o <level>		optimization level (0-7)		[default: 2]
    -v			run in verbose mode / show copyright and version info
General options:
    -backup, -keep	keep a backup of the modified files
    -clobber		overwrite existing files
    -fix		enable error recovery
    -force		enforce writing of a new output file
    -preserve		preserve file attributes if possible
    -quiet, -silent	run in quiet mode
    -simulate		run in simulation mode
    -out <file>		write output file to <file>
    -dir <directory>	write output file(s) to <directory>
    -log <file>		log messages to <file>
    --			stop option switch parsing
Optimization options:
    -f <filters>	PNG delta filters (0-5)			[default: 0,5]
    -i <type>		PNG interlace type (0-1)
    -zc <levels>	zlib compression levels (1-9)		[default: 9]
    -zm <levels>	zlib memory levels (1-9)		[default: 8]
    -zs <strategies>	zlib compression strategies (0-3)	[default: 0-3]
    -zw <size>		zlib window size (256,512,1k,2k,4k,8k,16k,32k)
    -full		produce a full report on IDAT (might reduce speed)
    -nb			no bit depth reduction
    -nc			no color type reduction
    -np			no palette reduction
    -nx			no reductions
    -nz			no IDAT recoding
Editing options:
    -snip		cut one image out of multi-image or animation files
    -strip <objects>	strip metadata objects (e.g. "all")
Optimization levels:
    -o0		<=>	-o1 -nx -nz				(0 or 1 trials)
    -o1		<=>	-zc9 -zm8 -zs0 -f0			(1 trial)
    		(or...)	-zc9 -zm8 -zs1 -f5			(1 trial)
    -o2		<=>	-zc9 -zm8 -zs0-3 -f0,5			(8 trials)
    -o3		<=>	-zc9 -zm8-9 -zs0-3 -f0,5		(16 trials)
    -o4		<=>	-zc9 -zm8 -zs0-3 -f0-5			(24 trials)
    -o5		<=>	-zc9 -zm8-9 -zs0-3 -f0-5		(48 trials)
    -o6		<=>	-zc1-9 -zm8 -zs0-3 -f0-5		(120 trials)
    -o7		<=>	-zc1-9 -zm8-9 -zs0-3 -f0-5		(240 trials)
    -o7 -zm1-9	<=>	-zc1-9 -zm1-9 -zs0-3 -f0-5		(1080 trials)
Notes:
    The combination for -o1 is chosen heuristically.
    Exhaustive combinations such as "-o7 -zm1-9" are not generally recommended.
Examples:
    optipng file.png						(default speed)
    optipng -o5 file.png					(slow)
    optipng -o7 file.png					(very slow)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No problem. We'll create an issue to explore these.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


### `void free_result()`

Frees the result created by `compress()`.
80 changes: 80 additions & 0 deletions codecs/optipng/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/bin/bash

set -e

export PREFIX="/src/build"
export CFLAGS="-I${PREFIX}/include/"
export CPPFLAGS="-I${PREFIX}/include/"
export LDFLAGS="-L${PREFIX}/lib/"

apt-get update
apt-get install -qqy autoconf libtool

echo "============================================="
echo "Compiling zlib"
echo "============================================="
test -n "$SKIP_ZLIB" || (
cd node_modules/zlib
emconfigure ./configure --prefix=${PREFIX}/
emmake make
emmake make install
)
echo "============================================="
echo "Compiling zlib done"
echo "============================================="

echo "============================================="
echo "Compiling libpng"
echo "============================================="
test -n "$SKIP_LIBPNG" || (
cd node_modules/libpng
autoreconf -i
emconfigure ./configure --with-zlib-prefix=${PREFIX}/ --prefix=${PREFIX}/
emmake make
emmake make install
)
echo "============================================="
echo "Compiling libpng done"
echo "============================================="

echo "============================================="
echo "Compiling optipng"
echo "============================================="
(
emcc \
-O3 \
-Wno-implicit-function-declaration \
-I ${PREFIX}/include \
-I node_modules/optipng/src/opngreduc \
-I node_modules/optipng/src/pngxtern \
-I node_modules/optipng/src/cexcept \
-I node_modules/optipng/src/gifread \
-I node_modules/optipng/src/pnmio \
-I node_modules/optipng/src/minitiff \
--std=c99 -c \
node_modules/optipng/src/opngreduc/*.c \
node_modules/optipng/src/pngxtern/*.c \
node_modules/optipng/src/gifread/*.c \
node_modules/optipng/src/minitiff/*.c \
node_modules/optipng/src/pnmio/*.c \
node_modules/optipng/src/optipng/*.c

emcc \
--bind -O3 \
-s ALLOW_MEMORY_GROWTH=1 -s MODULARIZE=1 -s 'EXPORT_NAME="optipng"' \
-I ${PREFIX}/include \
-I node_modules/optipng/src/opngreduc \
-I node_modules/optipng/src/pngxtern \
-I node_modules/optipng/src/cexcept \
-I node_modules/optipng/src/gifread \
-I node_modules/optipng/src/pnmio \
-I node_modules/optipng/src/minitiff \
-o "optipng.js" \
--std=c++11 \
optipng.cpp \
*.o \
${PREFIX}/lib/libz.so ${PREFIX}/lib/libpng.a
)
echo "============================================="
echo "Compiling optipng done"
echo "============================================="
19 changes: 19 additions & 0 deletions codecs/optipng/example.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!doctype html>
<script src='optipng.js'></script>
<script>
const Module = optipng();

Module.onRuntimeInitialized = async _ => {
console.log('Version:', Module.version().toString(16));
const image = await fetch('../example_palette.png').then(r => r.arrayBuffer());
const newImage = Module.compress(image, {level: 3});
console.log('done');
Module.free_result();

console.log(`Old size: ${image.byteLength}, new size: ${newImage.byteLength} (${newImage.byteLength/image.byteLength*100}%)`);
const blobURL = URL.createObjectURL(new Blob([newImage], {type: 'image/png'}));
const img = document.createElement('img');
img.src = blobURL;
document.body.appendChild(img);
};
</script>
51 changes: 51 additions & 0 deletions codecs/optipng/optipng.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include "emscripten/bind.h"
#include "emscripten/val.h"

#include <stdio.h>

using namespace emscripten;

extern "C" int main(int argc, char *argv[]);

int version() {
// FIXME (@surma): Haven’t found a version in optipng :(
return 0;
}

struct OptiPngOpts {
int level;
};

uint8_t* result;
val compress(std::string png, OptiPngOpts opts) {
FILE* infile = fopen("input.png", "wb");
fwrite(png.c_str(), png.length(), 1, infile);
fflush(infile);
fclose(infile);

char optlevel[8];
sprintf(&optlevel[0], "-o%d", opts.level);
char* args[] = {"optipng", optlevel, "-out", "output.png", "input.png"};
main(5, args);

FILE *outfile = fopen("output.png", "rb");
fseek(outfile, 0, SEEK_END);
int fsize = ftell(outfile);
result = (uint8_t*) malloc(fsize);
fseek(outfile, 0, SEEK_SET);
fread(result, fsize, 1, outfile);
return val(typed_memory_view(fsize, result));
}

void free_result() {
free(result);
}

EMSCRIPTEN_BINDINGS(my_module) {
value_object<OptiPngOpts>("OptiPngOpts")
.field("level", &OptiPngOpts::level);

function("version", &version);
function("compress", &compress);
function("free_result", &free_result);
}
10 changes: 10 additions & 0 deletions codecs/optipng/optipng.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {EncodeOptions} from "src/codecs/optipng/encoder";

export interface OptiPngModule extends EmscriptenWasm.Module {
compress(data: BufferSource, opts: EncodeOptions): Uint8Array;
free_result(): void;
}

export default function(opts: EmscriptenWasm.ModuleOpts): OptiPngModule;


24 changes: 24 additions & 0 deletions codecs/optipng/optipng.js

Large diffs are not rendered by default.

Binary file added codecs/optipng/optipng.wasm
Binary file not shown.
Loading