8 * Hacked version for writing from Rawimage to file.
9 * Assumes 8 bits per component.
12 #define HSHIFT 3 /* HSHIFT==5 runs slightly faster, but hash table is 64x bigger */
13 #define NHASH (1<<(HSHIFT*NMATCH))
14 #define HMASK (NHASH-1)
15 #define hupdate(h, c) ((((h)<<HSHIFT)^(c))&HMASK)
16 typedef struct Hlist Hlist;
23 writerawimage(int fd, Rawimage *i)
25 uchar *outbuf, *outp, *eout; /* encoded data, pointer, end */
26 uchar *loutp; /* start of encoded line */
27 Hlist *hash; /* heads of hash chains of past strings */
28 Hlist *chain, *hp; /* hash chain members, pointer */
29 Hlist *cp; /* next Hlist to fall out of window */
30 int h; /* hash value */
31 uchar *line, *eline; /* input line, end pointer */
32 uchar *data, *edata; /* input buffer, end pointer */
33 ulong n; /* length of input buffer */
34 int bpl; /* input line length */
35 int offs, runlen; /* offset, length of consumed data */
36 uchar dumpbuf[NDUMP]; /* dump accumulator */
37 int ndump; /* length of dump accumulator */
38 int ncblock; /* size of buffer */
40 uchar *p, *q, *s, *es, *t;
41 char hdr[11+5*12+1], buf[16];
47 werrstr("can't handle chandesc %d", i->chandesc);
55 desc = CHAN2(CGrey, 8, CAlpha, 8);
63 desc = CHAN2(CMap, 8, CAlpha, 8);
74 ncblock = _compblocksize(r, bpl/Dx(r));
75 outbuf = malloc(ncblock);
76 hash = malloc(NHASH*sizeof(Hlist));
77 chain = malloc(NMEM*sizeof(Hlist));
78 if(outbuf == 0 || hash == 0 || chain == 0){
87 sprint(hdr, "compressed\n%11s %11d %11d %11d %11d ",
88 chantostr(buf, desc), r.min.x, r.min.y, r.max.x, r.max.y);
89 if(write(fd, hdr, 11+5*12) != 11+5*12){
90 werrstr("i/o error writing header");
94 eout = outbuf+ncblock;
98 memset(hash, 0, NHASH*sizeof(Hlist));
99 memset(chain, 0, NMEM*sizeof(Hlist));
103 for(n = 0; n != NMATCH; n++)
104 h = hupdate(h, line[n]);
106 while(line != edata){
109 for(p = line; p != eline; ){
116 for(hp = hash[h].next; hp; hp = hp->next){
140 if(eout-outp < ndump+1)
142 *outp++ = ndump-1+128;
143 memmove(outp, dumpbuf, ndump);
147 dumpbuf[ndump++] = *p;
152 if(eout-outp < ndump+1)
154 *outp++ = ndump-1+128;
155 memmove(outp, dumpbuf, ndump);
162 *outp++ = ((runlen-NMATCH)<<2) + (offs>>8);
165 for(q = p+runlen; p != q; p++){
168 cp->next = hash[h].next;
174 if(++cp == &chain[NMEM])
177 h = hupdate(h, p[NMATCH]);
181 if(eout-outp < ndump+1)
183 *outp++ = ndump-1+128;
184 memmove(outp, dumpbuf, ndump);
193 werrstr("compressor out of sync");
197 sprint(hdr, "%11d %11ld ", r.max.y, n);
198 write(fd, hdr, 2*12);
199 write(fd, outbuf, n);