maint: initialize MAINTAINERCLEANFILES
[gzip.git] / sample / sub.c
blobce83a983961b91df25ab814f9d97e15fe346dc39
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).
22 Examples:
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
36 #include <config.h>
37 #include <stdio.h>
38 #include <stdlib.h>
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 */
46 int
47 main (int argc, char **argv)
49 int n = 1; /* number of differences */
50 int i; /* difference counter */
51 int c; /* byte from input */
52 int atoi(); /* (avoid including stdlib for portability) */
54 /* process arguments */
55 if (argc > 2)
57 fputs("sub: only one argument needed--# of differences\n", stderr);
58 exit(EXIT_FAILURE);
60 if (argc > 1)
61 n = atoi(argv[1]);
63 if (n < 0) n = -n; /* tolerate "sub -2" */
64 if (n == 0 || n > MAX_DIST) {
65 fputs("sub: incorrect distance\n", stderr);
66 exit(EXIT_FAILURE);
69 /* initialize last byte */
70 i = n;
71 do {
72 a[--i] = 0;
73 } while (i);
75 /* write differenced data */
76 putchar(MAGIC1); putchar(MAGIC2); /* magic word for add */
77 putchar(n & 0xff); /* so add knows what to do */
78 putchar((n>>8) & 0xff);
80 while ((c = getchar()) != EOF)
82 putchar((c - a[i]) & 0xff); /* write difference */
83 a[i++] = c; /* save last byte */
84 if (i == n) /* cycle on n differences */
85 i = 0;
87 exit(EXIT_SUCCESS);
88 return 0; /* avoid warning */