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