forked from zertovitch/zip-ada
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrezip_lib.adb
1458 lines (1402 loc) · 57 KB
/
rezip_lib.adb
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
------------------------------------------------------------------------------
-- File: rezip_lib.adb
-- Description: Recompression tool to make archives smaller.
-- Core moved from Rezip (main). Still Q&D !
-- Author: Gautier de Montmollin
------------------------------------------------------------------------------
--
-- To do:
-- * In order to facilitate customization, ReZip could have a config file
-- ( http://sf.net/projects/ini-files/ ) to store external packer
-- program names. See ZipMax as an example...
--
-- External programs used (feel free to customize/add/remove):
-- 7-Zip, KZip, Zip (info-zip), AdvZip, DeflOpt
-- Web URL's: see Zipper_specification below or run ReZip without arguments.
with Zip.Create,
Zip.Compress,
Zip.Headers;
with Flexible_temp_files;
with UnZip;
with Zip_Streams;
with Zip_Console_IO;
with Ada.Calendar,
Ada.Characters.Handling,
Ada.Directories,
Ada.Float_Text_IO,
Ada.Integer_Text_IO,
Ada.IO_Exceptions,
Ada.Numerics.Discrete_Random,
Ada.Numerics.Elementary_Functions,
Ada.Numerics.Float_Random,
Ada.Streams.Stream_IO,
Ada.Strings.Fixed,
Ada.Strings.Unbounded,
Ada.Text_IO,
Ada.Unchecked_Deallocation;
with Dual_IO;
with Interfaces;
with GNAT.OS_Lib;
package body Rezip_lib is
function S (Source : Ada.Strings.Unbounded.Unbounded_String) return String
renames Ada.Strings.Unbounded.To_String;
function U (Source : String) return Ada.Strings.Unbounded.Unbounded_String
renames Ada.Strings.Unbounded.To_Unbounded_String;
use Ada.Strings.Unbounded;
use Interfaces;
-- This info might be better read from a config file...
--
type Zipper_Specification is record
name, title, URL, options : Unbounded_String;
expanded_options : Unbounded_String;
-- ^ Options with dynamically expanded tokens
made_by_version : Unsigned_16;
pkzm : Zip.PKZip_method;
limit : Zip.Zip_64_Data_Size_Type;
-- ^ Compression is considered too slow or unefficient beyond limit (if not 0).
-- E.g., kzip's algorithm might be O(N^2) or worse; on large files,
-- deflate_e or other methods are better anyway
randomized : Boolean;
end record;
NN : constant Unbounded_String := Null_Unbounded_String;
-- Give up recompression above a certain data size for some external packers like KZip
-- or Zopfli.
--
kzip_zopfli_limit : constant := 2_000_000;
type Approach is
(original,
presel_2, presel_1,
shrink,
reduce_4,
deflate_3,
deflate_r,
bzip2_3, bzip2_2, bzip2_1,
lzma_3, lzma_2,
external_01, external_02, external_03, external_04,
external_05, external_06, external_07, external_08,
external_09, external_10, external_11, external_12,
external_13, external_14, external_15);
subtype Internal is Approach
range Approach'Succ (Approach'First) .. Approach'Pred (external_01);
subtype External is Approach
range external_01 .. Approach'Last;
ext : array (External) of Zipper_Specification :=
( -- Zip 2.32 or later:
(U ("zip"), U ("Zip"), U ("http://info-zip.org/"),
U ("-9"), NN, 20, Zip.deflate, 0, False),
-- 7-Zip 4.64 or later; Deflate:
(U ("7z"),
U ("7-Zip"), U ("http://7-zip.org/"),
U ("a -tzip -mm=deflate -mfb=258 -mpass=#RAND#(7,15) -mmc=10000"),
NN, 20, Zip.deflate, 0, True),
(U ("7z"),
U ("7-Zip"), NN,
U ("a -tzip -mm=deflate64 -mfb=257 -mpass=15 -mmc=10000"),
NN, 21, Zip.deflate_e, 0, False),
-- KZip:
(U ("kzip"), U ("KZIP"), U ("http://www.advsys.net/ken/utils.htm"),
U ("/rn /b0"), NN, 20, Zip.deflate, kzip_zopfli_limit, True),
(U ("kzip"), U ("KZIP"), NN,
U ("/rn /b#RAND_EXP#(1,2048)"), NN, 20, Zip.deflate, kzip_zopfli_limit, True),
-- Zip 3.0 or later; BZip2:
(U ("zip"), U ("Zip"), NN,
U ("-#RAND#(1,9) -Z bzip2"), NN, 46, Zip.bzip2_meth, 0, True),
-- 7z:
(U ("7z"), U ("7-Zip"), NN,
U ("a -tzip -mm=BZip2:d=#RAND#(1,9)00k:pass=7"), NN, 46, Zip.bzip2_meth, 0, True),
-- 7-Zip 9.20 or later; LZMA:
(U ("7z"), U ("7-Zip"), NN,
U ("a -tzip -mm=LZMA -mx=9"), NN, 63, Zip.lzma_meth, 0, False),
(U ("7z"), U ("7-Zip"), NN, -- LZ77: BT3 or BT4, dictionary size 2**19 = 512 KiB
U ("a -tzip -mm=LZMA:a=2:d=19:mf=bt#RAND#(3,5):fb=273:lc=0:lp=2"), NN, 63, Zip.lzma_meth, 0, False),
(U ("7z"), U ("7-Zip"), NN, -- LZ77: BT3 or BT4, dictionary size 2**25 = 32 MiB
U ("a -tzip -mm=LZMA:a=2:d=25:mf=bt#RAND#(3,5):fb=273:lc=7"), NN, 63, Zip.lzma_meth, 0, False),
(U ("7z"), U ("7-Zip"), NN, -- LZ77: BT3 or BT4, dictionary size 2**26 = 64 MiB
U ("a -tzip -mm=LZMA:a=2:d=26:mf=bt#RAND#(3,5):fb=273:lc=8:lp0:pb1"), NN, 63, Zip.lzma_meth, 0, False),
(U ("7z"), U ("7-Zip"), NN, -- Super-randomized version
U ("a -tzip -mm=LZMA:a=2:d=#RAND_EXP#(1,65535)k:mf=bt#RAND#(2,5):fb=#RAND#(128,273):" &
"lc=#RAND#(0,8):lp#RAND#(0,4):pb#RAND#(0,4)"),
NN, 63, Zip.lzma_meth, 0, True),
-- AdvZip: advancecomp v1.19+ interesting for the Zopfli algorithm
(U ("advzip"), U ("AdvZip"), U ("http://advancemame.sf.net/comp-readme.html"),
U ("-a -2"), NN, 20, Zip.deflate, 0, False),
(U ("advzip"), U ("AdvZip"), NN,
U ("-a -3"), NN, 20, Zip.deflate, 0, False),
(U ("advzip"), U ("AdvZip"), NN,
U ("-a -4"), NN, 20, Zip.deflate, kzip_zopfli_limit, False));
defl_opt : constant Zipper_Specification :=
(U ("deflopt"), U ("DeflOpt"), U ("http://www.walbeehm.com/download/"),
NN, NN, 0, Zip.deflate, 0, False);
use Ada.Strings.Fixed, Ada.Strings;
procedure Rezip (
from_zip_file : String;
to_zip_file : String;
format_choice : Zip_format_set := all_formats; -- force output into selected format set
touch : Boolean := False; -- set time stamps to now
lower : Boolean := False; -- set full file names to lower case
delete_comment : Boolean := False; -- delete zip comment
randomized_stable : Positive := 1;
log_file : String := "";
html_report : String := "";
alt_tmp_file_radix : String := ""; -- e.g. "X:\temp\rz_"
internal_only : Boolean := False -- Zip-Ada algorithms only, no ext. call
)
is
use Zip.Create;
use Zip_Streams;
use Ada.Calendar, Ada.Characters.Handling, Ada.Directories, Ada.Text_IO;
package DFIO is new Dual_IO.Float_IO (Float);
procedure Rip_data (
archive : Zip.Zip_Info; -- from this archive...
input : in out Root_Zipstream_Type'Class;
data_name : String; -- extract this data
rip_rename : String; -- to this file (compressed)
unzip_rename : String; -- and this one (uncompressed)
header : out Zip.Headers.Local_File_Header
)
is
file_index : Zip_Streams.ZS_Index_Type;
comp_size : Zip.Zip_64_Data_Size_Type;
uncomp_size : Zip.Zip_64_Data_Size_Type;
file_out : Ada.Streams.Stream_IO.File_Type;
dummy_encoding : Zip.Zip_Name_Encoding;
dummy_crc : Unsigned_32;
mem : Zip_Streams.ZS_Index_Type;
head_extra : Zip.Headers.Local_File_Header_Extension;
dummy_offset : Unsigned_64 := 0; -- Initialized for avoiding random value = 16#FFFF_FFFF#
use UnZip, Ada.Streams.Stream_IO;
begin
Zip.Find_Offset (
info => archive,
name => data_name,
name_encoding => dummy_encoding,
file_index => file_index,
comp_size => comp_size,
uncomp_size => uncomp_size,
crc_32 => dummy_crc
);
Set_Index (input, file_index);
Zip.Headers.Read_and_Check (input, header);
-- Skip name
Set_Index (input,
Index (input) + Zip_Streams.ZS_Size_Type (header.filename_length)
);
mem := Index (input);
if header.extra_field_length >= 4 then
Zip.Headers.Read_and_Check (input, head_extra);
Zip.Headers.Interpret
(head_extra,
header.dd.uncompressed_size,
header.dd.compressed_size,
dummy_offset);
end if;
-- Skip extra field
Set_Index (input, mem + Zip_Streams.ZS_Size_Type (header.extra_field_length));
-- * Get the data, compressed
Ada.Streams.Stream_IO.Create (file_out, Out_File, rip_rename);
Zip.Copy_Chunk (input, Stream (file_out).all, Integer (comp_size));
Close (file_out);
if unzip_rename /= "" then
-- * Get the data, uncompressed
Extract (
from => archive,
what => data_name,
rename => unzip_rename,
options =>
(test_only => False,
junk_directories => False,
case_sensitive_match => True,
extract_as_text => False
)
);
end if;
end Rip_data;
Approach_to_Method : constant array (Internal) of Zip.Compress.Compression_Method :=
(shrink => Zip.Compress.Shrink,
reduce_4 => Zip.Compress.Reduce_4,
deflate_3 => Zip.Compress.Deflate_3,
deflate_r => Zip.Compress.Deflate_R,
bzip2_1 => Zip.Compress.BZip2_1,
bzip2_2 => Zip.Compress.BZip2_2,
bzip2_3 => Zip.Compress.BZip2_3,
lzma_2 => Zip.Compress.LZMA_2,
lzma_3 => Zip.Compress.LZMA_3,
presel_1 => Zip.Compress.Preselection_1,
presel_2 => Zip.Compress.Preselection_2);
type Packer_info is record
size : Zip.Zip_64_Data_Size_Type;
zfm : Unsigned_16;
count : Natural;
saved : Integer_64; -- Number of bytes saved by chosen method
-- NB: can be negative if -defl chosen: suboptimal recompression,
-- but compatible method.
saved_ex_aequo : Integer_64; -- Number of bytes saved if method is as good as
-- the winning method.
uncomp_size : Unsigned_64;
-- summed uncompressed sizes might be more than 2**32
expanded_options : Unbounded_String;
iter : Positive; -- iterations needed
LZMA_EOS : Boolean;
end record;
type Packer_info_array is array (Approach) of Packer_info;
type Dir_entry;
type p_Dir_entry is access Dir_entry;
--
type Dir_entry is record
head : Zip.Headers.Central_File_Header;
name : Unbounded_String;
next : p_Dir_entry := null;
chosen_approach : Approach := original;
info : Packer_info_array;
end record;
function Radix return String is
begin
if alt_tmp_file_radix = "" then
return Flexible_temp_files.Radix;
else
return alt_tmp_file_radix;
end if;
end Radix;
function Temp_name (
is_compressed : Boolean;
appr : Approach
)
return String
is
initial : constant array (Boolean) of Character := ('u', 'c');
begin
return
Radix &
"_!" & initial (is_compressed) &
'!' & Trim (Integer'Image (Approach'Pos (appr)), Left) &
"!_.tmp";
end Temp_name;
function Img (a : Approach; html : Boolean) return String is
function Repl (s : String) return String is
t : String := s;
begin
for i in t'Range loop
if html and t (i) = ':' then t (i) := ' '; end if; -- Break too long texts within a cell.
end loop;
return t;
end Repl;
begin
if a in External then
return "External: " & S (ext (a).title) & ", " & Repl (S (ext (a).expanded_options));
else
declare
s : constant String := Approach'Image (a);
begin
return s (s'First) & To_Lower (s (s'First + 1 .. s'Last) & (Approach'Width - s'Length + 1) * ' ');
end;
end if;
end Img;
-- From AZip_Common...
function Image_1000 (r : Zip.Zip_64_Data_Size_Type; separator : Character := ''') return String is
s : constant String := Zip.Zip_64_Data_Size_Type'Image (r);
t : String (s'First .. s'First + (s'Length * 4) / 3);
j, c : Natural;
begin
-- For signed integers
-- if r < 0 then
-- return '-' & Image_1000(abs r, separator);
-- end if;
--
-- We build result string t from right to left
j := t'Last + 1;
c := 0;
for i in reverse s'First .. s'Last loop
exit when s (i) = ' ' or s (i) = '-';
if c > 0 and then c mod 3 = 0 then
j := j - 1;
t (j) := separator;
end if;
j := j - 1;
t (j) := s (i);
c := c + 1;
end loop;
return t (j .. t'Last);
end Image_1000;
function Image_1000 (r : Integer_64; separator : Character := ''') return String is
s : constant String := Integer_64'Image (r);
t : String (s'First .. s'First + (s'Length * 4) / 3);
j, c : Natural;
begin
-- For signed integers
if r < 0 then
return '-' & Image_1000 (abs r, separator);
end if;
-- We build result string t from right to left
j := t'Last + 1;
c := 0;
for i in reverse s'First .. s'Last loop
exit when s (i) = ' ' or s (i) = '-';
if c > 0 and then c mod 3 = 0 then
j := j - 1;
t (j) := separator;
end if;
j := j - 1;
t (j) := s (i);
c := c + 1;
end loop;
return t (j .. t'Last);
end Image_1000;
procedure Call_External
(packer : String;
args : String;
is_tool_needed : Boolean)
is
use GNAT.OS_Lib;
procedure Dispose is
new Ada.Unchecked_Deallocation (Argument_List, Argument_List_Access);
list : Argument_List_Access;
ok : Boolean;
begin
Dual_IO.Put_Line (packer & " [" & args & ']');
list := Argument_String_To_List (args);
GNAT.OS_Lib.Spawn (packer, list.all, ok);
Dispose (list);
if not ok then
declare
msg : constant String := " cannot call external tool """ & packer &
""", or it has returned an error.";
begin
Dual_IO.New_Line;
Dual_IO.Put_Line ("**************");
if is_tool_needed then
Dual_IO.Put_Line ("ReZip ERROR:" & msg);
raise External_Tool_Failed;
else
Dual_IO.Put_Line ("ReZip warning:" & msg);
end if;
end;
end if;
end Call_External;
seed_iterator : Natural;
procedure Call_External_Expanded
(packer : String;
options : String;
other_args : String;
expand : in out Unbounded_String) -- expanded arguments
is
type Token is (rand, rand_exp);
begin
expand := U (options);
for t in Token loop
-- Replace all tokens: #<t>#(a,b)
loop
declare
tok : constant String := '#' & Token'Image (t) & '#';
idx : constant Natural := Index (expand, tok);
par : Natural;
replace_by : Unbounded_String;
begin
-- put_line("Token: " & Token'Image(t) & " " & S(expand));
exit when idx = 0; -- No more of token t to replace
par := Index (expand, ")", idx);
declare
opt : constant String := S (expand); -- partially processed option string
curr : constant String := opt (idx + 1 .. opt'Last); -- current option
par_a : constant Natural := Index (curr, "(");
par_z : constant Natural := Index (curr, ")");
comma : constant Natural := Index (curr, ",");
n1, n2, n : Integer;
begin
n1 := Integer'Value (curr (par_a + 1 .. comma - 1));
n2 := Integer'Value (curr (comma + 1 .. par_z - 1));
case t is
when rand =>
-- Replace #RAND#(n1,n2) by a number between n1 and n2.
-- Uniform distribution: U(n1,n2).
declare
subtype rng is Integer range n1 .. n2;
package Rnd is new Ada.Numerics.Discrete_Random (rng);
gen : Rnd.Generator;
begin
Rnd.Reset (gen, seed_iterator); -- seed_iterator is itself randomized.
seed_iterator := seed_iterator + 1;
n := Rnd.Random (gen);
end;
replace_by := U (Trim (Integer'Image (n), Left));
when rand_exp =>
-- Replace #RAND_EXP#(n1,n2) by a number between n1 and n2.
-- Strong bias towards small numbers (rather close to n1 than to n2).
--
-- Example (k=1, n1=1, n2=100): P(X in [1;10]) = 1/2; P(X in [10;100]) = 1/2.
--
-- The CDF is: F(x) = ((log x - log n1) / (log n2 - log n1)) ^ (1/k).
--
declare
use Ada.Numerics.Float_Random, Ada.Numerics.Elementary_Functions;
gen : Generator;
l1, l2, l, u : Float;
k : constant := 2;
begin
Reset (gen, seed_iterator); -- seed_iterator is itself randomized.
seed_iterator := seed_iterator + 1;
u := Random (gen); -- u is Uniform in [0;1]
l1 := Log (Float (n1));
l2 := Log (Float (n2));
l := l1 + (l2 - l1) * (u ** k);
n := Integer (Exp (l));
end;
replace_by := U (Trim (Integer'Image (n), Left));
end case;
Replace_Slice (expand, idx, par, S (replace_by));
end;
end;
end loop;
end loop;
Call_External (packer, S (expand) & ' ' & other_args, is_tool_needed => True);
end Call_External_Expanded;
function Temp_Zip_Name return String is
begin
return Simple_Name (Radix) & "_$temp$.zip";
end Temp_Zip_Name;
procedure Try_deleting_Temp_Zip_File is
begin
if Exists (Temp_Zip_Name) then
Delete_File (Temp_Zip_Name);
end if;
exception
when Ada.IO_Exceptions.Use_Error =>
null;
end Try_deleting_Temp_Zip_File;
procedure Process_External
(packer : String;
options : String;
out_name : String;
is_rand : Boolean;
is_deflate : Boolean;
info : out Packer_info)
is
rand_winner : constant String := Simple_Name (Radix) & "_$rand$.tmp";
options_winner : Unbounded_String;
data_name : constant String := Simple_Name (Temp_name (False, original));
header : Zip.Headers.Local_File_Header;
MyStream : aliased File_Zipstream;
cur_dir : constant String := Current_Directory;
size_memory : array (1 .. randomized_stable) of Zip.Zip_64_Data_Size_Type := (others => 0);
current_size : Zip.Zip_64_Data_Size_Type := 0;
zfm : Unsigned_16;
attempt : Positive := 1;
dummy_exp_opt : Unbounded_String;
zi_ext : Zip.Zip_Info;
begin
-- We jump into the TEMP directory, to avoid putting pathes into the
-- temporary zip file.
Set_Directory (Containing_Directory (Radix));
loop
Try_deleting_Temp_Zip_File; -- remove (eventually broken) zip
Call_External_Expanded (
packer,
options,
Temp_Zip_Name & ' ' & data_name,
info.expanded_options
);
if (not Exists (Temp_Zip_Name)) and then Ada.Directories.Size (data_name) = 0 then
-- ADVZip 1.19 doesn't create a zip file for a 0-size entry; we call Zip instead...
Call_External_Expanded ("zip", "", Temp_Zip_Name & ' ' & data_name, dummy_exp_opt);
end if;
if is_deflate then
-- Post processing of "deflated" entry with DeflOpt:
Call_External (S (defl_opt.name), Temp_Zip_Name, is_tool_needed => False);
end if;
-- Now, rip
Set_Name (MyStream, Temp_Zip_Name);
Open (MyStream, In_File);
Zip.Load (zi_ext, MyStream, True);
Rip_data (
archive => zi_ext,
input => MyStream,
data_name => data_name,
rip_rename => out_name,
unzip_rename => "",
header => header
);
Close (MyStream);
Try_deleting_Temp_Zip_File;
--
if randomized_stable = 1 or not is_rand then -- normal behaviour (1 attempt)
current_size := header.dd.compressed_size;
zfm := header.zip_type;
info.iter := 1;
exit;
end if;
--
-- Here, we process the cases where compressed sizes need
-- to be reduced and we expect a stable size over n=randomized_stable
-- attempts.
--
if attempt = 1 or else
header.dd.compressed_size < current_size -- better size
then
current_size := header.dd.compressed_size;
zfm := header.zip_type;
if Exists (rand_winner) then
Delete_File (rand_winner);
end if;
Rename (out_name, rand_winner);
options_winner := info.expanded_options;
end if;
--
-- Manage the array of last n=randomized_stable sizes
--
if attempt > size_memory'Last then
for i in size_memory'First + 1 .. size_memory'Last loop
size_memory (i - 1) := size_memory (i);
end loop;
size_memory (size_memory'Last) := current_size;
else
size_memory (attempt) := current_size;
end if;
--
-- Check stability over n=randomized_stable attempts
--
if attempt >= randomized_stable then
if size_memory (randomized_stable) = size_memory (1) then
if Exists (out_name) then
Delete_File (out_name);
end if;
Rename (rand_winner, out_name);
info.expanded_options := options_winner;
info.iter := attempt;
exit;
end if;
end if;
attempt := attempt + 1;
end loop;
info.size := current_size;
info.uncomp_size := header.dd.uncompressed_size;
-- uncomp_size should not matter (always the same).
info.zfm := zfm;
info.LZMA_EOS := (zfm = 14) and (header.bit_flag and Zip.Headers.LZMA_EOS_Flag_Bit) /= 0;
-- We jump back to the startup directory.
Set_Directory (cur_dir);
end Process_External;
-- Compress data as raw compressed data
procedure Process_Internal_Raw (a : Approach; e : in out Dir_entry) is
File_in : aliased File_Zipstream;
File_out : aliased File_Zipstream;
begin
Set_Name (File_in, Temp_name (False, original));
Open (File_in, In_File);
Set_Name (File_out, Temp_name (True, a));
Create (File_out, Out_File);
Zip.Compress.Compress_Data
(
input => File_in,
output => File_out,
input_size_known => True,
input_size => e.head.short_info.dd.uncompressed_size,
method => Approach_to_Method (a),
feedback => Zip_Console_IO.My_feedback'Access,
password => "",
content_hint => Zip.Compress.Guess_Type_from_Name (S (e.name)),
CRC => e.head.short_info.dd.crc_32,
-- we take the occasion to compute the CRC if not
-- yet available (e.g. JAR)
output_size => e.info (a).size,
zip_type => e.info (a).zfm
);
e.info (a).LZMA_EOS := e.info (a).zfm = 14;
Close (File_in);
Close (File_out);
end Process_Internal_Raw;
-- Compress data as a temp Zip archive (like external methods), then call post-processing.
-- Currently, only the DeflOpt post-processor is considered.
--
procedure Process_Internal_as_Zip (a : Approach; e : in out Dir_entry) is
zip_file : aliased File_Zipstream;
archive : Zip_Create_Info;
data_name : constant String := Simple_Name (Temp_name (False, original));
zi_ext : Zip.Zip_Info;
header : Zip.Headers.Local_File_Header;
MyStream : aliased File_Zipstream;
cur_dir : constant String := Current_Directory;
begin
Set_Directory (Containing_Directory (Radix));
Create_Archive (archive, zip_file'Unchecked_Access, Temp_Zip_Name);
Set (archive, Approach_to_Method (a));
Add_File (archive, data_name);
Finish (archive);
-- Post processing of "deflated" entry with DeflOpt:
Call_External (S (defl_opt.name), Temp_Zip_Name, is_tool_needed => False);
-- Now, rip
Set_Name (MyStream, Temp_Zip_Name);
Open (MyStream, In_File);
Zip.Load (zi_ext, MyStream, True);
Rip_data (
archive => zi_ext,
input => MyStream,
data_name => data_name,
rip_rename => Temp_name (True, a),
unzip_rename => "",
header => header
);
e.info (a).size := header.dd.compressed_size;
e.info (a).zfm := header.zip_type;
e.info (a).LZMA_EOS :=
(header.zip_type = 14) and (header.bit_flag and Zip.Headers.LZMA_EOS_Flag_Bit) /= 0;
Close (MyStream);
Try_deleting_Temp_Zip_File;
Set_Directory (cur_dir);
end Process_Internal_as_Zip;
time_0 : constant Ada.Calendar.Time := Clock;
procedure Repack_contents (orig_name, repacked_name, html_report_name : String)
is
zi : Zip.Zip_Info;
MyStream : aliased File_Zipstream;
list, e, curr : p_Dir_entry := null;
repacked_zip_file : aliased File_Zipstream;
null_packer_info : constant Packer_info := (0, 0, 0, 0, 0, 0, NN, 1, False);
total : Packer_info_array := (others => null_packer_info);
-- total(a).count counts the files where approach 'a' was optimal
-- total(a).saved counts the saved bytes when approach 'a' was optimal
total_choice : Packer_info := null_packer_info;
summary : Ada.Text_IO.File_Type;
T0, T1 : Ada.Calendar.Time;
repack_duration : Duration;
--
type Approach_Filtering is array (Approach) of Boolean;
consider_a_priori : Approach_Filtering;
--
lightred : constant String := "#ff8696";
lightorange : constant String := "#ffe0b0";
color_for_original : constant String := lightorange;
color_for_winner : constant String := "lightgreen";
use Ada.Float_Text_IO, Ada.Integer_Text_IO;
procedure Process_one (unique_name : String) is
comp_size : Zip.Zip_64_Data_Size_Type;
uncomp_size : Zip.Zip_64_Data_Size_Type;
choice : Approach := original;
deco : constant String := "-->-->-->" & (20 + unique_name'Length) * '-';
mth : Zip.PKZip_method;
consider : Approach_Filtering;
gain, gain_a : Integer_64;
--
procedure Winner_Color is
begin
if e.info (choice).size < e.info (original).size then
Put (summary, "<td bgcolor=" & color_for_winner & "><b>");
-- We were able to reduce the size. :-)
elsif e.info (choice).size = e.info (original).size then
if choice = original then
Put (summary, "<td bgcolor=" & color_for_original & "><b>");
else
-- Something else with exactly the same size as the
-- original was chosen.
-- Happens only if we force another format.
Put (summary, "<td bgcolor=lightblue><b>");
end if;
-- Original was already the best.
else
Put (summary, "<td bgcolor=" & lightred & "><b>");
-- Forced to a format with a less efficient compression. :-(
end if;
end Winner_Color;
--
use Zip;
needs_zip64 : Boolean;
fh_extra : Zip.Headers.Local_File_Header_Extension;
ex_aequo : Boolean;
begin
-- Start with the set of approaches that has been decided for all entries.
consider := consider_a_priori;
if unique_name = "" or else
(unique_name (unique_name'Last) = '\'
or unique_name (unique_name'Last) = '/'
)
then
return; -- directories are useless entries!
end if;
total_choice.count := total_choice.count + 1;
Dual_IO.Close_and_Append_Log; -- have an up to date copy on file system
Dual_IO.Put_Line (deco);
Dual_IO.Put_Line (
' ' &
Integer'Image ((100 * total_choice.count) / Zip.Entries (zi)) &
"% - Processing " &
unique_name & ',' &
Integer'Image (total_choice.count) &
" of" &
Integer'Image (Zip.Entries (zi))
);
Dual_IO.Put_Line (deco);
Dual_IO.New_Line;
--
e := new Dir_entry;
if curr = null then
curr := e;
list := e;
else
curr.next := e;
curr := e;
end if;
e.name := U (unique_name);
e.head.made_by_version := 20; -- version 2.0
e.head.comment_length := 0;
e.head.disk_number_start := 0;
e.head.internal_attributes := 0; -- 0: seems binary; 1, text
e.head.external_attributes := 0;
--
Dual_IO.Put (" Phase 1: dump & unzip -");
Rip_data (
archive => zi,
input => MyStream,
data_name => unique_name,
rip_rename => Temp_name (True, original),
unzip_rename => Temp_name (False, original),
header => e.head.short_info
);
--
if touch then
e.head.short_info.file_timedate := Zip.Convert (time_0);
end if;
if lower then
e.name := U (To_Lower (S (e.name)));
end if;
-- Get reliable data from zi
Zip.Get_Sizes (
info => zi,
name => unique_name,
comp_size => comp_size,
uncomp_size => uncomp_size
);
Dual_IO.Put_Line (" done");
--
-- Apply limitations: skip some methods if certain conditions are met.
-- For instance:
-- Shrink may in rare cases be better, but only for tiny files.
-- KZip and Zopfli are excellent but really too slow on large files.
--
for a in Approach loop
case a is
when original =>
null;
when shrink =>
consider (a) := consider (a) and uncomp_size <= 6000;
when reduce_4 =>
consider (a) := consider (a) and uncomp_size <= 9000;
when External =>
consider (a) := consider (a) and (ext (a).limit = 0 or uncomp_size <= ext (a).limit);
when others =>
null;
end case;
end loop;
Dual_IO.Put_Line (" Phase 2: try different tactics...");
--
Try_all_approaches :
--
for a in Approach loop
if consider (a) then
Dual_IO.Put (" -o-> " & Img (a, html => False));
e.info (a).iter := 1;
case a is
--
when original =>
-- This is from the original .zip - just record size and method
e.info (a).size := comp_size;
e.info (a).zfm := e.head.short_info.zip_type;
e.info (a).LZMA_EOS :=
(e.info (a).zfm = 14) and
(e.head.short_info.bit_flag and Zip.Headers.LZMA_EOS_Flag_Bit) /= 0;
mth := Zip.Method_from_Code (e.info (a).zfm);
--
when Internal =>
if Approach_to_Method (a) in Zip.Compress.Deflation_Method
and not internal_only
then
-- We will post-process our internal Deflate with DeflOpt.
Process_Internal_as_Zip (a, e.all);
else
Process_Internal_Raw (a, e.all);
end if;
when External =>
Dual_IO.New_Line;
Process_External (
S (ext (a).name),
S (ext (a).options),
Temp_name (True, a),
ext (a).randomized,
ext (a).pkzm = Zip.deflate,
e.info (a)
);
e.head.made_by_version := ext (a).made_by_version;
ext (a).expanded_options := e.info (a).expanded_options;
--
end case;
total (a).size := total (a).size + e.info (a).size;
if e.info (a).size < e.info (choice).size then
-- Hurra, we found a smaller size than previous choice!
choice := a;
end if;
if choice = original and not format_choice (mth) then
-- This occurs if we want to make an archive with only a certain set of formats,
-- for instance deflate_or_store, which is the most compatible.
-- Since approach _a_ uses a format in the desired set, the choice will be
-- forced out of original, even with a worse size.
choice := a;
end if;
Dual_IO.New_Line;
end if;
end loop Try_all_approaches;
--
total_choice.size := total_choice.size + e.info (choice).size;
total (choice).count := total (choice).count + 1;
total_choice.uncomp_size :=
total_choice.uncomp_size + Unsigned_64 (uncomp_size);
gain := Integer_64 (e.info (original).size) - Integer_64 (e.info (choice).size);
total (choice).saved := total (choice).saved + gain;
-- We award now the ex-aequo's. Caution: multiple counting if you take the sum of totals
-- over all approachs, but it is good for knowing the strength of an individual approach.
for a in Approach loop
if consider (a) then
gain_a := Integer_64 (e.info (original).size) - Integer_64 (e.info (a).size);
if gain_a = gain then
total (a).saved_ex_aequo := total (a).saved_ex_aequo + gain;
end if;
end if;
end loop;
total_choice.saved := total_choice.saved + gain;
--
Dual_IO.New_Line;
Dual_IO.Put (
" Phase 3: Winner is " & Img (choice, html => False) &
"; gain in bytes:" & Integer_64'Image (gain) &
"; writing data -"
);
-- * Summary outputs
Put (summary,
"<tr><td>" &
Trim (Integer'Image (total_choice.count), Left) &
-- '/' &
-- Trim(Integer'Image(Zip.Entries(zi)),Left) &
"</td>" &
"<td bgcolor=lightgrey><tt>" & unique_name & "</tt>, " &
Image_1000 (uncomp_size) & "</td>");
for a in Approach loop
if consider_a_priori (a) then
ex_aequo := e.info (a).size = e.info (choice).size;
if not consider (a) then
Put (summary, "<td bgcolor=lightgray>skipped");
elsif a = choice then
Winner_Color;
elsif ex_aequo then
Put (summary, "<td bgcolor=lightblue><b>");
elsif a = original then
Put (summary, "<td bgcolor=" & color_for_original & '>');
else
Put (summary, "<td>");
end if;
if consider (a) then
Put (summary, Image_1000 (e.info (a).size));
end if;
if ex_aequo then
Put (summary, "</b>");
end if;
Put (summary, "</td>");
end if;
end loop;
-- Recall winner approach:
Put
(summary,
"<td" &
(if choice = original then " bgcolor=" & color_for_original else "") & '>' &
Img (choice, html => True) & "</td>");
-- Recall winner format:
Put
(summary,
"<td" &
(if choice = original then
" bgcolor=" & color_for_original
elsif e.info (choice).size < e.info (original).size then
" bgcolor=" & color_for_winner
elsif e.info (choice).size > e.info (original).size then
" bgcolor=" & lightred
else
"") &
'>' & Zip.Image (Zip.Method_from_Code (e.info (choice).zfm)) & "</td>");
-- Recall original format:
Put
(summary,
"<td bgcolor=" & color_for_original & '>' &
Zip.Image (Zip.Method_from_Code (e.info (original).zfm)) & "</td>");
-- Recall winner size:
Winner_Color;
Put (summary, Image_1000 (e.info (choice).size));
Put (summary, "</b></td><td>");
if e.info (original).size > 0 then
Put (
summary,
100.0 * Float (e.info (choice).size) / Float (e.info (original).size),
3, 2, 0
);
Put (summary, "%");
end if;
Put (summary, "</td><td>");
if uncomp_size > 0 then
Put (
summary,
100.0 * Float (e.info (choice).size) / Float (uncomp_size),
3, 2, 0
);
Put (summary, "%");
end if;
Put (summary, "</td><td>");
Put (summary, Image_1000 (uncomp_size));
Put (summary, "</td><td>");
Put (summary, Integer'Image (e.info (choice).iter));
Put_Line (summary, "</td></tr>");
--
-- Write winning data:
--
e.head.short_info.extra_field_length := 0; -- We choose to ignore it...