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
#![cfg_attr(feature="dev", feature(plugin))]
#![cfg_attr(feature="dev", plugin(clippy))]
extern crate bit_vec;
extern crate byteorder;
extern crate crc;
extern crate itertools;
extern crate libc;
extern crate libz_sys;
extern crate miniz_sys;
extern crate num_cpus;
extern crate rayon;
extern crate zopfli;
use deflate::Deflaters;
use error::PngError;
use headers::Headers;
use rayon::prelude::*;
use std::collections::{HashMap, HashSet};
use std::fs::{File, copy};
use std::io::{BufWriter, Write, stderr, stdout};
use std::path::{Path, PathBuf};
pub mod colors;
pub mod deflate;
mod error;
mod filters;
pub mod headers;
mod interlace;
pub mod png;
mod reduction;
#[derive(Clone,Debug)]
pub struct Options {
pub backup: bool,
pub out_file: PathBuf,
pub out_dir: Option<PathBuf>,
pub stdout: bool,
pub fix_errors: bool,
pub pretend: bool,
pub recursive: bool,
pub clobber: bool,
pub create: bool,
pub force: bool,
pub preserve_attrs: bool,
pub verbosity: Option<u8>,
pub filter: HashSet<u8>,
pub interlace: Option<u8>,
pub compression: HashSet<u8>,
pub memory: HashSet<u8>,
pub strategies: HashSet<u8>,
pub window: u8,
pub bit_depth_reduction: bool,
pub color_type_reduction: bool,
pub palette_reduction: bool,
pub idat_recoding: bool,
pub strip: Headers,
pub deflate: Deflaters,
pub use_heuristics: bool,
pub threads: usize,
}
impl Options {
pub fn from_preset(level: u8) -> Options {
let mut opts = Options::default();
match level {
0 => {
opts.idat_recoding = false;
let mut compression = HashSet::new();
compression.insert(3);
opts.compression = compression;
}
1 => {
let filter = HashSet::new();
opts.filter = filter;
let strategies = HashSet::new();
opts.strategies = strategies;
opts.use_heuristics = true;
}
3 => {
let mut filter = HashSet::new();
filter.insert(0);
filter.insert(5);
opts.filter = filter;
let mut compression = HashSet::new();
compression.insert(9);
opts.compression = compression;
let mut memory = HashSet::new();
for i in 8..10 {
memory.insert(i);
}
opts.memory = memory;
let mut strategies = HashSet::new();
for i in 0..4 {
strategies.insert(i);
}
opts.strategies = strategies;
}
4 => {
let mut filter = HashSet::new();
for i in 0..6 {
filter.insert(i);
}
opts.filter = filter;
let mut compression = HashSet::new();
compression.insert(9);
opts.compression = compression;
let mut memory = HashSet::new();
for i in 8..10 {
memory.insert(i);
}
opts.memory = memory;
let mut strategies = HashSet::new();
for i in 0..4 {
strategies.insert(i);
}
opts.strategies = strategies;
}
5 => {
let mut filter = HashSet::new();
for i in 0..6 {
filter.insert(i);
}
opts.filter = filter;
let mut compression = HashSet::new();
for i in 3..10 {
compression.insert(i);
}
opts.compression = compression;
let mut memory = HashSet::new();
for i in 8..10 {
memory.insert(i);
}
opts.memory = memory;
let mut strategies = HashSet::new();
for i in 0..4 {
strategies.insert(i);
}
opts.strategies = strategies;
}
_ => {
let mut filter = HashSet::new();
for i in 0..6 {
filter.insert(i);
}
opts.filter = filter;
let mut compression = HashSet::new();
for i in 1..10 {
compression.insert(i);
}
opts.compression = compression;
let mut memory = HashSet::new();
for i in 7..10 {
memory.insert(i);
}
opts.memory = memory;
let mut strategies = HashSet::new();
for i in 0..4 {
strategies.insert(i);
}
opts.strategies = strategies;
}
}
opts
}
}
impl Default for Options {
fn default() -> Options {
let mut filter = HashSet::new();
filter.insert(0);
filter.insert(5);
let mut compression = HashSet::new();
compression.insert(9);
let mut memory = HashSet::new();
memory.insert(9);
let mut strategies = HashSet::new();
for i in 0..4 {
strategies.insert(i);
}
let num_cpus = num_cpus::get();
let thread_count = num_cpus + (num_cpus >> 1);
Options {
backup: false,
out_file: PathBuf::new(),
out_dir: None,
stdout: false,
pretend: false,
recursive: false,
fix_errors: false,
clobber: true,
create: true,
force: false,
preserve_attrs: false,
verbosity: Some(0),
filter: filter,
interlace: None,
compression: compression,
memory: memory,
strategies: strategies,
window: 15,
bit_depth_reduction: true,
color_type_reduction: true,
palette_reduction: true,
idat_recoding: true,
strip: Headers::None,
deflate: Deflaters::Zlib,
use_heuristics: false,
threads: thread_count,
}
}
}
pub fn optimize(filepath: &Path, opts: &Options) -> Result<(), PngError> {
let thread_count = opts.threads;
rayon::initialize(rayon::Configuration::new().set_num_threads(thread_count)).ok();
if opts.verbosity.is_some() {
writeln!(&mut stderr(), "Processing: {}", filepath.to_str().unwrap()).ok();
}
let in_file = Path::new(filepath);
let original_size = in_file.metadata().unwrap().len() as usize;
let mut png = match png::PngData::new(in_file, opts.fix_errors) {
Ok(x) => x,
Err(x) => return Err(x),
};
let optimized_output = optimize_png(&mut png, original_size, opts);
if is_fully_optimized(original_size, optimized_output.len(), opts) {
writeln!(&mut stderr(), "File already optimized").ok();
return Ok(());
}
if opts.pretend {
if opts.verbosity.is_some() {
writeln!(&mut stderr(), "Running in pretend mode, no output").ok();
}
} else {
if opts.backup {
match copy(in_file,
in_file.with_extension(format!("bak.{}",
in_file.extension()
.unwrap()
.to_str()
.unwrap()))) {
Ok(x) => x,
Err(_) => {
return Err(PngError::new(&format!("Unable to write to backup file at {}",
opts.out_file.display())))
}
};
}
if opts.stdout {
let mut buffer = BufWriter::new(stdout());
match buffer.write_all(&optimized_output) {
Ok(_) => (),
Err(_) => return Err(PngError::new("Unable to write to stdout")),
}
} else {
let out_file = match File::create(&opts.out_file) {
Ok(x) => x,
Err(_) => {
return Err(PngError::new(&format!("Unable to write to file {}",
opts.out_file.display())))
}
};
if opts.preserve_attrs {
match File::open(filepath) {
Ok(f) => {
match f.metadata() {
Ok(metadata) => {
{
match out_file.metadata() {
Ok(out_meta) => {
let readonly = metadata.permissions()
.readonly();
out_meta.permissions()
.set_readonly(readonly);
}
Err(_) => {
if opts.verbosity.is_some() {
writeln!(&mut stderr(),
"Failed to set permissions on output file")
.ok();
}
}
}
}
}
Err(_) => {
if opts.verbosity.is_some() {
writeln!(&mut stderr(),
"Failed to read permissions on input file")
.ok();
}
}
}
}
Err(_) => {
if opts.verbosity.is_some() {
writeln!(&mut stderr(), "Failed to read permissions on input file")
.ok();
}
}
};
}
let mut buffer = BufWriter::new(out_file);
match buffer.write_all(&optimized_output) {
Ok(_) => {
if opts.verbosity.is_some() {
writeln!(&mut stderr(), "Output: {}", opts.out_file.display()).ok();
}
}
Err(_) => {
return Err(PngError::new(&format!("Unable to write to file {}",
opts.out_file.display())))
}
}
}
}
Ok(())
}
pub fn optimize_from_memory(data: &[u8], opts: &Options) -> Result<Vec<u8>, PngError> {
let thread_count = opts.threads;
rayon::initialize(rayon::Configuration::new().set_num_threads(thread_count)).ok();
if opts.verbosity.is_some() {
writeln!(&mut stderr(), "Processing from memory").ok();
}
let original_size = data.len() as usize;
let mut png = match png::PngData::from_slice(data, opts.fix_errors) {
Ok(x) => x,
Err(x) => return Err(x),
};
let optimized_output = optimize_png(&mut png, original_size, opts);
if is_fully_optimized(original_size, optimized_output.len(), opts) {
writeln!(&mut stderr(), "Image already optimized").ok();
Ok(data.to_vec())
} else {
Ok(optimized_output)
}
}
fn optimize_png(mut png: &mut png::PngData, file_original_size: usize, opts: &Options) -> Vec<u8> {
type TrialWithData = (u8, u8, u8, u8, Vec<u8>);
let idat_original_size = png.idat_data.len();
if opts.verbosity.is_some() {
writeln!(&mut stderr(),
" {}x{} pixels, PNG format",
png.ihdr_data.width,
png.ihdr_data.height)
.ok();
if let Some(ref palette) = png.palette {
writeln!(&mut stderr(),
" {} bits/pixel, {} colors in palette",
png.ihdr_data.bit_depth,
palette.len() / 3)
.ok();
} else {
writeln!(&mut stderr(),
" {}x{} bits/pixel, {:?}",
png.channels_per_pixel(),
png.ihdr_data.bit_depth,
png.ihdr_data.color_type)
.ok();
}
writeln!(&mut stderr(),
" IDAT size = {} bytes",
idat_original_size)
.ok();
writeln!(&mut stderr(),
" File size = {} bytes",
file_original_size)
.ok();
}
let mut filter = opts.filter.clone();
let compression = &opts.compression;
let memory = &opts.memory;
let mut strategies = opts.strategies.clone();
if opts.use_heuristics {
if png.ihdr_data.bit_depth.as_u8() >= 8 &&
png.ihdr_data.color_type != colors::ColorType::Indexed {
if filter.is_empty() {
filter.insert(5);
}
if strategies.is_empty() {
strategies.insert(1);
}
} else {
if filter.is_empty() {
filter.insert(0);
}
if strategies.is_empty() {
strategies.insert(0);
}
}
}
let something_changed = perform_reductions(&mut png, opts);
if opts.idat_recoding || something_changed {
let combinations = if opts.deflate == Deflaters::Zlib {
filter.len() * compression.len() * memory.len() * strategies.len()
} else {
filter.len()
};
let mut results: Vec<(u8, u8, u8, u8)> = Vec::with_capacity(combinations);
if opts.verbosity.is_some() {
writeln!(&mut stderr(), "Trying: {} combinations", combinations).ok();
}
for f in &filter {
if opts.deflate == Deflaters::Zlib {
for zc in compression {
for zm in memory {
for zs in &strategies {
results.push((*f, *zc, *zm, *zs));
}
}
}
} else {
results.push((*f, 0, 0, 0));
}
}
let mut filters_tmp: Vec<(u8, Vec<u8>)> = Vec::with_capacity(filter.len());
filter.par_iter()
.weight_max()
.map(|f| (*f, png.filter_image(*f)))
.collect_into(&mut filters_tmp);
let filters: HashMap<u8, Vec<u8>> = filters_tmp.into_iter().collect();
let original_len = png.idat_data.len();
let interlacing_changed = opts.interlace.is_some() &&
opts.interlace != Some(png.ihdr_data.interlaced);
let best: Option<TrialWithData> = results.into_par_iter()
.weight_max()
.filter_map(|trial| {
let filtered = &filters[&trial.0];
let new_idat = if opts.deflate == Deflaters::Zlib {
deflate::deflate(filtered, trial.1, trial.2, trial.3, opts.window)
} else {
deflate::zopfli_deflate(filtered)
}
.unwrap();
if opts.verbosity == Some(1) {
writeln!(&mut stderr(),
" zc = {} zm = {} zs = {} f = {} {} bytes",
trial.1,
trial.2,
trial.3,
trial.0,
new_idat.len())
.ok();
}
if new_idat.len() < original_len || interlacing_changed || opts.force {
Some((trial.0, trial.1, trial.2, trial.3, new_idat))
} else {
None
}
})
.reduce_with(|i, j| if i.4.len() <= j.4.len() { i } else { j });
if let Some(better) = best {
png.idat_data = better.4;
if opts.verbosity.is_some() {
writeln!(&mut stderr(), "Found better combination:").ok();
writeln!(&mut stderr(),
" zc = {} zm = {} zs = {} f = {} {} bytes",
better.1,
better.2,
better.3,
better.0,
png.idat_data.len())
.ok();
}
}
}
perform_strip(&mut png, opts);
let output = png.output();
if opts.verbosity.is_some() {
if idat_original_size >= png.idat_data.len() {
writeln!(&mut stderr(),
" IDAT size = {} bytes ({} bytes decrease)",
png.idat_data.len(),
idat_original_size - png.idat_data.len())
.ok();
} else {
writeln!(&mut stderr(),
" IDAT size = {} bytes ({} bytes increase)",
png.idat_data.len(),
png.idat_data.len() - idat_original_size)
.ok();
}
if file_original_size >= output.len() {
writeln!(&mut stderr(),
" file size = {} bytes ({} bytes = {:.2}% decrease)",
output.len(),
file_original_size - output.len(),
(file_original_size - output.len()) as f64 / file_original_size as f64 *
100f64)
.ok();
} else {
writeln!(&mut stderr(),
" file size = {} bytes ({} bytes = {:.2}% increase)",
output.len(),
output.len() - file_original_size,
(output.len() - file_original_size) as f64 / file_original_size as f64 *
100f64)
.ok();
}
}
output
}
fn perform_reductions(png: &mut png::PngData, opts: &Options) -> bool {
let mut something_changed = false;
if opts.palette_reduction && png.reduce_palette() {
something_changed = true;
if opts.verbosity == Some(1) {
report_reduction(png);
}
}
if opts.bit_depth_reduction && png.reduce_bit_depth() {
something_changed = true;
if opts.verbosity == Some(1) {
report_reduction(png);
}
}
if opts.color_type_reduction && png.reduce_color_type() {
something_changed = true;
if opts.verbosity == Some(1) {
report_reduction(png);
}
}
if something_changed && opts.verbosity.is_some() {
report_reduction(png);
}
if let Some(interlacing) = opts.interlace {
if png.change_interlacing(interlacing) {
png.ihdr_data.interlaced = interlacing;
something_changed = true;
}
}
something_changed
}
#[inline]
fn report_reduction(png: &png::PngData) {
if let Some(ref palette) = png.palette {
writeln!(&mut stderr(),
"Reducing image to {} bits/pixel, {} colors in palette",
png.ihdr_data.bit_depth,
palette.len() / 3)
.ok();
} else {
writeln!(&mut stderr(),
"Reducing image to {}x{} bits/pixel, {}",
png.channels_per_pixel(),
png.ihdr_data.bit_depth,
png.ihdr_data.color_type)
.ok();
}
}
fn perform_strip(png: &mut png::PngData, opts: &Options) {
match opts.strip {
Headers::None => (),
Headers::Some(ref hdrs) => {
for hdr in hdrs {
png.aux_headers.remove(hdr);
}
}
Headers::Safe => {
const PRESERVED_HEADERS: [&'static str; 9] = ["cHRM", "gAMA", "iCCP", "sBIT", "sRGB",
"bKGD", "hIST", "pHYs", "sPLT"];
let hdrs = png.aux_headers.keys().cloned().collect::<Vec<String>>();
for hdr in hdrs {
if !PRESERVED_HEADERS.contains(&hdr.as_ref()) {
png.aux_headers.remove(&hdr);
}
}
}
Headers::All => {
png.aux_headers = HashMap::new();
}
}
}
#[inline]
fn is_fully_optimized(original_size: usize, optimized_size: usize, opts: &Options) -> bool {
original_size <= optimized_size && !opts.force && opts.interlace.is_none()
}