1 /* sub.c not copyrighted (n) 1993 by Mark Adler */
2 /* version 1.1 11 Jun 1993 */
4 /* sub is a simple filter to preprocess a data file before compression.
5 It can increase compression for data whose points tend to be close to
6 the last point. The output is the difference of successive bytes of
7 the input. The add filter is used to undo what sub does. This could
8 be used on 8-bit sound or graphics data.
10 sub can also take an argument to apply this to interleaved sets of
11 bytes. For example, if the data are 16-bit sound samples, then you
12 can use "sub 2" to take differences on the low-byte stream and the
13 high-byte stream. (This gives nearly the same effect as subtracting
14 the 16-bit values, but avoids the complexities of endianess of the
15 data.) The concept extends to RGB image data (sub 3), 16-bit stereo
16 data (sub 4), floating point data (sub 4 or sub 8), etc.
18 add takes no options, since the number of interleaved byte streams
19 is put in the first two bytes of the output stream for add to use
20 (in little-endian format).
24 sub < graph.vga | gzip -9 > graph.vga.sgz
25 sub < phone.snd | gzip -9 > phone.snd.sgz
26 sub 2 < audio.snd | gzip -9 > audio.snd.sgz
27 sub 3 < picture.rgb | gzip -9 > picture.rgb.sgz
28 sub 4 < stereo.snd | gzip -9 > stereo.snd.sgz
29 sub 8 < double.data | gzip -9 > double.data.sgz
31 To expand, use the reverse operation, as in:
33 gunzip < double.data.sgz | add > double.data
40 #define MAGIC1 'S' /* sub data */
41 #define MAGIC2 26 /* ^Z */
42 #define MAX_DIST 16384
44 char a
[MAX_DIST
]; /* last byte buffer for up to MAX_DIST differences */
50 int n
= 1; /* number of differences */
51 int i
; /* difference counter */
52 int c
; /* byte from input */
53 int atoi(); /* (avoid including stdlib for portability) */
55 /* process arguments */
58 fputs("sub: only one argument needed--# of differences\n", stderr
);
64 if (n
< 0) n
= -n
; /* tolerate "sub -2" */
65 if (n
== 0 || n
> MAX_DIST
) {
66 fputs("sub: incorrect distance\n", stderr
);
70 /* initialize last byte */
76 /* write differenced data */
77 putchar(MAGIC1
); putchar(MAGIC2
); /* magic word for add */
78 putchar(n
& 0xff); /* so add knows what to do */
79 putchar((n
>>8) & 0xff);
81 while ((c
= getchar()) != EOF
)
83 putchar((c
- a
[i
]) & 0xff); /* write difference */
84 a
[i
++] = c
; /* save last byte */
85 if (i
== n
) /* cycle on n differences */
89 return 0; /* avoid warning */