-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathguetzli_emscripten.cc
445 lines (394 loc) · 12.5 KB
/
guetzli_emscripten.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <memory>
#include <string>
#include <string.h>
//#include "png.h"
#include "guetzli/jpeg_data.h"
#include "guetzli/jpeg_data_reader.h"
#include "guetzli/processor.cc"
#include "guetzli/quality.cc"
#include "guetzli/stats.h"
#include "butteraugli/butteraugli.cc"
#include "lodepng/lodepng.cpp"
#define LODEPNG_NO_COMPILE_ENCODER
namespace {
constexpr int kDefaultJPEGQuality = 95;
// An upper estimate of memory usage of Guetzli. The bound is
// max(kLowerMemusaeMB * 1<<20, pixel_count * kBytesPerPixel)
constexpr int kBytesPerPixel = 300;
constexpr int kLowestMemusageMB = 100; // in MB
constexpr int kDefaultMemlimitMB = 6000; // in MB
inline uint8_t BlendOnBlack(const uint8_t val, const uint8_t alpha) {
return (static_cast<int>(val) * static_cast<int>(alpha) + 128) / 255;
}
/*
bool ReadPNG(FILE* f, int* xsize, int* ysize,
std::vector<uint8_t>* rgb) {
png_structp png_ptr =
png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (!png_ptr) {
return false;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
return false;
}
if (setjmp(png_jmpbuf(png_ptr)) != 0) {
// Ok we are here because of the setjmp.
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return false;
}
rewind(f);
png_init_io(png_ptr, f);
// The png_transforms flags are as follows:
// packing == convert 1,2,4 bit images,
// strip == 16 -> 8 bits / channel,
// shift == use sBIT dynamics, and
// expand == palettes -> rgb, grayscale -> 8 bit images, tRNS -> alpha.
const unsigned int png_transforms =
PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_STRIP_16;
png_read_png(png_ptr, info_ptr, png_transforms, nullptr);
png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);
*xsize = png_get_image_width(png_ptr, info_ptr);
*ysize = png_get_image_height(png_ptr, info_ptr);
rgb->resize(3 * (*xsize) * (*ysize));
const int components = png_get_channels(png_ptr, info_ptr);
switch (components) {
case 1: {
// GRAYSCALE
for (int y = 0; y < *ysize; ++y) {
const uint8_t* row_in = row_pointers[y];
uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];
for (int x = 0; x < *xsize; ++x) {
const uint8_t gray = row_in[x];
row_out[3 * x + 0] = gray;
row_out[3 * x + 1] = gray;
row_out[3 * x + 2] = gray;
}
}
break;
}
case 2: {
// GRAYSCALE + ALPHA
for (int y = 0; y < *ysize; ++y) {
const uint8_t* row_in = row_pointers[y];
uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];
for (int x = 0; x < *xsize; ++x) {
const uint8_t gray = BlendOnBlack(row_in[2 * x], row_in[2 * x + 1]);
row_out[3 * x + 0] = gray;
row_out[3 * x + 1] = gray;
row_out[3 * x + 2] = gray;
}
}
break;
}
case 3: {
// RGB
for (int y = 0; y < *ysize; ++y) {
const uint8_t* row_in = row_pointers[y];
uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];
memcpy(row_out, row_in, 3 * (*xsize));
}
break;
}
case 4: {
// RGBA
for (int y = 0; y < *ysize; ++y) {
const uint8_t* row_in = row_pointers[y];
uint8_t* row_out = &(*rgb)[3 * y * (*xsize)];
for (int x = 0; x < *xsize; ++x) {
const uint8_t alpha = row_in[4 * x + 3];
row_out[3 * x + 0] = BlendOnBlack(row_in[4 * x + 0], alpha);
row_out[3 * x + 1] = BlendOnBlack(row_in[4 * x + 1], alpha);
row_out[3 * x + 2] = BlendOnBlack(row_in[4 * x + 2], alpha);
}
}
break;
}
default:
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return false;
}
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
return true;
}
*/
std::string ReadFileOrDie(FILE* f) {
if (fseek(f, 0, SEEK_END) != 0) {
perror("fseek");
exit(1);
}
off_t size = ftell(f);
if (size < 0) {
perror("ftell");
exit(1);
}
if (fseek(f, 0, SEEK_SET) != 0) {
perror("fseek");
exit(1);
}
std::unique_ptr<char[]> buf(new char[size]);
if (fread(buf.get(), 1, size, f) != (size_t)size) {
perror("fread");
exit(1);
}
std::string result(buf.get(), size);
return result;
}
void WriteFileOrDie(FILE* f, const std::string& contents) {
if (fwrite(contents.data(), 1, contents.size(), f) != contents.size()) {
perror("fwrite");
exit(1);
}
if (fclose(f) < 0) {
perror("fclose");
exit(1);
}
}
void TerminateHandler() {
fprintf(stderr, "Unhandled exception. Most likely insufficient memory available.\n"
"Make sure that there is 300MB/MPix of memory available.\n");
exit(1);
}
void Usage() {
fprintf(stderr,
"Guetzli JPEG compressor. Usage: \n"
"guetzli [flags] input_filename output_filename\n"
"\n"
"Flags:\n"
" --verbose - Print a verbose trace of all attempts to standard output.\n"
" --quality Q - Visual quality to aim for, expressed as a JPEG quality value.\n"
" Default value is %d.\n"
" --memlimit M - Memory limit in MB. Guetzli will fail if unable to stay under\n"
" the limit. Default limit is %d MB.\n"
" --nomemlimit - Do not limit memory usage.\n", kDefaultJPEGQuality, kDefaultMemlimitMB);
exit(1);
}
} // namespace
int main(int argc, char** argv) {
std::set_terminate(TerminateHandler);
int verbose = 0;
int quality = kDefaultJPEGQuality;
int memlimit_mb = kDefaultMemlimitMB;
int opt_idx = 1;
for(;opt_idx < argc;opt_idx++) {
if (argv[opt_idx][0] != '-')
break;
if (!strcmp(argv[opt_idx], "--verbose")) {
verbose = 1;
} else if (!strcmp(argv[opt_idx], "--quality")) {
opt_idx++;
quality = atoi(argv[opt_idx]);
} else if (!strcmp(argv[opt_idx], "--memlimit")) {
opt_idx++;
memlimit_mb = atoi(argv[opt_idx]);
} else if (!strcmp(argv[opt_idx], "--nomemlimit")) {
memlimit_mb = -1;
} else {
fprintf(stderr, "Unknown commandline flag: %s\n", argv[opt_idx]);
Usage();
}
}
if (argc - opt_idx != 2) {
Usage();
}
FILE* fin = fopen(argv[opt_idx], "rb");
if (!fin) {
fprintf(stderr, "Can't open input file\n");
return 1;
}
std::string in_data = ReadFileOrDie(fin);
std::string out_data;
guetzli::Params params;
params.butteraugli_target =
guetzli::ButteraugliScoreForQuality(quality);
guetzli::ProcessStats stats;
if (verbose) {
stats.debug_output_file = stdout;
}
static const unsigned char kPNGMagicBytes[] = {
0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n',
};
if (in_data.size() >= 8 &&
memcmp(in_data.data(), kPNGMagicBytes, sizeof(kPNGMagicBytes)) == 0) {
unsigned xsize, ysize;
std::vector<uint8_t> rgb;
if (lodepng::decode(rgb, xsize, ysize, argv[opt_idx], LCT_RGB, 8)) { /*!ReadPNG(fin, &xsize, &ysize, &rgb)*/
fprintf(stderr, "Error reading PNG data from input file\n");
return 1;
}
int pixels = xsize * ysize;
if (memlimit_mb != -1
&& (pixels * kBytesPerPixel / (1 << 20) > memlimit_mb
|| memlimit_mb < kLowestMemusageMB)) {
fprintf(stderr, "Memory limit would be exceeded. Failing.\n");
return 1;
}
if (!guetzli::Process(params, &stats, rgb, xsize, ysize, &out_data)) {
fprintf(stderr, "Guetzli processing failed\n");
return 1;
}
} else {
guetzli::JPEGData jpg_header;
if (!guetzli::ReadJpeg(in_data, guetzli::JPEG_READ_HEADER, &jpg_header)) {
fprintf(stderr, "Error reading JPG data from input file\n");
return 1;
}
int pixels = jpg_header.width * jpg_header.height;
if (memlimit_mb != -1
&& (pixels * kBytesPerPixel / (1 << 20) > memlimit_mb
|| memlimit_mb < kLowestMemusageMB)) {
fprintf(stderr, "Memory limit would be exceeded. Failing.\n");
return 1;
}
if (!guetzli::Process(params, &stats, in_data, &out_data)) {
fprintf(stderr, "Guetzli processing failed\n");
return 1;
}
}
fclose(fin);
FILE* fout = fopen(argv[opt_idx + 1], "wb");
if (!fout) {
fprintf(stderr, "Can't open output file for writing\n");
return 1;
}
WriteFileOrDie(fout, out_data);
return 0;
}
extern "C" {
int Guetzli_encodeRGBA(const char* rgba, unsigned int xsize, unsigned int ysize, unsigned int quality, int verbose) {
//int verbose = 1;
//int quality = kDefaultJPEGQuality;
int memlimit_mb = kDefaultMemlimitMB;
//std::string in_data;// = ReadFileOrDie(fin);
std::string out_data;
guetzli::Params params;
params.butteraugli_target =
guetzli::ButteraugliScoreForQuality(quality);//FLAGS_quality
guetzli::ProcessStats stats;
if (verbose) {
stats.debug_output_file = stdout;
}
//int xsize, ysize;
std::vector<uint8_t> rgb;
rgb.resize(3 * (xsize) * (ysize));
for (int y = 0; y < ysize; ++y) {
const uint8_t* row_in = (uint8_t*)rgba + 4 * xsize * y;
uint8_t* row_out = &(rgb)[3 * y * (xsize)];
for (int x = 0; x < xsize; ++x) {
const uint8_t alpha = row_in[4 * x + 3];
row_out[3 * x + 0] = BlendOnBlack(row_in[4 * x + 0], alpha);
row_out[3 * x + 1] = BlendOnBlack(row_in[4 * x + 1], alpha);
row_out[3 * x + 2] = BlendOnBlack(row_in[4 * x + 2], alpha);
}
}
int size = rgb.size();
int pixels = xsize * ysize;
if (memlimit_mb != -1
&& (pixels * kBytesPerPixel / (1 << 20) > memlimit_mb
|| memlimit_mb < kLowestMemusageMB)) {
fprintf(stderr, "Memory limit would be exceeded. Failing.\n");
return 1;
}
if (!Process(params, &stats, rgb, xsize, ysize, &out_data)) {
fprintf(stderr, "Guetzli processing failed\n");
return 1;
}
FILE* fout = fopen("out.jpg", "wb");
if (!fout) {
fprintf(stderr, "Can't open output file for writing\n");
return 1;
}
WriteFileOrDie(fout, out_data);
return 0;
size = out_data.size();
//*out = out_data.c_str();
//return size;// 1;
}
int Guetzli_encode(unsigned int quality, int verbose) {
//int verbose = 1;
//int quality = kDefaultJPEGQuality;
int memlimit_mb = kDefaultMemlimitMB;
FILE* fin = fopen("in.ext", "rb");
if (!fin) {
fprintf(stderr, "Can't open input file\n");
return 1;
}
std::string in_data = ReadFileOrDie(fin);
std::string out_data;
guetzli::Params params;
params.butteraugli_target =
guetzli::ButteraugliScoreForQuality(quality);
guetzli::ProcessStats stats;
if (verbose) {
stats.debug_output_file = stdout;
}
static const unsigned char kPNGMagicBytes[] = {
0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n',
};
if (in_data.size() >= 8 &&
memcmp(in_data.data(), kPNGMagicBytes, sizeof(kPNGMagicBytes)) == 0) {
unsigned xsize, ysize;
std::vector<uint8_t> rgb;
if (lodepng::decode(rgb, xsize, ysize, "in.ext", LCT_RGB, 8)) { /*!ReadPNG(fin, &xsize, &ysize, &rgb)*/
fprintf(stderr, "Error reading PNG data from input file\n");
return 1;
}
int pixels = xsize * ysize;
if (memlimit_mb != -1
&& (pixels * kBytesPerPixel / (1 << 20) > memlimit_mb
|| memlimit_mb < kLowestMemusageMB)) {
fprintf(stderr, "Memory limit would be exceeded. Failing.\n");
return 1;
}
if (!guetzli::Process(params, &stats, rgb, xsize, ysize, &out_data)) {
fprintf(stderr, "Guetzli processing failed\n");
return 1;
}
}
else {
guetzli::JPEGData jpg_header;
if (!guetzli::ReadJpeg(in_data, guetzli::JPEG_READ_HEADER, &jpg_header)) {
fprintf(stderr, "Error reading JPG data from input file\n");
return 1;
}
int pixels = jpg_header.width * jpg_header.height;
if (memlimit_mb != -1
&& (pixels * kBytesPerPixel / (1 << 20) > memlimit_mb
|| memlimit_mb < kLowestMemusageMB)) {
fprintf(stderr, "Memory limit would be exceeded. Failing.\n");
return 1;
}
if (!guetzli::Process(params, &stats, in_data, &out_data)) {
fprintf(stderr, "Guetzli processing failed\n");
return 1;
}
}
fclose(fin);
FILE* fout = fopen("out.jpg", "wb");
if (!fout) {
fprintf(stderr, "Can't open output file for writing\n");
return 1;
}
WriteFileOrDie(fout, out_data);
return 0;
}
}