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