]> www.fi.muni.cz Git - evince.git/blob - pdf/xpdf/Stream.cc
08b806a7caec958737dffc33ab8157954394124b
[evince.git] / pdf / xpdf / Stream.cc
1 //========================================================================
2 //
3 // Stream.cc
4 //
5 // Copyright 1996 Derek B. Noonburg
6 //
7 //========================================================================
8
9 #ifdef __GNUC__
10 #pragma implementation
11 #endif
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <stddef.h>
16 #ifndef WIN32
17 #include <unistd.h>
18 #endif
19 #include <string.h>
20 #include <ctype.h>
21 #include "gmem.h"
22 #include "config.h"
23 #include "Error.h"
24 #include "Object.h"
25 #include "Stream.h"
26 #include "Stream-CCITT.h"
27
28 #ifdef _MSC_VER
29 #define popen _popen
30 #define pclose _pclose
31 #endif
32
33 #ifdef __DJGPP__
34 static GBool setDJSYSFLAGS = gFalse;
35 #endif
36
37 #ifdef VMS
38 #if (__VMS_VER < 70000000)
39 extern "C" int unlink(char *filename);
40 #endif
41 #ifdef __GNUC__
42 #define SEEK_SET 0
43 #define SEEK_CUR 1
44 #define SEEK_END 2
45 #endif
46 #endif
47
48 //------------------------------------------------------------------------
49
50 #define headerSearchSize 1024   // read this many bytes at beginning of
51                                 //   file to look for '%PDF'
52
53 //------------------------------------------------------------------------
54 // Stream (base class)
55 //------------------------------------------------------------------------
56
57 Stream::Stream() {
58   ref = 1;
59 }
60
61 Stream::~Stream() {
62 }
63
64 int Stream::getRawChar() {
65   error(-1, "Internal: called getRawChar() on non-predictor stream");
66   return EOF;
67 }
68
69 char *Stream::getLine(char *buf, int size) {
70   int i;
71   int c;
72
73   if (lookChar() == EOF)
74     return NULL;
75   for (i = 0; i < size - 1; ++i) {
76     c = getChar();
77     if (c == EOF || c == '\n')
78       break;
79     if (c == '\r') {
80       if ((c = lookChar()) == '\n')
81         getChar();
82       break;
83     }
84     buf[i] = c;
85   }
86   buf[i] = '\0';
87   return buf;
88 }
89
90 void Stream::setPos(int pos) {
91   error(-1, "Internal: called setPos() on non-FileStream");
92 }
93
94 GString *Stream::getPSFilter(char *indent) {
95   return new GString();
96 }
97
98 Stream *Stream::addFilters(Object *dict) {
99   Object obj, obj2;
100   Object params, params2;
101   Stream *str;
102   int i;
103
104   str = this;
105   dict->dictLookup("Filter", &obj);
106   if (obj.isNull()) {
107     obj.free();
108     dict->dictLookup("F", &obj);
109   }
110   dict->dictLookup("DecodeParms", &params);
111   if (params.isNull()) {
112     params.free();
113     dict->dictLookup("DP", &params);
114   }
115   if (obj.isName()) {
116     str = makeFilter(obj.getName(), str, &params);
117   } else if (obj.isArray()) {
118     for (i = 0; i < obj.arrayGetLength(); ++i) {
119       obj.arrayGet(i, &obj2);
120       if (params.isArray())
121         params.arrayGet(i, &params2);
122       else
123         params2.initNull();
124       if (obj2.isName()) {
125         str = makeFilter(obj2.getName(), str, &params2);
126       } else {
127         error(getPos(), "Bad filter name");
128         str = new EOFStream(str);
129       }
130       obj2.free();
131       params2.free();
132     }
133   } else if (!obj.isNull()) {
134     error(getPos(), "Bad 'Filter' attribute in stream");
135   }
136   obj.free();
137   params.free();
138
139   return str;
140 }
141
142 Stream *Stream::makeFilter(char *name, Stream *str, Object *params) {
143   int pred;                     // parameters
144   int colors;
145   int bits;
146   int early;
147   int encoding;
148   GBool endOfLine, byteAlign, endOfBlock, black;
149   int columns, rows;
150   Object obj;
151
152   if (!strcmp(name, "ASCIIHexDecode") || !strcmp(name, "AHx")) {
153     str = new ASCIIHexStream(str);
154   } else if (!strcmp(name, "ASCII85Decode") || !strcmp(name, "A85")) {
155     str = new ASCII85Stream(str);
156   } else if (!strcmp(name, "LZWDecode") || !strcmp(name, "LZW")) {
157     pred = 1;
158     columns = 1;
159     colors = 1;
160     bits = 8;
161     early = 1;
162     if (params->isDict()) {
163       params->dictLookup("Predictor", &obj);
164       if (obj.isInt())
165         pred = obj.getInt();
166       obj.free();
167       params->dictLookup("Columns", &obj);
168       if (obj.isInt())
169         columns = obj.getInt();
170       obj.free();
171       params->dictLookup("Colors", &obj);
172       if (obj.isInt())
173         colors = obj.getInt();
174       obj.free();
175       params->dictLookup("BitsPerComponent", &obj);
176       if (obj.isInt())
177         bits = obj.getInt();
178       obj.free();
179       params->dictLookup("EarlyChange", &obj);
180       if (obj.isInt())
181         early = obj.getInt();
182       obj.free();
183     }
184     str = new LZWStream(str, pred, columns, colors, bits, early);
185   } else if (!strcmp(name, "RunLengthDecode") || !strcmp(name, "RL")) {
186     str = new RunLengthStream(str);
187   } else if (!strcmp(name, "CCITTFaxDecode") || !strcmp(name, "CCF")) {
188     encoding = 0;
189     endOfLine = gFalse;
190     byteAlign = gFalse;
191     columns = 1728;
192     rows = 0;
193     endOfBlock = gTrue;
194     black = gFalse;
195     if (params->isDict()) {
196       params->dictLookup("K", &obj);
197       if (obj.isInt()) {
198         encoding = obj.getInt();
199       }
200       obj.free();
201       params->dictLookup("EndOfLine", &obj);
202       if (obj.isBool()) {
203         endOfLine = obj.getBool();
204       }
205       obj.free();
206       params->dictLookup("EncodedByteAlign", &obj);
207       if (obj.isBool()) {
208         byteAlign = obj.getBool();
209       }
210       obj.free();
211       params->dictLookup("Columns", &obj);
212       if (obj.isInt()) {
213         columns = obj.getInt();
214       }
215       obj.free();
216       params->dictLookup("Rows", &obj);
217       if (obj.isInt()) {
218         rows = obj.getInt();
219       }
220       obj.free();
221       params->dictLookup("EndOfBlock", &obj);
222       if (obj.isBool()) {
223         endOfBlock = obj.getBool();
224       }
225       obj.free();
226       params->dictLookup("BlackIs1", &obj);
227       if (obj.isBool()) {
228         black = obj.getBool();
229       }
230       obj.free();
231     }
232     str = new CCITTFaxStream(str, encoding, endOfLine, byteAlign,
233                              columns, rows, endOfBlock, black);
234   } else if (!strcmp(name, "DCTDecode") || !strcmp(name, "DCT")) {
235     str = new DCTStream(str);
236   } else if (!strcmp(name, "FlateDecode") || !strcmp(name, "Fl")) {
237     pred = 1;
238     columns = 1;
239     colors = 1;
240     bits = 8;
241     if (params->isDict()) {
242       params->dictLookup("Predictor", &obj);
243       if (obj.isInt())
244         pred = obj.getInt();
245       obj.free();
246       params->dictLookup("Columns", &obj);
247       if (obj.isInt())
248         columns = obj.getInt();
249       obj.free();
250       params->dictLookup("Colors", &obj);
251       if (obj.isInt())
252         colors = obj.getInt();
253       obj.free();
254       params->dictLookup("BitsPerComponent", &obj);
255       if (obj.isInt())
256         bits = obj.getInt();
257       obj.free();
258     }
259     str = new FlateStream(str, pred, columns, colors, bits);
260   } else {
261     error(getPos(), "Unknown filter '%s'", name);
262     str = new EOFStream(str);
263   }
264   return str;
265 }
266
267 //------------------------------------------------------------------------
268 // ImageStream
269 //------------------------------------------------------------------------
270
271 ImageStream::ImageStream(Stream *str, int width, int nComps, int nBits) {
272   int imgLineSize;
273
274   this->str = str;
275   this->width = width;
276   this->nComps = nComps;
277   this->nBits = nBits;
278
279   nVals = width * nComps;
280   if (nBits == 1) {
281     imgLineSize = (nVals + 7) & ~7;
282   } else {
283     imgLineSize = nVals;
284   }
285   imgLine = (Guchar *)gmalloc(imgLineSize * sizeof(Guchar));
286   imgIdx = nVals;
287 }
288
289 ImageStream::~ImageStream() {
290   gfree(imgLine);
291 }
292
293 void ImageStream::reset() {
294   str->reset();
295 }
296
297 GBool ImageStream::getPixel(Guchar *pix) {
298   Gulong buf, bitMask;
299   int bits;
300   int c;
301   int i;
302
303   if (imgIdx >= nVals) {
304
305     // read one line of image pixels
306     if (nBits == 1) {
307       for (i = 0; i < nVals; i += 8) {
308         c = str->getChar();
309         imgLine[i+0] = (Guchar)((c >> 7) & 1);
310         imgLine[i+1] = (Guchar)((c >> 6) & 1);
311         imgLine[i+2] = (Guchar)((c >> 5) & 1);
312         imgLine[i+3] = (Guchar)((c >> 4) & 1);
313         imgLine[i+4] = (Guchar)((c >> 3) & 1);
314         imgLine[i+5] = (Guchar)((c >> 2) & 1);
315         imgLine[i+6] = (Guchar)((c >> 1) & 1);
316         imgLine[i+7] = (Guchar)(c & 1);
317       }
318     } else if (nBits == 8) {
319       for (i = 0; i < nVals; ++i) {
320         imgLine[i] = str->getChar();
321       }
322     } else {
323       bitMask = (1 << nBits) - 1;
324       buf = 0;
325       bits = 0;
326       for (i = 0; i < nVals; ++i) {
327         if (bits < nBits) {
328           buf = (buf << 8) | (str->getChar() & 0xff);
329           bits += 8;
330         }
331         imgLine[i] = (Guchar)((buf >> (bits - nBits)) & bitMask);
332         bits -= nBits;
333       }
334     }
335
336     // reset to start of line
337     imgIdx = 0;
338   }
339
340   for (i = 0; i < nComps; ++i)
341     pix[i] = imgLine[imgIdx++];
342   return gTrue;
343 }
344
345 void ImageStream::skipLine() {
346   int n, i;
347
348   n = (nVals * nBits + 7) >> 3;
349   for (i = 0; i < n; ++i) {
350     str->getChar();
351   }
352 }
353
354 //------------------------------------------------------------------------
355 // StreamPredictor
356 //------------------------------------------------------------------------
357
358 StreamPredictor::StreamPredictor(Stream *str, int predictor,
359                                  int width, int nComps, int nBits) {
360   this->str = str;
361   this->predictor = predictor;
362   this->width = width;
363   this->nComps = nComps;
364   this->nBits = nBits;
365
366   nVals = width * nComps;
367   pixBytes = (nComps * nBits + 7) >> 3;
368   rowBytes = ((nVals * nBits + 7) >> 3) + pixBytes;
369   predLine = (Guchar *)gmalloc(rowBytes);
370   memset(predLine, 0, rowBytes);
371   predIdx = rowBytes;
372 }
373
374 StreamPredictor::~StreamPredictor() {
375   gfree(predLine);
376 }
377
378 int StreamPredictor::lookChar() {
379   if (predIdx >= rowBytes) {
380     if (!getNextLine()) {
381       return EOF;
382     }
383   }
384   return predLine[predIdx];
385 }
386
387 int StreamPredictor::getChar() {
388   if (predIdx >= rowBytes) {
389     if (!getNextLine()) {
390       return EOF;
391     }
392   }
393   return predLine[predIdx++];
394 }
395
396 GBool StreamPredictor::getNextLine() {
397   int curPred;
398   Guchar upLeftBuf[4];
399   int left, up, upLeft, p, pa, pb, pc;
400   int c;
401   Gulong inBuf, outBuf, bitMask;
402   int inBits, outBits;
403   int i, j, k;
404
405   // get PNG optimum predictor number
406   if (predictor == 15) {
407     if ((curPred = str->getRawChar()) == EOF) {
408       return gFalse;
409     }
410     curPred += 10;
411   } else {
412     curPred = predictor;
413   }
414
415   // read the raw line, apply PNG (byte) predictor
416   upLeftBuf[0] = upLeftBuf[1] = upLeftBuf[2] = upLeftBuf[3] = 0;
417   for (i = pixBytes; i < rowBytes; ++i) {
418     upLeftBuf[3] = upLeftBuf[2];
419     upLeftBuf[2] = upLeftBuf[1];
420     upLeftBuf[1] = upLeftBuf[0];
421     upLeftBuf[0] = predLine[i];
422     if ((c = str->getRawChar()) == EOF) {
423       break;
424     }
425     switch (curPred) {
426     case 11:                    // PNG sub
427       predLine[i] = predLine[i - pixBytes] + (Guchar)c;
428       break;
429     case 12:                    // PNG up
430       predLine[i] = predLine[i] + (Guchar)c;
431       break;
432     case 13:                    // PNG average
433       predLine[i] = ((predLine[i - pixBytes] + predLine[i]) >> 1) +
434                     (Guchar)c;
435       break;
436     case 14:                    // PNG Paeth
437       left = predLine[i - pixBytes];
438       up = predLine[i];
439       upLeft = upLeftBuf[pixBytes];
440       p = left + up - upLeft;
441       if ((pa = p - left) < 0)
442         pa = -pa;
443       if ((pb = p - up) < 0)
444         pb = -pb;
445       if ((pc = p - upLeft) < 0)
446         pc = -pc;
447       if (pa <= pb && pa <= pc)
448         predLine[i] = pa + (Guchar)c;
449       else if (pb <= pc)
450         predLine[i] = pb + (Guchar)c;
451       else
452         predLine[i] = pc + (Guchar)c;
453       break;
454     case 10:                    // PNG none
455     default:                    // no predictor or TIFF predictor
456       predLine[i] = (Guchar)c;
457       break;
458     }
459   }
460
461   // apply TIFF (component) predictor
462   //~ this is completely untested
463   if (predictor == 2) {
464     if (nBits == 1) {
465       inBuf = predLine[pixBytes - 1];
466       for (i = pixBytes; i < rowBytes; i += 8) {
467         // 1-bit add is just xor
468         inBuf = (inBuf << 8) | predLine[i];
469         predLine[i] ^= inBuf >> nComps;
470       }
471     } else if (nBits == 8) {
472       for (i = pixBytes; i < rowBytes; ++i) {
473         predLine[i] += predLine[i - nComps];
474       }
475     } else {
476       upLeftBuf[0] = upLeftBuf[1] = upLeftBuf[2] = upLeftBuf[3] = 0;
477       bitMask = (1 << nBits) - 1;
478       inBuf = outBuf = 0;
479       inBits = outBits = 0;
480       j = k = pixBytes;
481       for (i = 0; i < nVals; ++i) {
482         if (inBits < nBits) {
483           inBuf = (inBuf << 8) | (predLine[j++] & 0xff);
484           inBits += 8;
485         }
486         upLeftBuf[3] = upLeftBuf[2];
487         upLeftBuf[2] = upLeftBuf[1];
488         upLeftBuf[1] = upLeftBuf[0];
489         upLeftBuf[0] = (upLeftBuf[nComps] +
490                         (inBuf >> (inBits - nBits))) & bitMask;
491         outBuf = (outBuf << nBits) | upLeftBuf[0];
492         inBits -= nBits;
493         outBits += nBits;
494         if (outBits > 8) {
495           predLine[k++] = (Guchar)(outBuf >> (outBits - 8));
496         }
497       }
498       if (outBits > 0) {
499         predLine[k++] = (Guchar)(outBuf << (8 - outBits));
500       }
501     }
502   }
503
504   // reset to start of line
505   predIdx = pixBytes;
506
507   return gTrue;
508 }
509
510 //------------------------------------------------------------------------
511 // FileStream
512 //------------------------------------------------------------------------
513
514 GBool FileStream::checkHeader() {
515   char hdrBuf[headerSearchSize+1];
516   char *p;
517   double version;
518   int i;
519
520   for (i = 0; i < headerSearchSize; ++i)
521     hdrBuf[i] = getChar();
522   hdrBuf[headerSearchSize] = '\0';
523   for (i = 0; i < headerSearchSize - 5; ++i) {
524     if (!strncmp(&hdrBuf[i], "%PDF-", 5))
525       break;
526   }
527   if (i >= headerSearchSize - 5) {
528     error(-1, "May not be a PDF file (continuing anyway)");
529     return gFalse;
530   }
531   start += i;
532   p = strtok(&hdrBuf[i+5], " \t\n\r");
533   version = atof(p);
534   if (!(hdrBuf[i+5] >= '0' && hdrBuf[i+5] <= '9') ||
535       version > pdfVersionNum + 0.0001) {
536     error(getPos(), "PDF version %s -- xpdf supports version %s"
537           " (continuing anyway)", p, pdfVersion);
538     return gFalse;
539   }
540   return gTrue;
541 }
542
543 FILE *fileOpen (GString *fileName1) {
544   GString *fileName2;
545   // try to open file
546   fileName2 = NULL;
547   FILE *file = NULL;
548
549 #ifdef VMS
550   if (!(file = fopen(fileName->getCString(), "rb", "ctx=stm"))) {
551     error(-1, "Couldn't open file '%s'", fileName->getCString());
552     return NULL;
553   }
554 #else
555   if (!(file = fopen(fileName1->getCString(), "rb"))) {
556     fileName2 = fileName1->copy();
557     fileName2->lowerCase();
558     if (!(file = fopen(fileName2->getCString(), "rb"))) {
559       fileName2->upperCase();
560       if (!(file = fopen(fileName2->getCString(), "rb"))) {
561         error(-1, "Couldn't open file '%s'", fileName1->getCString());
562         delete fileName2;
563         return NULL;
564       }
565     }
566     delete fileName2;
567   }
568 #endif
569   return file;
570 }
571
572 FileStream::FileStream() {
573 }
574
575 FileStream::FileStream(FILE *f1) {
576   f = f1;
577   start = 0;
578   length = -1;
579   bufPtr = bufEnd = buf;
580   bufPos = start;
581   savePos = -1;
582   dict.initNull();
583   if (f)
584     checkHeader();
585 }
586
587 Stream *FileStream::subStream (int start1, int length1, Object *dict1) {
588   FileStream *scp = new FileStream ();
589   scp->f = f;
590   scp->start = start1;
591   scp->length = length1;
592   scp->bufPtr = bufEnd = buf;
593   scp->bufPos = start;
594   scp->savePos = -1;
595   scp->dict = *dict1;
596   return scp;
597 }
598
599 FileStream::~FileStream() {
600   if (savePos >= 0)
601     fseek(f, savePos, SEEK_SET);
602   dict.free();
603 }
604
605 void FileStream::reset() {
606   savePos = (int)ftell(f);
607   fseek(f, start, SEEK_SET);
608   bufPtr = bufEnd = buf;
609   bufPos = start;
610 }
611
612 GBool FileStream::fillBuf() {
613   int n;
614
615   bufPos += bufEnd - buf;
616   bufPtr = bufEnd = buf;
617   if (length >= 0 && bufPos >= start + length)
618     return gFalse;
619   if (length >= 0 && bufPos + 256 > start + length)
620     n = start + length - bufPos;
621   else
622     n = 256;
623   n = fread(buf, 1, n, f);
624   bufEnd = buf + n;
625   if (bufPtr >= bufEnd)
626     return gFalse;
627   return gTrue;
628 }
629
630 void FileStream::setPos(int pos1) {
631   long size;
632
633   if (pos1 >= 0) {
634     fseek(f, pos1, SEEK_SET);
635     bufPos = pos1;
636   } else {
637     fseek(f, 0, SEEK_END);
638     size = ftell(f);
639     if (pos1 < -size)
640       pos1 = (int)(-size);
641     fseek(f, pos1, SEEK_END);
642     bufPos = (int)ftell(f);
643   }
644   bufPtr = bufEnd = buf;
645 }
646
647 //------------------------------------------------------------------------
648 // SubStream
649 //------------------------------------------------------------------------
650
651 SubStream::SubStream(Stream *str1, Object *dict1) {
652   str = str1;
653   dict = *dict1;
654 }
655
656 SubStream::~SubStream() {
657   dict.free();
658 }
659
660 //------------------------------------------------------------------------
661 // ASCIIHexStream
662 //------------------------------------------------------------------------
663
664 ASCIIHexStream::ASCIIHexStream(Stream *str1) {
665   str = str1;
666   buf = EOF;
667   eof = gFalse;
668 }
669
670 ASCIIHexStream::~ASCIIHexStream() {
671   delete str;
672 }
673
674 void ASCIIHexStream::reset() {
675   str->reset();
676   buf = EOF;
677   eof = gFalse;
678 }
679
680 int ASCIIHexStream::lookChar() {
681   int c1, c2, x;
682
683   if (buf != EOF)
684     return buf;
685   if (eof) {
686     buf = EOF;
687     return EOF;
688   }
689   do {
690     c1 = str->getChar();
691   } while (isspace(c1));
692   if (c1 == '>') {
693     eof = gTrue;
694     buf = EOF;
695     return buf;
696   }
697   do {
698     c2 = str->getChar();
699   } while (isspace(c2));
700   if (c2 == '>') {
701     eof = gTrue;
702     c2 = '0';
703   }
704   if (c1 >= '0' && c1 <= '9') {
705     x = (c1 - '0') << 4;
706   } else if (c1 >= 'A' && c1 <= 'F') {
707     x = (c1 - 'A' + 10) << 4;
708   } else if (c1 >= 'a' && c1 <= 'f') {
709     x = (c1 - 'a' + 10) << 4;
710   } else if (c1 == EOF) {
711     eof = gTrue;
712     x = 0;
713   } else {
714     error(getPos(), "Illegal character <%02x> in ASCIIHex stream", c1);
715     x = 0;
716   }
717   if (c2 >= '0' && c2 <= '9') {
718     x += c2 - '0';
719   } else if (c2 >= 'A' && c2 <= 'F') {
720     x += c2 - 'A' + 10;
721   } else if (c2 >= 'a' && c2 <= 'f') {
722     x += c2 - 'a' + 10;
723   } else if (c2 == EOF) {
724     eof = gTrue;
725     x = 0;
726   } else {
727     error(getPos(), "Illegal character <%02x> in ASCIIHex stream", c2);
728   }
729   buf = x & 0xff;
730   return buf;
731 }
732
733 GString *ASCIIHexStream::getPSFilter(char *indent) {
734   GString *s;
735
736   s = str->getPSFilter(indent);
737   s->append(indent)->append("/ASCIIHexDecode filter\n");
738   return s;
739 }
740
741 GBool ASCIIHexStream::isBinary(GBool last) {
742   return str->isBinary(gFalse);
743 }
744
745 //------------------------------------------------------------------------
746 // ASCII85Stream
747 //------------------------------------------------------------------------
748
749 ASCII85Stream::ASCII85Stream(Stream *str1) {
750   str = str1;
751   index = n = 0;
752   eof = gFalse;
753 }
754
755 ASCII85Stream::~ASCII85Stream() {
756   delete str;
757 }
758
759 void ASCII85Stream::reset() {
760   str->reset();
761   index = n = 0;
762   eof = gFalse;
763 }
764
765 int ASCII85Stream::lookChar() {
766   int k;
767   Gulong t;
768
769   if (index >= n) {
770     if (eof)
771       return EOF;
772     index = 0;
773     do {
774       c[0] = str->getChar();
775     } while (c[0] == '\n' || c[0] == '\r');
776     if (c[0] == '~' || c[0] == EOF) {
777       eof = gTrue;
778       n = 0;
779       return EOF;
780     } else if (c[0] == 'z') {
781       b[0] = b[1] = b[2] = b[3] = 0;
782       n = 4;
783     } else {
784       for (k = 1; k < 5; ++k) {
785         do {
786           c[k] = str->getChar();
787         } while (c[k] == '\n' || c[k] == '\r');
788         if (c[k] == '~' || c[k] == EOF)
789           break;
790       }
791       n = k - 1;
792       if (k < 5 && (c[k] == '~' || c[k] == EOF)) {
793         for (++k; k < 5; ++k)
794           c[k] = 0x21 + 84;
795         eof = gTrue;
796       }
797       t = 0;
798       for (k = 0; k < 5; ++k)
799         t = t * 85 + (c[k] - 0x21);
800       for (k = 3; k >= 0; --k) {
801         b[k] = (int)(t & 0xff);
802         t >>= 8;
803       }
804     }
805   }
806   return b[index];
807 }
808
809 GString *ASCII85Stream::getPSFilter(char *indent) {
810   GString *s;
811
812   s = str->getPSFilter(indent);
813   s->append(indent)->append("/ASCII85Decode filter\n");
814   return s;
815 }
816
817 GBool ASCII85Stream::isBinary(GBool last) {
818   return str->isBinary(gFalse);
819 }
820
821 //------------------------------------------------------------------------
822 // LZWStream
823 //------------------------------------------------------------------------
824
825 LZWStream::LZWStream(Stream *str1, int predictor1, int columns1, int colors1,
826                      int bits1, int early1) {
827   str = str1;
828   if (predictor1 != 1) {
829     pred = new StreamPredictor(this, predictor1, columns1, colors1, bits1);
830   } else {
831     pred = NULL;
832   }
833   early = early1;
834   zPipe = NULL;
835   bufPtr = bufEnd = buf;
836 }
837
838 LZWStream::~LZWStream() {
839   if (zPipe) {
840 #ifdef HAVE_POPEN
841     pclose(zPipe);
842 #else
843     fclose(zPipe);
844 #endif
845     zPipe = NULL;
846     unlink(zName);
847   }
848   if (pred) {
849     delete pred;
850   }
851   delete str;
852 }
853
854 int LZWStream::getChar() {
855   if (pred) {
856     return pred->getChar();
857   }
858   return (bufPtr >= bufEnd && !fillBuf()) ? EOF : (*bufPtr++ & 0xff);
859 }
860
861 int LZWStream::lookChar() {
862   if (pred) {
863     return pred->lookChar();
864   }
865   return (bufPtr >= bufEnd && !fillBuf()) ? EOF : (*bufPtr & 0xff);
866 }
867
868 int LZWStream::getRawChar() {
869   return (bufPtr >= bufEnd && !fillBuf()) ? EOF : (*bufPtr++ & 0xff);
870 }
871
872 void LZWStream::reset() {
873   FILE *f;
874
875   str->reset();
876   bufPtr = bufEnd = buf;
877   if (zPipe) {
878 #ifdef HAVE_POPEN
879     pclose(zPipe);
880 #else
881     fclose(zPipe);
882 #endif
883     zPipe = NULL;
884     unlink(zName);
885   }
886 #if __DJGPP__
887   if (!setDJSYSFLAGS) {
888     setenv("DJSYSFLAGS", "0x0002", 0);
889     setDJSYSFLAGS = gTrue;
890   }
891 #endif
892   strcpy(zCmd, uncompressCmd);
893   strcat(zCmd, " ");
894   zName = zCmd + strlen(zCmd);
895   tmpnam(zName);
896 #ifdef _MSC_VER
897   zName[strlen(zName) - 2] = '\0';
898 #endif
899   strcat(zName, ".Z");
900   if (!(f = fopen(zName, "wb"))) {
901     error(getPos(), "Couldn't open temporary file '%s'", zName);
902     return;
903   }
904   dumpFile(f);
905   fclose(f);
906 #ifdef HAVE_POPEN
907   if (!(zPipe = popen(zCmd, "r"))) {
908     error(getPos(), "Couldn't popen '%s'", zCmd);
909     unlink(zName);
910     return;
911   }
912 #else
913 #ifdef VMS
914   if (!system(zCmd)) {
915 #else
916   if (system(zCmd)) {
917 #endif
918     error(getPos(), "Couldn't execute '%s'", zCmd);
919     unlink(zName);
920     return;
921   }
922   zName[strlen(zName) - 2] = '\0';
923   if (!(zPipe = fopen(zName, "rb"))) {
924     error(getPos(), "Couldn't open uncompress file '%s'", zName);
925     unlink(zName);
926     return;
927   }
928 #endif
929 }
930
931 void LZWStream::dumpFile(FILE *f) {
932   int outCodeBits;              // size of output code
933   int outBits;                  // max output code
934   int outBuf[8];                // output buffer
935   int outData;                  // temporary output buffer
936   int inCode, outCode;          // input and output codes
937   int nextCode;                 // next code index
938   GBool eof;                    // set when EOF is reached
939   GBool clear;                  // set if table needs to be cleared
940   GBool first;                  // indicates first code word after clear
941   int i, j;
942
943   // magic number
944   fputc(0x1f, f);
945   fputc(0x9d, f);
946
947   // max code length, block mode flag
948   fputc(0x8c, f);
949
950   // init input side
951   inCodeBits = 9;
952   inputBuf = 0;
953   inputBits = 0;
954   eof = gFalse;
955
956   // init output side
957   outCodeBits = 9;
958
959   // clear table
960   first = gTrue;
961   nextCode = 258;
962
963   clear = gFalse;
964   do {
965     for (i = 0; i < 8; ++i) {
966       // check for table overflow
967       if (nextCode + early > 0x1001) {
968         inCode = 256;
969
970       // read input code
971       } else {
972         do {
973           inCode = getCode();
974           if (inCode == EOF) {
975             eof = gTrue;
976             inCode = 0;
977           }
978         } while (first && inCode == 256);
979       }
980
981       // compute output code
982       if (inCode < 256) {
983         outCode = inCode;
984       } else if (inCode == 256) {
985         outCode = 256;
986         clear = gTrue;
987       } else if (inCode == 257) {
988         outCode = 0;
989         eof = gTrue;
990       } else {
991         outCode = inCode - 1;
992       }
993       outBuf[i] = outCode;
994
995       // next code index
996       if (first)
997         first = gFalse;
998       else
999         ++nextCode;
1000
1001       // check input code size
1002       if (nextCode + early == 0x200)
1003         inCodeBits = 10;
1004       else if (nextCode + early == 0x400) {
1005         inCodeBits = 11;
1006       } else if (nextCode + early == 0x800) {
1007         inCodeBits = 12;
1008       }
1009
1010       // check for eof/clear
1011       if (eof)
1012         break;
1013       if (clear) {
1014         i = 8;
1015         break;
1016       }
1017     }
1018
1019     // write output block
1020     outData = 0;
1021     outBits = 0;
1022     j = 0;
1023     while (j < i || outBits > 0) {
1024       if (outBits < 8 && j < i) {
1025         outData = outData | (outBuf[j++] << outBits);
1026         outBits += outCodeBits;
1027       }
1028       fputc(outData & 0xff, f);
1029       outData >>= 8;
1030       outBits -= 8;
1031     }
1032
1033     // check output code size
1034     if (nextCode - 1 == 512 ||
1035         nextCode - 1 == 1024 ||
1036         nextCode - 1 == 2048 ||
1037         nextCode - 1 == 4096) {
1038       outCodeBits = inCodeBits;
1039     }
1040
1041     // clear table if necessary
1042     if (clear) {
1043       inCodeBits = 9;
1044       outCodeBits = 9;
1045       first = gTrue;
1046       nextCode = 258;
1047       clear = gFalse;
1048     }
1049   } while (!eof);
1050 }
1051
1052 int LZWStream::getCode() {
1053   int c;
1054   int code;
1055
1056   while (inputBits < inCodeBits) {
1057     if ((c = str->getChar()) == EOF)
1058       return EOF;
1059     inputBuf = (inputBuf << 8) | (c & 0xff);
1060     inputBits += 8;
1061   }
1062   code = (inputBuf >> (inputBits - inCodeBits)) & ((1 << inCodeBits) - 1);
1063   inputBits -= inCodeBits;
1064   return code;
1065 }
1066
1067 GBool LZWStream::fillBuf() {
1068   int n;
1069
1070   if (!zPipe)
1071     return gFalse;
1072   if ((n = fread(buf, 1, 256, zPipe)) < 256) {
1073 #ifdef HAVE_POPEN
1074     pclose(zPipe);
1075 #else
1076     fclose(zPipe);
1077 #endif
1078     zPipe = NULL;
1079     unlink(zName);
1080   }
1081   bufPtr = buf;
1082   bufEnd = buf + n;
1083   return n > 0;
1084 }
1085
1086 GString *LZWStream::getPSFilter(char *indent) {
1087   GString *s;
1088
1089   if (pred) {
1090     return NULL;
1091   }
1092   s = str->getPSFilter(indent);
1093   s->append(indent)->append("/LZWDecode filter\n");
1094   return s;
1095 }
1096
1097 GBool LZWStream::isBinary(GBool last) {
1098   return str->isBinary(gTrue);
1099 }
1100
1101 //------------------------------------------------------------------------
1102 // RunLengthStream
1103 //------------------------------------------------------------------------
1104
1105 RunLengthStream::RunLengthStream(Stream *str1) {
1106   str = str1;
1107   bufPtr = bufEnd = buf;
1108   eof = gFalse;
1109 }
1110
1111 RunLengthStream::~RunLengthStream() {
1112   delete str;
1113 }
1114
1115 void RunLengthStream::reset() {
1116   str->reset();
1117   bufPtr = bufEnd = buf;
1118   eof = gFalse;
1119 }
1120
1121 GString *RunLengthStream::getPSFilter(char *indent) {
1122   GString *s;
1123
1124   s = str->getPSFilter(indent);
1125   s->append(indent)->append("/RunLengthDecode filter\n");
1126   return s;
1127 }
1128
1129 GBool RunLengthStream::isBinary(GBool last) {
1130   return str->isBinary(gTrue);
1131 }
1132
1133 GBool RunLengthStream::fillBuf() {
1134   int c;
1135   int n, i;
1136
1137   if (eof)
1138     return gFalse;
1139   c = str->getChar();
1140   if (c == 0x80 || c == EOF) {
1141     eof = gTrue;
1142     return gFalse;
1143   }
1144   if (c < 0x80) {
1145     n = c + 1;
1146     for (i = 0; i < n; ++i)
1147       buf[i] = (char)str->getChar();
1148   } else {
1149     n = 0x101 - c;
1150     c = str->getChar();
1151     for (i = 0; i < n; ++i)
1152       buf[i] = (char)c;
1153   }
1154   bufPtr = buf;
1155   bufEnd = buf + n;
1156   return gTrue;
1157 }
1158
1159 //------------------------------------------------------------------------
1160 // CCITTFaxStream
1161 //------------------------------------------------------------------------
1162
1163 CCITTFaxStream::CCITTFaxStream(Stream *str, int encoding, GBool endOfLine,
1164                                GBool byteAlign, int columns, int rows,
1165                                GBool endOfBlock, GBool black) {
1166   this->str = str;
1167   this->encoding = encoding;
1168   this->endOfLine = endOfLine;
1169   this->byteAlign = byteAlign;
1170   this->columns = columns;
1171   this->rows = rows;
1172   this->endOfBlock = endOfBlock;
1173   this->black = black;
1174   refLine = (short *)gmalloc((columns + 2) * sizeof(short));
1175   codingLine = (short *)gmalloc((columns + 2) * sizeof(short));
1176
1177   eof = gFalse;
1178   row = 0;
1179   nextLine2D = encoding < 0;
1180   inputBits = 0;
1181   codingLine[0] = 0;
1182   codingLine[1] = refLine[2] = columns;
1183   a0 = 1;
1184
1185   buf = EOF;
1186 }
1187
1188 CCITTFaxStream::~CCITTFaxStream() {
1189   delete str;
1190   gfree(refLine);
1191   gfree(codingLine);
1192 }
1193
1194 void CCITTFaxStream::reset() {
1195   int n;
1196
1197   str->reset();
1198   eof = gFalse;
1199   row = 0;
1200   nextLine2D = encoding < 0;
1201   inputBits = 0;
1202   codingLine[0] = 0;
1203   codingLine[1] = refLine[2] = columns;
1204   a0 = 1;
1205   buf = EOF;
1206
1207   // get initial end-of-line marker and 2D encoding tag
1208   if (endOfBlock) {
1209     if (lookBits(12) == 0x001) {
1210       eatBits(12);
1211     }
1212   } else {
1213     for (n = 0; n < 11 && lookBits(n) == 0; ++n) ;
1214     if (n == 11 && lookBits(12) == 0x001) {
1215       eatBits(12);
1216     }
1217   }
1218   if (encoding > 0) {
1219     nextLine2D = !lookBits(1);
1220     eatBits(1);
1221   }
1222 }
1223
1224 int CCITTFaxStream::lookChar() {
1225   short code1, code2, code3;
1226   int a0New;
1227 #if 0 //~
1228   GBool err;
1229 #endif
1230   int ret;
1231   int bits, i, n;
1232
1233   // if at eof just return EOF
1234   if (eof && codingLine[a0] >= columns) {
1235     return EOF;
1236   }
1237
1238   // read the next row
1239 #if 0 //~
1240   err = gFalse;
1241 #endif
1242   if (codingLine[a0] >= columns) {
1243
1244     // 2-D encoding
1245     if (nextLine2D) {
1246       for (i = 0; codingLine[i] < columns; ++i)
1247         refLine[i] = codingLine[i];
1248       refLine[i] = refLine[i + 1] = columns;
1249       b1 = 1;
1250       a0New = codingLine[a0 = 0] = 0;
1251       do {
1252         code1 = getTwoDimCode();
1253         switch (code1) {
1254         case twoDimPass:
1255           if (refLine[b1] < columns) {
1256             a0New = refLine[b1 + 1];
1257             b1 += 2;
1258           }
1259           break;
1260         case twoDimHoriz:
1261           if ((a0 & 1) == 0) {
1262             code1 = code2 = 0;
1263             do {
1264               code1 += code3 = getWhiteCode();
1265             } while (code3 >= 64);
1266             do {
1267               code2 += code3 = getBlackCode();
1268             } while (code3 >= 64);
1269           } else {
1270             code1 = code2 = 0;
1271             do {
1272               code1 += code3 = getBlackCode();
1273             } while (code3 >= 64);
1274             do {
1275               code2 += code3 = getWhiteCode();
1276             } while (code3 >= 64);
1277           }
1278           codingLine[a0 + 1] = a0New + code1;
1279           ++a0;
1280           a0New = codingLine[a0 + 1] = codingLine[a0] + code2;
1281           ++a0;
1282           while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
1283             b1 += 2;
1284           break;
1285         case twoDimVert0:
1286           a0New = codingLine[++a0] = refLine[b1];
1287           if (refLine[b1] < columns) {
1288             ++b1;
1289             while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
1290               b1 += 2;
1291           }
1292           break;
1293         case twoDimVertR1:
1294           a0New = codingLine[++a0] = refLine[b1] + 1;
1295           if (refLine[b1] < columns) {
1296             ++b1;
1297             while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
1298               b1 += 2;
1299           }
1300           break;
1301         case twoDimVertL1:
1302           a0New = codingLine[++a0] = refLine[b1] - 1;
1303           --b1;
1304           while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
1305             b1 += 2;
1306           break;
1307         case twoDimVertR2:
1308           a0New = codingLine[++a0] = refLine[b1] + 2;
1309           if (refLine[b1] < columns) {
1310             ++b1;
1311             while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
1312               b1 += 2;
1313           }
1314           break;
1315         case twoDimVertL2:
1316           a0New = codingLine[++a0] = refLine[b1] - 2;
1317           --b1;
1318           while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
1319             b1 += 2;
1320           break;
1321         case twoDimVertR3:
1322           a0New = codingLine[++a0] = refLine[b1] + 3;
1323           if (refLine[b1] < columns) {
1324             ++b1;
1325             while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
1326               b1 += 2;
1327           }
1328           break;
1329         case twoDimVertL3:
1330           a0New = codingLine[++a0] = refLine[b1] - 3;
1331           --b1;
1332           while (refLine[b1] <= codingLine[a0] && refLine[b1] < columns)
1333             b1 += 2;
1334           break;
1335         case EOF:
1336           eof = gTrue;
1337           codingLine[a0 = 0] = columns;
1338           return EOF;
1339         default:
1340           error(getPos(), "Bad 2D code %04x in CCITTFax stream", code1);
1341 #if 0 //~
1342           err = gTrue;
1343           break;
1344 #else
1345           eof = gTrue;
1346           return EOF;
1347 #endif
1348         }
1349       } while (codingLine[a0] < columns);
1350
1351     // 1-D encoding
1352     } else {
1353       codingLine[a0 = 0] = 0;
1354       while (1) {
1355         code1 = 0;
1356         do {
1357           code1 += code3 = getWhiteCode();
1358         } while (code3 >= 64);
1359         codingLine[a0+1] = codingLine[a0] + code1;
1360         ++a0;
1361         if (codingLine[a0] >= columns)
1362           break;
1363         code2 = 0;
1364         do {
1365           code2 += code3 = getBlackCode();
1366         } while (code3 >= 64);
1367         codingLine[a0+1] = codingLine[a0] + code2;
1368         ++a0;
1369         if (codingLine[a0] >= columns)
1370           break;
1371       }
1372     }
1373
1374     if (codingLine[a0] != columns) {
1375       error(getPos(), "CCITTFax row is wrong length (%d)", codingLine[a0]);
1376 #if 0 //~
1377       err = gTrue;
1378 #endif
1379     }
1380
1381     // byte-align the row
1382     if (byteAlign) {
1383       inputBits &= ~7;
1384     }
1385
1386     // check for end-of-line marker, end-of-block marker, and
1387     // 2D encoding tag
1388     if (endOfBlock) {
1389       code1 = lookBits(12);
1390       if (code1 == EOF) {
1391         eof = gTrue;
1392       } else if (code1 == 0x001) {
1393         eatBits(12);
1394         if (encoding > 0) {
1395           nextLine2D = !lookBits(1);
1396           eatBits(1);
1397         }
1398         code1 = lookBits(12);
1399         if (code1 == 0x001) {
1400           eatBits(12);
1401           if (encoding > 0) {
1402             lookBits(1);
1403             eatBits(1);
1404           }
1405           if (encoding >= 0) {
1406             for (i = 0; i < 4; ++i) {
1407               code1 = lookBits(12);
1408               if (code1 != 0x001) {
1409                 error(getPos(), "Bad RTC code in CCITTFax stream");
1410               }
1411               eatBits(12);
1412               if (encoding > 0) {
1413                 lookBits(1);
1414                 eatBits(1);
1415               }
1416             }
1417           }
1418           eof = gTrue;
1419         }
1420       } else {
1421         if (encoding > 0) {
1422           nextLine2D = !lookBits(1);
1423           eatBits(1);
1424         }
1425       }
1426     } else {
1427       if (row == rows - 1) {
1428         eof = gTrue;
1429       } else {
1430         for (n = 0; n < 11 && lookBits(n) == 0; ++n) ;
1431         if (n == 11 && lookBits(12) == 0x001) {
1432           eatBits(12);
1433         }
1434         if (encoding > 0) {
1435           nextLine2D = !lookBits(1);
1436           eatBits(1);
1437         }
1438       }
1439     }
1440
1441 #if 0 //~
1442     // This looks for an end-of-line marker after an error, however
1443     // some (most?) CCITT streams in PDF files don't use end-of-line
1444     // markers, and the just-plow-on technique works better in those
1445     // cases.
1446     else if (err) {
1447       do {
1448         if (code1 == EOF) {
1449           eof = gTrue;
1450           return EOF;
1451         }
1452         eatBits(1);
1453         code1 = look13Bits();
1454       } while ((code1 >> 1) != 0x001);
1455       eatBits(12); 
1456       codingLine[++a0] = columns;
1457       if (encoding > 0) {
1458         eatBits(1);
1459         nextLine2D = !(code1 & 1);
1460       }
1461     }
1462 #endif
1463
1464     a0 = 0;
1465     outputBits = codingLine[1] - codingLine[0];
1466     if (outputBits == 0) {
1467       a0 = 1;
1468       outputBits = codingLine[2] - codingLine[1];
1469     }
1470
1471     ++row;
1472   }
1473
1474   // get a byte
1475   if (outputBits >= 8) {
1476     ret = ((a0 & 1) == 0) ? 0xff : 0x00;
1477     if ((outputBits -= 8) == 0) {
1478       ++a0;
1479       if (codingLine[a0] < columns) {
1480         outputBits = codingLine[a0 + 1] - codingLine[a0];
1481       }
1482     }
1483   } else {
1484     bits = 8;
1485     ret = 0;
1486     do {
1487       if (outputBits > bits) {
1488         i = bits;
1489         bits = 0;
1490         if ((a0 & 1) == 0) {
1491           ret |= 0xff >> (8 - i);
1492         }
1493         outputBits -= i;
1494       } else {
1495         i = outputBits;
1496         bits -= outputBits;
1497         if ((a0 & 1) == 0) {
1498           ret |= (0xff >> (8 - i)) << bits;
1499         }
1500         outputBits = 0;
1501         ++a0;
1502         if (codingLine[a0] < columns) {
1503           outputBits = codingLine[a0 + 1] - codingLine[a0];
1504         }
1505       }
1506     } while (bits > 0 && codingLine[a0] < columns);
1507   }
1508   buf = black ? (ret ^ 0xff) : ret;
1509   return buf;
1510 }
1511
1512 short CCITTFaxStream::getTwoDimCode() {
1513   short code;
1514   CCITTCode *p;
1515   int n;
1516
1517   code = 0; // make gcc happy
1518   if (endOfBlock) {
1519     code = lookBits(7);
1520     p = &twoDimTab1[code];
1521     if (p->bits > 0) {
1522       eatBits(p->bits);
1523       return p->n;
1524     }
1525   } else {
1526     for (n = 1; n <= 7; ++n) {
1527       code = lookBits(n);
1528       if (n < 7) {
1529         code <<= 7 - n;
1530       }
1531       p = &twoDimTab1[code];
1532       if (p->bits == n) {
1533         eatBits(n);
1534         return p->n;
1535       }
1536     }
1537   }
1538   error(getPos(), "Bad two dim code (%04x) in CCITTFax stream", code);
1539   return EOF;
1540 }
1541
1542 short CCITTFaxStream::getWhiteCode() {
1543   short code;
1544   CCITTCode *p;
1545   int n;
1546
1547   code = 0; // make gcc happy
1548   if (endOfBlock) {
1549     code = lookBits(12);
1550     if ((code >> 5) == 0)
1551       p = &whiteTab1[code];
1552     else
1553       p = &whiteTab2[code >> 3];
1554     if (p->bits > 0) {
1555       eatBits(p->bits);
1556       return p->n;
1557     }
1558   } else {
1559     for (n = 1; n <= 9; ++n) {
1560       code = lookBits(n);
1561       if (n < 9) {
1562         code <<= 9 - n;
1563       }
1564       p = &whiteTab2[code];
1565       if (p->bits == n) {
1566         eatBits(n);
1567         return p->n;
1568       }
1569     }
1570     for (n = 11; n <= 12; ++n) {
1571       code = lookBits(n);
1572       if (n < 12) {
1573         code <<= 12 - n;
1574       }
1575       p = &whiteTab1[code];
1576       if (p->bits == n) {
1577         eatBits(n);
1578         return p->n;
1579       }
1580     }
1581   }
1582   error(getPos(), "Bad white code (%04x) in CCITTFax stream", code);
1583   return EOF;
1584 }
1585
1586 short CCITTFaxStream::getBlackCode() {
1587   short code;
1588   CCITTCode *p;
1589   int n;
1590
1591   code = 0; // make gcc happy
1592   if (endOfBlock) {
1593     code = lookBits(13);
1594     if ((code >> 7) == 0)
1595       p = &blackTab1[code];
1596     else if ((code >> 9) == 0)
1597       p = &blackTab2[(code >> 1) - 64];
1598     else
1599       p = &blackTab3[code >> 7];
1600     if (p->bits > 0) {
1601       eatBits(p->bits);
1602       return p->n;
1603     }
1604   } else {
1605     for (n = 2; n <= 6; ++n) {
1606       code = lookBits(n);
1607       if (n < 6) {
1608         code <<= 6 - n;
1609       }
1610       p = &blackTab3[code];
1611       if (p->bits == n) {
1612         eatBits(n);
1613         return p->n;
1614       }
1615     }
1616     for (n = 7; n <= 12; ++n) {
1617       code = lookBits(n);
1618       if (n < 12) {
1619         code <<= 12 - n;
1620       }
1621       if (code >= 64) {
1622         p = &blackTab2[code - 64];
1623         if (p->bits == n) {
1624           eatBits(n);
1625           return p->n;
1626         }
1627       }
1628     }
1629     for (n = 10; n <= 13; ++n) {
1630       code = lookBits(n);
1631       if (n < 13) {
1632         code <<= 13 - n;
1633       }
1634       p = &blackTab1[code];
1635       if (p->bits == n) {
1636         eatBits(n);
1637         return p->n;
1638       }
1639     }
1640   }
1641   error(getPos(), "Bad black code (%04x) in CCITTFax stream", code);
1642   return EOF;
1643 }
1644
1645 short CCITTFaxStream::lookBits(int n) {
1646   int c;
1647
1648   while (inputBits < n) {
1649     if ((c = str->getChar()) == EOF) {
1650       if (inputBits == 0)
1651         return EOF;
1652       c = 0;
1653     }
1654     inputBuf = (inputBuf << 8) + c;
1655     inputBits += 8;
1656   }
1657   return (inputBuf >> (inputBits - n)) & (0xffff >> (16 - n));
1658 }
1659
1660 GString *CCITTFaxStream::getPSFilter(char *indent) {
1661   GString *s;
1662   char s1[50];
1663
1664   s = str->getPSFilter(indent);
1665   s->append(indent)->append("<< ");
1666   if (encoding != 0) {
1667     sprintf(s1, "/K %d ", encoding);
1668     s->append(s1);
1669   }
1670   if (endOfLine) {
1671     s->append("/EndOfLine true ");
1672   }
1673   if (byteAlign) {
1674     s->append("/EncodedByteAlign true ");
1675   }
1676   sprintf(s1, "/Columns %d ", columns);
1677   s->append(s1);
1678   if (rows != 0) {
1679     sprintf(s1, "/Rows %d ", rows);
1680     s->append(s1);
1681   }
1682   if (!endOfBlock) {
1683     s->append("/EndOfBlock false ");
1684   }
1685   if (black) {
1686     s->append("/BlackIs1 true ");
1687   }
1688   s->append(">> /CCITTFaxDecode filter\n");
1689   return s;
1690 }
1691
1692 GBool CCITTFaxStream::isBinary(GBool last) {
1693   return str->isBinary(gTrue);
1694 }
1695
1696 //------------------------------------------------------------------------
1697 // DCTStream
1698 //------------------------------------------------------------------------
1699
1700 // IDCT constants (20.12 fixed point format)
1701 #ifndef FP_IDCT
1702 #define dctCos1    4017         // cos(pi/16)
1703 #define dctSin1     799         // sin(pi/16)
1704 #define dctCos3    3406         // cos(3*pi/16)
1705 #define dctSin3    2276         // sin(3*pi/16)
1706 #define dctCos6    1567         // cos(6*pi/16)
1707 #define dctSin6    3784         // sin(6*pi/16)
1708 #define dctSqrt2   5793         // sqrt(2)
1709 #define dctSqrt1d2 2896         // sqrt(2) / 2
1710 #endif
1711
1712 // IDCT constants
1713 #ifdef FP_IDCT
1714 #define dctCos1    0.98078528   // cos(pi/16)
1715 #define dctSin1    0.19509032   // sin(pi/16)
1716 #define dctCos3    0.83146961   // cos(3*pi/16)
1717 #define dctSin3    0.55557023   // sin(3*pi/16)
1718 #define dctCos6    0.38268343   // cos(6*pi/16)
1719 #define dctSin6    0.92387953   // sin(6*pi/16)
1720 #define dctSqrt2   1.41421356   // sqrt(2)
1721 #define dctSqrt1d2 0.70710678   // sqrt(2) / 2
1722 #endif
1723
1724 // color conversion parameters (16.16 fixed point format)
1725 #define dctCrToR   91881        //  1.4020
1726 #define dctCbToG  -22553        // -0.3441363
1727 #define dctCrToG  -46802        // -0.71413636
1728 #define dctCbToB  116130        //  1.772
1729
1730 // clip [-256,511] --> [0,255]
1731 #define dctClipOffset 256
1732 static Guchar dctClip[768];
1733 static int dctClipInit = 0;
1734
1735 // zig zag decode map
1736 static int dctZigZag[64] = {
1737    0,
1738    1,  8,
1739   16,  9,  2,
1740    3, 10, 17, 24,
1741   32, 25, 18, 11, 4,
1742    5, 12, 19, 26, 33, 40,
1743   48, 41, 34, 27, 20, 13,  6,
1744    7, 14, 21, 28, 35, 42, 49, 56,
1745   57, 50, 43, 36, 29, 22, 15,
1746   23, 30, 37, 44, 51, 58,
1747   59, 52, 45, 38, 31,
1748   39, 46, 53, 60,
1749   61, 54, 47,
1750   55, 62,
1751   63
1752 };
1753
1754 DCTStream::DCTStream(Stream *str1) {
1755   int i, j;
1756
1757   str = str1;
1758   width = height = 0;
1759   mcuWidth = mcuHeight = 0;
1760   numComps = 0;
1761   comp = 0;
1762   x = y = dy = 0;
1763   for (i = 0; i < 4; ++i)
1764     for (j = 0; j < 32; ++j)
1765       rowBuf[i][j] = NULL;
1766
1767   if (!dctClipInit) {
1768     for (i = -256; i < 0; ++i)
1769       dctClip[dctClipOffset + i] = 0;
1770     for (i = 0; i < 256; ++i)
1771       dctClip[dctClipOffset + i] = i;
1772     for (i = 256; i < 512; ++i)
1773       dctClip[dctClipOffset + i] = 255;
1774     dctClipInit = 1;
1775   }
1776 }
1777
1778 DCTStream::~DCTStream() {
1779   int i, j;
1780
1781   delete str;
1782   for (i = 0; i < numComps; ++i)
1783     for (j = 0; j < mcuHeight; ++j)
1784       gfree(rowBuf[i][j]);
1785 }
1786
1787 void DCTStream::reset() {
1788   str->reset();
1789   if (!readHeader()) {
1790     y = height;
1791     return;
1792   }
1793   restartMarker = 0xd0;
1794   restart();
1795 }
1796
1797 int DCTStream::getChar() {
1798   int c;
1799
1800   c = lookChar();
1801   if (c == EOF)
1802     return EOF;
1803   if (++comp == numComps) {
1804     comp = 0;
1805     if (++x == width) {
1806       x = 0;
1807       ++y;
1808       ++dy;
1809     }
1810   }
1811   if (y == height)
1812     readTrailer();
1813   return c;
1814 }
1815
1816 int DCTStream::lookChar() {
1817   if (y >= height)
1818     return EOF;
1819   if (dy >= mcuHeight) {
1820     if (!readMCURow()) {
1821       y = height;
1822       return EOF;
1823     }
1824     comp = 0;
1825     x = 0;
1826     dy = 0;
1827   }
1828   return rowBuf[comp][dy][x];
1829 }
1830
1831 void DCTStream::restart() {
1832   int i;
1833
1834   inputBits = 0;
1835   restartCtr = restartInterval;
1836   for (i = 0; i < numComps; ++i)
1837     compInfo[i].prevDC = 0;
1838 }
1839
1840 GBool DCTStream::readMCURow() {
1841   Guchar data[64];
1842   Guchar *p1, *p2;
1843   int pY, pCb, pCr, pR, pG, pB;
1844   int h, v, horiz, vert, hSub, vSub;
1845   int x1, x2, y2, x3, y3, x4, y4, x5, y5, cc, i;
1846   int c;
1847
1848   for (x1 = 0; x1 < width; x1 += mcuWidth) {
1849
1850     // deal with restart marker
1851     if (restartInterval > 0 && restartCtr == 0) {
1852       c = readMarker();
1853       if (c != restartMarker) {
1854         error(getPos(), "Bad DCT data: incorrect restart marker");
1855         return gFalse;
1856       }
1857       if (++restartMarker == 0xd8)
1858         restartMarker = 0xd0;
1859       restart();
1860     }
1861
1862     // read one MCU
1863     for (cc = 0; cc < numComps; ++cc) {
1864       h = compInfo[cc].hSample;
1865       v = compInfo[cc].vSample;
1866       horiz = mcuWidth / h;
1867       vert = mcuHeight / v;
1868       hSub = horiz / 8;
1869       vSub = vert / 8;
1870       for (y2 = 0; y2 < mcuHeight; y2 += vert) {
1871         for (x2 = 0; x2 < mcuWidth; x2 += horiz) {
1872           if (!readDataUnit(&dcHuffTables[compInfo[cc].dcHuffTable],
1873                             &acHuffTables[compInfo[cc].acHuffTable],
1874                             quantTables[compInfo[cc].quantTable],
1875                             &compInfo[cc].prevDC,
1876                             data))
1877             return gFalse;
1878           if (hSub == 1 && vSub == 1) {
1879             for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) {
1880               p1 = &rowBuf[cc][y2+y3][x1+x2];
1881               p1[0] = data[i];
1882               p1[1] = data[i+1];
1883               p1[2] = data[i+2];
1884               p1[3] = data[i+3];
1885               p1[4] = data[i+4];
1886               p1[5] = data[i+5];
1887               p1[6] = data[i+6];
1888               p1[7] = data[i+7];
1889             }
1890           } else if (hSub == 2 && vSub == 2) {
1891             for (y3 = 0, i = 0; y3 < 16; y3 += 2, i += 8) {
1892               p1 = &rowBuf[cc][y2+y3][x1+x2];
1893               p2 = &rowBuf[cc][y2+y3+1][x1+x2];
1894               p1[0] = p1[1] = p2[0] = p2[1] = data[i];
1895               p1[2] = p1[3] = p2[2] = p2[3] = data[i+1];
1896               p1[4] = p1[5] = p2[4] = p2[5] = data[i+2];
1897               p1[6] = p1[7] = p2[6] = p2[7] = data[i+3];
1898               p1[8] = p1[9] = p2[8] = p2[9] = data[i+4];
1899               p1[10] = p1[11] = p2[10] = p2[11] = data[i+5];
1900               p1[12] = p1[13] = p2[12] = p2[13] = data[i+6];
1901               p1[14] = p1[15] = p2[14] = p2[15] = data[i+7];
1902             }
1903           } else {
1904             i = 0;
1905             for (y3 = 0, y4 = 0; y3 < 8; ++y3, y4 += vSub) {
1906               for (x3 = 0, x4 = 0; x3 < 8; ++x3, x4 += hSub) {
1907                 for (y5 = 0; y5 < vSub; ++y5)
1908                   for (x5 = 0; x5 < hSub; ++x5)
1909                     rowBuf[cc][y2+y4+y5][x1+x2+x4+x5] = data[i];
1910                 ++i;
1911               }
1912             }
1913           }
1914         }
1915       }
1916     }
1917     --restartCtr;
1918
1919     // color space conversion
1920     if (colorXform) {
1921       // convert YCbCr to RGB
1922       if (numComps == 3) {
1923         for (y2 = 0; y2 < mcuHeight; ++y2) {
1924           for (x2 = 0; x2 < mcuWidth; ++x2) {
1925             pY = rowBuf[0][y2][x1+x2];
1926             pCb = rowBuf[1][y2][x1+x2] - 128;
1927             pCr = rowBuf[2][y2][x1+x2] - 128;
1928             pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
1929             rowBuf[0][y2][x1+x2] = dctClip[dctClipOffset + pR];
1930             pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr + 32768) >> 16;
1931             rowBuf[1][y2][x1+x2] = dctClip[dctClipOffset + pG];
1932             pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
1933             rowBuf[2][y2][x1+x2] = dctClip[dctClipOffset + pB];
1934           }
1935         }
1936       // convert YCbCrK to CMYK (K is passed through unchanged)
1937       } else if (numComps == 4) {
1938         for (y2 = 0; y2 < mcuHeight; ++y2) {
1939           for (x2 = 0; x2 < mcuWidth; ++x2) {
1940             pY = rowBuf[0][y2][x1+x2];
1941             pCb = rowBuf[1][y2][x1+x2] - 128;
1942             pCr = rowBuf[2][y2][x1+x2] - 128;
1943             pR = ((pY << 16) + dctCrToR * pCr + 32768) >> 16;
1944             rowBuf[0][y2][x1+x2] = 255 - dctClip[dctClipOffset + pR];
1945             pG = ((pY << 16) + dctCbToG * pCb + dctCrToG * pCr + 32678) >> 16;
1946             rowBuf[1][y2][x1+x2] = 255 - dctClip[dctClipOffset + pG];
1947             pB = ((pY << 16) + dctCbToB * pCb + 32768) >> 16;
1948             rowBuf[2][y2][x1+x2] = 255 - dctClip[dctClipOffset + pB];
1949           }
1950         }
1951       }
1952     }
1953   }
1954   return gTrue;
1955 }
1956
1957 // This IDCT algorithm is taken from:
1958 //   Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
1959 //   "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
1960 //   IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
1961 //   988-991.
1962 // The stage numbers mentioned in the comments refer to Figure 1 in this
1963 // paper.
1964 #ifndef FP_IDCT
1965 GBool DCTStream::readDataUnit(DCTHuffTable *dcHuffTable,
1966                               DCTHuffTable *acHuffTable,
1967                               Guchar quantTable[64], int *prevDC,
1968                               Guchar data[64]) {
1969   int tmp1[64];
1970   int v0, v1, v2, v3, v4, v5, v6, v7, t;
1971   int run, size, amp;
1972   int c;
1973   int i, j;
1974
1975   // Huffman decode and dequantize
1976   size = readHuffSym(dcHuffTable);
1977   if (size == 9999)
1978     return gFalse;
1979   if (size > 0) {
1980     amp = readAmp(size);
1981     if (amp == 9999)
1982       return gFalse;
1983   } else {
1984     amp = 0;
1985   }
1986   tmp1[0] = (*prevDC += amp) * quantTable[0];
1987   for (i = 1; i < 64; ++i)
1988     tmp1[i] = 0;
1989   i = 1;
1990   while (i < 64) {
1991     run = 0;
1992     while ((c = readHuffSym(acHuffTable)) == 0xf0 && run < 0x30)
1993       run += 0x10;
1994     if (c == 9999)
1995       return gFalse;
1996     if (c == 0x00) {
1997       break;
1998     } else {
1999       run += (c >> 4) & 0x0f;
2000       size = c & 0x0f;
2001       amp = readAmp(size);
2002       if (amp == 9999)
2003         return gFalse;
2004       i += run;
2005       j = dctZigZag[i++];
2006       tmp1[j] = amp * quantTable[j];
2007     }
2008   }
2009
2010   // inverse DCT on rows
2011   for (i = 0; i < 64; i += 8) {
2012
2013     // stage 4
2014     v0 = (dctSqrt2 * tmp1[i+0] + 128) >> 8;
2015     v1 = (dctSqrt2 * tmp1[i+4] + 128) >> 8;
2016     v2 = tmp1[i+2];
2017     v3 = tmp1[i+6];
2018     v4 = (dctSqrt1d2 * (tmp1[i+1] - tmp1[i+7]) + 128) >> 8;
2019     v7 = (dctSqrt1d2 * (tmp1[i+1] + tmp1[i+7]) + 128) >> 8;
2020     v5 = tmp1[i+3] << 4;
2021     v6 = tmp1[i+5] << 4;
2022
2023     // stage 3
2024     t = (v0 - v1+ 1) >> 1;
2025     v0 = (v0 + v1 + 1) >> 1;
2026     v1 = t;
2027     t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
2028     v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
2029     v3 = t;
2030     t = (v4 - v6 + 1) >> 1;
2031     v4 = (v4 + v6 + 1) >> 1;
2032     v6 = t;
2033     t = (v7 + v5 + 1) >> 1;
2034     v5 = (v7 - v5 + 1) >> 1;
2035     v7 = t;
2036
2037     // stage 2
2038     t = (v0 - v3 + 1) >> 1;
2039     v0 = (v0 + v3 + 1) >> 1;
2040     v3 = t;
2041     t = (v1 - v2 + 1) >> 1;
2042     v1 = (v1 + v2 + 1) >> 1;
2043     v2 = t;
2044     t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
2045     v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
2046     v7 = t;
2047     t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
2048     v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
2049     v6 = t;
2050
2051     // stage 1
2052     tmp1[i+0] = v0 + v7;
2053     tmp1[i+7] = v0 - v7;
2054     tmp1[i+1] = v1 + v6;
2055     tmp1[i+6] = v1 - v6;
2056     tmp1[i+2] = v2 + v5;
2057     tmp1[i+5] = v2 - v5;
2058     tmp1[i+3] = v3 + v4;
2059     tmp1[i+4] = v3 - v4;
2060   }
2061
2062   // inverse DCT on columns
2063   for (i = 0; i < 8; ++i) {
2064
2065     // stage 4
2066     v0 = (dctSqrt2 * tmp1[0*8+i] + 2048) >> 12;
2067     v1 = (dctSqrt2 * tmp1[4*8+i] + 2048) >> 12;
2068     v2 = tmp1[2*8+i];
2069     v3 = tmp1[6*8+i];
2070     v4 = (dctSqrt1d2 * (tmp1[1*8+i] - tmp1[7*8+i]) + 2048) >> 12;
2071     v7 = (dctSqrt1d2 * (tmp1[1*8+i] + tmp1[7*8+i]) + 2048) >> 12;
2072     v5 = tmp1[3*8+i];
2073     v6 = tmp1[5*8+i];
2074
2075     // stage 3
2076     t = (v0 - v1 + 1) >> 1;
2077     v0 = (v0 + v1 + 1) >> 1;
2078     v1 = t;
2079     t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
2080     v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
2081     v3 = t;
2082     t = (v4 - v6 + 1) >> 1;
2083     v4 = (v4 + v6 + 1) >> 1;
2084     v6 = t;
2085     t = (v7 + v5 + 1) >> 1;
2086     v5 = (v7 - v5 + 1) >> 1;
2087     v7 = t;
2088
2089     // stage 2
2090     t = (v0 - v3 + 1) >> 1;
2091     v0 = (v0 + v3 + 1) >> 1;
2092     v3 = t;
2093     t = (v1 - v2 + 1) >> 1;
2094     v1 = (v1 + v2 + 1) >> 1;
2095     v2 = t;
2096     t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
2097     v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
2098     v7 = t;
2099     t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
2100     v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
2101     v6 = t;
2102
2103     // stage 1
2104     tmp1[0*8+i] = v0 + v7;
2105     tmp1[7*8+i] = v0 - v7;
2106     tmp1[1*8+i] = v1 + v6;
2107     tmp1[6*8+i] = v1 - v6;
2108     tmp1[2*8+i] = v2 + v5;
2109     tmp1[5*8+i] = v2 - v5;
2110     tmp1[3*8+i] = v3 + v4;
2111     tmp1[4*8+i] = v3 - v4;
2112   }
2113
2114   // convert to 8-bit integers
2115   for (i = 0; i < 64; ++i)
2116     data[i] = dctClip[dctClipOffset + 128 + ((tmp1[i] + 8) >> 4)];
2117
2118   return gTrue;
2119 }
2120 #endif
2121
2122 #ifdef FP_IDCT
2123 GBool DCTStream::readDataUnit(DCTHuffTable *dcHuffTable,
2124                               DCTHuffTable *acHuffTable,
2125                               Guchar quantTable[64], int *prevDC,
2126                               Guchar data[64]) {
2127   double tmp1[64];
2128   double v0, v1, v2, v3, v4, v5, v6, v7, t;
2129   int run, size, amp;
2130   int c;
2131   int i, j;
2132
2133   // Huffman decode and dequantize
2134   size = readHuffSym(dcHuffTable);
2135   if (size == 9999)
2136     return gFalse;
2137   if (size > 0) {
2138     amp = readAmp(size);
2139     if (amp == 9999)
2140       return gFalse;
2141   } else {
2142     amp = 0;
2143   }
2144   tmp1[0] = (*prevDC += amp) * quantTable[0];
2145   for (i = 1; i < 64; ++i)
2146     tmp1[i] = 0;
2147   i = 1;
2148   while (i < 64) {
2149     run = 0;
2150     while ((c = readHuffSym(acHuffTable)) == 0xf0 && run < 0x30)
2151       run += 0x10;
2152     if (c == 9999)
2153       return gFalse;
2154     if (c == 0x00) {
2155       break;
2156     } else {
2157       run += (c >> 4) & 0x0f;
2158       size = c & 0x0f;
2159       amp = readAmp(size);
2160       if (amp == 9999)
2161         return gFalse;
2162       i += run;
2163       j = dctZigZag[i++];
2164       tmp1[j] = amp * quantTable[j];
2165     }
2166   }
2167
2168   // inverse DCT on rows
2169   for (i = 0; i < 64; i += 8) {
2170
2171     // stage 4
2172     v0 = dctSqrt2 * tmp1[i+0];
2173     v1 = dctSqrt2 * tmp1[i+4];
2174     v2 = tmp1[i+2];
2175     v3 = tmp1[i+6];
2176     v4 = dctSqrt1d2 * (tmp1[i+1] - tmp1[i+7]);
2177     v7 = dctSqrt1d2 * (tmp1[i+1] + tmp1[i+7]);
2178     v5 = tmp1[i+3];
2179     v6 = tmp1[i+5];
2180
2181     // stage 3
2182     t = 0.5 * (v0 - v1);
2183     v0 = 0.5 * (v0 + v1);
2184     v1 = t;
2185     t = v2 * dctSin6 + v3 * dctCos6;
2186     v2 = v2 * dctCos6 - v3 * dctSin6;
2187     v3 = t;
2188     t = 0.5 * (v4 - v6);
2189     v4 = 0.5 * (v4 + v6);
2190     v6 = t;
2191     t = 0.5 * (v7 + v5);
2192     v5 = 0.5 * (v7 - v5);
2193     v7 = t;
2194
2195     // stage 2
2196     t = 0.5 * (v0 - v3);
2197     v0 = 0.5 * (v0 + v3);
2198     v3 = t;
2199     t = 0.5 * (v1 - v2);
2200     v1 = 0.5 * (v1 + v2);
2201     v2 = t;
2202     t = v4 * dctSin3 + v7 * dctCos3;
2203     v4 = v4 * dctCos3 - v7 * dctSin3;
2204     v7 = t;
2205     t = v5 * dctSin1 + v6 * dctCos1;
2206     v5 = v5 * dctCos1 - v6 * dctSin1;
2207     v6 = t;
2208
2209     // stage 1
2210     tmp1[i+0] = v0 + v7;
2211     tmp1[i+7] = v0 - v7;
2212     tmp1[i+1] = v1 + v6;
2213     tmp1[i+6] = v1 - v6;
2214     tmp1[i+2] = v2 + v5;
2215     tmp1[i+5] = v2 - v5;
2216     tmp1[i+3] = v3 + v4;
2217     tmp1[i+4] = v3 - v4;
2218   }
2219
2220   // inverse DCT on columns
2221   for (i = 0; i < 8; ++i) {
2222
2223     // stage 4
2224     v0 = dctSqrt2 * tmp1[0*8+i];
2225     v1 = dctSqrt2 * tmp1[4*8+i];
2226     v2 = tmp1[2*8+i];
2227     v3 = tmp1[6*8+i];
2228     v4 = dctSqrt1d2 * (tmp1[1*8+i] - tmp1[7*8+i]);
2229     v7 = dctSqrt1d2 * (tmp1[1*8+i] + tmp1[7*8+i]);
2230     v5 = tmp1[3*8+i];
2231     v6 = tmp1[5*8+i];
2232
2233     // stage 3
2234     t = 0.5 * (v0 - v1);
2235     v0 = 0.5 * (v0 + v1);
2236     v1 = t;
2237     t = v2 * dctSin6 + v3 * dctCos6;
2238     v2 = v2 * dctCos6 - v3 * dctSin6;
2239     v3 = t;
2240     t = 0.5 * (v4 - v6);
2241     v4 = 0.5 * (v4 + v6);
2242     v6 = t;
2243     t = 0.5 * (v7 + v5);
2244     v5 = 0.5 * (v7 - v5);
2245     v7 = t;
2246
2247     // stage 2
2248     t = 0.5 * (v0 - v3);
2249     v0 = 0.5 * (v0 + v3);
2250     v3 = t;
2251     t = 0.5 * (v1 - v2);
2252     v1 = 0.5 * (v1 + v2);
2253     v2 = t;
2254     t = v4 * dctSin3 + v7 * dctCos3;
2255     v4 = v4 * dctCos3 - v7 * dctSin3;
2256     v7 = t;
2257     t = v5 * dctSin1 + v6 * dctCos1;
2258     v5 = v5 * dctCos1 - v6 * dctSin1;
2259     v6 = t;
2260
2261     // stage 1
2262     tmp1[0*8+i] = v0 + v7;
2263     tmp1[7*8+i] = v0 - v7;
2264     tmp1[1*8+i] = v1 + v6;
2265     tmp1[6*8+i] = v1 - v6;
2266     tmp1[2*8+i] = v2 + v5;
2267     tmp1[5*8+i] = v2 - v5;
2268     tmp1[3*8+i] = v3 + v4;
2269     tmp1[4*8+i] = v3 - v4;
2270   }
2271
2272   // convert to 8-bit integers
2273   for (i = 0; i < 64; ++i)
2274     data[i] = dctClip[dctClipOffset + (int)(tmp1[i] + 128.5)];
2275
2276   return gTrue;
2277 }
2278 #endif
2279
2280 int DCTStream::readHuffSym(DCTHuffTable *table) {
2281   Gushort code;
2282   int bit;
2283   int codeBits;
2284
2285   code = 0;
2286   codeBits = 0;
2287   do {
2288     // add a bit to the code
2289     if ((bit = readBit()) == EOF)
2290       return 9999;
2291     code = (code << 1) + bit;
2292     ++codeBits;
2293
2294     // look up code
2295     if (code - table->firstCode[codeBits] < table->numCodes[codeBits]) {
2296       code -= table->firstCode[codeBits];
2297       return table->sym[table->firstSym[codeBits] + code];
2298     }
2299   } while (codeBits < 16);
2300
2301   error(getPos(), "Bad Huffman code in DCT stream");
2302   return 9999;
2303 }
2304
2305 int DCTStream::readAmp(int size) {
2306   int amp, bit;
2307   int bits;
2308
2309   amp = 0;
2310   for (bits = 0; bits < size; ++bits) {
2311     if ((bit = readBit()) == EOF)
2312       return 9999;
2313     amp = (amp << 1) + bit;
2314   }
2315   if (amp < (1 << (size - 1)))
2316     amp -= (1 << size) - 1;
2317   return amp;
2318 }
2319
2320 int DCTStream::readBit() {
2321   int bit;
2322   int c, c2;
2323
2324   if (inputBits == 0) {
2325     if ((c = str->getChar()) == EOF)
2326       return EOF;
2327     if (c == 0xff) {
2328       do {
2329         c2 = str->getChar();
2330       } while (c2 == 0xff);
2331       if (c2 != 0x00) {
2332         error(getPos(), "Bad DCT data: missing 00 after ff");
2333         return EOF;
2334       }
2335     }
2336     inputBuf = c;
2337     inputBits = 8;
2338   }
2339   bit = (inputBuf >> (inputBits - 1)) & 1;
2340   --inputBits;
2341   return bit;
2342 }
2343
2344 GBool DCTStream::readHeader() {
2345   GBool doScan;
2346   int minHSample, minVSample;
2347   int bufWidth;
2348   int n;
2349   int c = 0;
2350   int i, j;
2351
2352   width = height = 0;
2353   numComps = 0;
2354   numQuantTables = 0;
2355   numDCHuffTables = 0;
2356   numACHuffTables = 0;
2357   colorXform = 0;
2358   gotAdobeMarker = gFalse;
2359   restartInterval = 0;
2360
2361   // read headers
2362   doScan = gFalse;
2363   while (!doScan) {
2364     c = readMarker();
2365     switch (c) {
2366     case 0xc0:                  // SOF0
2367       if (!readFrameInfo())
2368         return gFalse;
2369       break;
2370     case 0xc4:                  // DHT
2371       if (!readHuffmanTables())
2372         return gFalse;
2373       break;
2374     case 0xd8:                  // SOI
2375       break;
2376     case 0xda:                  // SOS
2377       if (!readScanInfo())
2378         return gFalse;
2379       doScan = gTrue;
2380       break;
2381     case 0xdb:                  // DQT
2382       if (!readQuantTables())
2383         return gFalse;
2384       break;
2385     case 0xdd:                  // DRI
2386       if (!readRestartInterval())
2387         return gFalse;
2388       break;
2389     case 0xee:                  // APP14
2390       if (!readAdobeMarker())
2391         return gFalse;
2392       break;
2393     case EOF:
2394       error(getPos(), "Bad DCT header");
2395       return gFalse;
2396     default:
2397       // skip APPn / COM / etc.
2398       if (c >= 0xe0) {
2399         n = read16() - 2;
2400         for (i = 0; i < n; ++i)
2401           str->getChar();
2402       } else {
2403         error(getPos(), "Unknown DCT marker <%02x>", c);
2404         return gFalse;
2405       }
2406       break;
2407     }
2408   }
2409
2410   // compute MCU size
2411   mcuWidth = minHSample = compInfo[0].hSample;
2412   mcuHeight = minVSample = compInfo[0].vSample;
2413   for (i = 1; i < numComps; ++i) {
2414     if (compInfo[i].hSample < minHSample)
2415       minHSample = compInfo[i].hSample;
2416     if (compInfo[i].vSample < minVSample)
2417       minVSample = compInfo[i].vSample;
2418     if (compInfo[i].hSample > mcuWidth)
2419       mcuWidth = compInfo[i].hSample;
2420     if (compInfo[i].vSample > mcuHeight)
2421       mcuHeight = compInfo[i].vSample;
2422   }
2423   for (i = 0; i < numComps; ++i) {
2424     compInfo[i].hSample /= minHSample;
2425     compInfo[i].vSample /= minVSample;
2426   }
2427   mcuWidth = (mcuWidth / minHSample) * 8;
2428   mcuHeight = (mcuHeight / minVSample) * 8;
2429
2430   // allocate buffers
2431   bufWidth = ((width + mcuWidth - 1) / mcuWidth) * mcuWidth;
2432   for (i = 0; i < numComps; ++i)
2433     for (j = 0; j < mcuHeight; ++j)
2434       rowBuf[i][j] = (Guchar *)gmalloc(bufWidth * sizeof(Guchar));
2435
2436   // figure out color transform
2437   if (!gotAdobeMarker && numComps == 3) {
2438     if (compInfo[0].id == 1 && compInfo[1].id == 2 && compInfo[2].id == 3) {
2439       colorXform = 1;
2440     }
2441   }
2442
2443   // initialize counters
2444   comp = 0;
2445   x = 0;
2446   y = 0;
2447   dy = mcuHeight;
2448
2449   return gTrue;
2450 }
2451
2452 GBool DCTStream::readFrameInfo() {
2453   int length;
2454   int prec;
2455   int i;
2456   int c;
2457
2458   length = read16() - 2;
2459   prec = str->getChar();
2460   height = read16();
2461   width = read16();
2462   numComps = str->getChar();
2463   length -= 6;
2464   if (prec != 8) {
2465     error(getPos(), "Bad DCT precision %d", prec);
2466     return gFalse;
2467   }
2468   for (i = 0; i < numComps; ++i) {
2469     compInfo[i].id = str->getChar();
2470     compInfo[i].inScan = gFalse;
2471     c = str->getChar();
2472     compInfo[i].hSample = (c >> 4) & 0x0f;
2473     compInfo[i].vSample = c & 0x0f;
2474     compInfo[i].quantTable = str->getChar();
2475     compInfo[i].dcHuffTable = 0;
2476     compInfo[i].acHuffTable = 0;
2477   }
2478   return gTrue;
2479 }
2480
2481 GBool DCTStream::readScanInfo() {
2482   int length;
2483   int scanComps, id, c;
2484   int i, j;
2485
2486   length = read16() - 2;
2487   scanComps = str->getChar();
2488   --length;
2489   if (length != 2 * scanComps + 3) {
2490     error(getPos(), "Bad DCT scan info block");
2491     return gFalse;
2492   }
2493   for (i = 0; i < scanComps; ++i) {
2494     id = str->getChar();
2495     for (j = 0; j < numComps; ++j) {
2496       if (id == compInfo[j].id)
2497         break;
2498     }
2499     if (j == numComps) {
2500       error(getPos(), "Bad DCT component ID in scan info block");
2501       return gFalse;
2502     }
2503     compInfo[j].inScan = gTrue;
2504     c = str->getChar();
2505     compInfo[j].dcHuffTable = (c >> 4) & 0x0f;
2506     compInfo[j].acHuffTable = c & 0x0f;
2507   }
2508   str->getChar();
2509   str->getChar();
2510   str->getChar();
2511   return gTrue;
2512 }
2513
2514 GBool DCTStream::readQuantTables() {
2515   int length;
2516   int i;
2517   int index;
2518
2519   length = read16() - 2;
2520   while (length > 0) {
2521     index = str->getChar();
2522     if ((index & 0xf0) || index >= 4) {
2523       error(getPos(), "Bad DCT quantization table");
2524       return gFalse;
2525     }
2526     if (index == numQuantTables)
2527       numQuantTables = index + 1;
2528     for (i = 0; i < 64; ++i)
2529       quantTables[index][dctZigZag[i]] = str->getChar();
2530     length -= 65;
2531   }
2532   return gTrue;
2533 }
2534
2535 GBool DCTStream::readHuffmanTables() {
2536   DCTHuffTable *tbl;
2537   int length;
2538   int index;
2539   Gushort code;
2540   Guchar sym;
2541   int i;
2542   int c;
2543
2544   length = read16() - 2;
2545   while (length > 0) {
2546     index = str->getChar();
2547     --length;
2548     if ((index & 0x0f) >= 4) {
2549       error(getPos(), "Bad DCT Huffman table");
2550       return gFalse;
2551     }
2552     if (index & 0x10) {
2553       index &= 0x0f;
2554       if (index >= numACHuffTables)
2555         numACHuffTables = index+1;
2556       tbl = &acHuffTables[index];
2557     } else {
2558       if (index >= numDCHuffTables)
2559         numDCHuffTables = index+1;
2560       tbl = &dcHuffTables[index];
2561     }
2562     sym = 0;
2563     code = 0;
2564     for (i = 1; i <= 16; ++i) {
2565       c = str->getChar();
2566       tbl->firstSym[i] = sym;
2567       tbl->firstCode[i] = code;
2568       tbl->numCodes[i] = c;
2569       sym += c;
2570       code = (code + c) << 1;
2571     }
2572     length -= 16;
2573     for (i = 0; i < sym; ++i)
2574       tbl->sym[i] = str->getChar();
2575     length -= sym;
2576   }
2577   return gTrue;
2578 }
2579
2580 GBool DCTStream::readRestartInterval() {
2581   int length;
2582
2583   length = read16();
2584   if (length != 4) {
2585     error(getPos(), "Bad DCT restart interval");
2586     return gFalse;
2587   }
2588   restartInterval = read16();
2589   return gTrue;
2590 }
2591
2592 GBool DCTStream::readAdobeMarker() {
2593   int length, i;
2594   char buf[12];
2595   int c;
2596
2597   length = read16();
2598   if (length != 14)
2599     goto err;
2600   for (i = 0; i < 12; ++i) {
2601     if ((c = str->getChar()) == EOF)
2602       goto err;
2603     buf[i] = c;
2604   }
2605   if (strncmp(buf, "Adobe", 5))
2606     goto err;
2607   colorXform = buf[11];
2608   gotAdobeMarker = gTrue;
2609   return gTrue;
2610
2611  err:
2612   error(getPos(), "Bad DCT Adobe APP14 marker");
2613   return gFalse;
2614 }
2615
2616 GBool DCTStream::readTrailer() {
2617   int c;
2618
2619   c = readMarker();
2620   if (c != 0xd9) {              // EOI
2621     error(getPos(), "Bad DCT trailer");
2622     return gFalse;
2623   }
2624   return gTrue;
2625 }
2626
2627 int DCTStream::readMarker() {
2628   int c;
2629
2630   do {
2631     do {
2632       c = str->getChar();
2633     } while (c != 0xff);
2634     do {
2635       c = str->getChar();
2636     } while (c == 0xff);
2637   } while (c == 0x00);
2638   return c;
2639 }
2640
2641 int DCTStream::read16() {
2642   int c1, c2;
2643
2644   if ((c1 = str->getChar()) == EOF)
2645     return EOF;
2646   if ((c2 = str->getChar()) == EOF)
2647     return EOF;
2648   return (c1 << 8) + c2;
2649 }
2650
2651 GString *DCTStream::getPSFilter(char *indent) {
2652   GString *s;
2653
2654   s = str->getPSFilter(indent);
2655   s->append(indent)->append("<< >> /DCTDecode filter\n");
2656   return s;
2657 }
2658
2659 GBool DCTStream::isBinary(GBool last) {
2660   return str->isBinary(gTrue);
2661 }
2662
2663 //------------------------------------------------------------------------
2664 // FlateStream
2665 //------------------------------------------------------------------------
2666
2667 int FlateStream::codeLenCodeMap[flateMaxCodeLenCodes] = {
2668   16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
2669 };
2670
2671 FlateDecode FlateStream::lengthDecode[flateMaxLitCodes-257] = {
2672   {0,   3},
2673   {0,   4},
2674   {0,   5},
2675   {0,   6},
2676   {0,   7},
2677   {0,   8},
2678   {0,   9},
2679   {0,  10},
2680   {1,  11},
2681   {1,  13},
2682   {1,  15},
2683   {1,  17},
2684   {2,  19},
2685   {2,  23},
2686   {2,  27},
2687   {2,  31},
2688   {3,  35},
2689   {3,  43},
2690   {3,  51},
2691   {3,  59},
2692   {4,  67},
2693   {4,  83},
2694   {4,  99},
2695   {4, 115},
2696   {5, 131},
2697   {5, 163},
2698   {5, 195},
2699   {5, 227},
2700   {0, 258}
2701 };
2702
2703 FlateDecode FlateStream::distDecode[flateMaxDistCodes] = {
2704   { 0,     1},
2705   { 0,     2},
2706   { 0,     3},
2707   { 0,     4},
2708   { 1,     5},
2709   { 1,     7},
2710   { 2,     9},
2711   { 2,    13},
2712   { 3,    17},
2713   { 3,    25},
2714   { 4,    33},
2715   { 4,    49},
2716   { 5,    65},
2717   { 5,    97},
2718   { 6,   129},
2719   { 6,   193},
2720   { 7,   257},
2721   { 7,   385},
2722   { 8,   513},
2723   { 8,   769},
2724   { 9,  1025},
2725   { 9,  1537},
2726   {10,  2049},
2727   {10,  3073},
2728   {11,  4097},
2729   {11,  6145},
2730   {12,  8193},
2731   {12, 12289},
2732   {13, 16385},
2733   {13, 24577}
2734 };
2735
2736 FlateStream::FlateStream(Stream *str1, int predictor1, int columns1,
2737                          int colors1, int bits1) {
2738   str = str1;
2739   if (predictor1 != 1) {
2740     pred = new StreamPredictor(this, predictor1, columns1, colors1, bits1);
2741   } else {
2742     pred = NULL;
2743   }
2744 }
2745
2746 FlateStream::~FlateStream() {
2747   if (pred) {
2748     delete pred;
2749   }
2750   delete str;
2751 }
2752
2753 void FlateStream::reset() {
2754   int cmf, flg;
2755
2756   str->reset();
2757
2758   // read header
2759   //~ need to look at window size?
2760   endOfBlock = eof = gTrue;
2761   cmf = str->getChar();
2762   flg = str->getChar();
2763   if (cmf == EOF || flg == EOF)
2764     return;
2765   if ((cmf & 0x0f) != 0x08) {
2766     error(getPos(), "Unknown compression method in flate stream");
2767     return;
2768   }
2769   if ((((cmf << 8) + flg) % 31) != 0) {
2770     error(getPos(), "Bad FCHECK in flate stream");
2771     return;
2772   }
2773   if (flg & 0x20) {
2774     error(getPos(), "FDICT bit set in flate stream");
2775     return;
2776   }
2777
2778   // initialize
2779   index = 0;
2780   remain = 0;
2781   codeBuf = 0;
2782   codeSize = 0;
2783   compressedBlock = gFalse;
2784   endOfBlock = gTrue;
2785   eof = gFalse;
2786 }
2787
2788 int FlateStream::getChar() {
2789   int c;
2790
2791   if (pred) {
2792     return pred->getChar();
2793   }
2794   while (remain == 0) {
2795     if (endOfBlock && eof)
2796       return EOF;
2797     readSome();
2798   }
2799   c = buf[index];
2800   index = (index + 1) & flateMask;
2801   --remain;
2802   return c;
2803 }
2804
2805 int FlateStream::lookChar() {
2806   int c;
2807
2808   if (pred) {
2809     return pred->lookChar();
2810   }
2811   while (remain == 0) {
2812     if (endOfBlock && eof)
2813       return EOF;
2814     readSome();
2815   }
2816   c = buf[index];
2817   return c;
2818 }
2819
2820 int FlateStream::getRawChar() {
2821   int c;
2822
2823   while (remain == 0) {
2824     if (endOfBlock && eof)
2825       return EOF;
2826     readSome();
2827   }
2828   c = buf[index];
2829   index = (index + 1) & flateMask;
2830   --remain;
2831   return c;
2832 }
2833
2834 GString *FlateStream::getPSFilter(char *indent) {
2835   return NULL;
2836 }
2837
2838 GBool FlateStream::isBinary(GBool last) {
2839   return str->isBinary(gTrue);
2840 }
2841
2842 void FlateStream::readSome() {
2843   int code1, code2;
2844   int len, dist;
2845   int i, j, k;
2846   int c;
2847
2848   if (endOfBlock) {
2849     if (!startBlock())
2850       return;
2851   }
2852
2853   if (compressedBlock) {
2854     if ((code1 = getHuffmanCodeWord(&litCodeTab)) == EOF)
2855       goto err;
2856     if (code1 < 256) {
2857       buf[index] = code1;
2858       remain = 1;
2859     } else if (code1 == 256) {
2860       endOfBlock = gTrue;
2861       remain = 0;
2862     } else {
2863       code1 -= 257;
2864       code2 = lengthDecode[code1].bits;
2865       if (code2 > 0 && (code2 = getCodeWord(code2)) == EOF)
2866         goto err;
2867       len = lengthDecode[code1].first + code2;
2868       if ((code1 = getHuffmanCodeWord(&distCodeTab)) == EOF)
2869         goto err;
2870       code2 = distDecode[code1].bits;
2871       if (code2 > 0 && (code2 = getCodeWord(code2)) == EOF)
2872         goto err;
2873       dist = distDecode[code1].first + code2;
2874       i = index;
2875       j = (index - dist) & flateMask;
2876       for (k = 0; k < len; ++k) {
2877         buf[i] = buf[j];
2878         i = (i + 1) & flateMask;
2879         j = (j + 1) & flateMask;
2880       }
2881       remain = len;
2882     }
2883
2884   } else {
2885     len = (blockLen < flateWindow) ? blockLen : flateWindow;
2886     for (i = 0, j = index; i < len; ++i, j = (j + 1) & flateMask) {
2887       if ((c = str->getChar()) == EOF) {
2888         endOfBlock = eof = gTrue;
2889         break;
2890       }
2891       buf[j] = c & 0xff;
2892     }
2893     remain = i;
2894     blockLen -= len;
2895     if (blockLen == 0)
2896       endOfBlock = gTrue;
2897   }
2898
2899   return;
2900
2901 err:
2902   error(getPos(), "Unexpected end of file in flate stream");
2903   endOfBlock = eof = gTrue;
2904   remain = 0;
2905 }
2906
2907 GBool FlateStream::startBlock() {
2908   int blockHdr;
2909   int c;
2910   int check;
2911
2912   // read block header
2913   blockHdr = getCodeWord(3);
2914   if (blockHdr & 1)
2915     eof = gTrue;
2916   blockHdr >>= 1;
2917
2918   // uncompressed block
2919   if (blockHdr == 0) {
2920     compressedBlock = gFalse;
2921     if ((c = str->getChar()) == EOF)
2922       goto err;
2923     blockLen = c & 0xff;
2924     if ((c = str->getChar()) == EOF)
2925       goto err;
2926     blockLen |= (c & 0xff) << 8;
2927     if ((c = str->getChar()) == EOF)
2928       goto err;
2929     check = c & 0xff;
2930     if ((c = str->getChar()) == EOF)
2931       goto err;
2932     check |= (c & 0xff) << 8;
2933     if (check != (~blockLen & 0xffff))
2934       error(getPos(), "Bad uncompressed block length in flate stream");
2935     codeBuf = 0;
2936     codeSize = 0;
2937
2938   // compressed block with fixed codes
2939   } else if (blockHdr == 1) {
2940     compressedBlock = gTrue;
2941     loadFixedCodes();
2942
2943   // compressed block with dynamic codes
2944   } else if (blockHdr == 2) {
2945     compressedBlock = gTrue;
2946     if (!readDynamicCodes())
2947       goto err;
2948
2949   // unknown block type
2950   } else {
2951     goto err;
2952   }
2953
2954   endOfBlock = gFalse;
2955   return gTrue;
2956
2957 err:
2958   error(getPos(), "Bad block header in flate stream");
2959   endOfBlock = eof = gTrue;
2960   return gFalse;
2961 }
2962
2963 void FlateStream::loadFixedCodes() {
2964   int i;
2965
2966   // set up code arrays
2967   litCodeTab.codes = allCodes;
2968   distCodeTab.codes = allCodes + flateMaxLitCodes;
2969
2970   // initialize literal code table
2971   for (i = 0; i <= 143; ++i)
2972     litCodeTab.codes[i].len = 8;
2973   for (i = 144; i <= 255; ++i)
2974     litCodeTab.codes[i].len = 9;
2975   for (i = 256; i <= 279; ++i)
2976     litCodeTab.codes[i].len = 7;
2977   for (i = 280; i <= 287; ++i)
2978     litCodeTab.codes[i].len = 8;
2979   compHuffmanCodes(&litCodeTab, flateMaxLitCodes);
2980
2981   // initialize distance code table
2982   for (i = 0; i < 5; ++i)
2983     distCodeTab.start[i] = 0;
2984   distCodeTab.start[5] = 0;
2985   for (i = 6; i <= flateMaxHuffman+1; ++i)
2986     distCodeTab.start[6] = flateMaxDistCodes;
2987   for (i = 0; i < flateMaxDistCodes; ++i) {
2988     distCodeTab.codes[i].len = 5;
2989     distCodeTab.codes[i].code = i;
2990     distCodeTab.codes[i].val = i;
2991   }
2992 }
2993
2994 GBool FlateStream::readDynamicCodes() {
2995   int numCodeLenCodes;
2996   int numLitCodes;
2997   int numDistCodes;
2998   FlateCode codeLenCodes[flateMaxCodeLenCodes];
2999   FlateHuffmanTab codeLenCodeTab;
3000   int len, repeat, code;
3001   int i;
3002
3003   // read lengths
3004   if ((numLitCodes = getCodeWord(5)) == EOF)
3005     goto err;
3006   numLitCodes += 257;
3007   if ((numDistCodes = getCodeWord(5)) == EOF)
3008     goto err;
3009   numDistCodes += 1;
3010   if ((numCodeLenCodes = getCodeWord(4)) == EOF)
3011     goto err;
3012   numCodeLenCodes += 4;
3013   if (numLitCodes > flateMaxLitCodes ||
3014       numDistCodes > flateMaxDistCodes ||
3015       numCodeLenCodes > flateMaxCodeLenCodes)
3016     goto err;
3017
3018   // read code length code table
3019   codeLenCodeTab.codes = codeLenCodes;
3020   for (i = 0; i < flateMaxCodeLenCodes; ++i)
3021     codeLenCodes[i].len = 0;
3022   for (i = 0; i < numCodeLenCodes; ++i) {
3023     if ((codeLenCodes[codeLenCodeMap[i]].len = getCodeWord(3)) == -1)
3024       goto err;
3025   }
3026   compHuffmanCodes(&codeLenCodeTab, flateMaxCodeLenCodes);
3027
3028   // set up code arrays
3029   litCodeTab.codes = allCodes;
3030   distCodeTab.codes = allCodes + numLitCodes;
3031
3032   // read literal and distance code tables
3033   len = 0;
3034   repeat = 0;
3035   i = 0;
3036   while (i < numLitCodes + numDistCodes) {
3037     if ((code = getHuffmanCodeWord(&codeLenCodeTab)) == EOF)
3038       goto err;
3039     if (code == 16) {
3040       if ((repeat = getCodeWord(2)) == EOF)
3041         goto err;
3042       for (repeat += 3; repeat > 0; --repeat)
3043         allCodes[i++].len = len;
3044     } else if (code == 17) {
3045       if ((repeat = getCodeWord(3)) == EOF)
3046         goto err;
3047       len = 0;
3048       for (repeat += 3; repeat > 0; --repeat)
3049         allCodes[i++].len = 0;
3050     } else if (code == 18) {
3051       if ((repeat = getCodeWord(7)) == EOF)
3052         goto err;
3053       len = 0;
3054       for (repeat += 11; repeat > 0; --repeat)
3055         allCodes[i++].len = 0;
3056     } else {
3057       allCodes[i++].len = len = code;
3058     }
3059   }
3060   compHuffmanCodes(&litCodeTab, numLitCodes);
3061   compHuffmanCodes(&distCodeTab, numDistCodes);
3062
3063   return gTrue;
3064
3065 err:
3066   error(getPos(), "Bad dynamic code table in flate stream");
3067   return gFalse;
3068 }
3069
3070 // On entry, the <tab->codes> array contains the lengths of each code,
3071 // stored in code value order.  This function computes the code words.
3072 // The result is sorted in order of (1) code length and (2) code word.
3073 // The length values are no longer valid.  The <tab->start> array is
3074 // filled with the indexes of the first code of each length.
3075 void FlateStream::compHuffmanCodes(FlateHuffmanTab *tab, int n) {
3076   int numLengths[flateMaxHuffman+1];
3077   int nextCode[flateMaxHuffman+1];
3078   int nextIndex[flateMaxHuffman+2];
3079   int code;
3080   int i, j;
3081
3082   // count number of codes for each code length
3083   for (i = 0; i <= flateMaxHuffman; ++i)
3084     numLengths[i] = 0;
3085   for (i = 0; i < n; ++i)
3086     ++numLengths[tab->codes[i].len];
3087
3088   // compute first index for each length
3089   tab->start[0] = nextIndex[0] = 0;
3090   for (i = 1; i <= flateMaxHuffman + 1; ++i)
3091     tab->start[i] = nextIndex[i] = tab->start[i-1] + numLengths[i-1];
3092
3093   // compute first code for each length
3094   code = 0;
3095   numLengths[0] = 0;
3096   for (i = 1; i <= flateMaxHuffman; ++i) {
3097     code = (code + numLengths[i-1]) << 1;
3098     nextCode[i] = code;
3099   }
3100
3101   // compute the codes -- this permutes the codes array from value
3102   // order to length/code order
3103   for (i = 0; i < n; ++i) {
3104     j = nextIndex[tab->codes[i].len]++;
3105     if (tab->codes[i].len == 0)
3106       tab->codes[j].code = 0;
3107     else
3108       tab->codes[j].code = nextCode[tab->codes[i].len]++;
3109     tab->codes[j].val = i;
3110   }
3111 }
3112
3113 int FlateStream::getHuffmanCodeWord(FlateHuffmanTab *tab) {
3114   int len;
3115   int code;
3116   int c;
3117   int i, j;
3118
3119   code = 0;
3120   for (len = 1; len <= flateMaxHuffman; ++len) {
3121
3122     // add a bit to the code
3123     if (codeSize == 0) {
3124       if ((c = str->getChar()) == EOF)
3125         return EOF;
3126       codeBuf = c & 0xff;
3127       codeSize = 8;
3128     }
3129     code = (code << 1) | (codeBuf & 1);
3130     codeBuf >>= 1;
3131     --codeSize;
3132
3133     // look for code
3134     i = tab->start[len];
3135     j = tab->start[len + 1];
3136     if (i < j && code >= tab->codes[i].code && code <= tab->codes[j-1].code) {
3137       i += code - tab->codes[i].code;
3138       return tab->codes[i].val;
3139     }
3140   }
3141
3142   // not found
3143   error(getPos(), "Bad code (%04x) in flate stream", code);
3144   return EOF;
3145 }
3146
3147 int FlateStream::getCodeWord(int bits) {
3148   int c;
3149
3150   while (codeSize < bits) {
3151     if ((c = str->getChar()) == EOF)
3152       return EOF;
3153     codeBuf |= (c & 0xff) << codeSize;
3154     codeSize += 8;
3155   }
3156   c = codeBuf & ((1 << bits) - 1);
3157   codeBuf >>= bits;
3158   codeSize -= bits;
3159   return c;
3160 }
3161
3162 //------------------------------------------------------------------------
3163 // EOFStream
3164 //------------------------------------------------------------------------
3165
3166 EOFStream::EOFStream(Stream *str1) {
3167   str = str1;
3168 }
3169
3170 EOFStream::~EOFStream() {
3171   delete str;
3172 }
3173
3174 //------------------------------------------------------------------------
3175 // FixedLengthEncoder
3176 //------------------------------------------------------------------------
3177
3178 FixedLengthEncoder::FixedLengthEncoder(Stream *str1, int length1) {
3179   str = str1;
3180   length = length1;
3181   count = 0;
3182 }
3183
3184 FixedLengthEncoder::~FixedLengthEncoder() {
3185   if (str->isEncoder())
3186     delete str;
3187 }
3188
3189 void FixedLengthEncoder::reset() {
3190   str->reset();
3191   count = 0;
3192 }
3193
3194 int FixedLengthEncoder::getChar() {
3195   if (length >= 0 && count >= length)
3196     return EOF;
3197   ++count;
3198   return str->getChar();
3199 }
3200
3201 int FixedLengthEncoder::lookChar() {
3202   if (length >= 0 && count >= length)
3203     return EOF;
3204   return str->getChar();
3205 }
3206
3207 //------------------------------------------------------------------------
3208 // ASCII85Encoder
3209 //------------------------------------------------------------------------
3210
3211 ASCII85Encoder::ASCII85Encoder(Stream *str1) {
3212   str = str1;
3213   bufPtr = bufEnd = buf;
3214   lineLen = 0;
3215   eof = gFalse;
3216 }
3217
3218 ASCII85Encoder::~ASCII85Encoder() {
3219   if (str->isEncoder())
3220     delete str;
3221 }
3222
3223 void ASCII85Encoder::reset() {
3224   str->reset();
3225   bufPtr = bufEnd = buf;
3226   lineLen = 0;
3227   eof = gFalse;
3228 }
3229
3230 GBool ASCII85Encoder::fillBuf() {
3231   Gulong t;
3232   char buf1[5];
3233   int c;
3234   int n, i;
3235
3236   if (eof)
3237     return gFalse;
3238   t = 0;
3239   for (n = 0; n < 4; ++n) {
3240     if ((c = str->getChar()) == EOF)
3241       break;
3242     t = (t << 8) + c;
3243   }
3244   bufPtr = bufEnd = buf;
3245   if (n > 0) {
3246     if (n == 4 && t == 0) {
3247       *bufEnd++ = 'z';
3248       if (++lineLen == 65) {
3249         *bufEnd++ = '\n';
3250         lineLen = 0;
3251       }
3252     } else {
3253       if (n < 4)
3254         t <<= 8 * (4 - n);
3255       for (i = 4; i >= 0; --i) {
3256         buf1[i] = (char)(t % 85 + 0x21);
3257         t /= 85;
3258       }
3259       for (i = 0; i <= n; ++i) {
3260         *bufEnd++ = buf1[i];
3261         if (++lineLen == 65) {
3262           *bufEnd++ = '\n';
3263           lineLen = 0;
3264         }
3265       }
3266     }
3267   }
3268   if (n < 4) {
3269     *bufEnd++ = '~';
3270     *bufEnd++ = '>';
3271     eof = gTrue;
3272   }
3273   return bufPtr < bufEnd;
3274 }
3275
3276 //------------------------------------------------------------------------
3277 // RunLengthEncoder
3278 //------------------------------------------------------------------------
3279
3280 RunLengthEncoder::RunLengthEncoder(Stream *str1) {
3281   str = str1;
3282   bufPtr = bufEnd = nextEnd = buf;
3283   eof = gFalse;
3284 }
3285
3286 RunLengthEncoder::~RunLengthEncoder() {
3287   if (str->isEncoder())
3288     delete str;
3289 }
3290
3291 void RunLengthEncoder::reset() {
3292   str->reset();
3293   bufPtr = bufEnd = nextEnd = buf;
3294   eof = gFalse;
3295 }
3296
3297 //
3298 // When fillBuf finishes, buf[] looks like this:
3299 //   +-----+--------------+-----------------+--
3300 //   + tag | ... data ... | next 0, 1, or 2 |
3301 //   +-----+--------------+-----------------+--
3302 //    ^                    ^                 ^
3303 //    bufPtr               bufEnd            nextEnd
3304 //
3305 GBool RunLengthEncoder::fillBuf() {
3306   int c, c1, c2;
3307   int n;
3308
3309   // already hit EOF?
3310   if (eof)
3311     return gFalse;
3312
3313   // grab two bytes
3314   if (nextEnd < bufEnd + 1) {
3315     if ((c1 = str->getChar()) == EOF) {
3316       eof = gTrue;
3317       return gFalse;
3318     }
3319   } else {
3320     c1 = bufEnd[0] & 0xff;
3321   }
3322   if (nextEnd < bufEnd + 2) {
3323     if ((c2 = str->getChar()) == EOF) {
3324       eof = gTrue;
3325       buf[0] = 0;
3326       buf[1] = c1;
3327       bufPtr = buf;
3328       bufEnd = &buf[2];
3329       return gTrue;
3330     }
3331   } else {
3332     c2 = bufEnd[1] & 0xff;
3333   }
3334
3335   // check for repeat
3336   if (c1 == c2) {
3337     n = 2;
3338     while (n < 128 && (c = str->getChar()) == c1)
3339       ++n;
3340     buf[0] = (char)(257 - n);
3341     buf[1] = c1;
3342     bufEnd = &buf[2];
3343     if (c == EOF) {
3344       eof = gTrue;
3345     } else if (n < 128) {
3346       buf[2] = c;
3347       nextEnd = &buf[3];
3348     } else {
3349       nextEnd = bufEnd;
3350     }
3351
3352   // get up to 128 chars
3353   } else {
3354     buf[1] = c1;
3355     buf[2] = c2;
3356     n = 2;
3357     while (n < 128) {
3358       if ((c = str->getChar()) == EOF) {
3359         eof = gTrue;
3360         break;
3361       }
3362       ++n;
3363       buf[n] = c;
3364       if (buf[n] == buf[n-1])
3365         break;
3366     }
3367     if (buf[n] == buf[n-1]) {
3368       buf[0] = (char)(n-2-1);
3369       bufEnd = &buf[n-1];
3370       nextEnd = &buf[n+1];
3371     } else {
3372       buf[0] = (char)(n-1);
3373       bufEnd = nextEnd = &buf[n+1];
3374     }
3375   }
3376   bufPtr = buf;
3377   return gTrue;
3378 }