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