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