forked from hoehrmann/pngwolf
-
Notifications
You must be signed in to change notification settings - Fork 4
/
pngwolf.cxx
executable file
·2239 lines (1783 loc) · 69.2 KB
/
pngwolf.cxx
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////
//
// pngwolf - Optimize PNG file size by genetically finding filters
//
// Copyright (C) 2008-2011 Bjoern Hoehrmann <bjoern@hoehrmann.de>
//
// Modified to use Zopfli for the final compression step
// Copyright (C) 2015-2017 Joergen Ibsen
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// $Id$
//
////////////////////////////////////////////////////////////////////
#include <float.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <bitset>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <vector>
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <WinSock2.h>
#else
#include <arpa/inet.h>
#endif
#include "ga/ga.h"
#include "libdeflate.h"
#include "zlib.h"
#include "zopfli.h"
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t)-1)
#endif
#ifdef _MSC_VER
#pragma warning(push, 4)
#pragma warning(disable: 4996)
#pragma warning(disable: 4100)
#endif
#define PNGWOLF_VERSION "1.1.2"
////////////////////////////////////////////////////////////////////
// Miscellaneous structures and types
////////////////////////////////////////////////////////////////////
enum PngFilter {
None = 0,
Sub = 1,
Up = 2,
Avg = 3,
Paeth = 4
};
struct PngChunk {
uint32_t size;
uint32_t type;
uint32_t crc32;
std::vector<unsigned char> data;
};
struct IhdrChunk {
uint32_t width;
uint32_t height;
uint32_t depth;
uint32_t color;
uint32_t comp;
uint32_t filter;
uint32_t interlace;
};
using PngFilterGenome = GA1DArrayAlleleGenome<PngFilter>;
class Deflater {
public:
virtual std::vector<unsigned char> deflate(const std::vector<unsigned char>&) = 0;
virtual bool parse_option(const std::string&) = 0;
virtual ~Deflater() {}
};
class PngWolf {
public:
// IHDR data
IhdrChunk ihdr;
// Derived IHDR data
size_t scanline_width;
size_t scanline_delta;
// The input image as list of chunks
std::list<PngChunk> chunks;
// Urfilter
std::vector<PngFilter> original_filters;
// Filters
std::map<std::string, std::unique_ptr<PngFilterGenome>> genomes;
std::vector<std::unique_ptr<PngFilterGenome>> best_genomes;
// ...
GAPopulation initial_pop;
// Command line options
unsigned max_stagnate_time;
unsigned max_time;
unsigned max_evaluations;
unsigned max_deflate;
size_t population_size;
const char* in_path = nullptr;
const char* out_path = nullptr;
bool verbose_analysis;
bool verbose_summary;
bool verbose_genomes;
bool exclude_singles;
bool exclude_original;
bool exclude_heuristic;
bool exclude_experiment1;
bool exclude_experiment2;
bool exclude_experiment3;
bool exclude_experiment4;
bool normalize_alpha;
bool even_if_bigger;
bool auto_mpass;
bool bigger_is_better;
int zlib_level;
std::vector<uint32_t> strip_chunks;
bool strip_optional;
std::vector<uint32_t> keep_chunks;
//
std::unique_ptr<Deflater> deflate_estimator;
std::unique_ptr<Deflater> deflate_out;
// User input
bool should_abort;
// Keeping track of time
time_t program_begun_at;
time_t search_begun_at;
time_t last_improvement_at;
time_t last_step_at;
time_t done_deflating_at;
// IDAT
std::vector<unsigned char> original_inflated;
std::vector<unsigned char> original_deflated;
std::vector<unsigned char> original_unfiltered;
//
std::map<PngFilter, std::vector<unsigned char>> flt_singles;
//
std::map<uint32_t, size_t> invis_colors;
//
unsigned nth_generation;
unsigned genomes_evaluated;
//
std::vector<unsigned char> best_inflated;
std::vector<unsigned char> best_deflated;
// The genetic algorithm
GAGeneticAlgorithm* ga = nullptr;
// Logging
void log_analysis();
void log_critter(const PngFilterGenome& curr_best);
void log_summary();
void log_genome(const PngFilterGenome& ge);
// Various
bool read_file();
bool save_file();
bool save_best_idat(const char* path);
bool save_original_idat(const char* path);
bool save_idat(const char* path, std::vector<unsigned char>& deflated, std::vector<unsigned char>& inflated);
void init_filters();
void run();
void recompress();
std::vector<unsigned char> refilter(const PngFilterGenome& ge);
bool recompress_optional_chunk(PngChunk &chunk);
// Constructor
PngWolf() :
should_abort(false),
done_deflating_at(0),
nth_generation(0),
genomes_evaluated(0) {
}
~PngWolf() {
// TODO: This should probably delete the genomes, both
// the ge_ ones and the ones in the best_genomes vector
}
};
struct DeflateLibdeflate : public Deflater {
public:
std::vector<unsigned char> deflate(const std::vector<unsigned char>& inflated) override {
struct libdeflate_compressor *compressor = nullptr;
compressor = libdeflate_alloc_compressor(z_level);
if (compressor == nullptr)
abort();
const size_t maxsize = libdeflate_zlib_compress_bound(compressor, inflated.size());
std::vector<unsigned char> new_deflated(maxsize);
size_t res = libdeflate_zlib_compress(compressor, inflated.data(), inflated.size(),
new_deflated.data(), new_deflated.size());
libdeflate_free_compressor(compressor);
// TODO: aborting here probably leaks memory
if (res == 0)
abort();
new_deflated.resize(res);
return new_deflated;
}
bool parse_option(const std::string& opt) override {
auto i = opt.find('=');
if (i == std::string::npos) {
return false;
}
if (opt.compare(0, i, "level") == 0) {
int level = stoi(opt.substr(i + 1));
if (level >= 1 && level <= 12) {
z_level = level;
return true;
}
}
return false;
}
DeflateLibdeflate(int level=4) :
z_level(level) {
}
private:
int z_level;
};
struct DeflateZlib : public Deflater {
public:
std::vector<unsigned char> deflate(const std::vector<unsigned char>& inflated) override {
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
if (deflateInit2(&strm, z_level, Z_DEFLATED,
z_windowBits, z_memLevel, z_strategy) != Z_OK) {
// TODO:
abort();
}
strm.next_in = const_cast<unsigned char*>(inflated.data());
strm.avail_in = inflated.size();
size_t max = deflateBound(&strm, inflated.size());
std::vector<unsigned char> new_deflated(max);
strm.next_out = new_deflated.data();
strm.avail_out = new_deflated.size();
// TODO: aborting here probably leaks memory
if (::deflate(&strm, Z_FINISH) != Z_STREAM_END)
abort();
new_deflated.resize(max - strm.avail_out);
deflateEnd(&strm);
return new_deflated;
}
bool parse_option(const std::string& opt) override {
auto i = opt.find('=');
if (i == std::string::npos) {
return false;
}
if (opt.compare(0, i, "level") == 0) {
int level = stoi(opt.substr(i + 1));
if (level >= 0 && level <= 9) {
z_level = level;
return true;
}
} else if (opt.compare(0, i, "memlevel") == 0) {
int memlevel = stoi(opt.substr(i + 1));
if (memlevel >= 1 && memlevel <= 9) {
z_memLevel = memlevel;
return true;
}
} else if (opt.compare(0, i, "strategy") == 0) {
int strategy = stoi(opt.substr(i + 1));
if (strategy == Z_DEFAULT_STRATEGY || strategy == Z_FILTERED
|| strategy == Z_HUFFMAN_ONLY || strategy == Z_RLE) {
z_strategy = strategy;
return true;
}
} else if (opt.compare(0, i, "window") == 0) {
int windowbits = stoi(opt.substr(i + 1));
if (windowbits >= 8 && windowbits <= 15) {
z_windowBits = windowbits;
return true;
}
}
return false;
}
DeflateZlib(int level=3, int windowBits=15, int memLevel=8, int strategy=0) :
z_level(level),
z_windowBits(windowBits),
z_memLevel(memLevel),
z_strategy(strategy) {
}
private:
int z_level;
int z_windowBits;
int z_memLevel;
int z_strategy;
};
struct DeflateZopfli : public Deflater {
public:
std::vector<unsigned char> deflate(const std::vector<unsigned char>& inflated) override {
ZopfliOptions zopt;
unsigned char* pout = 0;
size_t outsize = 0;
ZopfliInitOptions(&zopt);
zopt.verbose = zop_verbose > 0;
zopt.verbose_more = zop_verbose > 1;
zopt.numiterations = zop_iter;
zopt.blocksplittingmax = zop_maxsplit;
// TODO: figure out what to do with errors here
ZopfliCompress(&zopt, ZOPFLI_FORMAT_ZLIB,
inflated.data(),
inflated.size(), &pout, &outsize);
std::vector<unsigned char> deflated(pout, pout + outsize);
free(pout);
return deflated;
}
bool parse_option(const std::string& opt) override {
auto i = opt.find('=');
if (i == std::string::npos) {
return false;
}
if (opt.compare(0, i, "iter") == 0) {
int iter = stoi(opt.substr(i + 1));
if (iter > 0) {
zop_iter = iter;
return true;
}
} else if (opt.compare(0, i, "maxsplit") == 0) {
int maxsplit = stoi(opt.substr(i + 1));
if (maxsplit >= 0) {
zop_maxsplit = maxsplit;
return true;
}
} else if (opt.compare(0, i, "verbose") == 0) {
int verbose = stoi(opt.substr(i + 1));
if (verbose >= 0 && verbose <= 2) {
zop_verbose = verbose;
return true;
}
}
return false;
}
DeflateZopfli(int iter=15, int maxsplit=15, int verbose=0) :
zop_iter(iter),
zop_maxsplit(maxsplit),
zop_verbose(verbose) {
}
private:
int zop_iter;
int zop_maxsplit;
int zop_verbose;
};
static const char PNG_MAGIC[] = "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
static const uint32_t IHDR_TYPE = 0x49484452;
static const uint32_t PLTE_TYPE = 0x504c5445;
static const uint32_t tRNS_TYPE = 0x74524e53;
static const uint32_t IDAT_TYPE = 0x49444154;
static const uint32_t IEND_TYPE = 0x49454e44;
static const uint32_t tEXt_TYPE = 0x74455874;
static const uint32_t iTXt_TYPE = 0x69545874;
static const uint32_t zTXt_TYPE = 0x7a545874;
static const uint32_t iCCP_TYPE = 0x69434350;
////////////////////////////////////////////////////////////////////
// Global PngWolf instance
////////////////////////////////////////////////////////////////////
static PngWolf wolf;
////////////////////////////////////////////////////////////////////
// PNG Scanline Filters
////////////////////////////////////////////////////////////////////
unsigned char paeth_predictor(unsigned char a, unsigned char b, unsigned char c) {
unsigned int p = a + b - c;
unsigned int pa = abs((int)(p - a));
unsigned int pb = abs((int)(p - b));
unsigned int pc = abs((int)(p - c));
if (pa <= pb && pa <= pc)
return a;
if (pb <= pc)
return b;
return c;
}
void filter_row_none(unsigned char* src, unsigned char* dst, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
memcpy(dst + xix, src + xix, bytes - 1);
}
void filter_row_sub(unsigned char* src, unsigned char* dst, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
size_t aix = xix;
size_t end = (row+1)*bytes;
for (; xix < row * bytes + 1 + pwidth; ++xix)
dst[xix] = src[xix];
for (; xix < end; ++xix, ++aix)
dst[xix] = src[xix] - src[aix];
}
void filter_row_up(unsigned char* src, unsigned char* dst, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
size_t bix = xix - bytes;
size_t end = (row+1)*bytes;
if (row == 0) {
memcpy(dst + 1, src + 1, bytes - 1);
return;
}
for (; xix < end; ++xix, ++bix)
dst[xix] = src[xix] - src[bix];
}
void filter_row_avg(unsigned char* src, unsigned char* dst, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
size_t bix = xix - bytes;
size_t aix = xix;
size_t end = (row+1)*bytes;
if (row == 0) {
for (; xix < row * bytes + 1 + pwidth; ++xix)
dst[xix] = src[xix];
for (; xix < end; ++xix, ++aix)
dst[xix] = src[xix] - (src[aix] >> 1);
return;
}
for (; xix < row * bytes + 1 + pwidth; ++xix, ++bix)
dst[xix] = src[xix] - (src[bix] >> 1);
for (; xix < end; ++xix, ++aix, ++bix)
dst[xix] = src[xix] - ((src[aix] + src[bix]) >> 1);
}
void filter_row_paeth(unsigned char* src, unsigned char* dst, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
size_t aix = xix;
size_t bix = xix - bytes;
size_t cix = xix - bytes;
size_t end = (row+1)*bytes;
if (row == 0) {
for (; xix < row * bytes + 1 + pwidth; ++xix)
dst[xix] = src[xix];
for (; xix < end; ++xix, ++aix)
dst[xix] = src[xix] - paeth_predictor(src[aix], 0 , 0);
return;
}
// TODO: this should not change pwidth
for (; pwidth > 0; --pwidth, ++xix, ++bix)
dst[xix] = src[xix] - paeth_predictor(0, src[bix] , 0);
for (; xix < end; ++xix, ++aix, ++bix, ++cix)
dst[xix] = src[xix] - paeth_predictor(src[aix], src[bix], src[cix]);
}
void unfilter_row_sub(unsigned char* idat, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
size_t aix = xix;
size_t end = (row+1)*bytes;
xix += pwidth;
while (xix < end)
idat[xix++] += idat[aix++];
}
void unfilter_row_up(unsigned char* idat, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
size_t bix = xix - bytes;
size_t end = (row+1)*bytes;
if (row == 0)
return;
while (xix < end)
idat[xix++] += idat[bix++];
}
void unfilter_row_avg(unsigned char* idat, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
size_t bix = xix - bytes;
size_t end = (row+1)*bytes;
size_t aix;
if (row == 0) {
size_t aix = xix;
xix += pwidth;
while (xix < end)
idat[xix++] += idat[aix++] >> 1;
return;
}
aix = xix;
for (; pwidth > 0; --pwidth)
idat[xix++] += idat[bix++] >> 1;
while (xix < end)
idat[xix++] += (idat[aix++] + idat[bix++]) >> 1;
}
void unfilter_row_paeth(unsigned char* idat, size_t row, size_t pwidth, size_t bytes) {
size_t xix = row * bytes + 1;
size_t bix = xix - bytes;
size_t aix, cix;
size_t end = (row+1)*bytes;
if (row == 0) {
size_t aix = xix;
xix += pwidth;
while (xix < end)
idat[xix++] += paeth_predictor(idat[aix++], 0 , 0);
return;
}
aix = xix;
cix = aix - bytes;
for (; pwidth > 0; --pwidth)
idat[xix++] += paeth_predictor(0, idat[bix++] , 0);
while (xix < end)
idat[xix++] += paeth_predictor(idat[aix++], idat[bix++] , idat[cix++]);
}
void unfilter_idat(unsigned char* idat, size_t rows, size_t pwidth, size_t bytes) {
size_t row;
for (row = 0; row < rows; ++row) {
switch(idat[row*bytes]) {
case 0:
break;
case 1:
unfilter_row_sub(idat, row, pwidth, bytes);
break;
case 2:
unfilter_row_up(idat, row, pwidth, bytes);
break;
case 3:
unfilter_row_avg(idat, row, pwidth, bytes);
break;
case 4:
unfilter_row_paeth(idat, row, pwidth, bytes);
break;
default:
assert(!"bad filter type");
}
idat[row*bytes] = 0;
}
}
void filter_idat(unsigned char* src, unsigned char* dst, const PngFilterGenome& filter, size_t pwidth, size_t bytes) {
for (int row = 0; row < filter.size(); ++row) {
switch(filter.gene(row)) {
case 0:
filter_row_none(src, dst, row, pwidth, bytes);
break;
case 1:
filter_row_sub(src, dst, row, pwidth, bytes);
break;
case 2:
filter_row_up(src, dst, row, pwidth, bytes);
break;
case 3:
filter_row_avg(src, dst, row, pwidth, bytes);
break;
case 4:
filter_row_paeth(src, dst, row, pwidth, bytes);
break;
default:
assert(!"bad filter type");
}
// TODO: check that src uses the `none` filter
dst[row*bytes] = (unsigned char)filter.gene(row);
}
}
////////////////////////////////////////////////////////////////////
// Signal handlers
////////////////////////////////////////////////////////////////////
#if defined(_MSC_VER) || defined(__MINGW32__)
BOOL WINAPI console_event_handler(DWORD Event) {
switch (Event) {
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
wolf.should_abort = true;
return TRUE;
}
return FALSE;
}
#else
void sigint_handler(int signum) {
wolf.should_abort = true;
}
#endif
////////////////////////////////////////////////////////////////////
// Genome Helpers
////////////////////////////////////////////////////////////////////
template <> PngFilter
GAAlleleSet<PngFilter>::allele() const {
return (PngFilter)GARandomInt(lower(), upper());
}
std::vector<unsigned char> inflate_zlib(std::vector<unsigned char>& deflated) {
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = deflated.data();
strm.avail_in = deflated.size();
std::vector<unsigned char> inflated;
std::vector<unsigned char> temp(65535);
if (inflateInit(&strm) != Z_OK)
goto error;
do {
strm.next_out = temp.data();
strm.avail_out = temp.size();
int ret = inflate(&strm, Z_NO_FLUSH);
// TODO: going to `error` here probably leaks some memory
// but it would be freed when exiting the process, so this
// is mostly important when turning this into a library.
if (ret != Z_STREAM_END && ret != Z_OK)
goto error;
size_t have = temp.size() - strm.avail_out;
inflated.insert(inflated.end(),
temp.begin(), temp.begin() + have);
} while (strm.avail_out == 0);
if (inflateEnd(&strm) != Z_OK)
goto error;
return inflated;
error:
// TODO: ...
abort();
return inflated;
}
std::vector<unsigned char> PngWolf::refilter(const PngFilterGenome& ge) {
std::vector<unsigned char> refiltered(original_unfiltered.size());
filter_idat(original_unfiltered.data(), refiltered.data(), ge,
scanline_delta, scanline_width);
return refiltered;
}
float Evaluator(GAGenome& genome) {
PngFilterGenome& ge =
(PngFilterGenome&)genome;
// TODO: wolf should be user data, not a global
if (wolf.should_abort)
return FLT_MAX;
#ifdef _OPENMP
#pragma omp atomic
#endif
wolf.genomes_evaluated++;
if (wolf.flt_singles.begin() == wolf.flt_singles.end()) {
// TODO: ...
abort();
}
// TODO: it would be better to do this incrementally.
std::vector<unsigned char> filtered(wolf.original_unfiltered.size());
for (int row = 0; row < ge.size(); ++row) {
size_t pos = wolf.scanline_width * row;
memcpy(&filtered[pos],
&wolf.flt_singles[ge.gene(row)][pos], wolf.scanline_width);
}
std::vector<unsigned char> deflated = wolf.deflate_estimator->deflate(filtered);
return float(deflated.size());
}
////////////////////////////////////////////////////////////////////
// Helper
////////////////////////////////////////////////////////////////////
unsigned sum_abs(unsigned c1, unsigned char c2) {
return c1 + (c2 < 128 ? c2 : 256 - c2);
}
void update_chunk_crc(PngChunk &chunk) {
const uint32_t chunk_type_network = htonl(chunk.type);
chunk.crc32 = crc32(0L, Z_NULL, 0);
chunk.crc32 = crc32(chunk.crc32,
(const Bytef*)&chunk_type_network,
sizeof(chunk_type_network));
chunk.crc32 = crc32(chunk.crc32,
(const Bytef*)&chunk.data[0],
chunk.data.size());
}
////////////////////////////////////////////////////////////////////
// Logging
////////////////////////////////////////////////////////////////////
void PngWolf::log_genome(const PngFilterGenome& ge) {
for (int gix = 0; gix < ge.size(); ++gix) {
if (gix % 72 == 0)
fprintf(stdout, "\n ");
fprintf(stdout, "%1d", ge.gene(gix));
}
fprintf(stdout, "\n");
}
void PngWolf::log_summary() {
int diff = original_deflated.size() - best_deflated.size();
if (verbose_summary) {
fprintf(stdout, "best filter sequence found:");
log_genome(*best_genomes.back());
fprintf(stdout, ""
"best deflated idat size: %0.0f\n"
"total time spent optimizing: %0.0f\n"
"number of genomes evaluated: %u\n"
"size of Zopfli deflated data: %u\n"
"size difference to original: %d\n",
best_genomes.back()->score(),
difftime(time(NULL), program_begun_at),
genomes_evaluated,
(unsigned int) best_deflated.size(),
-diff);
}
if (diff >= 0)
fprintf(stdout, "# IDAT %d bytes smaller\n", diff);
else
fprintf(stdout, "# IDAT %d bytes bigger\n", abs(diff));
fflush(stdout);
}
void PngWolf::log_analysis() {
fprintf(stdout, "---\n"
"# %u x %u pixels at depth %u (mode %u) with IDAT %u bytes (%u deflated)\n",
ihdr.width, ihdr.height, ihdr.depth, ihdr.color,
(unsigned int) original_inflated.size(),
(unsigned int) original_deflated.size());
if (!verbose_analysis)
return;
fprintf(stdout, ""
"image file path: %s\n"
"width in pixels: %u\n"
"height in pixels: %u\n"
"color mode: %u\n"
"color bit depth: %u\n"
"interlaced: %u\n"
"scanline width: %u\n"
"scanline delta: %u\n"
"inflated idat size: %u\n"
"deflated idat size: %u\n"
"chunks present: ",
this->in_path,
this->ihdr.width,
this->ihdr.height,
this->ihdr.color,
this->ihdr.depth,
this->ihdr.interlace,
(unsigned int) this->scanline_width,
(unsigned int) this->scanline_delta,
(unsigned int) this->original_inflated.size(),
(unsigned int) this->original_deflated.size());
for (const auto& chunk : chunks) {
// TODO: check that this is broken on bad endianess systems
// Also, since no validation is performed for the types, it
// is possible to break the YAML output with bad files, but
// that does not seem all that important at the moment.
fprintf(stdout, "%c", (chunk.type >> 24));
fprintf(stdout, "%c", (chunk.type >> 16));
fprintf(stdout, "%c", (chunk.type >> 8));
fprintf(stdout, "%c", (chunk.type >> 0));
fprintf(stdout, " ");
}
if (ihdr.color == 6 && ihdr.depth == 8) {
fprintf(stdout, "\ninvisible colors:\n");
uint32_t total = 0;
// TODO: htonl is probably not right here
for (const auto& it : invis_colors) {
fprintf(stdout, " - %08X # %u times\n",
(unsigned int) htonl(it.first), (unsigned int) it.second);
total += it.second;
}
bool skip = invis_colors.size() == 1
&& invis_colors.begin()->first == 0x00000000;
fprintf(stdout, " # %u pixels (%0.2f%%) are fully transparent\n",
total, (double)total / ((double)ihdr.width * (double)ihdr.height));
if (invis_colors.size() > 0 && !skip)
fprintf(stdout, " # --normalize-alpha changes them into transparent black\n");
} else {
fprintf(stdout, "\n");
}
fprintf(stdout, ""
"deflated idat sizes:\n"
" original filter: %0.0f\n"
" none: %0.0f\n"
" sub: %0.0f\n"
" up: %0.0f\n"
" avg: %0.0f\n"
" paeth: %0.0f\n"
" deflate scanline: %0.0f\n"
" distinct bytes: %0.0f\n"
" distinct bigrams: %0.0f\n"
" incremental: %0.0f\n"
" basic heuristic: %0.0f\n",
this->genomes["original"]->score(),
this->genomes["all set to none"]->score(),
this->genomes["all set to sub"]->score(),
this->genomes["all set to up"]->score(),
this->genomes["all set to avg"]->score(),
this->genomes["all set to paeth"]->score(),
this->genomes["deflate scanline"]->score(),
this->genomes["distinct bytes"]->score(),
this->genomes["distinct bigrams"]->score(),
this->genomes["incremental"]->score(),
this->genomes["heuristic"]->score());
fprintf(stdout, "original filters:");
log_genome(*this->genomes["original"]);
fprintf(stdout, "basic heuristic filters:");
log_genome(*this->genomes["heuristic"]);
fprintf(stdout, "deflate scanline filters:");
log_genome(*this->genomes["deflate scanline"]);
fprintf(stdout, "distinct bytes filters:");
log_genome(*this->genomes["distinct bytes"]);
fprintf(stdout, "distinct bigrams filters:");
log_genome(*this->genomes["distinct bigrams"]);
fprintf(stdout, "incremental filters:");
log_genome(*this->genomes["incremental"]);
fflush(stdout);
}
void PngWolf::log_critter(const PngFilterGenome& curr_best) {
const PngFilterGenome& prev_best = *best_genomes.back();
if (!this->verbose_genomes) {
fprintf(stdout, ""
"- deflated idat size: %7u # %+5d bytes %+4.0f seconds\n",
unsigned(curr_best.score()),
signed(curr_best.score() - initial_pop.best().score()),
difftime(time(NULL), program_begun_at));
return;
}
fprintf(stdout, ""
" #####################################################################\n"
"- deflated idat size: %7u # %+5d bytes %+4.0f seconds since previous\n"
" #####################################################################\n"
" deflated bytes since previous improvement: %+d\n"
" deflated bytes since first generation: %+d\n"
" seconds since program launch: %+0.0f\n"
" seconds since previous improvement: %+0.0f\n"
" current generation is the nth: %u\n"
" number of genomes evaluated: %u\n"
" best filters so far:",
unsigned(curr_best.score()),
signed(curr_best.score() - prev_best.score()),
difftime(time(NULL), last_improvement_at),
signed(curr_best.score() - prev_best.score()),
signed(curr_best.score() - best_genomes.front()->score()),
difftime(time(NULL), program_begun_at),
difftime(time(NULL), last_improvement_at),
nth_generation,
genomes_evaluated);
log_genome(curr_best);
fflush(stdout);
}
void PngWolf::init_filters() {
GAAlleleSet<PngFilter> allele(None, Paeth);
PngFilterGenome ge(ihdr.height, allele, Evaluator);
// Copy the Urcritter to all the critters we want to hold
// on to for anlysis and for the initial population.
// TODO: Can clone fail? What do we do then?