]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/jpg/readgif.c
awk: make empty FS unicodely-correct.
[plan9front.git] / sys / src / cmd / jpg / readgif.c
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <draw.h>
5 #include "imagefile.h"
6
7 typedef struct Entry Entry;
8 typedef struct Header Header;
9
10 struct Entry{
11         int             prefix;
12         int             exten;
13 };
14
15 struct Header{
16         Biobuf  *fd;
17         char            err[256];
18         jmp_buf errlab;
19         uchar   buf[3*256];
20         char            vers[8];
21         uchar   *globalcmap;
22         int             screenw;
23         int             screenh;
24         int             fields;
25         int             bgrnd;
26         int             aspect;
27         int             flags;
28         int             delay;
29         int             trindex;
30         int             loopcount;
31         Entry   tbl[4096];
32         Rawimage        **array;
33         Rawimage        *new;
34
35         uchar   *pic;
36 };
37
38 static char             readerr[] = "ReadGIF: read error: %r";
39 static char             extreaderr[] = "ReadGIF: can't read extension: %r";
40 static char             memerr[] = "ReadGIF: malloc failed: %r";
41
42 static Rawimage**       readarray(Header*, int);
43 static Rawimage*        readone(Header*);
44 static void                     readheader(Header*);
45 static void                     skipextension(Header*);
46 static uchar*           readcmap(Header*, int);
47 static uchar*           decode(Header*, Rawimage*, Entry*);
48 static void             interlace(Header*, Rawimage*);
49
50 static
51 void
52 clear(void **p)
53 {
54         if(*p){
55                 free(*p);
56                 *p = nil;
57         }
58 }
59
60 static
61 void
62 giffreeall(Header *h, int freeimage)
63 {
64         int i;
65
66         if(h->fd){
67                 Bterm(h->fd);
68                 h->fd = nil;
69         }
70         clear(&h->pic);
71         if(h->new){
72                 clear(&h->new->cmap);
73                 clear(&h->new->chans[0]);
74                 clear(&h->new);
75         }
76         clear(&h->globalcmap);
77         if(freeimage && h->array!=nil){
78                 for(i=0; h->array[i]; i++){
79                         clear(&h->array[i]->cmap);
80                         clear(&h->array[i]->chans[0]);
81                 }
82                 clear(&h->array);
83         }
84 }
85
86 static
87 void
88 giferror(Header *h, char *fmt, ...)
89 {
90         va_list arg;
91
92         va_start(arg, fmt);
93         vseprint(h->err, h->err+sizeof h->err, fmt, arg);
94         va_end(arg);
95
96         werrstr("%s", h->err);
97         giffreeall(h, 1);
98         longjmp(h->errlab, 1);
99 }
100
101
102 Rawimage**
103 readgif(int fd, int colorspace, int justone)
104 {
105         Rawimage **a;
106         Biobuf b;
107         Header *h;
108         char buf[ERRMAX];
109
110         buf[0] = '\0';
111         USED(colorspace);
112         if(Binit(&b, fd, OREAD) < 0)
113                 return nil;
114         h = malloc(sizeof(Header));
115         if(h == nil){
116                 Bterm(&b);
117                 return nil;
118         }
119         memset(h, 0, sizeof(Header));
120         h->fd = &b;
121         errstr(buf, sizeof buf);        /* throw it away */
122         if(setjmp(h->errlab))
123                 a = nil;
124         else
125                 a = readarray(h, justone);
126         giffreeall(h, 0);
127         free(h);
128         return a;
129 }
130
131 static
132 void
133 inittbl(Header *h)
134 {
135         int i;
136         Entry *tbl;
137
138         tbl = h->tbl;
139         for(i=0; i<258; i++) {
140                 tbl[i].prefix = -1;
141                 tbl[i].exten = i;
142         }
143 }
144
145 static
146 Rawimage**
147 readarray(Header *h, int justone)
148 {
149         Entry *tbl;
150         Rawimage *new, **array;
151         int c, nimages;
152
153         tbl = h->tbl;
154
155         readheader(h);
156
157         if(h->fields & 0x80)
158                 h->globalcmap = readcmap(h, (h->fields&7)+1);
159         array = malloc(sizeof(Rawimage*));
160         if(array == nil)
161                 giferror(h, memerr);
162         nimages = 0;
163         array[0] = nil;
164         h->array = array;
165                 
166         for(;;){
167                 switch(c = Bgetc(h->fd)){
168                 case Beof:
169                         goto Return;
170
171                 case 0x21:      /* Extension (ignored) */
172                         skipextension(h);
173                         break;
174
175                 case 0x2C:      /* Image Descriptor */
176                         inittbl(h);
177                         new = readone(h);
178                         if(new->fields & 0x80){
179                                 new->cmaplen = 3*(1<<((new->fields&7)+1));
180                                 new->cmap = readcmap(h, (new->fields&7)+1);
181                         }else{
182                                 if(h->globalcmap == nil)
183                                         giferror(h, "ReadGIF: globalcmap missing");
184                                 new->cmaplen = 3*(1<<((h->fields&7)+1));
185                                 new->cmap = malloc(new->cmaplen);
186                                 if(new->cmap == nil)
187                                         giferror(h, memerr);
188                                 memmove(new->cmap, h->globalcmap, new->cmaplen);
189                         }
190                         h->new = new;
191                         new->chans[0] = decode(h, new, tbl);
192                         if(new->fields & 0x40)
193                                 interlace(h, new);
194                         new->gifflags = h->flags;
195                         new->gifdelay = h->delay;
196                         new->giftrindex = h->trindex;
197                         new->gifloopcount = h->loopcount;
198                         array = realloc(h->array, (nimages+2)*sizeof(Rawimage*));
199                         if(array == nil)
200                                 giferror(h, memerr);
201                         array[nimages++] = new;
202                         array[nimages] = nil;
203                         h->array = array;
204                         h->new = nil;
205                         if(justone)
206                                 goto Return;
207                         break;
208
209                 case 0x3B:      /* Trailer */
210                         goto Return;
211
212                 default:
213                         fprint(2, "ReadGIF: unknown block type: 0x%.2x\n", c);
214                         goto Return;
215                 }
216         }
217
218    Return:
219         if(array[0]==nil || array[0]->chans[0] == nil)
220                 giferror(h, "ReadGIF: no picture in file");
221
222         return array;
223 }
224
225 static
226 void
227 readheader(Header *h)
228 {
229         if(Bread(h->fd, h->buf, 13) != 13)
230                 giferror(h, "ReadGIF: can't read header: %r");
231         memmove(h->vers, h->buf, 6);
232         if(strcmp(h->vers, "GIF87a")!=0 &&  strcmp(h->vers, "GIF89a")!=0)
233                 giferror(h, "ReadGIF: can't recognize format %s", h->vers);
234         h->screenw = h->buf[6]+(h->buf[7]<<8);
235         h->screenh = h->buf[8]+(h->buf[9]<<8);
236         h->fields = h->buf[10];
237         h->bgrnd = h->buf[11];
238         h->aspect = h->buf[12];
239         h->flags = 0;
240         h->delay = 0;
241         h->trindex = 0;
242         h->loopcount = -1;
243 }
244
245 static
246 uchar*
247 readcmap(Header *h, int size)
248 {
249         uchar *map;
250
251         if(size > 8)
252                 giferror(h, "ReadGIF: can't handles %d bits per pixel", size);
253         size = 3*(1<<size);
254         if(Bread(h->fd, h->buf, size) != size)
255                 giferror(h, "ReadGIF: short read on color map");
256         map = malloc(size);
257         if(map == nil)
258                 giferror(h, memerr);
259         memmove(map, h->buf, size);
260         return map;
261 }
262
263 static
264 Rawimage*
265 readone(Header *h)
266 {
267         Rawimage *i;
268         int left, top, width, height;
269
270         if(Bread(h->fd, h->buf, 9) != 9)
271                 giferror(h, "ReadGIF: can't read image descriptor: %r");
272         i = malloc(sizeof(Rawimage));
273         if(i == nil)
274                 giferror(h, memerr);
275         left = h->buf[0]+(h->buf[1]<<8);
276         top = h->buf[2]+(h->buf[3]<<8);
277         width = h->buf[4]+(h->buf[5]<<8);
278         height = h->buf[6]+(h->buf[7]<<8);
279         i->fields = h->buf[8];
280         i->r.min.x = left;
281         i->r.min.y = top;
282         i->r.max.x = left+width;
283         i->r.max.y = top+height;
284         i->nchans = 1;
285         i->chandesc = CRGB1;
286         memset(i->chans, 0, sizeof(i->chans));
287         return i;
288 }
289
290
291 static
292 int
293 readdata(Header *h, uchar *data)
294 {
295         int nbytes, n;
296
297         nbytes = Bgetc(h->fd);
298         if(nbytes < 0)
299                 giferror(h, "ReadGIF: can't read data: %r");
300         if(nbytes == 0)
301                 return 0;
302         n = Bread(h->fd, data, nbytes);
303         if(n < 0)
304                 giferror(h, "ReadGIF: can't read data: %r");
305         if(n != nbytes)
306                 fprint(2, "ReadGIF: short data subblock\n");
307         return n;
308 }
309
310 static
311 void
312 graphiccontrol(Header *h)
313 {
314         if(Bread(h->fd, h->buf, 5+1) != 5+1)
315                 giferror(h, readerr);
316         h->flags = h->buf[1];
317         h->delay = h->buf[2]+(h->buf[3]<<8);
318         h->trindex = h->buf[4];
319 }
320
321 static
322 void
323 skipextension(Header *h)
324 {
325         int type, hsize, hasdata, n;
326         uchar data[256];
327
328         hsize = 0;
329         hasdata = 0;
330
331         type = Bgetc(h->fd);
332         switch(type){
333         case Beof:
334                 giferror(h, extreaderr);
335                 break;
336         case 0x01:      /* Plain Text Extension */
337                 hsize = 13;
338                 hasdata = 1;
339                 break;
340         case 0xF9:      /* Graphic Control Extension */
341                 graphiccontrol(h);
342                 return;
343         case 0xFE:      /* Comment Extension */
344                 hasdata = 1;
345                 break;
346         case 0xFF:      /* Application Extension */
347                 hsize = Bgetc(h->fd);
348                 /* standard says this must be 11, but Adobe likes to put out 10-byte ones,
349                  * so we pay attention to the field. */
350                 hasdata = 1;
351                 break;
352         default:
353                 giferror(h, "ReadGIF: unknown extension");
354         }
355         if(hsize>0 && Bread(h->fd, h->buf, hsize) != hsize)
356                 giferror(h, extreaderr);
357         if(!hasdata){
358                 /*
359                  * This code used to check h->buf[hsize-1] != 0
360                  * and giferror if so, but if !hasdata, hsize == 0.
361                  */
362                 return;
363         }
364
365         /* loop counter: Application Extension with NETSCAPE2.0 as string and 1 <loop.count> in data */
366         if(type == 0xFF && hsize==11 && memcmp(h->buf, "NETSCAPE2.0", 11)==0){
367                 n = readdata(h, data);
368                 if(n == 0)
369                         return;
370                 if(n==3 && data[0]==1)
371                         h->loopcount = data[1] | (data[2]<<8);
372         }
373         while(readdata(h, data) != 0)
374                 ;
375 }
376
377 static
378 uchar*
379 decode(Header *h, Rawimage *i, Entry *tbl)
380 {
381         int c, incode, codesize, CTM, EOD, pici, datai, stacki, nbits, sreg, fc, code, piclen;
382         int csize, nentry, maxentry, first, ocode, ndata, nb;
383         uchar clip, *p, *pic;
384         uchar stack[4096], data[256];
385
386         if(Bread(h->fd, h->buf, 1) != 1)
387                 giferror(h, "ReadGIF: can't read data: %r");
388         codesize = h->buf[0];
389         if(codesize>8 || 0>codesize)
390                 giferror(h, "ReadGIF: can't handle codesize %d", codesize);
391
392         CTM =1<<codesize;
393         EOD = CTM+1;
394
395         piclen = (i->r.max.x-i->r.min.x)*(i->r.max.y-i->r.min.y);
396         i->chanlen = piclen;
397         pic = malloc(piclen);
398         if(pic == nil)
399                 giferror(h, memerr);
400         h->pic = pic;
401         pici = 0;
402         ndata = 0;
403         datai = 0;
404         nbits = 0;
405         sreg = 0;
406         fc = 0;
407
408     Loop:
409         for(;;){
410                 csize = codesize+1;
411                 nentry = EOD+1;
412                 maxentry = (1<<csize)-1;
413                 first = 1;
414                 ocode = -1;
415
416                 for(;; ocode = incode) {
417                         while(nbits < csize) {
418                                 if(datai == ndata){
419                                         ndata = readdata(h, data);
420                                         if(ndata == 0)
421                                                 goto Return;
422                                         datai = 0;
423                                 }
424                                 c = data[datai++];
425                                 sreg |= c<<nbits;
426                                 nbits += 8;
427                         }
428                         code = sreg & ((1<<csize) - 1);
429                         sreg >>= csize;
430                         nbits -= csize;
431
432                         if(code == EOD){
433                                 ndata = readdata(h, data);
434                                 if(ndata != 0)
435                                         fprint(2, "ReadGIF: unexpected data past EOD\n");
436                                 goto Return;
437                         }
438
439                         if(code == CTM)
440                                 goto Loop;
441
442                         stacki = (sizeof stack)-1;
443
444                         incode = code;
445
446                         /* special case for KwKwK */
447                         if(code == nentry) {
448                                 stack[stacki--] = fc;
449                                 code = ocode;
450                         }
451
452                         if(code > nentry){
453                                 fprint(2, "ReadGIF: GIF invalid, code out of range, %x > %x\n", code, nentry);
454                                 code = nentry;
455                         }
456                         for(c=code; stacki>0 && c>=0; c=tbl[c].prefix)
457                                 stack[stacki--] = tbl[c].exten;
458
459                         nb = (sizeof stack)-(stacki+1);
460                         if(pici+nb > piclen){
461                                 /* this common error is harmless
462                                  * we have to keep reading to keep the blocks in sync */
463                                 ;
464                         }else{
465                                 memmove(pic+pici, stack+stacki+1, sizeof stack - (stacki+1));
466                                 pici += nb;
467                         }
468
469                         fc = stack[stacki+1];
470
471                         if(first){
472                                 first = 0;
473                                 continue;
474                         }
475                         #define early 0 /* peculiar tiff feature here for reference */
476                         if(nentry == maxentry-early) {
477                                 if(csize >= 12)
478                                         continue;
479                                 csize++;
480                                 maxentry = (1<<csize);
481                                 if(csize < 12)
482                                         maxentry--;
483                         }
484                         tbl[nentry].prefix = ocode;
485                         tbl[nentry].exten = fc;
486                         nentry++;
487                 }
488         }
489
490 Return:
491         if(i->cmap!=nil && i->cmaplen!=3*256){
492                 clip = (i->cmaplen/3)-1;
493                 for(p = pic; p < pic+piclen; p++)
494                         if(*p > clip)
495                                 *p = clip;
496         }
497         h->pic = nil;
498         return pic;
499 }
500
501 static
502 void
503 interlace(Header *h, Rawimage *image)
504 {
505         uchar *pic;
506         Rectangle r;
507         int dx, yy, y;
508         uchar *ipic;
509
510         pic = image->chans[0];
511         r = image->r;
512         dx = r.max.x-r.min.x;
513         ipic = malloc(dx*(r.max.y-r.min.y));
514         if(ipic == nil)
515                 giferror(h, nil);
516
517         /* Group 1: every 8th row, starting with row 0 */
518         yy = 0;
519         for(y=r.min.y; y<r.max.y; y+=8){
520                 memmove(&ipic[(y-r.min.y)*dx], &pic[yy*dx], dx);
521                 yy++;
522         }
523
524         /* Group 2: every 8th row, starting with row 4 */
525         for(y=r.min.y+4; y<r.max.y; y+=8){
526                 memmove(&ipic[(y-r.min.y)*dx], &pic[yy*dx], dx);
527                 yy++;
528         }
529
530         /* Group 3: every 4th row, starting with row 2 */
531         for(y=r.min.y+2; y<r.max.y; y+=4){
532                 memmove(&ipic[(y-r.min.y)*dx], &pic[yy*dx], dx);
533                 yy++;
534         }
535
536         /* Group 4: every 2nd row, starting with row 1 */
537         for(y=r.min.y+1; y<r.max.y; y+=2){
538                 memmove(&ipic[(y-r.min.y)*dx], &pic[yy*dx], dx);
539                 yy++;
540         }
541
542         free(image->chans[0]);
543         image->chans[0] = ipic;
544 }