Stream.cc 117 KB
Newer Older
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1 2 3 4 5 6 7
//========================================================================
//
// Stream.cc
//
// Copyright 1996-2003 Glyph & Cog, LLC
//
//========================================================================
8 9 10 11 12

//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
13 14 15
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
16
// Copyright (C) 2005 Jeff Muizelaar <jeff@infidigm.net>
17
// Copyright (C) 2006-2010, 2012-2014, 2016, 2017, 2018 Albert Astals Cid <aacid@kde.org>
18 19
// Copyright (C) 2007 Krzysztof Kowalczyk <kkowalczyk@gmail.com>
// Copyright (C) 2008 Julien Rebetez <julien@fhtagn.net>
20
// Copyright (C) 2009 Carlos Garcia Campos <carlosgc@gnome.org>
Glenn Ganz's avatar
Glenn Ganz committed
21
// Copyright (C) 2009 Glenn Ganz <glenn.ganz@uptime.ch>
Hib Eris's avatar
Hib Eris committed
22 23
// Copyright (C) 2009 Stefan Thomas <thomas@eload24.com>
// Copyright (C) 2010 Hib Eris <hib@hiberis.nl>
24
// Copyright (C) 2010 Tomas Hoger <thoger@redhat.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
25
// Copyright (C) 2011, 2012, 2016 William Bader <williambader@hotmail.com>
Thomas Freitag's avatar
Thomas Freitag committed
26
// Copyright (C) 2012, 2013 Thomas Freitag <Thomas.Freitag@alfa.de>
Oliver Sander's avatar
Oliver Sander committed
27
// Copyright (C) 2012 Oliver Sander <sander@mi.fu-berlin.de>
28
// Copyright (C) 2012 Fabio D'Urso <fabiodurso@hotmail.it>
29
// Copyright (C) 2012 Even Rouault <even.rouault@mines-paris.org>
Adrian Johnson's avatar
Adrian Johnson committed
30
// Copyright (C) 2013, 2017, 2018 Adrian Johnson <ajohnson@redneon.com>
31
// Copyright (C) 2013 Adam Reichold <adamreichold@myopera.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
32
// Copyright (C) 2013 Pino Toscano <pino@kde.org>
Albert Astals Cid's avatar
Albert Astals Cid committed
33
// Copyright (C) 2015 Suzuki Toshiya <mpsuzuki@hiroshima-u.ac.jp>
34
// Copyright (C) 2015 Jason Crain <jason@aquaticape.us>
35
// Copyright (C) 2017 Jose Aliste <jaliste@src.gnome.org>
36
// Copyright (C) 2017 Kay Dohmann <k.dohmann@gmx.net>
37 38 39 40 41
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
Kristian Høgsberg's avatar
Kristian Høgsberg committed
42 43 44 45 46 47 48 49 50 51

#include <config.h>

#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
52
#include <limits.h>
53
#ifdef HAVE_UNISTD_H
Kristian Høgsberg's avatar
Kristian Høgsberg committed
54 55 56 57 58 59 60 61 62
#include <unistd.h>
#endif
#include <string.h>
#include <ctype.h>
#include "goo/gmem.h"
#include "goo/gfile.h"
#include "poppler-config.h"
#include "Error.h"
#include "Object.h"
63 64
#include "Lexer.h"
#include "GfxState.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
65
#include "Stream.h"
66
#include "XRef.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
67 68
#include "JBIG2Stream.h"
#include "Stream-CCITT.h"
Hib Eris's avatar
Hib Eris committed
69
#include "CachedFile.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
70

71 72 73 74
#ifdef ENABLE_LIBJPEG
#include "DCTStream.h"
#endif

75
#ifdef ENABLE_ZLIB_UNCOMPRESS
76 77 78
#include "FlateStream.h"
#endif

79 80 81 82 83 84
#ifdef ENABLE_LIBOPENJPEG
#include "JPEG2000Stream.h"
#else
#include "JPXStream.h"
#endif

Kristian Høgsberg's avatar
Kristian Høgsberg committed
85 86 87 88 89 90 91 92 93 94 95 96
#ifdef __DJGPP__
static GBool setDJSYSFLAGS = gFalse;
#endif

#ifdef VMS
#ifdef __GNUC__
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
#endif
#endif

97
#ifdef MULTITHREADED
98
#  define streamLocker()   MutexLocker locker(&mutex)
Thomas Freitag's avatar
Thomas Freitag committed
99
#else
100
#  define streamLocker()
Thomas Freitag's avatar
Thomas Freitag committed
101
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
102 103 104 105 106 107
//------------------------------------------------------------------------
// Stream (base class)
//------------------------------------------------------------------------

Stream::Stream() {
  ref = 1;
108
#ifdef MULTITHREADED
Thomas Freitag's avatar
Thomas Freitag committed
109 110
  gInitMutex(&mutex);
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
111 112 113
}

Stream::~Stream() {
114
#ifdef MULTITHREADED
Thomas Freitag's avatar
Thomas Freitag committed
115 116 117 118 119
  gDestroyMutex(&mutex);
#endif
}

int Stream::incRef() {
120
  streamLocker();
Thomas Freitag's avatar
Thomas Freitag committed
121 122 123 124 125
  ++ref;
  return ref;
}

int Stream::decRef() {
126
  streamLocker();
Thomas Freitag's avatar
Thomas Freitag committed
127 128
  --ref;
  return ref;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
129 130 131 132 133 134
}

void Stream::close() {
}

int Stream::getRawChar() {
135
  error(errInternal, -1, "Internal: called getRawChar() on non-predictor stream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
136 137 138
  return EOF;
}

139
int Stream::getChars(int nChars, Guchar *buffer) {
140
  error(errInternal, -1, "Internal: called getChars() on non-predictor stream");
141 142 143 144
  return 0;
}

void Stream::getRawChars(int nChars, int *buffer) {
145
  error(errInternal, -1, "Internal: called getRawChars() on non-predictor stream");
146 147
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
148 149 150 151
char *Stream::getLine(char *buf, int size) {
  int i;
  int c;

152
  if (lookChar() == EOF || size < 0)
153
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  for (i = 0; i < size - 1; ++i) {
    c = getChar();
    if (c == EOF || c == '\n')
      break;
    if (c == '\r') {
      if ((c = lookChar()) == '\n')
	getChar();
      break;
    }
    buf[i] = c;
  }
  buf[i] = '\0';
  return buf;
}

169
GooString *Stream::getPSFilter(int psLevel, const char *indent) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
170 171 172
  return new GooString();
}

173
Stream *Stream::addFilters(Dict *dict, int recursion) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
174 175 176 177 178 179
  Object obj, obj2;
  Object params, params2;
  Stream *str;
  int i;

  str = this;
Albert Astals Cid's avatar
Albert Astals Cid committed
180
  obj = dict->lookup("Filter", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
181
  if (obj.isNull()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
182
    obj = dict->lookup("F", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
183
  }
Albert Astals Cid's avatar
Albert Astals Cid committed
184
  params = dict->lookup("DecodeParms", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
185
  if (params.isNull()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
186
    params = dict->lookup("DP", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
187 188
  }
  if (obj.isName()) {
189
    str = makeFilter(obj.getName(), str, &params, recursion, dict);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
190 191
  } else if (obj.isArray()) {
    for (i = 0; i < obj.arrayGetLength(); ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
192
      obj2 = obj.arrayGet(i, recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
193
      if (params.isArray())
Albert Astals Cid's avatar
Albert Astals Cid committed
194
	params2 = params.arrayGet(i, recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
195
      else
Albert Astals Cid's avatar
Albert Astals Cid committed
196
	params2.setToNull();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
197
      if (obj2.isName()) {
Thomas Freitag's avatar
Thomas Freitag committed
198
	str = makeFilter(obj2.getName(), str, &params2, recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
199
      } else {
200
	error(errSyntaxError, getPos(), "Bad filter name");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
201 202 203 204
	str = new EOFStream(str);
      }
    }
  } else if (!obj.isNull()) {
205
    error(errSyntaxError, getPos(), "Bad 'Filter' attribute in stream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
206 207 208 209 210
  }

  return str;
}

211
Stream *Stream::makeFilter(const char *name, Stream *str, Object *params, int recursion, Dict *dict) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
212 213 214 215 216
  int pred;			// parameters
  int colors;
  int bits;
  int early;
  int encoding;
217
  GBool endOfLine, byteAlign, endOfBlock, black, damagedRowsBeforeError;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231
  int columns, rows;
  Object globals, obj;

  if (!strcmp(name, "ASCIIHexDecode") || !strcmp(name, "AHx")) {
    str = new ASCIIHexStream(str);
  } else if (!strcmp(name, "ASCII85Decode") || !strcmp(name, "A85")) {
    str = new ASCII85Stream(str);
  } else if (!strcmp(name, "LZWDecode") || !strcmp(name, "LZW")) {
    pred = 1;
    columns = 1;
    colors = 1;
    bits = 8;
    early = 1;
    if (params->isDict()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
232
      obj = params->dictLookup("Predictor", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
233 234
      if (obj.isInt())
	pred = obj.getInt();
Albert Astals Cid's avatar
Albert Astals Cid committed
235
      obj = params->dictLookup("Columns", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
236 237
      if (obj.isInt())
	columns = obj.getInt();
Albert Astals Cid's avatar
Albert Astals Cid committed
238
      obj = params->dictLookup("Colors", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
239 240
      if (obj.isInt())
	colors = obj.getInt();
Albert Astals Cid's avatar
Albert Astals Cid committed
241
      obj = params->dictLookup("BitsPerComponent", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
242 243
      if (obj.isInt())
	bits = obj.getInt();
Albert Astals Cid's avatar
Albert Astals Cid committed
244
      obj = params->dictLookup("EarlyChange", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258
      if (obj.isInt())
	early = obj.getInt();
    }
    str = new LZWStream(str, pred, columns, colors, bits, early);
  } else if (!strcmp(name, "RunLengthDecode") || !strcmp(name, "RL")) {
    str = new RunLengthStream(str);
  } else if (!strcmp(name, "CCITTFaxDecode") || !strcmp(name, "CCF")) {
    encoding = 0;
    endOfLine = gFalse;
    byteAlign = gFalse;
    columns = 1728;
    rows = 0;
    endOfBlock = gTrue;
    black = gFalse;
259 260
    damagedRowsBeforeError = 0;
  if (params->isDict()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
261
      obj = params->dictLookup("K", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
262 263 264
      if (obj.isInt()) {
	encoding = obj.getInt();
      }
Albert Astals Cid's avatar
Albert Astals Cid committed
265
      obj = params->dictLookup("EndOfLine", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
266 267 268
      if (obj.isBool()) {
	endOfLine = obj.getBool();
      }
Albert Astals Cid's avatar
Albert Astals Cid committed
269
      obj = params->dictLookup("EncodedByteAlign", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
270 271 272
      if (obj.isBool()) {
	byteAlign = obj.getBool();
      }
Albert Astals Cid's avatar
Albert Astals Cid committed
273
      obj = params->dictLookup("Columns", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
274 275 276
      if (obj.isInt()) {
	columns = obj.getInt();
      }
Albert Astals Cid's avatar
Albert Astals Cid committed
277
      obj = params->dictLookup("Rows", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
278 279 280
      if (obj.isInt()) {
	rows = obj.getInt();
      }
Albert Astals Cid's avatar
Albert Astals Cid committed
281
      obj = params->dictLookup("EndOfBlock", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
282 283 284
      if (obj.isBool()) {
	endOfBlock = obj.getBool();
      }
Albert Astals Cid's avatar
Albert Astals Cid committed
285
      obj = params->dictLookup("BlackIs1", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
286 287 288
      if (obj.isBool()) {
	black = obj.getBool();
      }
289 290 291 292
      obj = params->dictLookup("DamagedRowsBeforeError", recursion);
      if (obj.isInt()) {
	damagedRowsBeforeError = obj.getInt();
      }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
293 294
    }
    str = new CCITTFaxStream(str, encoding, endOfLine, byteAlign,
295
			     columns, rows, endOfBlock, black, damagedRowsBeforeError);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
296
  } else if (!strcmp(name, "DCTDecode") || !strcmp(name, "DCT")) {
297
#ifdef HAVE_DCT_DECODER
298
    int colorXform = -1;
299
    if (params->isDict()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
300 301
      obj = params->dictLookup("ColorTransform", recursion);
      if (obj.isInt()) {
302 303 304
	colorXform = obj.getInt();
      }
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
305
    str = new DCTStream(str, colorXform, dict, recursion);
306 307 308 309
#else
    error(errSyntaxError, getPos(), "Unknown filter '{0:s}'", name);
    str = new EOFStream(str);
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
310 311 312 313 314 315
  } else if (!strcmp(name, "FlateDecode") || !strcmp(name, "Fl")) {
    pred = 1;
    columns = 1;
    colors = 1;
    bits = 8;
    if (params->isDict()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
316
      obj = params->dictLookup("Predictor", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
317 318
      if (obj.isInt())
	pred = obj.getInt();
Albert Astals Cid's avatar
Albert Astals Cid committed
319
      obj = params->dictLookup("Columns", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
320 321
      if (obj.isInt())
	columns = obj.getInt();
Albert Astals Cid's avatar
Albert Astals Cid committed
322
      obj = params->dictLookup("Colors", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
323 324
      if (obj.isInt())
	colors = obj.getInt();
Albert Astals Cid's avatar
Albert Astals Cid committed
325
      obj = params->dictLookup("BitsPerComponent", recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
326 327 328 329 330 331
      if (obj.isInt())
	bits = obj.getInt();
    }
    str = new FlateStream(str, pred, columns, colors, bits);
  } else if (!strcmp(name, "JBIG2Decode")) {
    if (params->isDict()) {
332
      XRef *xref = params->getDict()->getXRef();
Albert Astals Cid's avatar
Albert Astals Cid committed
333 334
      obj = params->dictLookupNF("JBIG2Globals");
      globals = obj.fetch(xref, recursion);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
335
    }
336
    str = new JBIG2Stream(str, &globals, &obj);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
337
  } else if (!strcmp(name, "JPXDecode")) {
338
#ifdef HAVE_JPX_DECODER
Kristian Høgsberg's avatar
Kristian Høgsberg committed
339
    str = new JPXStream(str);
340 341 342 343
#else
    error(errSyntaxError, getPos(), "Unknown filter '{0:s}'", name);
    str = new EOFStream(str);
#endif
Thomas Freitag's avatar
Thomas Freitag committed
344 345 346 347 348 349
  } else if (!strcmp(name, "Crypt")) {
    if (str->getKind() == strCrypt) {
      str = str->getBaseStream();
    } else {
      error(errSyntaxError, getPos(), "Can't revert non decrypt streams");
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
350
  } else {
351
    error(errSyntaxError, getPos(), "Unknown filter '{0:s}'", name);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
352 353 354 355 356
    str = new EOFStream(str);
  }
  return str;
}

357 358 359 360 361 362 363 364 365 366 367 368 369 370
//------------------------------------------------------------------------
// OutStream
//------------------------------------------------------------------------
OutStream::OutStream ()
{
}

OutStream::~OutStream ()
{
}

//------------------------------------------------------------------------
// FileOutStream
//------------------------------------------------------------------------
Adrian Johnson's avatar
Adrian Johnson committed
371
FileOutStream::FileOutStream (FILE* fa, Goffset startA)
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
{
  f = fa;
  start = startA;
}

FileOutStream::~FileOutStream ()
{
  close ();
}

void FileOutStream::close ()
{

}

Adrian Johnson's avatar
Adrian Johnson committed
387
Goffset FileOutStream::getPos ()
388
{
389
  return Gftell(f);
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
}

void FileOutStream::put (char c)
{
  fputc(c,f);
}

void FileOutStream::printf(const char *format, ...)
{
  va_list argptr;
  va_start (argptr, format);
  vfprintf(f, format, argptr);
  va_end (argptr);
}


Kristian Høgsberg's avatar
Kristian Høgsberg committed
406 407 408 409
//------------------------------------------------------------------------
// BaseStream
//------------------------------------------------------------------------

Albert Astals Cid's avatar
Albert Astals Cid committed
410 411
BaseStream::BaseStream(Object &&dictA, Goffset lengthA) {
  dict = std::move(dictA);
Hib Eris's avatar
Hib Eris committed
412
  length = lengthA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
}

BaseStream::~BaseStream() {
}

//------------------------------------------------------------------------
// FilterStream
//------------------------------------------------------------------------

FilterStream::FilterStream(Stream *strA) {
  str = strA;
}

FilterStream::~FilterStream() {
}

void FilterStream::close() {
  str->close();
}

Adrian Johnson's avatar
Adrian Johnson committed
433
void FilterStream::setPos(Goffset pos, int dir) {
434
  error(errInternal, -1, "Internal: called setPos() on FilterStream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
}

//------------------------------------------------------------------------
// ImageStream
//------------------------------------------------------------------------

ImageStream::ImageStream(Stream *strA, int widthA, int nCompsA, int nBitsA) {
  int imgLineSize;

  str = strA;
  width = widthA;
  nComps = nCompsA;
  nBits = nBitsA;

  nVals = width * nComps;
450
  inputLineSize = (nVals * nBits + 7) >> 3;
451
  if (nComps <= 0 || nBits <= 0 || nVals > INT_MAX / nBits - 7 || width > INT_MAX / nComps) {
452 453
    inputLineSize = -1;
  }
454
  inputLine = (Guchar *)gmallocn_checkoverflow(inputLineSize, sizeof(char));
455 456 457 458 459 460 461 462
  if (nBits == 8) {
    imgLine = (Guchar *)inputLine;
  } else {
    if (nBits == 1) {
      imgLineSize = (nVals + 7) & ~7;
    } else {
      imgLineSize = nVals;
    }
463
    if (nComps <= 0 || width > INT_MAX / nComps) {
464 465
      imgLineSize = -1;
    }
466
    imgLine = (Guchar *)gmallocn_checkoverflow(imgLineSize, sizeof(Guchar));
467
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
468 469 470 471
  imgIdx = nVals;
}

ImageStream::~ImageStream() {
472 473 474 475
  if (imgLine != (Guchar *)inputLine) {
    gfree(imgLine);
  }
  gfree(inputLine);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
476 477 478 479 480 481
}

void ImageStream::reset() {
  str->reset();
}

482 483 484 485
void ImageStream::close() {
  str->close();
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
486 487 488 489
GBool ImageStream::getPixel(Guchar *pix) {
  int i;

  if (imgIdx >= nVals) {
490 491 492
    if (!getLine()) {
      return gFalse;
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
493 494 495 496 497 498 499 500 501 502 503 504 505
    imgIdx = 0;
  }
  for (i = 0; i < nComps; ++i) {
    pix[i] = imgLine[imgIdx++];
  }
  return gTrue;
}

Guchar *ImageStream::getLine() {
  Gulong buf, bitMask;
  int bits;
  int c;
  int i;
506
  Guchar *p;
507
  
508 509
  if (unlikely(inputLine == nullptr)) {
      return nullptr;
510
  }
511 512 513
 
  int readChars = str->doGetChars(inputLineSize, inputLine);
  for ( ; readChars < inputLineSize; readChars++) inputLine[readChars] = EOF;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
514
  if (nBits == 1) {
515
    p = inputLine;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
516
    for (i = 0; i < nVals; i += 8) {
517
      c = *p++;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
518 519 520 521 522 523 524 525 526 527
      imgLine[i+0] = (Guchar)((c >> 7) & 1);
      imgLine[i+1] = (Guchar)((c >> 6) & 1);
      imgLine[i+2] = (Guchar)((c >> 5) & 1);
      imgLine[i+3] = (Guchar)((c >> 4) & 1);
      imgLine[i+4] = (Guchar)((c >> 3) & 1);
      imgLine[i+5] = (Guchar)((c >> 2) & 1);
      imgLine[i+6] = (Guchar)((c >> 1) & 1);
      imgLine[i+7] = (Guchar)(c & 1);
    }
  } else if (nBits == 8) {
528
    // special case: imgLine == inputLine
529 530 531 532 533
  } else if (nBits == 16) {
    // this is a hack to support 16 bits images, everywhere
    // we assume a component fits in 8 bits, with this hack
    // we treat 16 bit images as 8 bit ones until it's fixed correctly.
    // The hack has another part on GfxImageColorMap::GfxImageColorMap
534
    p = inputLine;
535
    for (i = 0; i < nVals; ++i) {
536 537
      imgLine[i] = *p++;
      p++;
538
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
539 540 541 542
  } else {
    bitMask = (1 << nBits) - 1;
    buf = 0;
    bits = 0;
543
    p = inputLine;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
544 545
    for (i = 0; i < nVals; ++i) {
      if (bits < nBits) {
546
	buf = (buf << 8) | (*p++ & 0xff);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
547 548 549 550 551 552 553 554 555 556
	bits += 8;
      }
      imgLine[i] = (Guchar)((buf >> (bits - nBits)) & bitMask);
      bits -= nBits;
    }
  }
  return imgLine;
}

void ImageStream::skipLine() {
557
  str->doGetChars(inputLineSize, inputLine);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
558 559 560 561 562 563 564 565 566 567 568 569 570
}

//------------------------------------------------------------------------
// StreamPredictor
//------------------------------------------------------------------------

StreamPredictor::StreamPredictor(Stream *strA, int predictorA,
				 int widthA, int nCompsA, int nBitsA) {
  str = strA;
  predictor = predictorA;
  width = widthA;
  nComps = nCompsA;
  nBits = nBitsA;
571
  predLine = nullptr;
572
  ok = gFalse;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
573

574
  nVals = width * nComps;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
575
  pixBytes = (nComps * nBits + 7) >> 3;
576
  rowBytes = ((nVals * nBits + 7) >> 3) + pixBytes;
577 578 579 580 581
  if (width <= 0 || nComps <= 0 || nBits <= 0 ||
      nComps > gfxColorMaxComps ||
      nBits > 16 ||
      width >= INT_MAX / nComps ||      // check for overflow in nVals
      nVals >= (INT_MAX - 7) / nBits) { // check for overflow in rowBytes
582 583
    return;
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
584 585 586
  predLine = (Guchar *)gmalloc(rowBytes);
  memset(predLine, 0, rowBytes);
  predIdx = rowBytes;
587 588

  ok = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
}

StreamPredictor::~StreamPredictor() {
  gfree(predLine);
}

int StreamPredictor::lookChar() {
  if (predIdx >= rowBytes) {
    if (!getNextLine()) {
      return EOF;
    }
  }
  return predLine[predIdx];
}

int StreamPredictor::getChar() {
605 606 607 608 609 610
  if (predIdx >= rowBytes) {
    if (!getNextLine()) {
      return EOF;
    }
  }
  return predLine[predIdx++];
611 612
}

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
int StreamPredictor::getChars(int nChars, Guchar *buffer) {
  int n, m;

  n = 0;
  while (n < nChars) {
    if (predIdx >= rowBytes) {
      if (!getNextLine()) {
	break;
      }
    }
    m = rowBytes - predIdx;
    if (m > nChars - n) {
      m = nChars - n;
    }
    memcpy(buffer + n, predLine + predIdx, m);
    predIdx += m;
    n += m;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
630
  }
631
  return n;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
632 633 634 635
}

GBool StreamPredictor::getNextLine() {
  int curPred;
636
  Guchar upLeftBuf[gfxColorMaxComps * 2 + 1];
Kristian Høgsberg's avatar
Kristian Høgsberg committed
637 638 639 640
  int left, up, upLeft, p, pa, pb, pc;
  int c;
  Gulong inBuf, outBuf, bitMask;
  int inBits, outBits;
641
  int i, j, k, kk;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
642 643 644 645 646 647 648 649 650 651 652 653

  // get PNG optimum predictor number
  if (predictor >= 10) {
    if ((curPred = str->getRawChar()) == EOF) {
      return gFalse;
    }
    curPred += 10;
  } else {
    curPred = predictor;
  }

  // read the raw line, apply PNG (byte) predictor
654 655
  int *rawCharLine = new int[rowBytes - pixBytes];
  str->getRawChars(rowBytes - pixBytes, rawCharLine);
656
  memset(upLeftBuf, 0, pixBytes + 1);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
657
  for (i = pixBytes; i < rowBytes; ++i) {
658 659 660
    for (j = pixBytes; j > 0; --j) {
      upLeftBuf[j] = upLeftBuf[j-1];
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
661
    upLeftBuf[0] = predLine[i];
662
    if ((c = rawCharLine[i - pixBytes]) == EOF) {
663 664 665 666 667 668
      if (i > pixBytes) {
	// this ought to return false, but some (broken) PDF files
	// contain truncated image data, and Adobe apparently reads the
	// last partial line
	break;
      }
Albert Astals Cid's avatar
Albert Astals Cid committed
669
      delete[] rawCharLine;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
      return gFalse;
    }
    switch (curPred) {
    case 11:			// PNG sub
      predLine[i] = predLine[i - pixBytes] + (Guchar)c;
      break;
    case 12:			// PNG up
      predLine[i] = predLine[i] + (Guchar)c;
      break;
    case 13:			// PNG average
      predLine[i] = ((predLine[i - pixBytes] + predLine[i]) >> 1) +
	            (Guchar)c;
      break;
    case 14:			// PNG Paeth
      left = predLine[i - pixBytes];
      up = predLine[i];
      upLeft = upLeftBuf[pixBytes];
      p = left + up - upLeft;
      if ((pa = p - left) < 0)
	pa = -pa;
      if ((pb = p - up) < 0)
	pb = -pb;
      if ((pc = p - upLeft) < 0)
	pc = -pc;
      if (pa <= pb && pa <= pc)
	predLine[i] = left + (Guchar)c;
      else if (pb <= pc)
	predLine[i] = up + (Guchar)c;
      else
	predLine[i] = upLeft + (Guchar)c;
      break;
    case 10:			// PNG none
    default:			// no predictor or TIFF predictor
      predLine[i] = (Guchar)c;
      break;
    }
  }
707
  delete[] rawCharLine;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

  // apply TIFF (component) predictor
  if (predictor == 2) {
    if (nBits == 1) {
      inBuf = predLine[pixBytes - 1];
      for (i = pixBytes; i < rowBytes; i += 8) {
	// 1-bit add is just xor
	inBuf = (inBuf << 8) | predLine[i];
	predLine[i] ^= inBuf >> nComps;
      }
    } else if (nBits == 8) {
      for (i = pixBytes; i < rowBytes; ++i) {
	predLine[i] += predLine[i - nComps];
      }
    } else {
723
      memset(upLeftBuf, 0, nComps + 1);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
724 725 726 727
      bitMask = (1 << nBits) - 1;
      inBuf = outBuf = 0;
      inBits = outBits = 0;
      j = k = pixBytes;
728 729
      for (i = 0; i < width; ++i) {
	for (kk = 0; kk < nComps; ++kk) {
730 731 732 733 734 735 736
	  if (inBits < nBits) {
	    inBuf = (inBuf << 8) | (predLine[j++] & 0xff);
	    inBits += 8;
	  }
	  upLeftBuf[kk] = (Guchar)((upLeftBuf[kk] +
				    (inBuf >> (inBits - nBits))) & bitMask);
	  inBits -= nBits;
737
	  outBuf = (outBuf << nBits) | upLeftBuf[kk];
738
	  outBits += nBits;
739
	  if (outBits >= 8) {
740
	    predLine[k++] = (Guchar)(outBuf >> (outBits - 8));
741 742
	    outBits -= 8;
	  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
743 744 745
	}
      }
      if (outBits > 0) {
746 747
	predLine[k++] = (Guchar)((outBuf << (8 - outBits)) +
				 (inBuf & ((1 << (8 - outBits)) - 1)));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
748 749 750 751 752 753 754 755 756 757 758 759 760 761
      }
    }
  }

  // reset to start of line
  predIdx = pixBytes;

  return gTrue;
}

//------------------------------------------------------------------------
// FileStream
//------------------------------------------------------------------------

762
FileStream::FileStream(GooFile* fileA, Goffset startA, GBool limitedA,
Albert Astals Cid's avatar
Albert Astals Cid committed
763 764
		       Goffset lengthA, Object &&dictA):
    BaseStream(std::move(dictA), lengthA) {
765 766
  file = fileA;
  offset = start = startA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
767 768 769 770 771 772 773 774 775 776 777 778
  limited = limitedA;
  length = lengthA;
  bufPtr = bufEnd = buf;
  bufPos = start;
  savePos = 0;
  saved = gFalse;
}

FileStream::~FileStream() {
  close();
}

Thomas Freitag's avatar
Thomas Freitag committed
779
BaseStream *FileStream::copy() {
Albert Astals Cid's avatar
Albert Astals Cid committed
780
  return new FileStream(file, start, limited, length, dict.copy());
Thomas Freitag's avatar
Thomas Freitag committed
781 782
}

Adrian Johnson's avatar
Adrian Johnson committed
783
Stream *FileStream::makeSubStream(Goffset startA, GBool limitedA,
Albert Astals Cid's avatar
Albert Astals Cid committed
784 785
				  Goffset lengthA, Object &&dictA) {
  return new FileStream(file, startA, limitedA, lengthA, std::move(dictA));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
786 787 788
}

void FileStream::reset() {
789 790
  savePos = offset;
  offset = start;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
791 792 793 794 795 796 797
  saved = gTrue;
  bufPtr = bufEnd = buf;
  bufPos = start;
}

void FileStream::close() {
  if (saved) {
798
    offset = savePos;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
    saved = gFalse;
  }
}

GBool FileStream::fillBuf() {
  int n;

  bufPos += bufEnd - buf;
  bufPtr = bufEnd = buf;
  if (limited && bufPos >= start + length) {
    return gFalse;
  }
  if (limited && bufPos + fileStreamBufSize > start + length) {
    n = start + length - bufPos;
  } else {
    n = fileStreamBufSize;
  }
816
  n = file->read(buf, n, offset);
817 818 819
  if (n == -1) {
    return gFalse;
  }
820
  offset += n;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
821 822 823 824 825 826 827
  bufEnd = buf + n;
  if (bufPtr >= bufEnd) {
    return gFalse;
  }
  return gTrue;
}

Adrian Johnson's avatar
Adrian Johnson committed
828 829
void FileStream::setPos(Goffset pos, int dir) {
  Goffset size;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
830 831

  if (dir >= 0) {
832
    offset = bufPos = pos;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
833
  } else {
834
    size = file->size();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
835
    if (pos > size)
Adrian Johnson's avatar
Adrian Johnson committed
836
      pos = size;
837 838
    offset = size - pos;
    bufPos = offset;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
839 840 841 842
  }
  bufPtr = bufEnd = buf;
}

Adrian Johnson's avatar
Adrian Johnson committed
843
void FileStream::moveStart(Goffset delta) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
844 845 846 847 848
  start += delta;
  bufPtr = bufEnd = buf;
  bufPos = start;
}

Hib Eris's avatar
Hib Eris committed
849 850 851 852
//------------------------------------------------------------------------
// CachedFileStream
//------------------------------------------------------------------------

Adrian Johnson's avatar
Adrian Johnson committed
853
CachedFileStream::CachedFileStream(CachedFile *ccA, Goffset startA,
Albert Astals Cid's avatar
Albert Astals Cid committed
854 855
        GBool limitedA, Goffset lengthA, Object &&dictA)
  : BaseStream(std::move(dictA), lengthA)
Hib Eris's avatar
Hib Eris committed
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
{
  cc = ccA;
  start = startA;
  limited = limitedA;
  length = lengthA;
  bufPtr = bufEnd = buf;
  bufPos = start;
  savePos = 0;
  saved = gFalse;
}

CachedFileStream::~CachedFileStream()
{
  close();
  cc->decRefCnt();
}

Thomas Freitag's avatar
Thomas Freitag committed
873 874
BaseStream *CachedFileStream::copy() {
  cc->incRefCnt();
Albert Astals Cid's avatar
Albert Astals Cid committed
875
  return new CachedFileStream(cc, start, limited, length, dict.copy());
Thomas Freitag's avatar
Thomas Freitag committed
876 877
}

Adrian Johnson's avatar
Adrian Johnson committed
878
Stream *CachedFileStream::makeSubStream(Goffset startA, GBool limitedA,
Albert Astals Cid's avatar
Albert Astals Cid committed
879
        Goffset lengthA, Object &&dictA)
Hib Eris's avatar
Hib Eris committed
880 881
{
  cc->incRefCnt();
Albert Astals Cid's avatar
Albert Astals Cid committed
882
  return new CachedFileStream(cc, startA, limitedA, lengthA, std::move(dictA));
Hib Eris's avatar
Hib Eris committed
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
}

void CachedFileStream::reset()
{
  savePos = (Guint)cc->tell();
  cc->seek(start, SEEK_SET);

  saved = gTrue;
  bufPtr = bufEnd = buf;
  bufPos = start;
}

void CachedFileStream::close()
{
  if (saved) {
    cc->seek(savePos, SEEK_SET);
    saved = gFalse;
  }
}

GBool CachedFileStream::fillBuf()
{
  int n;

  bufPos += bufEnd - buf;
  bufPtr = bufEnd = buf;
  if (limited && bufPos >= start + length) {
    return gFalse;
  }
  if (limited && bufPos + cachedStreamBufSize > start + length) {
    n = start + length - bufPos;
  } else {
Hib Eris's avatar
Hib Eris committed
915
    n = cachedStreamBufSize - (bufPos % cachedStreamBufSize);
Hib Eris's avatar
Hib Eris committed
916
  }
917
  n = cc->read(buf, 1, n);
Hib Eris's avatar
Hib Eris committed
918 919 920 921 922 923 924
  bufEnd = buf + n;
  if (bufPtr >= bufEnd) {
    return gFalse;
  }
  return gTrue;
}

Adrian Johnson's avatar
Adrian Johnson committed
925
void CachedFileStream::setPos(Goffset pos, int dir)
Hib Eris's avatar
Hib Eris committed
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
{
  Guint size;

  if (dir >= 0) {
    cc->seek(pos, SEEK_SET);
    bufPos = pos;
  } else {
    cc->seek(0, SEEK_END);
    size = (Guint)cc->tell();

    if (pos > size)
      pos = (Guint)size;

    cc->seek(-(int)pos, SEEK_END);
    bufPos = (Guint)cc->tell();
  }

  bufPtr = bufEnd = buf;
}

Adrian Johnson's avatar
Adrian Johnson committed
946
void CachedFileStream::moveStart(Goffset delta)
Hib Eris's avatar
Hib Eris committed
947 948 949 950 951 952
{
  start += delta;
  bufPtr = bufEnd = buf;
  bufPos = start;
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
953 954 955 956
//------------------------------------------------------------------------
// EmbedStream
//------------------------------------------------------------------------

Albert Astals Cid's avatar
Albert Astals Cid committed
957
EmbedStream::EmbedStream(Stream *strA, Object &&dictA,
958
			 GBool limitedA, Goffset lengthA, GBool reusableA):
Albert Astals Cid's avatar
Albert Astals Cid committed
959
    BaseStream(std::move(dictA), lengthA) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
960 961 962
  str = strA;
  limited = limitedA;
  length = lengthA;
963 964 965 966 967 968 969 970 971
  reusable = reusableA;
  record = gFalse;
  replay = gFalse;
  if (reusable) {
    bufData = (unsigned char*)gmalloc(16384);
    bufMax = 16384;
    bufLen = 0;
    record = gTrue;
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
972 973 974
}

EmbedStream::~EmbedStream() {
975 976
  if (reusable)
    gfree(bufData);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
977 978
}

Thomas Freitag's avatar
Thomas Freitag committed
979 980
BaseStream *EmbedStream::copy() {
  error(errInternal, -1, "Called copy() on EmbedStream");
981
  return nullptr;
Thomas Freitag's avatar
Thomas Freitag committed
982 983
}

Adrian Johnson's avatar
Adrian Johnson committed
984
Stream *EmbedStream::makeSubStream(Goffset start, GBool limitedA,
Albert Astals Cid's avatar
Albert Astals Cid committed
985
				   Goffset lengthA, Object &&dictA) {
986
  error(errInternal, -1, "Called makeSubStream() on EmbedStream");
987
  return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
988 989
}

990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
void EmbedStream::rewind() {
  record = gFalse;
  replay = gTrue;
  bufPos = 0;
}

void EmbedStream::restore() {
  replay = gFalse;
}

Goffset EmbedStream::getPos() {
  if (replay)
    return bufPos;
  else
    return str->getPos();
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1007
int EmbedStream::getChar() {
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
  if (replay) {
    if (bufPos < bufLen)
      return bufData[bufPos++];
    else
      return EOF;
  } else {
    if (limited && !length) {
      return EOF;
    }
    int c = str->getChar();
    --length;
    if (record) {
      bufData[bufLen] = c;
      bufLen++;
      if (bufLen >= bufMax) {
        bufMax *= 2;
        bufData = (unsigned char *)grealloc(bufData, bufMax);
      }
    }
    return c;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1028 1029 1030 1031
  }
}

int EmbedStream::lookChar() {
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
  if (replay) {
    if (bufPos < bufLen)
      return bufData[bufPos];
    else
      return EOF;
  } else {
    if (limited && !length) {
      return EOF;
    }
    return str->lookChar();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1042 1043 1044
  }
}

1045
int EmbedStream::getChars(int nChars, Guchar *buffer) {
1046 1047
  int len;

1048 1049 1050
  if (nChars <= 0) {
    return 0;
  }
1051 1052 1053 1054 1055 1056
  if (replay) {
    if (bufPos >= bufLen)
      return EOF;
    len = bufLen - bufPos;
    if (nChars > len)
      nChars = len;
Adrian Johnson's avatar
Adrian Johnson committed
1057
    memcpy(buffer, bufData, nChars);
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    return len;
  } else {
    if (limited && length < nChars) {
      nChars = length;
    }
    len = str->doGetChars(nChars, buffer);
    if (record) {
      if (bufLen + len >= bufMax) {
        while (bufLen + len >= bufMax)
          bufMax *= 2;
        bufData = (unsigned char *)grealloc(bufData, bufMax);
      }
      memcpy(bufData+bufLen, buffer, len);
      bufLen += len;
    }
1073
  }
1074
  return len;
1075 1076
}

1077

Adrian Johnson's avatar
Adrian Johnson committed
1078
void EmbedStream::setPos(Goffset pos, int dir) {
1079
  error(errInternal, -1, "Internal: called setPos() on EmbedStream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1080 1081
}

Adrian Johnson's avatar
Adrian Johnson committed
1082
Goffset EmbedStream::getStart() {
1083
  error(errInternal, -1, "Internal: called getStart() on EmbedStream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1084 1085 1086
  return 0;
}

Adrian Johnson's avatar
Adrian Johnson committed
1087
void EmbedStream::moveStart(Goffset delta) {
1088
  error(errInternal, -1, "Internal: called moveStart() on EmbedStream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
}

//------------------------------------------------------------------------
// ASCIIHexStream
//------------------------------------------------------------------------

ASCIIHexStream::ASCIIHexStream(Stream *strA):
    FilterStream(strA) {
  buf = EOF;
  eof = gFalse;
}

ASCIIHexStream::~ASCIIHexStream() {
  delete str;
}

void ASCIIHexStream::reset() {
  str->reset();
  buf = EOF;
  eof = gFalse;
}

int ASCIIHexStream::lookChar() {
  int c1, c2, x;

  if (buf != EOF)
    return buf;
  if (eof) {
    buf = EOF;
    return EOF;
  }
  do {
    c1 = str->getChar();
  } while (isspace(c1));
  if (c1 == '>') {
    eof = gTrue;
    buf = EOF;
    return buf;
  }
  do {
    c2 = str->getChar();
  } while (isspace(c2));
  if (c2 == '>') {
    eof = gTrue;
    c2 = '0';
  }
  if (c1 >= '0' && c1 <= '9') {
    x = (c1 - '0') << 4;
  } else if (c1 >= 'A' && c1 <= 'F') {
    x = (c1 - 'A' + 10) << 4;
  } else if (c1 >= 'a' && c1 <= 'f') {
    x = (c1 - 'a' + 10) << 4;
  } else if (c1 == EOF) {
    eof = gTrue;
    x = 0;
  } else {
1145 1146
    error(errSyntaxError, getPos(),
	  "Illegal character <{0:02x}> in ASCIIHex stream", c1);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    x = 0;
  }
  if (c2 >= '0' && c2 <= '9') {
    x += c2 - '0';
  } else if (c2 >= 'A' && c2 <= 'F') {
    x += c2 - 'A' + 10;
  } else if (c2 >= 'a' && c2 <= 'f') {
    x += c2 - 'a' + 10;
  } else if (c2 == EOF) {
    eof = gTrue;
    x = 0;
  } else {
1159 1160
    error(errSyntaxError, getPos(),
	  "Illegal character <{0:02x}> in ASCIIHex stream", c2);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1161 1162 1163 1164 1165
  }
  buf = x & 0xff;
  return buf;
}

1166
GooString *ASCIIHexStream::getPSFilter(int psLevel, const char *indent) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1167 1168 1169
  GooString *s;

  if (psLevel < 2) {
1170
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1171 1172
  }
  if (!(s = str->getPSFilter(psLevel, indent))) {
1173
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
  }
  s->append(indent)->append("/ASCIIHexDecode filter\n");
  return s;
}

GBool ASCIIHexStream::isBinary(GBool last) {
  return str->isBinary(gFalse);
}

//------------------------------------------------------------------------
// ASCII85Stream
//------------------------------------------------------------------------

ASCII85Stream::ASCII85Stream(Stream *strA):
    FilterStream(strA) {
  index = n = 0;
  eof = gFalse;
}

ASCII85Stream::~ASCII85Stream() {
  delete str;
}

void ASCII85Stream::reset() {
  str->reset();
  index = n = 0;
  eof = gFalse;
}

int ASCII85Stream::lookChar() {
  int k;
  Gulong t;

  if (index >= n) {
    if (eof)
      return EOF;
    index = 0;
    do {
      c[0] = str->getChar();
1213
    } while (Lexer::isSpace(c[0]));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    if (c[0] == '~' || c[0] == EOF) {
      eof = gTrue;
      n = 0;
      return EOF;
    } else if (c[0] == 'z') {
      b[0] = b[1] = b[2] = b[3] = 0;
      n = 4;
    } else {
      for (k = 1; k < 5; ++k) {
	do {
	  c[k] = str->getChar();
1225
	} while (Lexer::isSpace(c[k]));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
	if (c[k] == '~' || c[k] == EOF)
	  break;
      }
      n = k - 1;
      if (k < 5 && (c[k] == '~' || c[k] == EOF)) {
	for (++k; k < 5; ++k)
	  c[k] = 0x21 + 84;
	eof = gTrue;
      }
      t = 0;
      for (k = 0; k < 5; ++k)
	t = t * 85 + (c[k] - 0x21);
      for (k = 3; k >= 0; --k) {
	b[k] = (int)(t & 0xff);
	t >>= 8;
      }
    }
  }
  return b[index];
}

1247
GooString *ASCII85Stream::getPSFilter(int psLevel, const char *indent) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1248 1249 1250
  GooString *s;

  if (psLevel < 2) {
1251
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1252 1253
  }
  if (!(s = str->getPSFilter(psLevel, indent))) {
1254
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
  }
  s->append(indent)->append("/ASCII85Decode filter\n");
  return s;
}

GBool ASCII85Stream::isBinary(GBool last) {
  return str->isBinary(gFalse);
}

//------------------------------------------------------------------------
// LZWStream
//------------------------------------------------------------------------

LZWStream::LZWStream(Stream *strA, int predictor, int columns, int colors,
		     int bits, int earlyA):
    FilterStream(strA) {
  if (predictor != 1) {
    pred = new StreamPredictor(this, predictor, columns, colors, bits);
1273 1274
    if (!pred->isOk()) {
      delete pred;
1275
      pred = nullptr;
1276
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1277
  } else {
1278
    pred = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
  }
  early = earlyA;
  eof = gFalse;
  inputBits = 0;
  clearTable();
}

LZWStream::~LZWStream() {
  if (pred) {
    delete pred;
  }
  delete str;
}

int LZWStream::getChar() {
  if (pred) {
    return pred->getChar();
  }
  if (eof) {
    return EOF;
  }
  if (seqIndex >= seqLength) {
    if (!processNextCode()) {
      return EOF;
    }
  }
  return seqBuf[seqIndex++];
}

int LZWStream::lookChar() {
  if (pred) {
    return pred->lookChar();
  }
  if (eof) {
    return EOF;
  }
  if (seqIndex >= seqLength) {
    if (!processNextCode()) {
      return EOF;
    }
  }
  return seqBuf[seqIndex];
}

1323 1324 1325 1326 1327
void LZWStream::getRawChars(int nChars, int *buffer) {
  for (int i = 0; i < nChars; ++i)
    buffer[i] = doGetRawChar();
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1328
int LZWStream::getRawChar() {
1329
  return doGetRawChar();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1330 1331
}

1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
int LZWStream::getChars(int nChars, Guchar *buffer) {
  int n, m;

  if (pred) {
    return pred->getChars(nChars, buffer);
  }
  if (eof) {
    return 0;
  }
  n = 0;
  while (n < nChars) {
    if (seqIndex >= seqLength) {
      if (!processNextCode()) {
	break;
      }
    }
    m = seqLength - seqIndex;
    if (m > nChars - n) {
      m = nChars - n;
    }
    memcpy(buffer + n, seqBuf + seqIndex, m);
    seqIndex += m;
    n += m;
  }
  return n;
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
void LZWStream::reset() {
  str->reset();
  eof = gFalse;
  inputBits = 0;
  clearTable();
}

GBool LZWStream::processNextCode() {
  int code;
  int nextLength;
  int i, j;

  // check for EOF
  if (eof) {
    return gFalse;
  }

  // check for eod and clear-table codes
 start:
  code = getCode();
  if (code == EOF || code == 257) {
    eof = gTrue;
    return gFalse;
  }
  if (code == 256) {
    clearTable();
    goto start;
  }

  // process the next code
  nextLength = seqLength + 1;
  if (code < 256) {
    seqBuf[0] = code;
    seqLength = 1;
  } else if (code < nextCode) {
    seqLength = table[code].length;
    for (i = seqLength - 1, j = code; i > 0; --i) {
      seqBuf[i] = table[j].tail;
      j = table[j].head;
    }
    seqBuf[0] = j;
  } else if (code == nextCode) {
    seqBuf[seqLength] = newChar;
    ++seqLength;
  } else {
1404
    error(errSyntaxError, getPos(), "Bad LZW stream - unexpected code");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1405 1406 1407 1408 1409 1410 1411
    eof = gTrue;
    return gFalse;
  }
  newChar = seqBuf[0];
  if (first) {
    first = gFalse;
  } else {
1412 1413 1414 1415 1416 1417
    if (nextCode < 4097) {
      table[nextCode].length = nextLength;
      table[nextCode].head = prevCode;
      table[nextCode].tail = newChar;
      ++nextCode;
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
    if (nextCode + early == 512)
      nextBits = 10;
    else if (nextCode + early == 1024)
      nextBits = 11;
    else if (nextCode + early == 2048)
      nextBits = 12;
  }
  prevCode = code;

  // reset buffer
  seqIndex = 0;

  return gTrue;
}

void LZWStream::clearTable() {
  nextCode = 258;
  nextBits = 9;
  seqIndex = seqLength = 0;
  first = gTrue;
1438
  newChar = 0;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1439 1440 1441 1442 1443 1444 1445 1446 1447
}

int LZWStream::getCode() {
  int c;
  int code;

  while (inputBits < nextBits) {
    if ((c = str->getChar()) == EOF)
      return EOF;
1448
    inputBuf = (inputBuf << 8) | (c & 0xff);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1449 1450 1451 1452 1453 1454 1455
    inputBits += 8;
  }
  code = (inputBuf >> (inputBits - nextBits)) & ((1 << nextBits) - 1);
  inputBits -= nextBits;
  return code;
}

1456
GooString *LZWStream::getPSFilter(int psLevel, const char *indent) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1457 1458 1459
  GooString *s;

  if (psLevel < 2 || pred) {
1460
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1461 1462
  }
  if (!(s = str->getPSFilter(psLevel, indent))) {
1463
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1464
  }
1465 1466 1467 1468 1469
  s->append(indent)->append("<< ");
  if (!early) {
    s->append("/EarlyChange 0 ");
  }
  s->append(">> /LZWDecode filter\n");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
  return s;
}

GBool LZWStream::isBinary(GBool last) {
  return str->isBinary(gTrue);
}

//------------------------------------------------------------------------
// RunLengthStream
//------------------------------------------------------------------------

RunLengthStream::RunLengthStream(Stream *strA):
    FilterStream(strA) {
  bufPtr = bufEnd = buf;
  eof = gFalse;
}

RunLengthStream::~RunLengthStream() {
  delete str;
}

void RunLengthStream::reset() {
  str->reset();
  bufPtr = bufEnd = buf;
  eof = gFalse;
}

1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
int RunLengthStream::getChars(int nChars, Guchar *buffer) {
  int n, m;

  n = 0;
  while (n < nChars) {
    if (bufPtr >= bufEnd) {
      if (!fillBuf()) {
	break;
      }
    }
    m = (int)(bufEnd - bufPtr);
    if (m > nChars - n) {
      m = nChars - n;
    }
    memcpy(buffer + n, bufPtr, m);
    bufPtr += m;
    n += m;
  }
  return n;
}

1518
GooString *RunLengthStream::getPSFilter(int psLevel, const char *indent) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1519 1520 1521
  GooString *s;

  if (psLevel < 2) {
1522
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1523 1524
  }
  if (!(s = str->getPSFilter(psLevel, indent))) {
1525
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
  }
  s->append(indent)->append("/RunLengthDecode filter\n");
  return s;
}

GBool RunLengthStream::isBinary(GBool last) {
  return str->isBinary(gTrue);
}

GBool RunLengthStream::fillBuf() {
  int c;
  int n, i;

  if (eof)
    return gFalse;
  c = str->getChar();