Skip to content

Commit

Permalink
Merge pull request #29 from cyrilwanner/feature/gifsicle
Browse files Browse the repository at this point in the history
  • Loading branch information
cyrilwanner committed Aug 5, 2020
2 parents c97e59d + 05f518e commit bbae5ec
Show file tree
Hide file tree
Showing 28 changed files with 7,411 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Currently, only Node.js builds are published. Browser builds will be supported a

- **[`@wasm-codecs/mozjpeg`](packages/mozjpeg)**
- **[`@wasm-codecs/oxipng`](packages/oxipng)**
- `@wasm-codecs/gifsicle` (*coming soon*)
- **[`@wasm-codecs/gifsicle`](packages/gifsicle)**
- `@wasm-codecs/webp` (*coming soon*)

## License
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"scripts": {
"build": "lerna run build --parallel",
"lint": "lerna run lint --parallel",
"lint:fix": "lerna run lint:fix --parallel",
"test": "lerna run test --parallel",
"test:sizes": "lerna run test:sizes --parallel",
"postinstall": "lerna bootstrap",
Expand Down
3 changes: 3 additions & 0 deletions packages/gifsicle/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "../../.babelrc"
}
2 changes: 2 additions & 0 deletions packages/gifsicle/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!Dockerfile
8 changes: 8 additions & 0 deletions packages/gifsicle/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../.eslintrc.json",
"rules": {
"import/no-unresolved": ["error", {
"ignore": ["/gifsicle$"]
}]
}
}
20 changes: 20 additions & 0 deletions packages/gifsicle/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
FROM trzeci/emscripten:1.39.18-upstream

RUN apt-get update && \
apt-get install -y \
autoconf \
libtool \
libpng-dev \
pkg-config && \
rm -rf /var/lib/apt/lists/*

RUN curl https://codeload.github.com/kohler/gifsicle/zip/v1.92 -o /tmp/gifsicle.zip && \
unzip /tmp/gifsicle.zip -d /lib && \
mv /lib/gifsicle-1.92 /lib/gifsicle && \
rm /tmp/gifsicle.zip

RUN cd /lib/gifsicle && \
sed -i 's/CC="$CC -W -Wall"/CC="$CC -W -Wall -s ERROR_ON_UNDEFINED_SYMBOLS=0"/g' configure.ac && \
./bootstrap.sh && \
emconfigure ./configure --disable-gifview && \
emmake make
21 changes: 21 additions & 0 deletions packages/gifsicle/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Cyril Wanner

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
80 changes: 80 additions & 0 deletions packages/gifsicle/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# `@wasm-codecs/gifsicle` [![npm version](https://badgen.net/npm/v/@wasm-codecs/gifsicle)](https://www.npmjs.com/package/@wasm-codecs/gifsicle) [![license](https://badgen.net/github/license/cyrilwanner/wasm-codecs)](https://github.com/cyrilwanner/wasm-codecs/blob/master/LICENSE) [![downloads](https://badgen.net/npm/dt/@wasm-codecs/gifsicle)](https://www.npmjs.com/package/@wasm-codecs/gifsicle)

> Gifsicle WebAssembly Codec
## Table of contents

1. [Installation](#installation)
1. [Usage](#usage)
1. [API](#api)
1. [Examples](#examples)
1. [License](#license)

## Installation

```bash
npm install @wasm-codecs/gifsicle
```

**Requirements:**
- Node.js 10 or later

## Usage

```typescript
import encode from '@wasm-codecs/gifsicle';

(async () => {
const encodedImage = await encode(image, encodeOptions);
})();
```

## API

### `encode(image, encodeOptions?): Buffer`

Returns a buffer containing the compressed image data.

##### `image: Buffer`

Buffer of a GIF image.

##### `encodeOptions?: EncodeOptions`

All encoding options are optional and fall back to the [default values](https://github.com/cyrilwanner/wasm-codecs/blob/master/packages/gifsicle/src/options.ts#L3-L6).

```typescript
type EncodeOptions = {
optimizationLevel?: number;
interlaced?: boolean;
colors?: number;
width?: number;
height?: number;
}
```
## Examples
### Using Node.js
```typescript
import fs from 'fs';
import encode from '@wasm-codecs/gifsicle';

(async () => {
// read input image as a buffer
const data = fs.readFileSync('in.gif');

// encode the image using @wasm-codecs/gifsicle
const output = await encode(data);

// save the image to the file system
fs.writeFileSync('out.png', output);
})();
```

## License

Licensed under the [MIT](https://github.com/cyrilwanner/wasm-codecs/blob/master/LICENSE) license.

© Copyright Cyril Wanner
Binary file added packages/gifsicle/__tests__/images/large.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packages/gifsicle/__tests__/images/medium.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packages/gifsicle/__tests__/images/small.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added packages/gifsicle/__tests__/images/tiny.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
105 changes: 105 additions & 0 deletions packages/gifsicle/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import {
initTestUtils,
cleanup,
getImageFile,
writeTmpBuffer,
getFileSize,
getImageMetadata,
} from '@wasm-codecs/test-utils';
import gifInfo from 'gif-info';
import encode from '../lib';

describe('gifsicle', () => {
beforeAll(() => {
initTestUtils(__dirname);
});

afterAll(() => cleanup());

// test all image sizes
['tiny', 'small', 'medium', 'large'].forEach((size) => {
it(`encodes a ${size} image`, async () => {
jest.setTimeout(20000);

const data = getImageFile(`images/${size}.gif`);
const originalSize = getFileSize(`images/${size}.gif`);
const originalMetadata = await getImageMetadata(`images/${size}.gif`);

const result = await encode(data);
const encodedPath = writeTmpBuffer(result, `${size}.gif`);
const encodedSize = getFileSize(encodedPath);

// expect the image size to be between 0.25 and 0.995 of the original image
expect(encodedSize).toBeLessThan(originalSize * 0.995);
expect(encodedSize).toBeGreaterThan(originalSize * 0.25);

// check if the image is still a valid jpeg image
const metadata = await getImageMetadata(encodedPath);
expect(metadata.format).toBe('gif');
expect(metadata.width).toBe(originalMetadata.width);
expect(metadata.height).toBe(originalMetadata.height);
});
});

it('respects optimization level option', async () => {
const data = getImageFile('images/small.gif');

// with level 1
const resultLevel1 = await encode(data, { optimizationLevel: 1 });
const pathLevel1 = writeTmpBuffer(resultLevel1, 'small-level1.gif');
const sizeLevel1 = getFileSize(pathLevel1);

// with level 3
const resultLevel3 = await encode(data, { optimizationLevel: 3 });
const pathLevel3 = writeTmpBuffer(resultLevel3, 'small-level3.gif');
const sizeLevel3 = getFileSize(pathLevel3);

expect(sizeLevel1).toBeGreaterThan(sizeLevel3);
});

it('resizes correctly with both sides given', async () => {
const data = getImageFile('images/medium.gif');
const result = await encode(data, { width: 20, height: 30 });
const encodedPath = writeTmpBuffer(result, 'medium-20x30.gif');

const metadata = await getImageMetadata(encodedPath);
expect(metadata.format).toBe('gif');
expect(metadata.width).toBe(20);
expect(metadata.height).toBe(30);
});

it('resizes correctly with only width given', async () => {
const data = getImageFile('images/medium.gif');
const result = await encode(data, { width: 50 });
const encodedPath = writeTmpBuffer(result, 'medium-50x_.gif');

const metadata = await getImageMetadata(encodedPath);
expect(metadata.format).toBe('gif');
expect(metadata.width).toBe(50);
expect(metadata.height).toBe(28);
});

it('resizes correctly with only height given', async () => {
const data = getImageFile('images/medium.gif');
const result = await encode(data, { height: 25 });
const encodedPath = writeTmpBuffer(result, 'medium-_x25.gif');

const metadata = await getImageMetadata(encodedPath);
expect(metadata.format).toBe('gif');
expect(metadata.width).toBe(44);
expect(metadata.height).toBe(25);
});

it('respects colors option', async () => {
const data = getImageFile('images/small.gif');
const originalInfo = gifInfo(new Uint8Array(data).buffer);
expect(originalInfo.globalPaletteSize).toBe(256);

const result = await encode(data, { colors: 32 });
writeTmpBuffer(result, `small-32colors.gif`);

// check if new gif has only 32 colors
const encodeInfo = gifInfo(new Uint8Array(result).buffer);
expect(encodeInfo.globalPaletteSize).toBe(32);
});
});
34 changes: 34 additions & 0 deletions packages/gifsicle/__tests__/performance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { initTestUtils, getImageFile, getFileSize } from '@wasm-codecs/test-utils';
import encode from '../lib';

describe('gifsicle performance', () => {
beforeAll(() => {
initTestUtils(__dirname);
});

it('encodes many images', async () => {
jest.setTimeout(100000);
process.setMaxListeners(0);

const data = getImageFile('images/medium.gif');
const originalSize = getFileSize('images/medium.gif');

const promises = [];
for (let i = 0; i < 15; i += 1) {
promises.push(encode(data));
}

const results = await Promise.all(promises);
let resultSize = -1;
for (let i = 0; i < 15; i += 1) {
expect(results[i].length).toBeLessThan(originalSize * 0.995);
expect(results[i].length).toBeGreaterThan(originalSize * 0.25);

if (resultSize < 0) {
resultSize = results[i].length;
} else {
expect(resultSize).toBe(results[i].length);
}
}
});
});
29 changes: 29 additions & 0 deletions packages/gifsicle/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#!/bin/bash

set -e

cd /build

echo "Building wasm-codecs-gifsicle.."
emcc \
/lib/gifsicle/src/clp.o \
/lib/gifsicle/src/fmalloc.o \
/lib/gifsicle/src/giffunc.o \
/lib/gifsicle/src/gifread.o \
/lib/gifsicle/src/gifunopt.o \
/lib/gifsicle/src/merge.o \
/lib/gifsicle/src/optimize.o \
/lib/gifsicle/src/quantize.o \
/lib/gifsicle/src/support.o \
/lib/gifsicle/src/xform.o \
/lib/gifsicle/src/gifsicle.o \
/lib/gifsicle/src/gifwrite.o \
-s MODULARIZE=1 \
-s EXPORT_NAME=gifsicle \
-s ALLOW_MEMORY_GROWTH=1 \
-s ERROR_ON_UNDEFINED_SYMBOLS=0 \
--pre-js lib/pre.js \
-s WASM=1 \
-Oz \
-flto \
-o ./lib/gifsicle.js
4 changes: 4 additions & 0 deletions packages/gifsicle/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
testEnvironment: 'node',
testMatch: ['**/__tests__/**/*.test.[jt]s?(x)'],
};
Loading

0 comments on commit bbae5ec

Please sign in to comment.