JBIG2Stream.cc 114 KB
Newer Older
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1 2 3 4 5 6 7 8
//========================================================================
//
// JBIG2Stream.cc
//
// Copyright 2002-2003 Glyph & Cog, LLC
//
//========================================================================

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 17
// Copyright (C) 2006 Raj Kumar <rkumar@archive.org>
// Copyright (C) 2006 Paul Walmsley <paul@booyaka.com>
18
// Copyright (C) 2006-2010, 2012, 2014-2019 Albert Astals Cid <aacid@kde.org>
19
// Copyright (C) 2009 David Benjamin <davidben@mit.edu>
20
// Copyright (C) 2011 Edward Jiang <ejiang@google.com>
21
// Copyright (C) 2012 William Bader <williambader@hotmail.com>
22
// Copyright (C) 2012 Thomas Freitag <Thomas.Freitag@alfa.de>
23
// Copyright (C) 2013 Adrian Johnson <ajohnson@redneon.com>
Fabio D'Urso's avatar
Fabio D'Urso committed
24
// Copyright (C) 2013, 2014 Fabio D'Urso <fabiodurso@hotmail.it>
Albert Astals Cid's avatar
Albert Astals Cid committed
25
// Copyright (C) 2015 Suzuki Toshiya <mpsuzuki@hiroshima-u.ac.jp>
26
// Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de>
27
// Copyright (C) 2019 LE GARREC Vincent <legarrec.vincent@gmail.com>
28
// Copyright (C) 2019 Oliver Sander <oliver.sander@tu-dresden.de>
29
// Copyright (C) 2019 Volker Krause <vkrause@kde.org>
30 31 32 33 34 35
//
// 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
36 37
#include <config.h>

38 39
#include <cstdlib>
#include <climits>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
40 41 42 43 44 45 46 47 48
#include "Error.h"
#include "JArithmeticDecoder.h"
#include "JBIG2Stream.h"

//~ share these tables
#include "Stream-CCITT.h"

//------------------------------------------------------------------------

49 50
static const int contextSize[4] = { 16, 13, 10, 10 };
static const int refContextSize[2] = { 13, 10 };
Kristian Høgsberg's avatar
Kristian Høgsberg committed
51 52 53 54 55 56 57 58 59 60 61

//------------------------------------------------------------------------
// JBIG2HuffmanTable
//------------------------------------------------------------------------

#define jbig2HuffmanLOW 0xfffffffd
#define jbig2HuffmanOOB 0xfffffffe
#define jbig2HuffmanEOT 0xffffffff

struct JBIG2HuffmanTable {
  int val;
62 63 64
  unsigned int prefixLen;
  unsigned int rangeLen;		// can also be LOW, OOB, or EOT
  unsigned int prefix;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
65 66
};

67
static const JBIG2HuffmanTable huffTableA[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
68 69 70 71 72 73 74
  {     0, 1,  4,              0x000 },
  {    16, 2,  8,              0x002 },
  {   272, 3, 16,              0x006 },
  { 65808, 3, 32,              0x007 },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

75
static const JBIG2HuffmanTable huffTableB[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
76 77 78 79 80 81 82 83 84 85
  {     0, 1,  0,              0x000 },
  {     1, 2,  0,              0x002 },
  {     2, 3,  0,              0x006 },
  {     3, 4,  3,              0x00e },
  {    11, 5,  6,              0x01e },
  {    75, 6, 32,              0x03e },
  {     0, 6, jbig2HuffmanOOB, 0x03f },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

86
static const JBIG2HuffmanTable huffTableC[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
87 88 89 90 91 92 93 94 95 96 97 98
  {     0, 1,  0,              0x000 },
  {     1, 2,  0,              0x002 },
  {     2, 3,  0,              0x006 },
  {     3, 4,  3,              0x00e },
  {    11, 5,  6,              0x01e },
  {     0, 6, jbig2HuffmanOOB, 0x03e },
  {    75, 7, 32,              0x0fe },
  {  -256, 8,  8,              0x0fe },
  {  -257, 8, jbig2HuffmanLOW, 0x0ff },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

99
static const JBIG2HuffmanTable huffTableD[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
100 101 102 103 104 105 106 107 108
  {     1, 1,  0,              0x000 },
  {     2, 2,  0,              0x002 },
  {     3, 3,  0,              0x006 },
  {     4, 4,  3,              0x00e },
  {    12, 5,  6,              0x01e },
  {    76, 5, 32,              0x01f },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

109
static const JBIG2HuffmanTable huffTableE[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
110 111 112 113 114 115 116 117 118 119 120
  {     1, 1,  0,              0x000 },
  {     2, 2,  0,              0x002 },
  {     3, 3,  0,              0x006 },
  {     4, 4,  3,              0x00e },
  {    12, 5,  6,              0x01e },
  {    76, 6, 32,              0x03e },
  {  -255, 7,  8,              0x07e },
  {  -256, 7, jbig2HuffmanLOW, 0x07f },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

121
static const JBIG2HuffmanTable huffTableF[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
  {     0, 2,  7,              0x000 },
  {   128, 3,  7,              0x002 },
  {   256, 3,  8,              0x003 },
  { -1024, 4,  9,              0x008 },
  {  -512, 4,  8,              0x009 },
  {  -256, 4,  7,              0x00a },
  {   -32, 4,  5,              0x00b },
  {   512, 4,  9,              0x00c },
  {  1024, 4, 10,              0x00d },
  { -2048, 5, 10,              0x01c },
  {  -128, 5,  6,              0x01d },
  {   -64, 5,  5,              0x01e },
  { -2049, 6, jbig2HuffmanLOW, 0x03e },
  {  2048, 6, 32,              0x03f },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

139
static const JBIG2HuffmanTable huffTableG[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  {  -512, 3,  8,              0x000 },
  {   256, 3,  8,              0x001 },
  {   512, 3,  9,              0x002 },
  {  1024, 3, 10,              0x003 },
  { -1024, 4,  9,              0x008 },
  {  -256, 4,  7,              0x009 },
  {   -32, 4,  5,              0x00a },
  {     0, 4,  5,              0x00b },
  {   128, 4,  7,              0x00c },
  {  -128, 5,  6,              0x01a },
  {   -64, 5,  5,              0x01b },
  {    32, 5,  5,              0x01c },
  {    64, 5,  6,              0x01d },
  { -1025, 5, jbig2HuffmanLOW, 0x01e },
  {  2048, 5, 32,              0x01f },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

158
static const JBIG2HuffmanTable huffTableH[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
  {     0, 2,  1,              0x000 },
  {     0, 2, jbig2HuffmanOOB, 0x001 },
  {     4, 3,  4,              0x004 },
  {    -1, 4,  0,              0x00a },
  {    22, 4,  4,              0x00b },
  {    38, 4,  5,              0x00c },
  {     2, 5,  0,              0x01a },
  {    70, 5,  6,              0x01b },
  {   134, 5,  7,              0x01c },
  {     3, 6,  0,              0x03a },
  {    20, 6,  1,              0x03b },
  {   262, 6,  7,              0x03c },
  {   646, 6, 10,              0x03d },
  {    -2, 7,  0,              0x07c },
  {   390, 7,  8,              0x07d },
  {   -15, 8,  3,              0x0fc },
  {    -5, 8,  1,              0x0fd },
  {    -7, 9,  1,              0x1fc },
  {    -3, 9,  0,              0x1fd },
  {   -16, 9, jbig2HuffmanLOW, 0x1fe },
  {  1670, 9, 32,              0x1ff },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

183
static const JBIG2HuffmanTable huffTableI[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
  {     0, 2, jbig2HuffmanOOB, 0x000 },
  {    -1, 3,  1,              0x002 },
  {     1, 3,  1,              0x003 },
  {     7, 3,  5,              0x004 },
  {    -3, 4,  1,              0x00a },
  {    43, 4,  5,              0x00b },
  {    75, 4,  6,              0x00c },
  {     3, 5,  1,              0x01a },
  {   139, 5,  7,              0x01b },
  {   267, 5,  8,              0x01c },
  {     5, 6,  1,              0x03a },
  {    39, 6,  2,              0x03b },
  {   523, 6,  8,              0x03c },
  {  1291, 6, 11,              0x03d },
  {    -5, 7,  1,              0x07c },
  {   779, 7,  9,              0x07d },
  {   -31, 8,  4,              0x0fc },
  {   -11, 8,  2,              0x0fd },
  {   -15, 9,  2,              0x1fc },
  {    -7, 9,  1,              0x1fd },
  {   -32, 9, jbig2HuffmanLOW, 0x1fe },
  {  3339, 9, 32,              0x1ff },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

209
static const JBIG2HuffmanTable huffTableJ[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
  {    -2, 2,  2,              0x000 },
  {     6, 2,  6,              0x001 },
  {     0, 2, jbig2HuffmanOOB, 0x002 },
  {    -3, 5,  0,              0x018 },
  {     2, 5,  0,              0x019 },
  {    70, 5,  5,              0x01a },
  {     3, 6,  0,              0x036 },
  {   102, 6,  5,              0x037 },
  {   134, 6,  6,              0x038 },
  {   198, 6,  7,              0x039 },
  {   326, 6,  8,              0x03a },
  {   582, 6,  9,              0x03b },
  {  1094, 6, 10,              0x03c },
  {   -21, 7,  4,              0x07a },
  {    -4, 7,  0,              0x07b },
  {     4, 7,  0,              0x07c },
  {  2118, 7, 11,              0x07d },
  {    -5, 8,  0,              0x0fc },
  {     5, 8,  0,              0x0fd },
  {   -22, 8, jbig2HuffmanLOW, 0x0fe },
  {  4166, 8, 32,              0x0ff },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

234
static const JBIG2HuffmanTable huffTableK[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
  {     1, 1,  0,              0x000 },
  {     2, 2,  1,              0x002 },
  {     4, 4,  0,              0x00c },
  {     5, 4,  1,              0x00d },
  {     7, 5,  1,              0x01c },
  {     9, 5,  2,              0x01d },
  {    13, 6,  2,              0x03c },
  {    17, 7,  2,              0x07a },
  {    21, 7,  3,              0x07b },
  {    29, 7,  4,              0x07c },
  {    45, 7,  5,              0x07d },
  {    77, 7,  6,              0x07e },
  {   141, 7, 32,              0x07f },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

251
static const JBIG2HuffmanTable huffTableL[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  {     1, 1,  0,              0x000 },
  {     2, 2,  0,              0x002 },
  {     3, 3,  1,              0x006 },
  {     5, 5,  0,              0x01c },
  {     6, 5,  1,              0x01d },
  {     8, 6,  1,              0x03c },
  {    10, 7,  0,              0x07a },
  {    11, 7,  1,              0x07b },
  {    13, 7,  2,              0x07c },
  {    17, 7,  3,              0x07d },
  {    25, 7,  4,              0x07e },
  {    41, 8,  5,              0x0fe },
  {    73, 8, 32,              0x0ff },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

268
static const JBIG2HuffmanTable huffTableM[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  {     1, 1,  0,              0x000 },
  {     2, 3,  0,              0x004 },
  {     7, 3,  3,              0x005 },
  {     3, 4,  0,              0x00c },
  {     5, 4,  1,              0x00d },
  {     4, 5,  0,              0x01c },
  {    15, 6,  1,              0x03a },
  {    17, 6,  2,              0x03b },
  {    21, 6,  3,              0x03c },
  {    29, 6,  4,              0x03d },
  {    45, 6,  5,              0x03e },
  {    77, 7,  6,              0x07e },
  {   141, 7, 32,              0x07f },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

285
static const JBIG2HuffmanTable huffTableN[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
286 287 288 289 290 291 292 293
  {     0, 1,  0,              0x000 },
  {    -2, 3,  0,              0x004 },
  {    -1, 3,  0,              0x005 },
  {     1, 3,  0,              0x006 },
  {     2, 3,  0,              0x007 },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

294
static const JBIG2HuffmanTable huffTableO[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
  {     0, 1,  0,              0x000 },
  {    -1, 3,  0,              0x004 },
  {     1, 3,  0,              0x005 },
  {    -2, 4,  0,              0x00c },
  {     2, 4,  0,              0x00d },
  {    -4, 5,  1,              0x01c },
  {     3, 5,  1,              0x01d },
  {    -8, 6,  2,              0x03c },
  {     5, 6,  2,              0x03d },
  {   -24, 7,  4,              0x07c },
  {     9, 7,  4,              0x07d },
  {   -25, 7, jbig2HuffmanLOW, 0x07e },
  {    25, 7, 32,              0x07f },
  {     0, 0, jbig2HuffmanEOT, 0     }
};

//------------------------------------------------------------------------
// JBIG2HuffmanDecoder
//------------------------------------------------------------------------

class JBIG2HuffmanDecoder {
public:

  JBIG2HuffmanDecoder();
  ~JBIG2HuffmanDecoder();
  void setStream(Stream *strA) { str = strA; }

  void reset();

  // Returns false for OOB, otherwise sets *<x> and returns true.
325
  bool decodeInt(int *x, const JBIG2HuffmanTable *table);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
326

327 328
  unsigned int readBits(unsigned int n);
  unsigned int readBit();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
329 330

  // Sort the table by prefix length and assign prefix values.
331
  static bool buildTable(JBIG2HuffmanTable *table, unsigned int len);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
332 333 334 335

private:

  Stream *str;
336 337
  unsigned int buf;
  unsigned int bufLen;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
338 339 340
};

JBIG2HuffmanDecoder::JBIG2HuffmanDecoder() {
341
  str = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
342 343 344 345 346 347 348 349 350 351 352 353
  reset();
}

JBIG2HuffmanDecoder::~JBIG2HuffmanDecoder() {
}

void JBIG2HuffmanDecoder::reset() {
  buf = 0;
  bufLen = 0;
}

//~ optimize this
354
bool JBIG2HuffmanDecoder::decodeInt(int *x, const JBIG2HuffmanTable *table) {
355
  unsigned int i, len, prefix;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
356 357 358 359 360 361 362 363 364 365 366

  i = 0;
  len = 0;
  prefix = 0;
  while (table[i].rangeLen != jbig2HuffmanEOT) {
    while (len < table[i].prefixLen) {
      prefix = (prefix << 1) | readBit();
      ++len;
    }
    if (prefix == table[i].prefix) {
      if (table[i].rangeLen == jbig2HuffmanOOB) {
367
	return false;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
368 369 370 371 372 373 374 375
      }
      if (table[i].rangeLen == jbig2HuffmanLOW) {
	*x = table[i].val - readBits(32);
      } else if (table[i].rangeLen > 0) {
	*x = table[i].val + readBits(table[i].rangeLen);
      } else {
	*x = table[i].val;
      }
376
      return true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
377 378 379
    }
    ++i;
  }
380
  return false;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
381 382
}

383 384
unsigned int JBIG2HuffmanDecoder::readBits(unsigned int n) {
  unsigned int x, mask, nLeft;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406

  mask = (n == 32) ? 0xffffffff : ((1 << n) - 1);
  if (bufLen >= n) {
    x = (buf >> (bufLen - n)) & mask;
    bufLen -= n;
  } else {
    x = buf & ((1 << bufLen) - 1);
    nLeft = n - bufLen;
    bufLen = 0;
    while (nLeft >= 8) {
      x = (x << 8) | (str->getChar() & 0xff);
      nLeft -= 8;
    }
    if (nLeft > 0) {
      buf = str->getChar();
      bufLen = 8 - nLeft;
      x = (x << nLeft) | ((buf >> bufLen) & ((1 << nLeft) - 1));
    }
  }
  return x;
}

407
unsigned int JBIG2HuffmanDecoder::readBit() {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
408 409 410 411 412 413 414 415
  if (bufLen == 0) {
    buf = str->getChar();
    bufLen = 8;
  }
  --bufLen;
  return (buf >> bufLen) & 1;
}

416
bool JBIG2HuffmanDecoder::buildTable(JBIG2HuffmanTable *table, unsigned int len) {
417
  unsigned int i, j, k, prefix;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
  JBIG2HuffmanTable tab;

  // stable selection sort:
  // - entries with prefixLen > 0, in ascending prefixLen order
  // - entry with prefixLen = 0, rangeLen = EOT
  // - all other entries with prefixLen = 0
  // (on entry, table[len] has prefixLen = 0, rangeLen = EOT)
  for (i = 0; i < len; ++i) {
    for (j = i; j < len && table[j].prefixLen == 0; ++j) ;
    if (j == len) {
      break;
    }
    for (k = j + 1; k < len; ++k) {
      if (table[k].prefixLen > 0 &&
	  table[k].prefixLen < table[j].prefixLen) {
	j = k;
      }
    }
    if (j != i) {
      tab = table[j];
      for (k = j; k > i; --k) {
	table[k] = table[k - 1];
      }
      table[i] = tab;
    }
  }
  table[i] = table[len];

  // assign prefixes
447 448 449 450 451
  if (table[0].rangeLen != jbig2HuffmanEOT) {
    i = 0;
    prefix = 0;
    table[i++].prefix = prefix++;
    for (; table[i].rangeLen != jbig2HuffmanEOT; ++i) {
452 453 454 455 456 457
      if (table[i].prefixLen - table[i-1].prefixLen > 32) {
	error(errSyntaxError, -1, "Failed to build table for JBIG2 stream");
	return false;
      } else {
	prefix <<= table[i].prefixLen - table[i-1].prefixLen;
      }
458 459
      table[i].prefix = prefix++;
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
460
  }
461 462

  return true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
}

//------------------------------------------------------------------------
// JBIG2MMRDecoder
//------------------------------------------------------------------------

class JBIG2MMRDecoder {
public:

  JBIG2MMRDecoder();
  ~JBIG2MMRDecoder();
  void setStream(Stream *strA) { str = strA; }
  void reset();
  int get2DCode();
  int getBlackCode();
  int getWhiteCode();
479 480
  unsigned int get24Bits();
  void skipTo(unsigned int length);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
481 482 483 484

private:

  Stream *str;
485 486 487
  unsigned int buf;
  unsigned int bufLen;
  unsigned int nBytesRead;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
488 489 490
};

JBIG2MMRDecoder::JBIG2MMRDecoder() {
491
  str = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
492 493 494 495 496 497 498 499 500 501 502 503 504
  reset();
}

JBIG2MMRDecoder::~JBIG2MMRDecoder() {
}

void JBIG2MMRDecoder::reset() {
  buf = 0;
  bufLen = 0;
  nBytesRead = 0;
}

int JBIG2MMRDecoder::get2DCode() {
505
  const CCITTCode *p = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
506 507 508 509 510 511 512 513

  if (bufLen == 0) {
    buf = str->getChar() & 0xff;
    bufLen = 8;
    ++nBytesRead;
    p = &twoDimTab1[(buf >> 1) & 0x7f];
  } else if (bufLen == 8) {
    p = &twoDimTab1[(buf >> 1) & 0x7f];
514
  } else if (bufLen < 8) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
515 516 517 518 519 520 521 522
    p = &twoDimTab1[(buf << (7 - bufLen)) & 0x7f];
    if (p->bits < 0 || p->bits > (int)bufLen) {
      buf = (buf << 8) | (str->getChar() & 0xff);
      bufLen += 8;
      ++nBytesRead;
      p = &twoDimTab1[(buf >> (bufLen - 7)) & 0x7f];
    }
  }
523
  if (p == nullptr || p->bits < 0) {
524
    error(errSyntaxError, str->getPos(), "Bad two dim code in JBIG2 MMR stream");
525
    return EOF;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
526 527 528 529 530 531
  }
  bufLen -= p->bits;
  return p->n;
}

int JBIG2MMRDecoder::getWhiteCode() {
532
  const CCITTCode *p;
533
  unsigned int code;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
534 535 536 537 538 539 540

  if (bufLen == 0) {
    buf = str->getChar() & 0xff;
    bufLen = 8;
    ++nBytesRead;
  }
  while (1) {
541
    if (bufLen >= 11 && ((buf >> (bufLen - 7)) & 0x7f) == 0) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
      if (bufLen <= 12) {
	code = buf << (12 - bufLen);
      } else {
	code = buf >> (bufLen - 12);
      }
      p = &whiteTab1[code & 0x1f];
    } else {
      if (bufLen <= 9) {
	code = buf << (9 - bufLen);
      } else {
	code = buf >> (bufLen - 9);
      }
      p = &whiteTab2[code & 0x1ff];
    }
    if (p->bits > 0 && p->bits <= (int)bufLen) {
      bufLen -= p->bits;
      return p->n;
    }
    if (bufLen >= 12) {
      break;
    }
    buf = (buf << 8) | (str->getChar() & 0xff);
    bufLen += 8;
    ++nBytesRead;
  }
567
  error(errSyntaxError, str->getPos(), "Bad white code in JBIG2 MMR stream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
568 569 570 571 572 573 574
  // eat a bit and return a positive number so that the caller doesn't
  // go into an infinite loop
  --bufLen;
  return 1;
}

int JBIG2MMRDecoder::getBlackCode() {
575
  const CCITTCode *p;
576
  unsigned int code;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
577 578 579 580 581 582 583

  if (bufLen == 0) {
    buf = str->getChar() & 0xff;
    bufLen = 8;
    ++nBytesRead;
  }
  while (1) {
584
    if (bufLen >= 10 && ((buf >> (bufLen - 6)) & 0x3f) == 0) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
585 586 587 588 589 590
      if (bufLen <= 13) {
	code = buf << (13 - bufLen);
      } else {
	code = buf >> (bufLen - 13);
      }
      p = &blackTab1[code & 0x7f];
591 592
    } else if (bufLen >= 7 && ((buf >> (bufLen - 4)) & 0x0f) == 0 &&
	       ((buf >> (bufLen - 6)) & 0x03) != 0) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
593 594 595 596 597
      if (bufLen <= 12) {
	code = buf << (12 - bufLen);
      } else {
	code = buf >> (bufLen - 12);
      }
Albert Astals Cid's avatar
Albert Astals Cid committed
598
      if (unlikely((code & 0xff) < 64)) {
599 600
        break;
      }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
      p = &blackTab2[(code & 0xff) - 64];
    } else {
      if (bufLen <= 6) {
	code = buf << (6 - bufLen);
      } else {
	code = buf >> (bufLen - 6);
      }
      p = &blackTab3[code & 0x3f];
    }
    if (p->bits > 0 && p->bits <= (int)bufLen) {
      bufLen -= p->bits;
      return p->n;
    }
    if (bufLen >= 13) {
      break;
    }
    buf = (buf << 8) | (str->getChar() & 0xff);
    bufLen += 8;
    ++nBytesRead;
  }
621
  error(errSyntaxError, str->getPos(), "Bad black code in JBIG2 MMR stream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
622 623 624 625 626 627
  // eat a bit and return a positive number so that the caller doesn't
  // go into an infinite loop
  --bufLen;
  return 1;
}

628
unsigned int JBIG2MMRDecoder::get24Bits() {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
629 630 631 632 633 634 635 636
  while (bufLen < 24) {
    buf = (buf << 8) | (str->getChar() & 0xff);
    bufLen += 8;
    ++nBytesRead;
  }
  return (buf >> (bufLen - 24)) & 0xffffff;
}

637
void JBIG2MMRDecoder::skipTo(unsigned int length) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
  while (nBytesRead < length) {
    str->getChar();
    ++nBytesRead;
  }
}

//------------------------------------------------------------------------
// JBIG2Segment
//------------------------------------------------------------------------

enum JBIG2SegmentType {
  jbig2SegBitmap,
  jbig2SegSymbolDict,
  jbig2SegPatternDict,
  jbig2SegCodeTable
};

class JBIG2Segment {
public:

658
  JBIG2Segment(unsigned int segNumA) { segNum = segNumA; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
659
  virtual ~JBIG2Segment() {}
660 661
  JBIG2Segment(const JBIG2Segment &) = delete;
  JBIG2Segment& operator=(const JBIG2Segment &) = delete;
662 663
  void setSegNum(unsigned int segNumA) { segNum = segNumA; }
  unsigned int getSegNum() { return segNum; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
664 665 666 667
  virtual JBIG2SegmentType getType() = 0;

private:

668
  unsigned int segNum;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
669 670 671 672 673 674 675
};

//------------------------------------------------------------------------
// JBIG2Bitmap
//------------------------------------------------------------------------

struct JBIG2BitmapPtr {
676
  unsigned char *p;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
677 678 679 680 681 682 683
  int shift;
  int x;
};

class JBIG2Bitmap: public JBIG2Segment {
public:

684
  JBIG2Bitmap(unsigned int segNumA, int wA, int hA);
Albert Astals Cid's avatar
Albert Astals Cid committed
685 686
  ~JBIG2Bitmap();
  JBIG2SegmentType getType() override { return jbig2SegBitmap; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
687
  JBIG2Bitmap *copy() { return new JBIG2Bitmap(0, this); }
688 689
  JBIG2Bitmap *getSlice(unsigned int x, unsigned int y, unsigned int wA, unsigned int hA);
  void expand(int newH, unsigned int pixel);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
690 691 692 693
  void clearToZero();
  void clearToOne();
  int getWidth() { return w; }
  int getHeight() { return h; }
694
  int getLineSize() { return line; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
695 696 697 698 699 700 701 702 703 704
  int getPixel(int x, int y)
    { return (x < 0 || x >= w || y < 0 || y >= h) ? 0 :
             (data[y * line + (x >> 3)] >> (7 - (x & 7))) & 1; }
  void setPixel(int x, int y)
    { data[y * line + (x >> 3)] |= 1 << (7 - (x & 7)); }
  void clearPixel(int x, int y)
    { data[y * line + (x >> 3)] &= 0x7f7f >> (x & 7); }
  void getPixelPtr(int x, int y, JBIG2BitmapPtr *ptr);
  int nextPixel(JBIG2BitmapPtr *ptr);
  void duplicateRow(int yDest, int ySrc);
705
  void combine(JBIG2Bitmap *bitmap, int x, int y, unsigned int combOp);
706
  unsigned char *getDataPtr() { return data; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
707
  int getDataSize() { return h * line; }
708
  bool isOk() { return data != nullptr; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
709 710 711

private:

712
  JBIG2Bitmap(unsigned int segNumA, JBIG2Bitmap *bitmap);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
713 714

  int w, h, line;
715
  unsigned char *data;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
716 717
};

718
JBIG2Bitmap::JBIG2Bitmap(unsigned int segNumA, int wA, int hA):
Kristian Høgsberg's avatar
Kristian Høgsberg committed
719 720 721 722 723
  JBIG2Segment(segNumA)
{
  w = wA;
  h = hA;
  line = (wA + 7) >> 3;
724

725
  if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
726
    error(errSyntaxError, -1, "invalid width/height");
727
    data = nullptr;
728 729
    return;
  }
730
  // need to allocate one extra guard byte for use in combine()
731
  data = (unsigned char *)gmalloc_checkoverflow(h * line + 1);
732
  if (data != nullptr) {
733 734
    data[h * line] = 0;
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
735 736
}

737
JBIG2Bitmap::JBIG2Bitmap(unsigned int segNumA, JBIG2Bitmap *bitmap):
Kristian Høgsberg's avatar
Kristian Høgsberg committed
738 739
  JBIG2Segment(segNumA)
{
740
  if (unlikely(bitmap == nullptr)) {
741 742
    error(errSyntaxError, -1, "NULL bitmap in JBIG2Bitmap");
    w = h = line = 0;
743
    data = nullptr;
744 745 746
    return;
  }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
747 748 749
  w = bitmap->w;
  h = bitmap->h;
  line = bitmap->line;
750

751
  if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) {
752
    error(errSyntaxError, -1, "invalid width/height");
753
    data = nullptr;
754 755
    return;
  }
756
  // need to allocate one extra guard byte for use in combine()
757
  data = (unsigned char *)gmalloc(h * line + 1);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
758
  memcpy(data, bitmap->data, h * line);
759
  data[h * line] = 0;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
760 761 762 763 764 765 766
}

JBIG2Bitmap::~JBIG2Bitmap() {
  gfree(data);
}

//~ optimize this
767
JBIG2Bitmap *JBIG2Bitmap::getSlice(unsigned int x, unsigned int y, unsigned int wA, unsigned int hA) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
768
  JBIG2Bitmap *slice;
769
  unsigned int xx, yy;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
770

771 772 773 774
  if (!data) {
      return nullptr;
  }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
775
  slice = new JBIG2Bitmap(0, wA, hA);
776 777 778 779 780 781 782
  if (slice->isOk()) {
    slice->clearToZero();
    for (yy = 0; yy < hA; ++yy) {
      for (xx = 0; xx < wA; ++xx) {
        if (getPixel(x + xx, y + yy)) {
	  slice->setPixel(xx, yy);
        }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
783 784
      }
    }
785 786
  } else {
    delete slice;
787
    slice = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
788 789 790 791
  }
  return slice;
}

792
void JBIG2Bitmap::expand(int newH, unsigned int pixel) {
793
  if (newH <= h || line <= 0 || newH >= (INT_MAX - 1) / line) {
794
    error(errSyntaxError, -1, "invalid width/height");
795
    gfree(data);
796
    data = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
797 798
    return;
  }
799
  // need to allocate one extra guard byte for use in combine()
800
  data = (unsigned char *)grealloc(data, newH * line + 1);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
801 802 803 804 805 806
  if (pixel) {
    memset(data + h * line, 0xff, (newH - h) * line);
  } else {
    memset(data + h * line, 0x00, (newH - h) * line);
  }
  h = newH;
807
  data[h * line] = 0;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
808 809 810 811 812 813 814 815 816 817 818 819
}

void JBIG2Bitmap::clearToZero() {
  memset(data, 0, h * line);
}

void JBIG2Bitmap::clearToOne() {
  memset(data, 0xff, h * line);
}

inline void JBIG2Bitmap::getPixelPtr(int x, int y, JBIG2BitmapPtr *ptr) {
  if (y < 0 || y >= h || x >= w) {
820
    ptr->p = nullptr;
821 822
    ptr->shift = 0; // make gcc happy
    ptr->x = 0; // make gcc happy
Kristian Høgsberg's avatar
Kristian Høgsberg committed
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
  } else if (x < 0) {
    ptr->p = &data[y * line];
    ptr->shift = 7;
    ptr->x = x;
  } else {
    ptr->p = &data[y * line + (x >> 3)];
    ptr->shift = 7 - (x & 7);
    ptr->x = x;
  }
}

inline int JBIG2Bitmap::nextPixel(JBIG2BitmapPtr *ptr) {
  int pix;

  if (!ptr->p) {
    pix = 0;
  } else if (ptr->x < 0) {
    ++ptr->x;
    pix = 0;
  } else {
    pix = (*ptr->p >> ptr->shift) & 1;
    if (++ptr->x == w) {
845
      ptr->p = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
    } else if (ptr->shift == 0) {
      ++ptr->p;
      ptr->shift = 7;
    } else {
      --ptr->shift;
    }
  }
  return pix;
}

void JBIG2Bitmap::duplicateRow(int yDest, int ySrc) {
  memcpy(data + yDest * line, data + ySrc * line, line);
}

void JBIG2Bitmap::combine(JBIG2Bitmap *bitmap, int x, int y,
861
			  unsigned int combOp) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
862
  int x0, x1, y0, y1, xx, yy;
863
  unsigned char *srcPtr, *destPtr;
864
  unsigned int src0, src1, src, dest, s1, s2, m1, m2, m3;
865
  bool oneByte;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
866

867 868 869 870
  // check for the pathological case where y = -2^31
  if (y < -0x7fffffff) {
    return;
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
  if (y < 0) {
    y0 = -y;
  } else {
    y0 = 0;
  }
  if (y + bitmap->h > h) {
    y1 = h - y;
  } else {
    y1 = bitmap->h;
  }
  if (y0 >= y1) {
    return;
  }

  if (x >= 0) {
    x0 = x & ~7;
  } else {
    x0 = 0;
  }
  x1 = x + bitmap->w;
  if (x1 > w) {
    x1 = w;
  }
  if (x0 >= x1) {
    return;
  }

  s1 = x & 7;
  s2 = 8 - s1;
  m1 = 0xff >> (x1 & 7);
  m2 = 0xff << (((x1 & 7) == 0) ? 0 : 8 - (x1 & 7));
  m3 = (0xff >> s1) & m2;

  oneByte = x0 == ((x1 - 1) & ~7);

  for (yy = y0; yy < y1; ++yy) {
907
    if (unlikely((y + yy >= h) || (y + yy < 0)))
908
      continue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

    // one byte per line -- need to mask both left and right side
    if (oneByte) {
      if (x >= 0) {
	destPtr = data + (y + yy) * line + (x >> 3);
	srcPtr = bitmap->data + yy * bitmap->line;
	dest = *destPtr;
	src1 = *srcPtr;
	switch (combOp) {
	case 0: // or
	  dest |= (src1 >> s1) & m2;
	  break;
	case 1: // and
	  dest &= ((0xff00 | src1) >> s1) | m1;
	  break;
	case 2: // xor
	  dest ^= (src1 >> s1) & m2;
	  break;
	case 3: // xnor
	  dest ^= ((src1 ^ 0xff) >> s1) & m2;
	  break;
	case 4: // replace
	  dest = (dest & ~m3) | ((src1 >> s1) & m3);
	  break;
	}
	*destPtr = dest;
      } else {
	destPtr = data + (y + yy) * line;
	srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3);
	dest = *destPtr;
	src1 = *srcPtr;
	switch (combOp) {
	case 0: // or
	  dest |= src1 & m2;
	  break;
	case 1: // and
	  dest &= src1 | m1;
	  break;
	case 2: // xor
	  dest ^= src1 & m2;
	  break;
	case 3: // xnor
	  dest ^= (src1 ^ 0xff) & m2;
	  break;
	case 4: // replace
	  dest = (src1 & m2) | (dest & m1);
	  break;
	}
	*destPtr = dest;
      }

    // multiple bytes per line -- need to mask left side of left-most
    // byte and right side of right-most byte
    } else {

      // left-most byte
      if (x >= 0) {
	destPtr = data + (y + yy) * line + (x >> 3);
	srcPtr = bitmap->data + yy * bitmap->line;
	src1 = *srcPtr++;
	dest = *destPtr;
	switch (combOp) {
	case 0: // or
	  dest |= src1 >> s1;
	  break;
	case 1: // and
	  dest &= (0xff00 | src1) >> s1;
	  break;
	case 2: // xor
	  dest ^= src1 >> s1;
	  break;
	case 3: // xnor
	  dest ^= (src1 ^ 0xff) >> s1;
	  break;
	case 4: // replace
	  dest = (dest & (0xff << s2)) | (src1 >> s1);
	  break;
	}
	*destPtr++ = dest;
	xx = x0 + 8;
      } else {
	destPtr = data + (y + yy) * line;
	srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3);
	src1 = *srcPtr++;
	xx = x0;
      }

      // middle bytes
      for (; xx < x1 - 8; xx += 8) {
	dest = *destPtr;
	src0 = src1;
	src1 = *srcPtr++;
	src = (((src0 << 8) | src1) >> s1) & 0xff;
	switch (combOp) {
	case 0: // or
	  dest |= src;
	  break;
	case 1: // and
	  dest &= src;
	  break;
	case 2: // xor
	  dest ^= src;
	  break;
	case 3: // xnor
	  dest ^= src ^ 0xff;
	  break;
	case 4: // replace
	  dest = src;
	  break;
	}
	*destPtr++ = dest;
      }

      // right-most byte
1023 1024 1025 1026
      // note: this last byte (src1) may not actually be used, depending
      // on the values of s1, m1, and m2 - and in fact, it may be off
      // the edge of the source bitmap, which means we need to allocate
      // one extra guard byte at the end of each bitmap
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
      dest = *destPtr;
      src0 = src1;
      src1 = *srcPtr++;
      src = (((src0 << 8) | src1) >> s1) & 0xff;
      switch (combOp) {
      case 0: // or
	dest |= src & m2;
	break;
      case 1: // and
	dest &= src | m1;
	break;
      case 2: // xor
	dest ^= src & m2;
	break;
      case 3: // xnor
	dest ^= (src ^ 0xff) & m2;
	break;
      case 4: // replace
	dest = (src & m2) | (dest & m1);
	break;
      }
      *destPtr = dest;
    }
  }
}

//------------------------------------------------------------------------
// JBIG2SymbolDict
//------------------------------------------------------------------------

class JBIG2SymbolDict: public JBIG2Segment {
public:

1060
  JBIG2SymbolDict(unsigned int segNumA, unsigned int sizeA);
Albert Astals Cid's avatar
Albert Astals Cid committed
1061 1062
  ~JBIG2SymbolDict();
  JBIG2SegmentType getType() override { return jbig2SegSymbolDict; }
1063 1064 1065
  unsigned int getSize() { return size; }
  void setBitmap(unsigned int idx, JBIG2Bitmap *bitmap) { bitmaps[idx] = bitmap; }
  JBIG2Bitmap *getBitmap(unsigned int idx) { return bitmaps[idx]; }
1066
  bool isOk() { return bitmaps != nullptr; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
  void setGenericRegionStats(JArithmeticDecoderStats *stats)
    { genericRegionStats = stats; }
  void setRefinementRegionStats(JArithmeticDecoderStats *stats)
    { refinementRegionStats = stats; }
  JArithmeticDecoderStats *getGenericRegionStats()
    { return genericRegionStats; }
  JArithmeticDecoderStats *getRefinementRegionStats()
    { return refinementRegionStats; }

private:

1078
  unsigned int size;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1079 1080 1081 1082 1083
  JBIG2Bitmap **bitmaps;
  JArithmeticDecoderStats *genericRegionStats;
  JArithmeticDecoderStats *refinementRegionStats;
};

1084
JBIG2SymbolDict::JBIG2SymbolDict(unsigned int segNumA, unsigned int sizeA):
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1085 1086
  JBIG2Segment(segNumA)
{
1087
  unsigned int i;
1088

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1089
  size = sizeA;
1090 1091
  bitmaps = (JBIG2Bitmap **)gmallocn_checkoverflow(size, sizeof(JBIG2Bitmap *));
  if (!bitmaps) size = 0;
1092
  for (i = 0; i < size; ++i) {
1093
    bitmaps[i] = nullptr;
1094
  }
1095 1096
  genericRegionStats = nullptr;
  refinementRegionStats = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1097 1098 1099
}

JBIG2SymbolDict::~JBIG2SymbolDict() {
1100
  unsigned int i;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

  for (i = 0; i < size; ++i) {
    delete bitmaps[i];
  }
  gfree(bitmaps);
  if (genericRegionStats) {
    delete genericRegionStats;
  }
  if (refinementRegionStats) {
    delete refinementRegionStats;
  }
}

//------------------------------------------------------------------------
// JBIG2PatternDict
//------------------------------------------------------------------------

class JBIG2PatternDict: public JBIG2Segment {
public:

1121
  JBIG2PatternDict(unsigned int segNumA, unsigned int sizeA);
Albert Astals Cid's avatar
Albert Astals Cid committed
1122 1123
  ~JBIG2PatternDict();
  JBIG2SegmentType getType() override { return jbig2SegPatternDict; }
1124 1125 1126
  unsigned int getSize() { return size; }
  void setBitmap(unsigned int idx, JBIG2Bitmap *bitmap) { if (likely(idx < size)) bitmaps[idx] = bitmap; }
  JBIG2Bitmap *getBitmap(unsigned int idx) { return (idx < size) ? bitmaps[idx] : nullptr; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1127 1128 1129

private:

1130
  unsigned int size;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1131 1132 1133
  JBIG2Bitmap **bitmaps;
};

1134
JBIG2PatternDict::JBIG2PatternDict(unsigned int segNumA, unsigned int sizeA):
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1135 1136
  JBIG2Segment(segNumA)
{
1137 1138 1139 1140 1141 1142 1143
  bitmaps = (JBIG2Bitmap **)gmallocn_checkoverflow(sizeA, sizeof(JBIG2Bitmap *));
  if (bitmaps) {
    size = sizeA;
  } else {
    size = 0;
    error(errSyntaxError, -1, "JBIG2PatternDict: can't allocate bitmaps");
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1144 1145 1146
}

JBIG2PatternDict::~JBIG2PatternDict() {
1147
  unsigned int i;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

  for (i = 0; i < size; ++i) {
    delete bitmaps[i];
  }
  gfree(bitmaps);
}

//------------------------------------------------------------------------
// JBIG2CodeTable
//------------------------------------------------------------------------

class JBIG2CodeTable: public JBIG2Segment {
public:

1162
  JBIG2CodeTable(unsigned int segNumA, JBIG2HuffmanTable *tableA);
Albert Astals Cid's avatar
Albert Astals Cid committed
1163 1164
  ~JBIG2CodeTable();
  JBIG2SegmentType getType() override { return jbig2SegCodeTable; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1165 1166 1167 1168 1169 1170 1171
  JBIG2HuffmanTable *getHuffTable() { return table; }

private:

  JBIG2HuffmanTable *table;
};

1172
JBIG2CodeTable::JBIG2CodeTable(unsigned int segNumA, JBIG2HuffmanTable *tableA):
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  JBIG2Segment(segNumA)
{
  table = tableA;
}

JBIG2CodeTable::~JBIG2CodeTable() {
  gfree(table);
}

//------------------------------------------------------------------------
// JBIG2Stream
//------------------------------------------------------------------------

1186
JBIG2Stream::JBIG2Stream(Stream *strA, Object &&globalsStreamA, Object *globalsStreamRefA):
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1187 1188
  FilterStream(strA)
{
1189
  pageBitmap = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

  arithDecoder = new JArithmeticDecoder();
  genericRegionStats = new JArithmeticDecoderStats(1 << 1);
  refinementRegionStats = new JArithmeticDecoderStats(1 << 1);
  iadhStats = new JArithmeticDecoderStats(1 << 9);
  iadwStats = new JArithmeticDecoderStats(1 << 9);
  iaexStats = new JArithmeticDecoderStats(1 << 9);
  iaaiStats = new JArithmeticDecoderStats(1 << 9);
  iadtStats = new JArithmeticDecoderStats(1 << 9);
  iaitStats = new JArithmeticDecoderStats(1 << 9);
  iafsStats = new JArithmeticDecoderStats(1 << 9);
  iadsStats = new JArithmeticDecoderStats(1 << 9);
  iardxStats = new JArithmeticDecoderStats(1 << 9);
  iardyStats = new JArithmeticDecoderStats(1 << 9);
  iardwStats = new JArithmeticDecoderStats(1 << 9);
  iardhStats = new JArithmeticDecoderStats(1 << 9);
  iariStats = new JArithmeticDecoderStats(1 << 9);
  iaidStats = new JArithmeticDecoderStats(1 << 1);
  huffDecoder = new JBIG2HuffmanDecoder();
  mmrDecoder = new JBIG2MMRDecoder();

1211 1212
  if (globalsStreamA.isStream()) {
    globalsStream = std::move(globalsStreamA);
1213 1214 1215 1216
    if (globalsStreamRefA->isRef())
      globalsStreamRef = globalsStreamRefA->getRef();
  }

1217 1218 1219
  segments = globalSegments = nullptr;
  curStr = nullptr;
  dataPtr = dataEnd = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1220 1221 1222
}

JBIG2Stream::~JBIG2Stream() {
1223
  close();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
  delete arithDecoder;
  delete genericRegionStats;
  delete refinementRegionStats;
  delete iadhStats;
  delete iadwStats;
  delete iaexStats;
  delete iaaiStats;
  delete iadtStats;
  delete iaitStats;
  delete iafsStats;
  delete iadsStats;
  delete iardxStats;
  delete iardyStats;
  delete iardwStats;
  delete iardhStats;
  delete iariStats;
  delete iaidStats;
  delete huffDecoder;
  delete mmrDecoder;
  delete str;
}

void JBIG2Stream::reset() {
1247
  // read the globals stream
1248
  globalSegments = new std::vector<JBIG2Segment*>();
1249 1250 1251 1252 1253 1254 1255 1256 1257
  if (globalsStream.isStream()) {
    segments = globalSegments;
    curStr = globalsStream.getStream();
    curStr->reset();
    arithDecoder->setStream(curStr);
    huffDecoder->setStream(curStr);
    mmrDecoder->setStream(curStr);
    readSegments();
    curStr->close();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1258 1259
  }

1260
  // read the main stream
1261
  segments = new std::vector<JBIG2Segment*>();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
  curStr = str;
  curStr->reset();
  arithDecoder->setStream(curStr);
  huffDecoder->setStream(curStr);
  mmrDecoder->setStream(curStr);
  readSegments();

  if (pageBitmap) {
    dataPtr = pageBitmap->getDataPtr();
    dataEnd = dataPtr + pageBitmap->getDataSize();
  } else {
1273
    dataPtr = dataEnd = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1274 1275 1276
  }
}

1277 1278 1279
void JBIG2Stream::close() {
  if (pageBitmap) {
    delete pageBitmap;
1280
    pageBitmap = nullptr;
1281 1282
  }
  if (segments) {
1283 1284 1285 1286
    for (auto entry : *segments) {
      delete entry;
    }
    delete segments;
1287
    segments = nullptr;
1288 1289
  }
  if (globalSegments) {
1290 1291 1292 1293
    for (auto entry : *globalSegments) {
      delete entry;
    }
    delete globalSegments;
1294
    globalSegments = nullptr;
1295
  }
1296
  dataPtr = dataEnd = nullptr;
1297 1298 1299
  FilterStream::close();
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
int JBIG2Stream::getChar() {
  if (dataPtr && dataPtr < dataEnd) {
    return (*dataPtr++ ^ 0xff) & 0xff;
  }
  return EOF;
}

int JBIG2Stream::lookChar() {
  if (dataPtr && dataPtr < dataEnd) {
    return (*dataPtr ^ 0xff) & 0xff;
  }
  return EOF;
}

Adrian Johnson's avatar
Adrian Johnson committed
1314
Goffset JBIG2Stream::getPos() {
1315
  if (pageBitmap == nullptr) {
1316 1317 1318 1319 1320
    return 0;
  }
  return dataPtr - pageBitmap->getDataPtr();
}

1321
int JBIG2Stream::getChars(int nChars, unsigned char *buffer) {
1322 1323
  int n, i;

1324
  if (nChars <= 0 || !dataPtr) {
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
    return 0;
  }
  if (dataEnd - dataPtr < nChars) {
    n = (int)(dataEnd - dataPtr);
  } else {
    n = nChars;
  }
  for (i = 0; i < n; ++i) {
    buffer[i] = *dataPtr++ ^ 0xff;
  }
  return n;
}

1338
GooString *JBIG2Stream::getPSFilter(int psLevel, const char *indent) {
1339
  return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1340 1341
}

1342 1343
bool JBIG2Stream::isBinary(bool last) {
  return str->isBinary(true);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1344 1345 1346
}

void JBIG2Stream::readSegments() {
1347 1348 1349
  unsigned int segNum, segFlags, segType, page, segLength;
  unsigned int refFlags, nRefSegs;
  unsigned int *refSegs;
Adrian Johnson's avatar
Adrian Johnson committed
1350
  Goffset segDataPos;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
  int c1, c2, c3;

  while (readULong(&segNum)) {

    // segment header flags
    if (!readUByte(&segFlags)) {
      goto eofError1;
    }
    segType = segFlags & 0x3f;

    // referred-to segment count and retention flags
    if (!readUByte(&refFlags)) {
      goto eofError1;
    }
    nRefSegs = refFlags >> 5;
    if (nRefSegs == 7) {
      if ((c1 = curStr->getChar()) == EOF ||
	  (c2 = curStr->getChar()) == EOF ||
	  (c3 = curStr->getChar()) == EOF) {
	goto eofError1;
      }
      refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3;
      nRefSegs = refFlags & 0x1fffffff;
1374
      for (unsigned int i = 0; i < (nRefSegs + 9) >> 3; ++i) {
1375 1376 1377
	if ((c1 = curStr->getChar()) == EOF) {
	  goto eofError1;
	}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1378 1379 1380 1381
      }
    }

    // referred-to segment numbers
1382
    refSegs = (unsigned int *)gmallocn(nRefSegs, sizeof(unsigned int));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1383
    if (segNum <= 256) {
1384
      for (unsigned int i = 0; i < nRefSegs; ++i) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1385 1386 1387 1388 1389
	if (!readUByte(&refSegs[i])) {
	  goto eofError2;
	}
      }
    } else if (segNum <= 65536) {
1390
      for (unsigned int i = 0; i < nRefSegs; ++i) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1391 1392 1393 1394 1395
	if (!readUWord(&refSegs[i])) {
	  goto eofError2;
	}
      }
    } else {
1396
      for (unsigned int i = 0; i < nRefSegs; ++i) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
	if (!readULong(&refSegs[i])) {
	  goto eofError2;
	}
      }
    }

    // segment page association
    if (segFlags & 0x40) {
      if (!readULong(&page)) {
	goto eofError2;
      }
    } else {
      if (!readUByte(&page)) {
	goto eofError2;
      }
    }

    // segment data length
    if (!readULong(&segLength)) {
      goto eofError2;
    }

1419 1420 1421
    // keep track of the start of the segment data 
    segDataPos = curStr->getPos();

1422 1423 1424
    // check for missing page information segment
    if (!pageBitmap && ((segType >= 4 && segType <= 7) ||
			(segType >= 20 && segType <= 43))) {
1425
      error(errSyntaxError, curStr->getPos(), "First JBIG2 segment associated with a page must be a page information segment");
1426 1427 1428
      goto syntaxError;
    }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1429 1430 1431
    // read the segment data
    switch (segType) {
    case 0:
1432 1433 1434
      if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) {
	goto syntaxError;
      }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1435 1436
      break;
    case 4:
1437
      readTextRegionSeg(segNum, false, false, segLength, refSegs, nRefSegs);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1438 1439
      break;
    case 6:
1440
      readTextRegionSeg(segNum, true, false, segLength, refSegs, nRefSegs);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1441 1442
      break;
    case 7:
1443
      readTextRegionSeg(segNum, true, true, segLength, refSegs, nRefSegs);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1444 1445 1446 1447 1448
      break;
    case 16:
      readPatternDictSeg(segNum, segLength);
      break;
    case 20:
1449
      readHalftoneRegionSeg(segNum, false, false, segLength,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1450 1451 1452
			    refSegs, nRefSegs);
      break;
    case 22:
1453
      readHalftoneRegionSeg(segNum, true, false, segLength,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1454 1455 1456
			    refSegs, nRefSegs);
      break;
    case 23:
1457
      readHalftoneRegionSeg(segNum, true, true, segLength,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1458 1459 1460
			    refSegs, nRefSegs);
      break;
    case 36:
1461
      readGenericRegionSeg(segNum, false, false, segLength);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1462 1463
      break;
    case 38:
1464
      readGenericRegionSeg(segNum, true, false, segLength);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1465 1466
      break;
    case 39:
1467
      readGenericRegionSeg(segNum, true, true, segLength);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1468 1469
      break;
    case 40:
1470
      readGenericRefinementRegionSeg(segNum, false, false, segLength,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1471 1472 1473
				     refSegs, nRefSegs);
      break;
    case 42:
1474
      readGenericRefinementRegionSeg(segNum, true, false, segLength,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1475 1476 1477
				     refSegs, nRefSegs);
      break;
    case 43:
1478
      readGenericRefinementRegionSeg(segNum, true, true, segLength,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
				     refSegs, nRefSegs);
      break;
    case 48:
      readPageInfoSeg(segLength);
      break;
    case 50:
      readEndOfStripeSeg(segLength);
      break;
    case 52:
      readProfilesSeg(segLength);
      break;
    case 53:
      readCodeTableSeg(segNum, segLength);
      break;
    case 62:
      readExtensionSeg(segLength);
      break;
    default:
1497
      error(errSyntaxError, curStr->getPos(), "Unknown segment type in JBIG2 stream");
1498
      for (unsigned int i = 0; i < segLength; ++i) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1499 1500 1501 1502 1503 1504 1505
	if ((c1 = curStr->getChar()) == EOF) {
	  goto eofError2;
	}
      }
      break;
    }

1506 1507 1508 1509 1510 1511
    // Make sure the segment handler read all of the bytes in the 
    // segment data, unless this segment is marked as having an
    // unknown length (section 7.2.7 of the JBIG2 Final Committee Draft)

    if (segLength != 0xffffffff) {

Adrian Johnson's avatar
Adrian Johnson committed
1512
      Goffset segExtraBytes = segDataPos + segLength - curStr->getPos();
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
      if (segExtraBytes > 0) {

	// If we didn't read all of the bytes in the segment data,
	// indicate an error, and throw away the rest of the data.
	
	// v.3.1.01.13 of the LuraTech PDF Compressor Server will
	// sometimes generate an extraneous NULL byte at the end of
	// arithmetic-coded symbol dictionary segments when numNewSyms
	// == 0.  Segments like this often occur for blank pages.
	
1523
	error(errSyntaxError, curStr->getPos(), "{0:lld} extraneous byte{1:s} after segment",
1524 1525 1526 1527 1528 1529
	      segExtraBytes, (segExtraBytes > 1) ? "s" : "");
	
	// Burn through the remaining bytes -- inefficient, but
	// hopefully we're not doing this much
	
	int trash;
Adrian Johnson's avatar
Adrian Johnson committed
1530
	for (Goffset i = segExtraBytes; i > 0; i--) {
1531
	  readByte(&trash);
1532
	}
1533 1534 1535 1536 1537 1538 1539 1540
	
      } else if (segExtraBytes < 0) {
	
	// If we read more bytes than we should have, according to the 
	// segment length field, note an error.
	
	error(errSyntaxError, curStr->getPos(), "Previous segment handler read too many bytes");
	
1541
      }
1542

1543 1544
    }
    
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1545 1546 1547 1548 1549
    gfree(refSegs);
  }

  return;

1550 1551 1552 1553
 syntaxError:
  gfree(refSegs);
  return;

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1554 1555 1556
 eofError2:
  gfree(refSegs);
 eofError1:
1557
  error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1558 1559
}

1560 1561
bool JBIG2Stream::readSymbolDictSeg(unsigned int segNum, unsigned int length,
				     unsigned int *refSegs, unsigned int nRefSegs) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1562
  JBIG2SymbolDict *symbolDict;
1563 1564
  const JBIG2HuffmanTable *huffDHTable, *huffDWTable;
  const JBIG2HuffmanTable *huffBMSizeTable, *huffAggInstTable;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1565
  JBIG2Segment *seg;
1566
  std::vector<JBIG2Segment*> *codeTables;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1567
  JBIG2SymbolDict *inputSymbolDict;
1568 1569 1570
  unsigned int flags, sdTemplate, sdrTemplate, huff, refAgg;
  unsigned int huffDH, huffDW, huffBMSize, huffAggInst;
  unsigned int contextUsed, contextRetained;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1571
  int sdATX[4], sdATY[4], sdrATX[2], sdrATY[2];
1572
  unsigned int numExSyms, numNewSyms, numInputSyms, symCodeLen;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1573 1574
  JBIG2Bitmap **bitmaps;
  JBIG2Bitmap *collBitmap, *refBitmap;
1575 1576
  unsigned int *symWidths;
  unsigned int symHeight, symWidth, totalWidth, x, symID;
1577
  int dh = 0, dw, refAggNum, refDX = 0, refDY = 0, bmSize;
1578
  bool ex;
1579
  int run, cnt, c;
1580
  unsigned int i, j, k;
1581
  unsigned char *p;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1582

1583
  symWidths = nullptr;
1584

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
  // symbol dictionary flags
  if (!readUWord(&flags)) {
    goto eofError;
  }
  sdTemplate = (flags >> 10) & 3;
  sdrTemplate = (flags >> 12) & 1;
  huff = flags & 1;
  refAgg = (flags >> 1) & 1;
  huffDH = (flags >> 2) & 3;
  huffDW = (flags >> 4) & 3;
  huffBMSize = (flags >> 6) & 1;
  huffAggInst = (flags >> 7) & 1;
  contextUsed = (flags >> 8) & 1;
  contextRetained = (flags >> 9) & 1;

  // symbol dictionary AT flags
  if (!huff) {
    if (sdTemplate == 0) {
      if (!readByte(&sdATX[0]) ||
	  !readByte(&sdATY[0]) ||
	  !readByte(&sdATX[1]) ||
	  !readByte(&sdATY[1]) ||
	  !readByte(&sdATX[2]) ||
	  !readByte(&sdATY[2]) ||
	  !readByte(&sdATX[3]) ||
	  !readByte(&sdATY[3])) {
	goto eofError;
      }
    } else {
      if (!readByte(&sdATX[0]) ||
	  !readByte(&sdATY[0])) {
	goto eofError;
      }
    }
  }

  // symbol dictionary refinement AT flags
  if (refAgg && !sdrTemplate) {
    if (!readByte(&sdrATX[0]) ||
	!readByte(&sdrATY[0]) ||
	!readByte(&sdrATX[1]) ||
	!readByte(&sdrATY[1])) {
      goto eofError;
    }
  }

  // SDNUMEXSYMS and SDNUMNEWSYMS
  if (!readULong(&numExSyms) || !readULong(&numNewSyms)) {
    goto eofError;
  }

  // get referenced segments: input symbol dictionaries and code tables
1637
  codeTables = new std::vector<JBIG2Segment*>();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1638 1639
  numInputSyms = 0;
  for (i = 0; i < nRefSegs; ++i) {
1640
    // This is need by bug 12014, returning false makes it not crash
1641 1642 1643 1644
    // but we end up with a empty page while acroread is able to render
    // part of it
    if ((seg = findSegment(refSegs[i]))) {
      if (seg->getType() == jbig2SegSymbolDict) {
1645 1646
	j = ((JBIG2SymbolDict *)seg)->getSize();
	if (numInputSyms > UINT_MAX - j) {
1647
	  error(errSyntaxError, curStr->getPos(), "Too many input symbols in JBIG2 symbol dictionary");
1648 1649 1650 1651
	  delete codeTables;
	  goto eofError;
	}
	numInputSyms += j;
1652
      } else if