-
Notifications
You must be signed in to change notification settings - Fork 17
/
README.html
2891 lines (2660 loc) · 110 KB
/
README.html
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
<html><head>
<title>Lossless Data Compression Program: Hybrid LZ77 RLE</title>
<link rev=made href="mailto:a1bert@iki.fi">
<link rel=parent href="index.html">
</head>
<body>
This page is <A HREF="http://www.iki.fi/a1bert/Dev/pucrunch/">
http://www.iki.fi/a1bert/Dev/pucrunch/</A><BR>
Other C64-related stuff -> <A HREF="http://www.iki.fi/a1bert/Dev/">
http://www.iki.fi/a1bert/Dev/</A><BR>
<HR>
Pucrunch found elsewhere in random order:<BR>
<A HREF="http://www.smspower.org/maxim/smssoftware/pucrunch.html">Maxim's World of Stuff - SMS/Meka stuff</A> <BR>
<A HREF="http://www.devrs.com/gb/asmcode.php#asmcomp">GameBoy Dev'rs - Compression</A> <BR>
<A HREF="http://members.iinet.net.au/~freeaxs/gbacomp/">Headspin's Guide to
Compression, Files Systems Screen Effects and MOD Players
for the Gameboy Advance </A> <BR>
<A HREF="http://hiwaay.net/~jfrohwei/gameboy/libs.html">Jeff Frohwein's GameBoy Libs</A> <BR>
<A HREF="http://www.dwedit.org/crunchyos/manual/crnchyos.html">CrunchyOS - an assembly shell for the TI83+ and TI83+SE calculators</A> <BR>
<HR>
First Version 14.3.1997, Rewritten Version 17.12.1997<BR>
Another Major Update 14.10.1998<BR>
Last Updated 22.11.2008<BR>
Pasi Ojala, <A HREF="http://www.iki.fi/a1bert/"><EM>a1bert@iki.fi</EM></A><BR>
<H2>An Optimizing Hybrid LZ77 RLE Data Compression Program, aka</H2>
<H2>Improving Compression Ratio for Low-Resource Decompression</H2>
Short:<BR>
Pucrunch is a Hybrid LZ77 and RLE compressor, uses an Elias Gamma Code for
lengths, mixture of Gamma Code and linear for LZ77 offset, and ranked RLE
bytes indexed by the same Gamma Code. Uses no extra memory in decompression.
<P>
<A HREF="#Progs">Programs</A> - Source code and executables
<HR>
<H2>Introduction</H2>
Since I started writing demos for the C64 in 1989 I have always wanted to
program a compression program. I had a lot of ideas but never had the time,
urge or the necessary knowledge or patience to create one. In retrospect,
most of the ideas I had then were simply bogus ("magic function theory" as
Mark Nelson nicely puts it). But years passed, I gathered more knowledge and
finally got an irresistible urge to finally realize my dream.
<P>
The nice thing about the delay is that I don't need to write the actual
compression program to run on a C64 anymore. I can write it in portable
ANSI-C code and just program it to create files that would uncompress
themselves when run on a C64. Running the compression program outside of
the target system provides at least the following advantages.
<UL>
<LI> I can use portable ANSI-C code. The compression program can be
compiled to run on a Unix box, Amiga, PC etc. And I have
all the tools to debug the program and gather profiling
information to see why it is so slow :-)
<LI> The program runs much faster than on C64. If it is still slow,
there is always multitasking to allow me to do something else
while I'm compressing a file.
<LI> There is 'enough' memory available. I can use all the memory I
possibly need and use every trick possible to increase the
compression ratio as long as the decompression remains possible
and feasible on a C64.
<LI> Large files can be compressed as easily as shorter files. Most C64
compressors can't handle files larger than around 52-54 kilobytes
(210-220 disk blocks).
<LI> Cross-development is easier because you don't have to transfer a file
into C64 just to compress it.
<LI> It is now possible to use the same program to handle VIC20 and C16/+4
files also. It hasn't been possible to compress VIC20 files at all.
At least I don't know any other VIC20 compressor around.
<P>
</UL>
<P>
<H4>Memory Refresh and Terms for Compression</H4>
<DL>
<DT> Statistical compression
<DD> Uses the uneven probability distribution of the source symbols to
shorten the average code length. Huffman code and arithmetic code
belong to this group. By giving a short code to symbols occurring
most often, the number ot bits needed to represent the symbols
decreases. Think of the Morse code for example: the characters you
need more often have shorter codes and it takes less time to send
the message.
<P>
<DT> Dictionary compression
<DD> Replaces repeating strings in the source with shorter
representations. These may be indices to an actual dictionary
(Lempel-Ziv 78) or pointers to previous occurrances (Lempel-Ziv 77).
As long as it takes fewer bits to represent the reference than the
string itself, we get compression. LZ78 is a lot like the way BASIC
substitutes tokens for keywords: one-byte tokens expand to whole
words like PRINT#. LZ77 replaces repeated strings with
(length,offset) pairs, thus the string <TT>VICIICI</TT> can be
encoded as <TT>VICI(3,3)</TT> -- the repeated occurrance of the
string <TT>ICI</TT> is replaced by a reference.
<P>
<DT> Run-length encoding
<DD> Replaces repeating symbols with a single occurrance of the symbol
and a repeat count. For example assembly compilers have a
<TT>.zero</TT> keyword or equivalent to fill a number of bytes
with zero without needing to list them all in the source code.
<P>
<DT> Variable-length code
<DD> Any code where the length of the code is not explicitly known but
changes depending on the bit values. A some kind of end marker or
length count must be provided to make a code a prefix code
(uniquely decodable). For ASCII (or Latin-1) text you know you get
the next letter by reading a full byte from the input.
A variable-length code requires you to read part of the data to know
how many bits to read next.
<P>
<DT> Universal codes
<DD> Universal codes are used to encode integer numbers without the need
to know the maximum value. Smaller integer values usually get
shorter codes. Different universal codes are optimal for different
distributions of the values. Universal codes include Elias Gamma and
Delta codes, Fibonacci code, and Golomb and Rice codes.
<P>
<DT> Lossless compression
<DD> Lossless compression algorithms are able to exactly reproduce the
original contents unlike lossy compression, which omits details
that are not important or perceivable by human sensory system.
This article only talks about lossless compression.
<P>
</DL>
<P>
My goal in the pucrunch project was to create a compression system in which
the decompressor would use minimal resources (both memory and processing
power) and still have the best possible compression ratio. A nice bonus
would be if it outperformed every other compression program available.
These understandingly opposite requirements (minimal resources and good
compression ratio) rule out most of the state-of-the-art compression
algorithms and in effect only leave RLE and LZ77 to be considered.
Another goal was to learn something about data compression and that goal
at least has been satisfied.
<P>
I started by developing a byte-aligned LZ77+RLE compressor/decompressor
and then added a Huffman backend to it. The Huffman tree takes 384 bytes
and the code that decodes the tree into an internal representation takes
100 bytes. I found out that while the Huffman code gained about 8% in my
40-kilobyte test files, the gain was reduced to only about 3% after
accounting the extra code and the Huffman tree.
<P>
Then I started a more detailed analysis of the LZ77 offset and length values
and the RLE values and concluded that I would get better compression by
using a variable-length code. I used a simple variable-length code and
scratched the Huffman backend code, as it didn't increase the compression
ratio anymore. This version became pucrunch.
<P>
Pucrunch does not use byte-aligned data, and is a bit slower than the
byte-aligned version because of this, but is much faster than the original
version with the Huffman backend attached. And pucrunch still does very well
compression-wise. In fact, it does very well indeed, beating even LhA,
Zip, and GZip in some cases. But let's not get too much ahead of ourselves.
<P>
To get an improvement to the compression ratio for LZ77, we have only
some options left. We can improve on the encoding of literal bytes
(bytes that are not compressed), we can reduce the number of literal bytes
we need to encode, and shorten the encoding of RLE and LZ77. In the
algorithm presented here all these improvement areas are addressed
both collectively (one change affects more than one area) and one at a time.
<P>
<OL>
<LI> By using a variable-length code we can gain compression for even
2-byte LZ77 matches, which in turn reduces the number of literal
bytes we need to encode. Most LZ77-variants require 3-byte matches
to get any compression because they use so many bits to identify
the length and offset values, thus making the code longer than
the original bytes would've taken.
<P>
<LI> By using a new literal byte tagging system which distinguishes
uncompressed and compressed data efficiently we can reduce number
of extra bits needed to make this distinction (the encoding
overhead for literal bytes). This is especially important
for files that do not compress well.
<P>
<LI> By using RLE in addition to LZ77 we can shorten the encoding for long
byte run sequences and at the same time set a convenient upper
limit to LZ77 match length. The upper limit performs two functions:
<UL>
<LI> we only need to encode integers in a specific range
<LI> we only need to search strings shorter than this limit
(if we find a string long enough, we can stop there)
</UL>
Short byte runs are compressed either using RLE or LZ77,
whichever gets the best results.
<P>
<LI> By doing statistical compression (more frequent symbols
get shorter representations) on the RLE bytes (in this case
symbol ranking) we can gain compression for even 2-byte run
lengths, which in turn reduces the number of literal bytes
we need to encode.
<P>
<LI> By carefully selecting which string matches and/or run lengths to use
we can take advantage of the variable-length code. It may be
advantageous to compress a string as two shorter matches instead of
one long match and a bunch of literal bytes, and it can be better
to compress a string as a literal byte and a long match instead of
two shorter matches.
</OL>
<P>
This document consists of several parts, which are:
<UL>
<LI> <A HREF="#C64">C64 Considerations</A> - Some words about the target system
<LI> <A HREF="#Tag">Escape codes</A> - A new tagging system for literal bytes
<LI> <A HREF="#Format">File format</A> - What primary units are output
<LI> <A HREF="#Graph">Graph search</A> - How to squeeze every byte out of this method
<LI> <A HREF="#Match">String match</A> - An evolution of how to speed up the LZ77 search
<LI> <A HREF="#Res1">Some results</A> on the target system files
<LI> Results on the <A HREF="#Res2">Calgary Corpus</A> Test Suite
<LI> <A HREF="#Decompressor">The Decompression routine</A> - 6510 code with commentary
<LI> <A HREF="#Progs">Programs</A> - Source code and some executables
<LI> <A HREF="#Log">The Log Book</A> - My progress reports and some random thoughts
</UL>
<HR>
<A NAME="C64"></A>
<H2>Commodore 64 Considerations</H2>
Our target environment (Commodore 64) imposes some restrictions which we
have to take into consideration when designing the ideal compression
system. A system with a 1-MHz 3-register 8-bit processor and 64 kilobytes
of memory certainly imposes a great challenge, and thus also a great
sense of achievement for good results.
<P>
First, we would like it to be able to decompress as big a program as
possible. This in turn requires that the decompression code is located in
low memory (most programs that we want to compress start at address 2049)
and is as short as possible. Also, the decompression code must not use any
extra memory or only very small amounts of it. Extra care must be taken to
make certain that the compressed data is not overwritten during the
decompression before it has been read.
<P>
Secondly, my number one personal requirement is that the basic end address
must be correctly set by the decompressor so that the program can be
optionally saved in uncompressed form after decompression (although the
current decompression code requires that you say "clr" before saving).
This also requires that the decompression code is system-friendly,
i.e. does not change KERNAL or BASIC variables or other structures.
Also, the decompressor shouldn't rely on file size or load end address
pointers, because these may be corrupted by e.g. X-modem file transfer
protocol (padding bytes may be added).
<P>
When these requirements are combined, there is not much selection in where
in the memory we can put the decompression code. There are some locations
among the first 256 addresses (zeropage) that can be used, the (currently)
unused part of the processor stack (0x100..0x1ff), the system input buffer
(0x200..0x258) and the tape I/O buffer plus some unused bytes (0x334-0x3ff).
The screen memory (0x400..0x7ff) can also be used if necessary. If we can
do without the screen memory and the tape buffer, we can potentially
decompress files that are located from 0x258 to 0xffff.
<P>
The third major requirement is that the decompression should be relatively
fast. After 10 seconds the user begins to wonder if the program crashed or
is it doing anything, even if there is some feedback like border color
flashing. This means that the arithmetic used should be mostly 8- or 9-bit
(instead of full 16 bits) and there should be very little of it per each
decompressed byte. Processor- and memory-intensive algorithms like
arithmetic coding and prediction by partial matching (PPM) are pretty much
out of the question, and it is saying it mildly. LZ77 seems the only
practical alternative. Still, run-length encoding handles long byte runs
better than LZ77 and can have a bigger length limit. If we can easily
incorporate RLE and LZ77 into the same algorithm, we should get the best
features from both.
<P>
A part of the decompressor efficiency depends on the format of the
compressed data. Byte-aligned codes, where everything is aligned into
byte boundaries can be accessed very quickly, non-byte-aligned variable
length codes are much slower to handle, but provide better compression.
Note that byte-aligned codes can still have other data sizes than 8.
For example you can use 4 bits for LZ77 length and 12 bits for LZ77 offset,
which preserves the byte alignment.
<P>
<HR>
<A NAME="Tag"></A>
<H2>The New Tagging System</H2>
I call the different types of information my compression algorithm outputs
<TT>primary units</TT>. The primary units in this compression algorithm are:
<UL>
<LI> literal (uncompressed) bytes and escape sequences,
<LI> LZ77 (length,offset)-pairs,
<LI> RLE (length,byte)-pairs, and
<LI> EOF (end of file marker).
</UL>
Literal bytes are those bytes that could not be represented by shorter codes,
unlike a part of previously seen data (LZ77), or a part of a longer sequence
of the same byte (RLE).
<P>
Most compression programs handle the selection between compressed data and
literal bytes in a straightforward way by using a prefix bit. If the bit
is 0, the following data is a literal byte (uncompressed). If the bit is 1,
the following data is compressed. However, this presents the problem that
non-compressible data will be expanded from the original 8 bits to 9 bits
per byte, i.e. by 12.5 %. If the data isn't very compressible, this overhead
consumes all the little savings you may have had using LZ77 or RLE.
<P>
Some other data compression algorithms use a value (using variable-length
code) that indicates the number of literal bytes that follow, but this is
really analogous to a prefix bit, because 1-byte uncompressed data is very
common for modestly compressible files. So, using a prefix bit may seem
like a good idea, but we may be able to do even better. Let's see what
we can come up with. My idea was to somehow use the data itself to mark
compressed and uncompressed data and thus I don't need any prefix bits.
<P>
Let's assume that 75% of the symbols generated are literal bytes.
In this case it seems viable to allocate shorter codes for literal bytes,
because they are more common than compressed data. This distribution
(75% are literal bytes) suggests that we should use 2 bits to determine
whether the data is compressed or a literal byte. One of the combinations
indicates compressed data, and three of the combinations indicate a literal
byte. At the same time those three values divide the literal bytes into
three distinct groups. But how do we make the connection between which
of the three bit patters we have and what are the literal byte values?
<P>
The simplest way is to use a direct mapping. We use two bits (let them be
the two most-significant bits) from the literal bytes themselves to
indicate compressed data. This way no actual prefix bits are needed.
We maintain an escape code (which doesn't need to be static), which is
compared to the bits, and if they match, compressed data follows. If the
bits do not match, the rest of the literal byte follows. In this way the
literal bytes do not expand at all if their most significant bits do not
match the escape code, thus less bits are needed to represent the literal
bytes.
<P>
Whenever those bits in a literal byte would match the escape code, an
escape sequence is generated. Otherwise we could not represent those
literal bytes which actually start like the escape code (the top bits
match). This escape sequence contains the offending data and a new escape
code. This escape sequence looks like <BR>
<PRE>
# of escape bits (escape code)
3 (escape mode select)
# of escape bits (new escape bits)
8-# of escape bits (rest of the byte)
= 8 + 3 + # of escape bits
= 13 for 2-bit escapes, i.e. expands the literal byte by 5 bits.
</PRE>
Read further to see how we can take advantage of the changing escape code.
<P>
You may also remember that in the run-length encoding presented in the
previous article two successive equal bytes are used to indicate compressed
data (escape condition) and all other bytes are literal bytes. A similar
technique is used in some C64 packers (RLE) and crunchers (LZ77), the only
difference is that the escape condition is indicated by a fixed byte value.
My tag system is in fact an extension to this. Instead of a full byte, I
use only a few bits.
<P>
We assumed an even distribution of the values and two escape bits, so 1/4
of the values have the same two most significant bits as the escape code.
I call this probability that a literal byte has to be escaped the
<TT>hit rate</TT>. Thus, literal bytes expand in average 25% of the time by
5 bits, making the average length 25% * 13 + 75% * 8 = 9.25. Not suprising,
this is longer than using one bit to tag the literal bytes. However, there
is one thing we haven't considered yet. The escape sequence has the
possibility to change the escape code. Using this feature to its optimum
(escape optimization), the average 25% <TT>hit rate</TT> becomes the
<STRONG>maximum</STRONG> <TT>hit rate</TT>.
<P>
Also, because the distribution of the (values of the) literal bytes is
seldom flat (some values are more common than others) and there is locality
(different parts of the file only contain some of the possible values),
from which we can also benefit, the actual hit rate is always much smaller
than that. Empirical studies on some test files show that for 2-bit escape
codes the actual realized hit rate is only 1.8-6.4%, while the theoretical
maximum is the already mentioned 25%.
<P>
Previously we assumed the distribution of 75% of literal bytes and 25% of
compressed data (other primary units). This prompted us to select 2 escape
bits. For other distributions (differently compressible files, not
necessarily better or worse) some other number of escape bits may be more
suitable. The compressor tries different number of escape bits and select
the value which gives the best overall results. The following table
summarizes the hit rates on the test files for different number of escape
bits.
<P>
<TABLE border cellpadding=1>
<TR align="left">
<TH>1-bit</TH> <TH>2-bit</TH> <TH>3-bit</TH> <TH>4-bit</TH> <TH>File</TH>
</TR>
<TR align="left">
<TD align="right">50.0%</TD>
<TD align="right">25.0%</TD>
<TD align="right">12.5%</TD>
<TD align="right">6.25%</TD>
<TD>Maximum</TD>
</TR>
<TR align="left">
<TD align="right">25.3%</TD>
<TD align="right">2.5%</TD>
<TD align="right">0.3002%</TD>
<TD align="right">0.0903%</TD>
<TD>ivanova.bin</TD>
</TR>
<TR align="left">
<TD align="right">26.5%</TD>
<TD align="right">2.4%</TD>
<TD align="right">0.7800%</TD>
<TD align="right">0.0631%</TD>
<TD>sheridan.bin</TD>
</TR>
<TR align="left">
<TD align="right">20.7%</TD>
<TD align="right">1.8%</TD>
<TD align="right">0.1954%</TD>
<TD align="right">0.0409%</TD>
<TD>delenn.bin</TD>
</TR>
<TR align="left">
<TD align="right">26.5%</TD>
<TD align="right">6.4%</TD>
<TD align="right">2.4909%</TD>
<TD align="right">0.7118%</TD>
<TD>bs.bin</TD>
</TR>
<TR align="left"><TH>9.06</TH> <TH>8.32</TH> <TH>8.15</TH> <TH>8.050</TH>
<TH>bits/Byte for bs.bin</TH></TR>
</TABLE>
<P>
As can be seen from the table, the realized hit rates are dramatically
smaller than the theoretical maximum values. A thought might occur that
we should always select 4-bit (or longer) escapes, because it reduces
the hit rate and presents the minimum overhead for literal bytes.
Unfortunately increasing the number of escape bits also increases the
code length of the compressed data. So, it is a matter of finding the
optimum setting.
<P>
If there are very few literal bytes compared to other primary units, 1-bit
escape or no escape at all gives very short codes to compressed data,
but causes more literal bytes to be escaped, which means 4 bits extra for
each escaped byte (with 1-bit escapes). If the majority of primary units
are literal bytes, for example a 6-bit escape code causes most of the
literal bytes to be output as 8-bit codes (no expansion), but makes the
other primary units 6 bits longer. Currently the compressor automatically
selects the best number of escape bits, but this can be overriden by
the user with the -e option.
<P>
The cases in the example with 1-bit escape code validates the original
suggestion: use a prefix bit. A simple prefix bit would produce better
results on three of the previous test files (although only slightly).
For delenn.bin (1 vs 0.828) the escape system works better. On the other
hand, 1-bit escape code is not selected for any of the files, because
2-bit escape gives better overall results.
<P>
<STRONG>Note:</STRONG> for 7-bit ASCII text files, where the top bit is
always 0 (like most of the Calgary Corpus files), the hit rate is 0% for
even 1-bit escapes. Thus, literal bytes do not expand at all. This is
equivalent to using a prefix bit and 7-bit literals, but does not need
seperate algorithm to detect and handle 7-bit literals.
<P>
For Calgary Corpus files the number of tag bits per primary unit (counting
the escape sequences and other overhead) ranges from as low as 0.46 (book1)
to 1.07 (geo) and 1.09 (pic). These two files (geo and pic) are the only
ones in the suite where a simple prefix bit would be better than the escape
system. The average is 0.74 tag bits per primary unit.
<P>
In Canterbury Corpus the tag bits per primary unit ranges from 0.44
(plrabn12.txt) to 1.09 (ptt5), which is the only one above 0.85 (sum).
The average is 0.61 tag bits per primary.
<P>
<HR>
<A NAME="Format"></A>
<H2>Primary Units Used for Compression</H2>
The compressor uses the previously described escape-bit system while
generating its output. I call the different groups of bits that are
generated primary units. The primary units in this compression
algorithm are: literal byte (and escape sequence), LZ77
(length,offset)-pair, RLE (length, byte)-pair, and EOF (end of file marker).
<P>
If the top bits of a literal byte do not match the escape code,
the byte is output as-is. If the bits match, an escape sequence is
generated, with the new escape code. Other primary units start with the
escape code.
<P>
The Elias Gamma Code is used extensively. This code consists of two
parts: a unary code (a one-bit preceded by zero-bits) and a binary code
part. The first part tells the decoder how many bits are used for the
binary code part. Being a universal code, it produces shorter codes for
small integers and longer codes for larger integers. Because we expect
we need to encode a lot of small integers (there are more short string
matches and shorter equal byte runs than long ones), this reduces the total
number of bits needed. See the previous article for a more in-depth delve
into statistical compression and universal codes. To understand this article,
you only need to keep in mind that small integer value equals short code.
The following discusses the encoding of the primary units.
<P>
The most frequent compressed data is LZ77. The length of the match is
output in Elias Gamma code, with "0" meaning the length of 2, "100"
length of 3, "101" length of 4 and so on. If the length is not 2,
a LZ77 offset value follows. This offset takes 9 to 22 bits. If the
length is 2, the next bit defines whether this is LZ77 or RLE/Escape.
If the bit is 0, an 8-bit LZ77 offset value follows. (Note that this
restricts the offset for 2-byte matches to 1..256.) If the bit is 1,
the next bit decides between escape (0) and RLE (1).
<P>
The code for an escape sequence is thus <TT>e..e010n..ne....e</TT>,
where <TT>E</TT> is the byte, and <TT>N</TT> is the new escape code.
Example:
<UL>
<LI> We are using 2-bit escapes
<LI> The current escape code is <TT>"11"</TT>
<LI> We need to encode a byte <TT>0xca == 0b11001010</TT>
<LI> The escape code and the byte high bits match (both are <TT>"11"</TT>)
<LI> We output the current escape code <TT>"11"</TT>
<LI> We output the escaped identification <TT>"010"</TT>
<LI> We output the new escape bits, for example <TT>"10"</TT>
(depends on escape optimization)
<LI> We output the rest of the escaped byte <TT>"001010"</TT>
<LI> So, we have output the string <TT>"1101010001010"</TT>
</UL>
When the decompressor receives this string of bits, it finds that
the first two bits match with the escape code, it finds the escape
identification (<TT>"010"</TT>) and then gets the new escape, the
rest of the original byte and combines it with the old escape code
to get a whole byte.
<P>
The end of file condition is encoded to the LZ77 offset and the RLE
is subdivided into long and short versions. Read further, and you get a
better idea about why this kind of encoding is selected.
<P>
When I studied the distribution of the length values (LZ77 and short
RLE lengths), I noticed that the smaller the value, the more occurrances.
The following table shows an example of length value distribution.
<PRE>
LZLEN S-RLE
2 1975 477
3-4 1480 330
5-8 492 166
9-16 125 57
17-32 31 33
33-64 8 15
</PRE>
The first column gives a range of values. The first entry has a single
value (2), the second two values (3 and 4), and so on. The second column
shows how many times the different LZ77 match lengths are used, the last
column shows how many times short RLE lengths are used. The distribution
of the values gives a hint of how to most efficiently encode the values.
We can see from the table for example that values 2-4 are used 3455 times,
while values 5-64 are used only 656 times. The more common values need
to get shorter codes, while the less-used ones can be longer.
<P>
Because in each "magnitude" there are approximately half as many
values than in the preciding one, it almost immediately occurred
to me that the optimal way to encode the length values (decremented
by one) is:
<PRE>
Value Encoding Range Gained
0000000 not possible
0000001 0 1 -6 bits
000001x 10x 2-3 -4 bits
00001xx 110xx 4-7 -2 bits
0001xxx 1110xxx 8-15 +0 bits
001xxxx 11110xxxx 16-31 +2 bits
01xxxxx 111110xxxxx 32-63 +4 bits
1xxxxxx 111111xxxxxx 64-127 +5 bits
</PRE>
The first column gives the binary code of the original value (with
<TT>x</TT> denoting 0 or 1, <TT>xx</TT> 0..3, <TT>xxx</TT> 0..7 and
so on), the second column gives the encoding of the value(s). The
third column lists the original value range in decimal notation.
<P>
The last column summarises the difference between this code and a
7-bit binary code. Using the previous encoding for the length
distribution presented reduces the number of bits used compared to
a direct binary representation considerably. Later I found out that
this encoding in fact is Elias Gamma Code, only the assignment of 0-
and 1-bits in the prefix is reversed, and in this version the length is
limited. Currently the maximum value is selectable between 64 and 256.
<P>
So, to recap, this version of the Gamma code can encode numbers from
1 to 255 (1 to 127 in the example). LZ77 and RLE lengths that are used
start from 2, because that is the shortest length that gives us any
compression. These length values are first decremented by one, thus
length 2 becomes <TT>"0"</TT>, and for example length 64 becomes
<TT>"11111011111"</TT>.
<P>
The distribution of the LZ77 offset values (pointer to a previous
occurrance of a string) is not at all similar to the length distribution.
Admittedly, the distribution isn't exactly flat, but it also isn't as
radical as the length value distribution either. I decided to encode the
lower 8 bits (automatically selected or user-selectable between 8 and
12 bits in the current version) of the offset as-is (i.e. binary code)
and the upper part with my version of the Elias Gamma Code. However,
2-byte matches always have an 8-bit offset value. The reason for this
is discussed shortly.
<P>
Because the upper part can contain the value 0 (so that we can represent
offsets from 0 to 255 with a 8-bit lower part), and the code can't directly
represent zero, the upper part of the LZ77 offset is incremented by one
before encoding (unlike the length values which are decremented by one).
Also, one code is reserved for an end of file (EOF) symbol. This restricts
the offset value somewhat, but the loss in compression is negligible.
<P>
With the previous encoding 2-byte LZ77 matches would only gain 4 bits
(with 2-bit escapes) for each offset from 1 to 256, and 2 bits for each
offset from 257 to 768. In the first case 9 bits would be used to represent
the offset (one bit for gamma code representing the high part 0, and
8 bits for the low part of the offset), in the latter case 11 bits are
used, because each "magnitude" of values in the Gamma code consumes two
more bits than the previous one.
<P>
The first case (offset 1..256) is much more frequent than the second case,
because it saves more bits, and also because the symbol source statistics
(whatever they are) guarantee 2-byte matches in recent history (much better
chance than for 3-byte matches, for example). If we restrict the offset
for a 2-byte LZ77 match to 8 bits (1..256), we don't lose so much
compression at all, but instead we could shorten the code by one bit.
This one bit comes from the fact that before we had to use one bit
to make the selection "8-bit or longer". Because we only have "8-bit"
now, we don't need that select bit anymore.
<P>
Or, we can use that select bit to a new purpose to select whether this
code really is LZ77 or something else. Compared to the older encoding
(which I'm not detailing here, for clarity's sake. This is already
much too complicated to follow, and only slightly easier to describe)
the codes for escape sequence, RLE and End of File are still the same
length, but the code for LZ77 has been shortened by one bit. Because
LZ77 is the most frequently used primary unit, this presents a saving
that more than compensates for the loss of 2-byte LZ77 matches with offsets
257..768 (which we can no longer represent, because we fixed the offset
for 2-byte matches to use exactly 8 bits).
<P>
Run length encoding is also a bit revised. I found out that a lot of
bits can be gained by using the same length encoding for RLE as for
LZ77. On the other hand, we still should be able to represent long
repeat counts as that's where RLE is most efficient. I decided to
split RLE into two modes:
<UL>
<LI> short RLE for short (e.g. 2..128) equal byte strings
<LI> long RLE for long equal byte strings
</UL>
The Long RLE selection is encoded into the Short RLE code. Short RLE only
uses half of its coding space, i.e. if the maximum value for the gamma
code is 127, short RLE uses only values 1..63. Larger values switches the
decoder into Long RLE mode and more bits are read to complete the run length
value.
<P>
For further compression in RLE we rank all the used RLE bytes (the values
that are repeated in RLE) in the decreasing probability order. The values
are put into a table, and only the table indices are output. The indices
are also encoded using a variable length code (the same gamma code,
surprise..), which uses less bits for smaller integer values. As there are
more RLE's with smaller indices, the average code length decreases.
In decompression we simply get the gamma code value and then use the value
as an index into the table to get the value to repeat.
<P>
Instead of reserving full 256 bytes for the table we only put the top 31 RLE
bytes into the table. Normally this is enough. If there happens to be a byte
run with a value not in the table we use a similar technique as for the
short/long RLE selection. If the table index is larger than 31, it means we
don't have the value in the table. We use the values 32..63 to select the
'escaped' mode and simultaneously send the 5 most significant bits of the
value (there are 32 distinct values in the range 32..63). The rest 3 bits
of the byte are sent separately.
<P>
If you are more than confused, forget everything I said in this chapter and
look at the decompression pseudo-code later in this article.
<P>
<HR>
<A NAME="Graph"></A>
<H2>Graph Search - Selecting Primary Units</H2>
In free-parse methods there are several ways to divide the file into parts,
each of which is equally valid but not necessary equally efficient in terms
of compression ratio.
<PRE>
"i just saw justin adjusting his sting"
"i just saw", (-9,4), "in ad", (-9,6), "g his", (-25,2), (-10,4)
"i just saw", (-9,4), "in ad", (-9,6), "g his ", (-10,5)
</PRE>
The latter two lines show how the sentence could be encoded using literal
bytes and (offset, length) pairs. As you can see, we have two different
encodings for a single string and they are both valid, i.e. they will
produce the same string after decompression. This is what free-parse is:
there are several possible ways to divide the input into parts. If we are
clever, we will of course select the encoding that produces the shortest
compressed version. But how do we find this shortest version? How does
the data compressor decide which primary unit to generate in each step?
<P>
The most efficient way the file can be divided is determined by a sort
of a graph-search algorithm, which finds the shortest possible route from
the start of the file to the end of the file. Well, actually the algorithm
proceeds from the end of the file to the beginning for efficiency reasons,
but the result is the same anyway: the path that minimizes the bits emitted
is determined and remembered. If the parameters (number of escape bits or
the variable length codes or their parameters) are changed, the graph search
must be re-executed.
<P>
<PRE>
"i just saw justin adjusting his sting"
\___/ \_____/ \_|___/
13 15 11 13
\____/
15
</PRE>
Think of the string as separate characters. You can jump to the next
character by paying 8 bits to do so (not shown in the figure), unless the
top bits of the character match with the escape code (in which case you need
more bits to send the character "escaped"). If the history buffer contains a
string that matches a string starting at the current character you can jump
over the string by paying as many bits as representing the LZ77
(offset,length)-pair takes (including escape bits), in this example from
11 to 15 bits. And the same applies if you have RLE starting at the character.
Then you just find the least-expensive way to get from the start of the file
to the end and you have found the optimal encoding. In this case the last
characters " sting" would be optimally encoded with
8(literal " ") + 15("sting") = 23 instead of 11(" s") + 13("ting") = 24 bits.
<P>
The algorithm can be written either cleverly or not-so. We can take a real
short-cut compared to a full-blown graph search because we can/need to only
go forwards in the file: we can simply start from the end! Our accounting
information which is updated when we pass each location in the data consists
of three values:
<OL>
<LI> the minimum bits from this location to the end of file.
<LI> the mode (literal, LZ77 or RLE) to use to get that minimum
<LI> the "jump" length for LZ77 and RLE
</OL>
For each location we try to jump forward (to a location we already processed)
one location, LZ77 match length locations (if a match exists), or RLE
length locations (if equal bytes follow) and select the shortest route,
update the tables accordingly. In addition, if we have a LZ77 or RLE
length of for example 18, we also check jumps 17, 16, 15, ... This gives
a little extra compression. Because we are doing the "tree traverse"
starting from the "leaves", we only need to visit/process each location
once. Nothing located after the current location can't change, so there is
never any need to update a location.
<P>
To be able to find the minimal path, the algorithm needs the length of
the RLE (the number of the identical bytes following) and the maximum
LZ77 length/offset (an identical string appearing earlier in the file)
for each byte/location in the file. This is the most time-consuming
<STRONG>and</STRONG> memory-consuming part of the compression. I have
used several methods to make the search faster.
See <A HREF="#Match">String Match Speedup</A> later in this article.
Fortunately these searches can be done first, and the actual optimization
can use the cached values.
<P>
Then what is the rationale behind this optimization? It works because you
are not forced to take every compression opportunity, but select the best
ones. The compression community calls this "lazy coding" or "non-greedy"
selection. You may want to emit a literal byte even if there is a 2-byte
LZ77 match, because in the next position in the file you may have a longer
match. This is actually more complicated than that, but just take my word
for it that there is a difference. Not a very big difference, and only
significant for variable-length code, but it is there and I was after
every last bit of compression, remember.
<P>
Note that the decision-making between primary units is quite simple if a
fixed-length code is used. A one-step lookahead is enough to guarantee
optimal parsing. If there is a more advantageous match in the next location,
we output a literal byte and that longer match instead of the shorter
match. I don't have time or space here to go very deeply on that, but
the main reason is that in fixed-length code it doesn't matter whether
you represent a part of data as two matches of lengths 2 and 8 or as
matches of lengths 3 and 7 or as any other possible combination (if
matches of those lengths exist). This is not true for a variable-length
code and/or a statistical compression backend. Different match lengths
and offsets no longer generate equal-length codes.
<P>
Note also that most LZ77 compression algorithms need at least 3-byte
match to break even, i.e. not expanding the data. This is not surprising
when you stop to think about it. To gain something from 2-byte matches
you need to encode the LZ77 match into 15 bits. This is very little.
A generic LZ77 compressor would use one bit to select between a literal
and LZ77, 12 bits for moderate offset, and you have 2 bits left for match
length. I imagine the rationale to exclude 2-byte matches also include
"the potential savings percentage for 2-byte matches is insignificant".
Pucrunch gets around this by using the tag system and Elias Gamma Code,
and does indeed gain bits from even 2-byte matches.
<P>
After we have decided on what primary units to output, we still have to make
sure we get the best results from the literal tag system. Escape optimization
handles this. In this stage we know which parts of the data are emitted as
literal bytes and we can select the minimal path from the first literal byte
to the last in the same way we optimized the primary units. Literal bytes
that match the escape code generate an escape sequence, thus using more bits
than unescaped literal bytes and we need to minimize these occurrances.
<P>
For each literal byte there is a corresponding new escape code which
minimizes the path to the end of the file. If the literal byte's high
bits match the current escape code, this new escape code is used next.
The escape optimization routine proceeds from the end of the file to
the beginning like the graph search, but it proceeds linearly and is
thus much faster.
<P>
I already noted that the new literal byte tagging system exploits the
locality in the literal byte values. If there is no correlation between
the bytes, the tagging system does not do well at all. Most of the time,
however, the system works very well, performing 50% better than the
prefix-bit approach.
<P>
The escape optimization routine is currently very fast. A little algorithmic
magic removed a lot of code from the original version. Fast escape
optimization routine is quite advantageous, because the number of escape
bits can now vary from 0 (uncompressed bytes always escaped) to 8 and we
need to run the routine again if we change the number of escape bits used
to select the optimal escape code changes.
<P>
Because escaped literal bytes actually expand the data, we need a safety
area, or otherwise the compressed data may get overwritten by the
decompressed data before we have used it. Some extra bytes need to be
reserved for the end of file marker. The compression routine finds
out how many bytes we need for safety buffer by keeping track of the
difference between input and output sizes while creating the compressed
file.
<PRE>
$1000 .. $2000
|OOOOOOOO| O=original file
$801 ..
|D|CCCCC| C=compressed data (D=decompressor)
$f7.. $1000 $2010
|D| |CCCCC| Before decompression starts
^ ^
W R W=write pointer, R=read pointer
</PRE>
If the original file is located at $1000-$1fff, and the calculated safety
area is 16 bytes, the compressed version will be copied by the decompression
routine higher in memory so that the last byte is at $200f. In this way, the
minimum amount of other memory is overwritten by the decompression. If the
safety area would exceed the top of memory, we need a wrap buffer. This is
handled automatically by the compressor. The read pointer wraps from the end
of memory to the wrap buffer, allowing the original file to extend upto the
end of the memory, all the way to $ffff. You can get the compression program
to tell you which memory areas it uses by specifying the "-s" option.
Normally the safety buffer needed is less than a dozen bytes.
<P>
To sum things up, Pucrunch operates in several steps:
<OL>
<LI> Find RLE and LZ77 data, pre-select RLE byte table
<LI> Graph search, i.e. which primary units to use
<LI> Primary Units/Literal bytes ratio decides how many escape bits to use
<LI> Escape optimization, which escape codes to use
<LI> Update RLE ranks and the RLE byte table
<LI> Determine the safety area size and output the file.
</OL>
<P>
<HR>
<A NAME="Match"></A>
<H2>String Match Speedup</H2>
To be able to select the most efficient combination of primary units we of
course first need to find out what kind of primary units are available for
selection. If the file doesn't have repeated bytes, we can't use RLE.
If the file doesn't have repeating byte strings, we can't use LZ77.
This string matching is the most time-consuming operation in LZ77
compression simply because of the amount of the comparison operations
needed. Any improvement in the match algorithm can decrease the compression
time considerably. Pucrunch is a living proof on that.
<P>
The RLE search is straightforward and fast: loop from the current position
(<TT>P</TT>) forwards in the file counting each step until a different-valued
byte is found or the end of the file is reached. This count can then be
used as the RLE byte count (if the graph search decides to use RLE).
The code can also be optimized to initialize counts for all locations that
belonged to the RLE, because by definition there are only one-valued bytes
in each one. Let us mark the current file position by <TT>P</TT>.
<PRE>
unsigned char *a = indata + P, val = *a++;
int top = inlen - P;
int rlelen = 1;
/* Loop for the whole RLE */
while (rlelen<top && *a++ == val)
rlelen++;
for (i=0; i<rlelen-1; i++)
rle[P+i] = rlelen-i;
</PRE>
<P>
With LZ77 we can't use the same technique as for RLE (i.e. using the
information about current match to skip subsequent file locations to
speed up the search). For LZ77 we need to find the longest possible, and
<STRONG>nearest</STRONG> possible, string that matches the bytes
starting from the current location. The nearer the match, the less bits
are needed to represent the offset from the current position.
<P>
Naively, we could start comparing the strings starting from <TT>P-1</TT>
and <TT>P</TT>, remembering the length of the matching part and then doing
the same at <TT>P-2</TT> and <TT>P</TT>, <TT>P-3</TT> and <TT>P</TT>, ..
<TT>P-j</TT> and <TT>P</TT> (<TT>j</TT> is the maximum search offset).
The longest match and its location (offset from the current position)
are then remembered and initialized. If we find a match longer or equal
than the maximum length we can actually use, we can stop the search
there. (The code used to represent the length values may have an upper
limit.)
<P>
This may be the first implementation that comes to your (and my) mind,
and might not seem so bad at first. In reality, it is a very slow way
to do the search, the <STRONG>Brute Force</STRONG> method. It could take
somewhere about (<TT>n^3</TT>) byte compares to process a file of the
length <TT>n</TT> (a mathematically inclined person would probably give
a better estimate). However, using the already determined RLE value to
our advantage permits us to rule out the worst-case projection, which
happens when all bytes are the same value. We only search LZ77 matches
if the current file position has shorter RLE sequence than the maximum
LZ77 copy length.
<P>
The first thing I did to improve the speed is to remember the position
where each byte has last been seen. A simple 256-entry table handles that.
Using this table, the search can directly start from the first potential
match, and we don't need to search for it byte-by-byte anymore. The table
is continually updated when we move toward to the end of the file.
<P>
That didn't give much of an improvement, but then I increased the table to
256*256 entries, making it possible to locate the latest occurrance of any
byte <STRONG>pair</STRONG> instead. The table indexed with the byte values
and the table contents directly gives the position in file where these two
bytes were last seen. Because the shortest possible string that would offer
any compression (for my encoding of LZ77) is two bytes long, this byte-pair
history is very suitable indeed. Also, the first (shortest possible, i.e.
2-byte) match is found directly from the byte-pair history. This gave a
moderate 30% decrease in compression time for one of my test files (from
28 minutes to 17 minutes on a 25 MHz 68030).
<P>
The second idea was to quickly discard the strings that had no chance of
being longer matches than the one already found. A one-byte hash value
(sort of a checksum here, it is never used to index a hash table in
this algorithm, but I rather use "hash value" than "checksum") is
calculated from each three bytes of data. The values are calculated once and
put into a table, so we only need two memory fetches to know if two 3-byte
strings are different. If the hash values are different, at least one of the
data bytes differ. If the hash values are equal, we have to compare the
original bytes. The hash values of the strategic positions of the strings to
compare are then .. compared. This strategic position is the location two
bytes earlier than the longest match so far. If the hash values differ, there
is no chance that the match is longer than the current one. It may be not
even be as long, because one of the two earlier bytes may be different. If the
hash values are equal, the brute-force byte-by-byte compare has to be done.
However, the hash value check already discards a huge number of candidates
and more than generously pays back its own memory references. Using the hash
values the compression time shortens by 50% (from 17 minutes to 8 minutes).
<P>
Okay, the byte-pair table tells us where the latest occurrance of any byte
pair is located. Still, for the latest occurrance before <STRONG>that</STRONG>
one we have to do a brute force search. The next improvement was to use the
byte-pair table to generate a linked list of the byte pairs with the same
value. In fact, this linked list can be trivially represented as a table,
using the same indexing as the file positions. To locate the previous
occurrance of a 2-byte string starting at location P, look at
<TT>backSkip[P]</TT>.
<PRE>
/* Update the two-byte history & backSkip */
if (P+1<inlen) {
int index = (indata[P]<<8) | indata[P+1];
backSkip[P] = lastPair[index];
lastPair[index] = P+1;
}
</PRE>
Actually the values in the table are one bigger than the real table
indices. This is because the values are of type unsigned short (can only
represent non-negative values), and I wanted zero to mean "not occurred".
<P>
This table makes the search of the next (previous) location to consider
much faster, because it is a single table reference. The compression time
was reduced from 6 minutes to 1 minute 10 seconds. Quite an improvement
from the original 28 minutes!
<P>
<PRE>
backSkip[] lastPair[]
___ _______ ____
\/ \/ \
...JOVE.....JOKA..JOKER
^ ^ ^
| | |