-
Notifications
You must be signed in to change notification settings - Fork 18
/
pngwolf.cxx
executable file
·1979 lines (1582 loc) · 60.8 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>
//
// 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$
//
////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <arpa/inet.h>
#endif
#include "Common/MyWindows.h"
#include "Common/MyInitGuid.h"
#include "7zip/IStream.h"
#include "7zip/Compress/ZlibEncoder.h"
#include "7zip/Common/FileStreams.h"
#include "7zip/Common/InBuffer.h"
#include "7zip/Common/StreamObjects.h"
#include <signal.h>
#include <stdlib.h>
#include <stdint.h>
#include <ga/ga.h>
#include <iostream>
#include <list>
#include <vector>
#include <stdio.h>
#include <ctime>
#include <iomanip>
#include <functional>
#include <numeric>
#include <zlib.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <map>
#include <bitset>
#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
////////////////////////////////////////////////////////////////////
// Miscellaneous structures and types
////////////////////////////////////////////////////////////////////
typedef enum {
None = 0,
Sub = 1,
Up = 2,
Avg = 3,
Paeth = 4
} PngFilter;
typedef struct PngChunk PngChunk;
struct PngChunk {
uint32_t size;
uint32_t type;
uint32_t crc32;
std::vector<char> data;
};
typedef struct IhdrChunk IhdrChunk;
struct IhdrChunk {
uint32_t width;
uint32_t height;
uint32_t depth;
uint32_t color;
uint32_t comp;
uint32_t filter;
uint32_t interlace;
};
typedef GA1DArrayAlleleGenome<PngFilter> PngFilterGenome;
class Deflater {
public:
virtual std::vector<char> deflate(const std::vector<char>&) = 0;
};
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; TODO: who owns them?
std::map<std::string, PngFilterGenome*> genomes;
std::vector<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;
const char* out_path;
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;
int zlib_windowBits;
int zlib_memLevel;
int zlib_strategy;
int szip_pass;
int szip_fast;
int szip_cycl;
//
Deflater* deflate_fast;
Deflater* deflate_good;
// 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<char> original_inflated;
std::vector<char> original_deflated;
std::vector<char> original_unfiltered;
//
std::map<PngFilter, std::vector<char> > flt_singles;
//
std::map<uint32_t, size_t> invis_colors;
//
unsigned nth_generation;
unsigned genomes_evaluated;
//
std::vector<char> best_inflated;
std::vector<char> best_deflated;
// The genetic algorithm
GAGeneticAlgorithm* ga;
// Logging
void log_analysis();
void log_critter(PngFilterGenome* curr_best);
void log_summary();
void log_genome(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<char>& deflated, std::vector<char>& inflated);
void init_filters();
void run();
void recompress();
std::vector<char> refilter(const PngFilterGenome& ge);
// Constructor
PngWolf() :
should_abort(false),
nth_generation(0),
genomes_evaluated(0),
done_deflating_at(0),
deflate_fast(NULL),
deflate_good(NULL)
{}
~PngWolf() {
// TODO: This should probably delete the genomes, both
// the ge_ ones and the ones in the best_genomes vector
}
};
struct DeflateZlib : public Deflater {
public:
std::vector<char> deflate(const std::vector<char>& inflated) {
if (deflateReset(&strm) != Z_OK) {
// TODO: ...
abort();
}
strm.next_in = (Bytef*)&inflated[0];
strm.avail_in = inflated.size();
size_t max = deflateBound(&strm, inflated.size());
std::vector<char> new_deflated(max);
strm.next_out = (Bytef*)&new_deflated[0];
strm.avail_out = max;
// TODO: aborting here probably leaks memory
if (::deflate(&strm, Z_FINISH) != Z_STREAM_END)
abort();
new_deflated.resize(max - strm.avail_out);
return new_deflated;
}
DeflateZlib(int level, int windowBits, int memLevel, int strategy) {
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
if (deflateInit2(&strm, level, Z_DEFLATED,
windowBits, memLevel, strategy) != Z_OK) {
// TODO:
abort();
}
}
z_stream strm;
};
struct Deflate7zip : public Deflater {
public:
std::vector<char> deflate(const std::vector<char>& inflated) {
NCompress::NZlib::CEncoder c;
PROPID algoProp = NCoderPropID::kAlgorithm;
PROPID passProp = NCoderPropID::kNumPasses;
PROPID fastProp = NCoderPropID::kNumFastBytes;
PROPID cyclProp = NCoderPropID::kMatchFinderCycles;
PROPVARIANT v;
v.vt = VT_UI4;
// TODO: figure out what to do with errors here
c.Create();
NCompress::NDeflate::NEncoder::CCOMCoder* d =
c.DeflateEncoderSpec;
v.ulVal = szip_algo;
if (d->SetCoderProperties(&algoProp, &v, 1) != S_OK) {
}
v.ulVal = szip_pass;
if (d->SetCoderProperties(&passProp, &v, 1) != S_OK) {
}
v.ulVal = szip_fast;
if (d->SetCoderProperties(&fastProp, &v, 1) != S_OK) {
}
v.ulVal = szip_cycl;
if (d->SetCoderProperties(&cyclProp, &v, 1) != S_OK) {
}
CBufInStream* in_buf = new CBufInStream;
// TODO: find a way to use a a fixed buffer since we know
// the maximum size for it and don't use more than one. It
// might also be a good idea to keep the other objects for
// all the passes through this to avoid re-allocations and
// the possible failures that might go along with them.
CDynBufSeqOutStream* out_buf = new CDynBufSeqOutStream;
in_buf->Init((const Byte*)&inflated[0], inflated.size());
CMyComPtr<ISequentialInStream> in(in_buf);
CMyComPtr<ISequentialOutStream> out(out_buf);
if (c.Code(in, out, NULL, NULL, NULL) != S_OK) {
}
std::vector<char> deflated(out_buf->GetSize());
memcpy(&deflated[0], out_buf->GetBuffer(), deflated.size());
return deflated;
}
Deflate7zip(int pass, int fast, int cycl) :
szip_pass(pass),
szip_fast(fast),
szip_cycl(cycl),
szip_algo(1) {
}
int szip_pass;
int szip_fast;
int szip_cycl;
int szip_algo;
};
static const char PNG_MAGIC[] = "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
static const uint32_t IDAT_TYPE = 0x49444154;
static const uint32_t IHDR_TYPE = 0x49484452;
static const uint32_t IEND_TYPE = 0x49454e44;
////////////////////////////////////////////////////////////////////
// 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
////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
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<char> inflate_zlib(std::vector<char>& deflated) {
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = (Bytef*)&deflated[0];
strm.avail_in = deflated.size();
std::vector<char> inflated;
std::vector<char> temp(65535);
if (inflateInit(&strm) != Z_OK)
goto error;
do {
strm.avail_out = temp.size();
strm.next_out = (Bytef*)&temp[0];
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<char> PngWolf::refilter(const PngFilterGenome& ge) {
std::vector<char> refiltered(original_unfiltered.size());
filter_idat((unsigned char*)&original_unfiltered[0],
(unsigned char*)&refiltered[0], 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;
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<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<char> deflated = wolf.deflate_fast->deflate(filtered);
return float(deflated.size());
}
////////////////////////////////////////////////////////////////////
// Helper
////////////////////////////////////////////////////////////////////
unsigned sum_abs(unsigned c1, unsigned char c2) {
return c1 + (c2 < 128 ? c2 : 256 - c2);
}
////////////////////////////////////////////////////////////////////
// Logging
////////////////////////////////////////////////////////////////////
void PngWolf::log_genome(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 zlib deflated idat size: %0.0f\n"
"total time spent optimizing: %0.0f\n"
"number of genomes evaluated: %u\n"
"size of 7zip deflated data: %u\n"
"size difference to original: %d\n",
best_genomes.back()->score(),
difftime(time(NULL), program_begun_at),
genomes_evaluated,
best_deflated.size(),
-diff);
}
if (diff >= 0)
fprintf(stdout, "# %u bytes smaller\n", diff);
else
fprintf(stdout, "# %u 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,
original_inflated.size(), 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,
this->scanline_width,
this->scanline_delta,
this->original_inflated.size(),
this->original_deflated.size());
std::list<PngChunk>::iterator c_it;
for (c_it = chunks.begin(); c_it != chunks.end(); ++c_it) {
// 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", (c_it->type >> 24));
fprintf(stdout, "%c", (c_it->type >> 16));
fprintf(stdout, "%c", (c_it->type >> 8));
fprintf(stdout, "%c", (c_it->type >> 0));
fprintf(stdout, " ");
}
if (ihdr.color == 6 && ihdr.depth == 8) {
fprintf(stdout, "\ninvisible colors:\n");
std::map<uint32_t, size_t>::iterator it;
uint32_t total = 0;
// TODO: htonl is probably not right here
for (it = invis_colors.begin(); it != invis_colors.end(); ++it) {
fprintf(stdout, " - %08X # %u times\n", htonl(it->first), 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, ""
"zlib 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(PngFilterGenome* curr_best) {
PngFilterGenome* prev_best = best_genomes.back();
if (!this->verbose_genomes) {
fprintf(stdout, ""
"- zlib 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"
"- zlib deflated idat size: %7u # %+5d bytes %+4.0f seconds since previous\n"
" ##########################################################################\n"
" zlib bytes since previous improvement: %+d\n"
" zlib 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?
genomes["all set to avg"] = (PngFilterGenome*)ge.clone();
genomes["all set to none"] = (PngFilterGenome*)ge.clone();
genomes["all set to sub"] = (PngFilterGenome*)ge.clone();
genomes["all set to up"] = (PngFilterGenome*)ge.clone();
genomes["all set to paeth"] = (PngFilterGenome*)ge.clone();
genomes["original"] = (PngFilterGenome*)ge.clone();
genomes["heuristic"] = (PngFilterGenome*)ge.clone();
genomes["deflate scanline"] = (PngFilterGenome*)ge.clone();
genomes["distinct bytes"] = (PngFilterGenome*)ge.clone();
genomes["distinct bigrams"] = (PngFilterGenome*)ge.clone();
genomes["incremental"] = (PngFilterGenome*)ge.clone();
for (int i = 0; i < ge.size(); ++i) {
genomes["original"]->gene(i, original_filters[i]);
genomes["all set to avg"]->gene(i, Avg);
genomes["all set to sub"]->gene(i, Sub);
genomes["all set to none"]->gene(i, None);
genomes["all set to paeth"]->gene(i, Paeth);
genomes["all set to up"]->gene(i, Up);
}
flt_singles[None] = refilter(*genomes["all set to none"]);
flt_singles[Sub] = refilter(*genomes["all set to sub"]);
flt_singles[Up] = refilter(*genomes["all set to up"]);
flt_singles[Avg] = refilter(*genomes["all set to avg"]);
flt_singles[Paeth] = refilter(*genomes["all set to paeth"]);
typedef std::map< PngFilter, std::vector<char> >::iterator flt_iter;
// TODO: for bigger_is_better it might make sense to have a
// function for the comparisons and set that so heuristics
// also work towards making the selection worse.
for (int row = 0; row < ge.size(); ++row) {
size_t best_sum = SIZE_MAX;
PngFilter best_flt = None;
// "The following simple heuristic has performed well in
// early tests: compute the output scanline using all five
// filters, and select the filter that gives the smallest
// sum of absolute values of outputs. (Consider the output
// bytes as signed differences for this test.) This method
// usually outperforms any single fixed filter choice." as
// per <http://www.w3.org/TR/PNG/#12Filter-selection>.
// Note that I've found this to be incorrect, as far as
// typical RGB and RGBA images found on the web go, using
// None for all scanlines outperforms the heuristic in 57%
// of the cases. Even if you carefully check whether they
// should really be stored as indexed images, there is not
// much evidence to support "usually". A better heuristic
// would be applying the heuristic and None to all and use
// the combination that performs better.
for (flt_iter fi = flt_singles.begin(); fi != flt_singles.end(); ++fi) {
std::vector<char>::iterator scanline =
flt_singles[fi->first].begin() + row * scanline_width;
size_t sum = std::accumulate(scanline + 1,
scanline + scanline_width, 0, sum_abs);
// If, for this scanline, the current filter is better
// then the previous best filter, we memorize this filter,
// otherwise this filter can be disregarded for the line.
if (sum >= best_sum)
continue;
best_sum = sum;
best_flt = fi->first;
}
genomes["heuristic"]->gene(row, (PngFilter)best_flt);
}
// As an experimental heuristic, this compresses each scanline
// individually and picks the filter that compresses the line
// best. This may be a useful clue for the others, but tests
// suggests this might interfere in cases where zlib is a poor
// estimator, tuning genomes too much for zlib instead of 7zip.
// Generally this should be expected to perform poorly for very
// small images. In the standard Alexa 1000 sample it performs
// better than the specification's heuristic in 73% of cases;
// files would be around 3% (median) and 4% (mean) smaller.
for (int row = 0; row < ge.size(); ++row) {
size_t best_sum = SIZE_MAX;
PngFilter best_flt = None;
for (flt_iter fi = flt_singles.begin(); fi != flt_singles.end(); ++fi) {
std::vector<char>::iterator scanline =
flt_singles[fi->first].begin() + row * scanline_width;
std::vector<char> line(scanline, scanline + scanline_width);
size_t sum = deflate_fast->deflate(line).size();
if (sum >= best_sum)
continue;
best_sum = sum;
best_flt = fi->first;
}
genomes["deflate scanline"]->gene(row, (PngFilter)best_flt);
}
// unigram heuristic
for (int row = 0; row < ge.size(); ++row) {
size_t best_sum = SIZE_MAX;
PngFilter best_flt = None;
for (flt_iter fi = flt_singles.begin(); fi != flt_singles.end(); ++fi) {
std::bitset<65536> seen;
std::vector<char>::iterator it;
std::vector<char>::iterator scanline =
flt_singles[fi->first].begin() + row * scanline_width;
for (it = scanline; it < scanline + scanline_width; ++it)
seen.set(uint8_t(*it));
size_t sum = seen.count();
if (sum >= best_sum)