Skip to content
Snippets Groups Projects
pdfjs.parser.js 337 KiB
Newer Older
  • Learn to ignore specific revisions
  •         return p[1];
          }
        } else {
          var result = this.findTableCode(2, 6, blackTable3);
          if (result[0]) {
            return result[1];
          }
    
          result = this.findTableCode(7, 12, blackTable2, 64);
          if (result[0]) {
            return result[1];
          }
    
          result = this.findTableCode(10, 13, blackTable1);
          if (result[0]) {
            return result[1];
          }
        }
        info('bad black code');
        this.eatBits(1);
        return 1;
      };
    
      CCITTFaxStream.prototype.lookBits = function CCITTFaxStream_lookBits(n) {
        var c;
        while (this.inputBits < n) {
          if ((c = this.str.getByte()) === -1) {
            if (this.inputBits === 0) {
              return EOF;
            }
            return ((this.inputBuf << (n - this.inputBits)) &
                    (0xFFFF >> (16 - n)));
          }
          this.inputBuf = (this.inputBuf << 8) + c;
          this.inputBits += 8;
        }
        return (this.inputBuf >> (this.inputBits - n)) & (0xFFFF >> (16 - n));
      };
    
      CCITTFaxStream.prototype.eatBits = function CCITTFaxStream_eatBits(n) {
        if ((this.inputBits -= n) < 0) {
          this.inputBits = 0;
        }
      };
    
      return CCITTFaxStream;
    })();
    
    var LZWStream = (function LZWStreamClosure() {
      function LZWStream(str, maybeLength, earlyChange) {
        this.str = str;
        this.dict = str.dict;
        this.cachedData = 0;
        this.bitsCached = 0;
    
        var maxLzwDictionarySize = 4096;
        var lzwState = {
          earlyChange: earlyChange,
          codeLength: 9,
          nextCode: 258,
          dictionaryValues: new Uint8Array(maxLzwDictionarySize),
          dictionaryLengths: new Uint16Array(maxLzwDictionarySize),
          dictionaryPrevCodes: new Uint16Array(maxLzwDictionarySize),
          currentSequence: new Uint8Array(maxLzwDictionarySize),
          currentSequenceLength: 0
        };
        for (var i = 0; i < 256; ++i) {
          lzwState.dictionaryValues[i] = i;
          lzwState.dictionaryLengths[i] = 1;
        }
        this.lzwState = lzwState;
    
        DecodeStream.call(this, maybeLength);
      }
    
      LZWStream.prototype = Object.create(DecodeStream.prototype);
    
      LZWStream.prototype.readBits = function LZWStream_readBits(n) {
        var bitsCached = this.bitsCached;
        var cachedData = this.cachedData;
        while (bitsCached < n) {
          var c = this.str.getByte();
          if (c === -1) {
            this.eof = true;
            return null;
          }
          cachedData = (cachedData << 8) | c;
          bitsCached += 8;
        }
        this.bitsCached = (bitsCached -= n);
        this.cachedData = cachedData;
        this.lastCode = null;
        return (cachedData >>> bitsCached) & ((1 << n) - 1);
      };
    
      LZWStream.prototype.readBlock = function LZWStream_readBlock() {
        var blockSize = 512;
        var estimatedDecodedSize = blockSize * 2, decodedSizeDelta = blockSize;
        var i, j, q;
    
        var lzwState = this.lzwState;
        if (!lzwState) {
          return; // eof was found
        }
    
        var earlyChange = lzwState.earlyChange;
        var nextCode = lzwState.nextCode;
        var dictionaryValues = lzwState.dictionaryValues;
        var dictionaryLengths = lzwState.dictionaryLengths;
        var dictionaryPrevCodes = lzwState.dictionaryPrevCodes;
        var codeLength = lzwState.codeLength;
        var prevCode = lzwState.prevCode;
        var currentSequence = lzwState.currentSequence;
        var currentSequenceLength = lzwState.currentSequenceLength;
    
        var decodedLength = 0;
        var currentBufferLength = this.bufferLength;
        var buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
    
        for (i = 0; i < blockSize; i++) {
          var code = this.readBits(codeLength);
          var hasPrev = currentSequenceLength > 0;
          if (code < 256) {
            currentSequence[0] = code;
            currentSequenceLength = 1;
          } else if (code >= 258) {
            if (code < nextCode) {
              currentSequenceLength = dictionaryLengths[code];
              for (j = currentSequenceLength - 1, q = code; j >= 0; j--) {
                currentSequence[j] = dictionaryValues[q];
                q = dictionaryPrevCodes[q];
              }
            } else {
              currentSequence[currentSequenceLength++] = currentSequence[0];
            }
          } else if (code === 256) {
            codeLength = 9;
            nextCode = 258;
            currentSequenceLength = 0;
            continue;
          } else {
            this.eof = true;
            delete this.lzwState;
            break;
          }
    
          if (hasPrev) {
            dictionaryPrevCodes[nextCode] = prevCode;
            dictionaryLengths[nextCode] = dictionaryLengths[prevCode] + 1;
            dictionaryValues[nextCode] = currentSequence[0];
            nextCode++;
            codeLength = (nextCode + earlyChange) & (nextCode + earlyChange - 1) ?
              codeLength : Math.min(Math.log(nextCode + earlyChange) /
              0.6931471805599453 + 1, 12) | 0;
          }
          prevCode = code;
    
          decodedLength += currentSequenceLength;
          if (estimatedDecodedSize < decodedLength) {
            do {
              estimatedDecodedSize += decodedSizeDelta;
            } while (estimatedDecodedSize < decodedLength);
            buffer = this.ensureBuffer(this.bufferLength + estimatedDecodedSize);
          }
          for (j = 0; j < currentSequenceLength; j++) {
            buffer[currentBufferLength++] = currentSequence[j];
          }
        }
        lzwState.nextCode = nextCode;
        lzwState.codeLength = codeLength;
        lzwState.prevCode = prevCode;
        lzwState.currentSequenceLength = currentSequenceLength;
    
        this.bufferLength = currentBufferLength;
      };
    
      return LZWStream;
    })();
    
    var NullStream = (function NullStreamClosure() {
      function NullStream() {
        Stream.call(this, new Uint8Array(0));
      }
    
      NullStream.prototype = Stream.prototype;
    
      return NullStream;
    })();
    
    // TODO refactor to remove dependency on parser.js
    function _setCoreParser(coreParser_) {
      coreParser = coreParser_;
      EOF = coreParser_.EOF;
      Lexer = coreParser_.Lexer;
    }
    exports._setCoreParser = _setCoreParser;
    
    // TODO refactor to remove dependency on colorspace.js
    function _setCoreColorSpace(coreColorSpace_) {
      coreColorSpace = coreColorSpace_;
      ColorSpace = coreColorSpace_.ColorSpace;
    }
    exports._setCoreColorSpace = _setCoreColorSpace;
    
    exports.Ascii85Stream = Ascii85Stream;
    exports.AsciiHexStream = AsciiHexStream;
    exports.CCITTFaxStream = CCITTFaxStream;
    exports.DecryptStream = DecryptStream;
    exports.DecodeStream = DecodeStream;
    exports.FlateStream = FlateStream;
    exports.Jbig2Stream = Jbig2Stream;
    exports.JpegStream = JpegStream;
    exports.JpxStream = JpxStream;
    exports.NullStream = NullStream;
    exports.PredictorStream = PredictorStream;
    exports.RunLengthStream = RunLengthStream;
    exports.Stream = Stream;
    exports.StreamsSequenceStream = StreamsSequenceStream;
    exports.StringStream = StringStream;
    exports.LZWStream = LZWStream;
    }));
    
    /* Copyright 2012 Mozilla Foundation
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    'use strict';
    
    (function (root, factory) {
    
    Damyan Mitev's avatar
    Damyan Mitev committed
      //if (typeof define === 'function' && define.amd) {
      //  define('pdfjs/core/parser', ['exports', 'pdfjs/shared/util',
      //    'pdfjs/core/primitives', 'pdfjs/core/stream'], factory);
    
      // } else if (typeof exports !== 'undefined') {
      //   factory(exports, require('../shared/util.js'), require('./primitives.js'),
      //     require('./stream.js'));
    
    Damyan Mitev's avatar
    Damyan Mitev committed
      //} else {
    
        factory((root.pdfjsCoreParser = {}), root.pdfjsSharedUtil,
          root.pdfjsCorePrimitives, root.pdfjsCoreStream);
    
    Damyan Mitev's avatar
    Damyan Mitev committed
      //}
    
    5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000
    }(window, function (exports, sharedUtil, corePrimitives, coreStream) {
    
    var MissingDataException = sharedUtil.MissingDataException;
    var StreamType = sharedUtil.StreamType;
    var assert = sharedUtil.assert;
    var error = sharedUtil.error;
    var info = sharedUtil.info;
    var isArray = sharedUtil.isArray;
    var isInt = sharedUtil.isInt;
    var isNum = sharedUtil.isNum;
    var isString = sharedUtil.isString;
    var warn = sharedUtil.warn;
    var Cmd = corePrimitives.Cmd;
    var Dict = corePrimitives.Dict;
    var Name = corePrimitives.Name;
    var Ref = corePrimitives.Ref;
    var isCmd = corePrimitives.isCmd;
    var isDict = corePrimitives.isDict;
    var isName = corePrimitives.isName;
    var Ascii85Stream = coreStream.Ascii85Stream;
    var AsciiHexStream = coreStream.AsciiHexStream;
    var CCITTFaxStream = coreStream.CCITTFaxStream;
    var FlateStream = coreStream.FlateStream;
    var Jbig2Stream = coreStream.Jbig2Stream;
    var JpegStream = coreStream.JpegStream;
    var JpxStream = coreStream.JpxStream;
    var LZWStream = coreStream.LZWStream;
    var NullStream = coreStream.NullStream;
    var PredictorStream = coreStream.PredictorStream;
    var RunLengthStream = coreStream.RunLengthStream;
    
    var EOF = {};
    
    function isEOF(v) {
      return (v === EOF);
    }
    
    var MAX_LENGTH_TO_CACHE = 1000;
    
    var Parser = (function ParserClosure() {
      function Parser(lexer, allowStreams, xref) {
        this.lexer = lexer;
        this.allowStreams = allowStreams;
        this.xref = xref;
        this.imageCache = {};
        this.refill();
      }
    
      Parser.prototype = {
        refill: function Parser_refill() {
          this.buf1 = this.lexer.getObj();
          this.buf2 = this.lexer.getObj();
        },
        shift: function Parser_shift() {
          if (isCmd(this.buf2, 'ID')) {
            this.buf1 = this.buf2;
            this.buf2 = null;
          } else {
            this.buf1 = this.buf2;
            this.buf2 = this.lexer.getObj();
          }
        },
        tryShift: function Parser_tryShift() {
          try {
            this.shift();
            return true;
          } catch (e) {
            if (e instanceof MissingDataException) {
              throw e;
            }
            // Upon failure, the caller should reset this.lexer.pos to a known good
            // state and call this.shift() twice to reset the buffers.
            return false;
          }
        },
        getObj: function Parser_getObj(cipherTransform) {
          var buf1 = this.buf1;
          this.shift();
    
          if (buf1 instanceof Cmd) {
            switch (buf1.cmd) {
              case 'BI': // inline image
                return this.makeInlineImage(cipherTransform);
              case '[': // array
                var array = [];
                while (!isCmd(this.buf1, ']') && !isEOF(this.buf1)) {
                  array.push(this.getObj(cipherTransform));
                }
                if (isEOF(this.buf1)) {
                  error('End of file inside array');
                }
                this.shift();
                return array;
              case '<<': // dictionary or stream
                var dict = new Dict(this.xref);
                while (!isCmd(this.buf1, '>>') && !isEOF(this.buf1)) {
                  if (!isName(this.buf1)) {
                    info('Malformed dictionary: key must be a name object');
                    this.shift();
                    continue;
                  }
                  var pos = this.lexer.stream.pos;
                  var key = this.buf1.name;
                  dict.set('#' +key+ '_offset', pos);
                  this.shift();
                  if (isEOF(this.buf1)) {
                    break;
                  }
                  dict.set(key, this.getObj(cipherTransform));
                  
                }
                if (isEOF(this.buf1)) {
                  error('End of file inside dictionary');
                }
    
                // Stream objects are not allowed inside content streams or
                // object streams.
                if (isCmd(this.buf2, 'stream')) {
                  return (this.allowStreams ?
                          this.makeStream(dict, cipherTransform) : dict);
                }
                this.shift();
                return dict;
              default: // simple object
                return buf1;
            }
          }
    
          if (isInt(buf1)) { // indirect reference or integer
            var num = buf1;
            if (isInt(this.buf1) && isCmd(this.buf2, 'R')) {
              var ref = new Ref(num, this.buf1);
              this.shift();
              this.shift();
              return ref;
            }
            return num;
          }
    
          if (isString(buf1)) { // string
            var str = buf1;
            if (cipherTransform) {
              str = cipherTransform.decryptString(str);
            }
            return str;
          }
    
          // simple object
          return buf1;
        },
        /**
         * Find the end of the stream by searching for the /EI\s/.
         * @returns {number} The inline stream length.
         */
        findDefaultInlineStreamEnd:
            function Parser_findDefaultInlineStreamEnd(stream) {
          var E = 0x45, I = 0x49, SPACE = 0x20, LF = 0xA, CR = 0xD;
          var startPos = stream.pos, state = 0, ch, i, n, followingBytes;
          while ((ch = stream.getByte()) !== -1) {
            if (state === 0) {
              state = (ch === E) ? 1 : 0;
            } else if (state === 1) {
              state = (ch === I) ? 2 : 0;
            } else {
              assert(state === 2);
              if (ch === SPACE || ch === LF || ch === CR) {
                // Let's check the next five bytes are ASCII... just be sure.
                n = 5;
                followingBytes = stream.peekBytes(n);
                for (i = 0; i < n; i++) {
                  ch = followingBytes[i];
                  if (ch !== LF && ch !== CR && (ch < SPACE || ch > 0x7F)) {
                    // Not a LF, CR, SPACE or any visible ASCII character, i.e.
                    // it's binary stuff. Resetting the state.
                    state = 0;
                    break;
                  }
                }
                if (state === 2) {
                  break;  // Finished!
                }
              } else {
                state = 0;
              }
            }
          }
          return ((stream.pos - 4) - startPos);
        },
        /**
         * Find the EOI (end-of-image) marker 0xFFD9 of the stream.
         * @returns {number} The inline stream length.
         */
        findDCTDecodeInlineStreamEnd:
            function Parser_findDCTDecodeInlineStreamEnd(stream) {
          var startPos = stream.pos, foundEOI = false, b, markerLength, length;
          while ((b = stream.getByte()) !== -1) {
            if (b !== 0xFF) { // Not a valid marker.
              continue;
            }
            switch (stream.getByte()) {
              case 0x00: // Byte stuffing.
                // 0xFF00 appears to be a very common byte sequence in JPEG images.
                break;
    
              case 0xFF: // Fill byte.
                // Avoid skipping a valid marker, resetting the stream position.
                stream.skip(-1);
                break;
    
              case 0xD9: // EOI
                foundEOI = true;
                break;
    
              case 0xC0: // SOF0
              case 0xC1: // SOF1
              case 0xC2: // SOF2
              case 0xC3: // SOF3
    
              case 0xC5: // SOF5
              case 0xC6: // SOF6
              case 0xC7: // SOF7
    
              case 0xC9: // SOF9
              case 0xCA: // SOF10
              case 0xCB: // SOF11
    
              case 0xCD: // SOF13
              case 0xCE: // SOF14
              case 0xCF: // SOF15
    
              case 0xC4: // DHT
              case 0xCC: // DAC
    
              case 0xDA: // SOS
              case 0xDB: // DQT
              case 0xDC: // DNL
              case 0xDD: // DRI
              case 0xDE: // DHP
              case 0xDF: // EXP
    
              case 0xE0: // APP0
              case 0xE1: // APP1
              case 0xE2: // APP2
              case 0xE3: // APP3
              case 0xE4: // APP4
              case 0xE5: // APP5
              case 0xE6: // APP6
              case 0xE7: // APP7
              case 0xE8: // APP8
              case 0xE9: // APP9
              case 0xEA: // APP10
              case 0xEB: // APP11
              case 0xEC: // APP12
              case 0xED: // APP13
              case 0xEE: // APP14
              case 0xEF: // APP15
    
              case 0xFE: // COM
                // The marker should be followed by the length of the segment.
                markerLength = stream.getUint16();
                if (markerLength > 2) {
                  // |markerLength| contains the byte length of the marker segment,
                  // including its own length (2 bytes) and excluding the marker.
                  stream.skip(markerLength - 2); // Jump to the next marker.
                } else {
                  // The marker length is invalid, resetting the stream position.
                  stream.skip(-2);
                }
                break;
            }
            if (foundEOI) {
              break;
            }
          }
          length = stream.pos - startPos;
          if (b === -1) {
            warn('Inline DCTDecode image stream: ' +
                 'EOI marker not found, searching for /EI/ instead.');
            stream.skip(-length); // Reset the stream position.
            return this.findDefaultInlineStreamEnd(stream);
          }
          this.inlineStreamSkipEI(stream);
          return length;
        },
        /**
         * Find the EOD (end-of-data) marker '~>' (i.e. TILDE + GT) of the stream.
         * @returns {number} The inline stream length.
         */
        findASCII85DecodeInlineStreamEnd:
            function Parser_findASCII85DecodeInlineStreamEnd(stream) {
          var TILDE = 0x7E, GT = 0x3E;
          var startPos = stream.pos, ch, length;
          while ((ch = stream.getByte()) !== -1) {
            if (ch === TILDE && stream.peekByte() === GT) {
              stream.skip();
              break;
            }
          }
          length = stream.pos - startPos;
          if (ch === -1) {
            warn('Inline ASCII85Decode image stream: ' +
                 'EOD marker not found, searching for /EI/ instead.');
            stream.skip(-length); // Reset the stream position.
            return this.findDefaultInlineStreamEnd(stream);
          }
          this.inlineStreamSkipEI(stream);
          return length;
        },
        /**
         * Find the EOD (end-of-data) marker '>' (i.e. GT) of the stream.
         * @returns {number} The inline stream length.
         */
        findASCIIHexDecodeInlineStreamEnd:
            function Parser_findASCIIHexDecodeInlineStreamEnd(stream) {
          var GT = 0x3E;
          var startPos = stream.pos, ch, length;
          while ((ch = stream.getByte()) !== -1) {
            if (ch === GT) {
              break;
            }
          }
          length = stream.pos - startPos;
          if (ch === -1) {
            warn('Inline ASCIIHexDecode image stream: ' +
                 'EOD marker not found, searching for /EI/ instead.');
            stream.skip(-length); // Reset the stream position.
            return this.findDefaultInlineStreamEnd(stream);
          }
          this.inlineStreamSkipEI(stream);
          return length;
        },
        /**
         * Skip over the /EI/ for streams where we search for an EOD marker.
         */
        inlineStreamSkipEI: function Parser_inlineStreamSkipEI(stream) {
          var E = 0x45, I = 0x49;
          var state = 0, ch;
          while ((ch = stream.getByte()) !== -1) {
            if (state === 0) {
              state = (ch === E) ? 1 : 0;
            } else if (state === 1) {
              state = (ch === I) ? 2 : 0;
            } else if (state === 2) {
              break;
            }
          }
        },
        makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
          var lexer = this.lexer;
          var stream = lexer.stream;
    
          // Parse dictionary.
          var dict = new Dict(this.xref);
          while (!isCmd(this.buf1, 'ID') && !isEOF(this.buf1)) {
            if (!isName(this.buf1)) {
              error('Dictionary key must be a name object');
            }
            var key = this.buf1.name;
            this.shift();
            if (isEOF(this.buf1)) {
              break;
            }
            dict.set(key, this.getObj(cipherTransform));
          }
    
          // Extract the name of the first (i.e. the current) image filter.
          var filter = dict.get('Filter', 'F'), filterName;
          if (isName(filter)) {
            filterName = filter.name;
          } else if (isArray(filter) && isName(filter[0])) {
            filterName = filter[0].name;
          }
    
          // Parse image stream.
          var startPos = stream.pos, length, i, ii;
          if (filterName === 'DCTDecode' || filterName === 'DCT') {
            length = this.findDCTDecodeInlineStreamEnd(stream);
          } else if (filterName === 'ASCII85Decide' || filterName === 'A85') {
            length = this.findASCII85DecodeInlineStreamEnd(stream);
          } else if (filterName === 'ASCIIHexDecode' || filterName === 'AHx') {
            length = this.findASCIIHexDecodeInlineStreamEnd(stream);
          } else {
            length = this.findDefaultInlineStreamEnd(stream);
          }
          var imageStream = stream.makeSubStream(startPos, length, dict);
    
          // Cache all images below the MAX_LENGTH_TO_CACHE threshold by their
          // adler32 checksum.
          var adler32;
          if (length < MAX_LENGTH_TO_CACHE) {
            var imageBytes = imageStream.getBytes();
            imageStream.reset();
    
            var a = 1;
            var b = 0;
            for (i = 0, ii = imageBytes.length; i < ii; ++i) {
              // No modulo required in the loop if imageBytes.length < 5552.
              a += imageBytes[i] & 0xff;
              b += a;
            }
            adler32 = ((b % 65521) << 16) | (a % 65521);
    
            if (this.imageCache.adler32 === adler32) {
              this.buf2 = Cmd.get('EI');
              this.shift();
    
              this.imageCache[adler32].reset();
              return this.imageCache[adler32];
            }
          }
    
          if (cipherTransform) {
            imageStream = cipherTransform.createStream(imageStream, length);
          }
    
          imageStream = this.filter(imageStream, dict, length);
          imageStream.dict = dict;
          if (adler32 !== undefined) {
            imageStream.cacheKey = 'inline_' + length + '_' + adler32;
            this.imageCache[adler32] = imageStream;
          }
    
          this.buf2 = Cmd.get('EI');
          this.shift();
    
          return imageStream;
        },
        makeStream: function Parser_makeStream(dict, cipherTransform) {
          var lexer = this.lexer;
          var stream = lexer.stream;
    
          // get stream start position
          lexer.skipToNextLine();
          var pos = stream.pos - 1;
    
          // get length
          var length = dict.get('Length');
          if (!isInt(length)) {
            info('Bad ' + length + ' attribute in stream');
            length = 0;
          }
    
          // skip over the stream data
          stream.pos = pos + length;
          lexer.nextChar();
    
          // Shift '>>' and check whether the new object marks the end of the stream
          if (this.tryShift() && isCmd(this.buf2, 'endstream')) {
            this.shift(); // 'stream'
          } else {
            // bad stream length, scanning for endstream
            stream.pos = pos;
            var SCAN_BLOCK_SIZE = 2048;
            var ENDSTREAM_SIGNATURE_LENGTH = 9;
            var ENDSTREAM_SIGNATURE = [0x65, 0x6E, 0x64, 0x73, 0x74, 0x72, 0x65,
                                       0x61, 0x6D];
            var skipped = 0, found = false, i, j;
            while (stream.pos < stream.end) {
              var scanBytes = stream.peekBytes(SCAN_BLOCK_SIZE);
              var scanLength = scanBytes.length - ENDSTREAM_SIGNATURE_LENGTH;
              if (scanLength <= 0) {
                break;
              }
              found = false;
              for (i = 0, j = 0; i < scanLength; i++) {
                var b = scanBytes[i];
                if (b !== ENDSTREAM_SIGNATURE[j]) {
                  i -= j;
                  j = 0;
                } else {
                  j++;
                  if (j >= ENDSTREAM_SIGNATURE_LENGTH) {
                    i++;
                    found = true;
                    break;
                  }
                }
              }
              if (found) {
                skipped += i - ENDSTREAM_SIGNATURE_LENGTH;
                stream.pos += i - ENDSTREAM_SIGNATURE_LENGTH;
                break;
              }
              skipped += scanLength;
              stream.pos += scanLength;
            }
            if (!found) {
              error('Missing endstream');
            }
            length = skipped;
    
            lexer.nextChar();
            this.shift();
            this.shift();
          }
          this.shift(); // 'endstream'
    
          stream = stream.makeSubStream(pos, length, dict);
          if (cipherTransform) {
            stream = cipherTransform.createStream(stream, length);
          }
          stream = this.filter(stream, dict, length);
          stream.dict = dict;
          return stream;
        },
        filter: function Parser_filter(stream, dict, length) {
          var filter = dict.get('Filter', 'F');
          var params = dict.get('DecodeParms', 'DP');
          if (isName(filter)) {
            return this.makeFilter(stream, filter.name, length, params);
          }
    
          var maybeLength = length;
          if (isArray(filter)) {
            var filterArray = filter;
            var paramsArray = params;
            for (var i = 0, ii = filterArray.length; i < ii; ++i) {
              filter = filterArray[i];
              if (!isName(filter)) {
                error('Bad filter name: ' + filter);
              }
    
              params = null;
              if (isArray(paramsArray) && (i in paramsArray)) {
                params = paramsArray[i];
              }
              stream = this.makeFilter(stream, filter.name, maybeLength, params);
              // after the first stream the length variable is invalid
              maybeLength = null;
            }
          }
          return stream;
        },
        makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {
          if (stream.dict.get('Length') === 0 && !maybeLength) {
            warn('Empty "' + name + '" stream.');
            return new NullStream(stream);
          }
          try {
            if (params && this.xref) {
              params = this.xref.fetchIfRef(params);
            }
            var xrefStreamStats = this.xref.stats.streamTypes;
            if (name === 'FlateDecode' || name === 'Fl') {
              xrefStreamStats[StreamType.FLATE] = true;
              if (params) {
                return new PredictorStream(new FlateStream(stream, maybeLength),
                                           maybeLength, params);
              }
              return new FlateStream(stream, maybeLength);
            }
            if (name === 'LZWDecode' || name === 'LZW') {
              xrefStreamStats[StreamType.LZW] = true;
              var earlyChange = 1;
              if (params) {
                if (params.has('EarlyChange')) {
                  earlyChange = params.get('EarlyChange');
                }
                return new PredictorStream(
                  new LZWStream(stream, maybeLength, earlyChange),
                  maybeLength, params);
              }
              return new LZWStream(stream, maybeLength, earlyChange);
            }
            if (name === 'DCTDecode' || name === 'DCT') {
              xrefStreamStats[StreamType.DCT] = true;
              return new JpegStream(stream, maybeLength, stream.dict, this.xref);
            }
            if (name === 'JPXDecode' || name === 'JPX') {
              xrefStreamStats[StreamType.JPX] = true;
              return new JpxStream(stream, maybeLength, stream.dict);
            }
            if (name === 'ASCII85Decode' || name === 'A85') {
              xrefStreamStats[StreamType.A85] = true;
              return new Ascii85Stream(stream, maybeLength);
            }
            if (name === 'ASCIIHexDecode' || name === 'AHx') {
              xrefStreamStats[StreamType.AHX] = true;
              return new AsciiHexStream(stream, maybeLength);
            }
            if (name === 'CCITTFaxDecode' || name === 'CCF') {
              xrefStreamStats[StreamType.CCF] = true;
              return new CCITTFaxStream(stream, maybeLength, params);
            }
            if (name === 'RunLengthDecode' || name === 'RL') {
              xrefStreamStats[StreamType.RL] = true;
              return new RunLengthStream(stream, maybeLength);
            }
            if (name === 'JBIG2Decode') {
              xrefStreamStats[StreamType.JBIG] = true;
              return new Jbig2Stream(stream, maybeLength, stream.dict);
            }
            warn('filter "' + name + '" not supported yet');
            return stream;
          } catch (ex) {
            if (ex instanceof MissingDataException) {
              throw ex;
            }
            warn('Invalid stream: \"' + ex + '\"');
            return new NullStream(stream);
          }
        }
      };
    
      return Parser;
    })();
    
    var Lexer = (function LexerClosure() {
      function Lexer(stream, knownCommands) {
        this.stream = stream;
        this.nextChar();
    
        // While lexing, we build up many strings one char at a time. Using += for
        // this can result in lots of garbage strings. It's better to build an
        // array of single-char strings and then join() them together at the end.
        // And reusing a single array (i.e. |this.strBuf|) over and over for this
        // purpose uses less memory than using a new array for each string.
        this.strBuf = [];
    
        // The PDFs might have "glued" commands with other commands, operands or
        // literals, e.g. "q1". The knownCommands is a dictionary of the valid
        // commands and their prefixes. The prefixes are built the following way:
        // if there a command that is a prefix of the other valid command or
        // literal (e.g. 'f' and 'false') the following prefixes must be included,
        // 'fa', 'fal', 'fals'. The prefixes are not needed, if the command has no
        // other commands or literals as a prefix. The knowCommands is optional.
        this.knownCommands = knownCommands;
      }
    
      Lexer.isSpace = function Lexer_isSpace(ch) {
        // Space is one of the following characters: SPACE, TAB, CR or LF.
        return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
      };
    
      // A '1' in this array means the character is white space. A '1' or
      // '2' means the character ends a name or command.
      var specialChars = [
        1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // 0x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1x
        1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, // 2x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, // 3x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 5x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, // 7x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9x
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ax
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // bx
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // cx
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // dx
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ex
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0  // fx
      ];
    
      function toHexDigit(ch) {
        if (ch >= 0x30 && ch <= 0x39) { // '0'-'9'
          return ch & 0x0F;
        }
        if ((ch >= 0x41 && ch <= 0x46) || (ch >= 0x61 && ch <= 0x66)) {
          // 'A'-'F', 'a'-'f'
          return (ch & 0x0F) + 9;
        }
        return -1;
      }
    
      Lexer.prototype = {
        nextChar: function Lexer_nextChar() {
          return (this.currentChar = this.stream.getByte());
        },
        peekChar: function Lexer_peekChar() {
          return this.stream.peekByte();
        },
        getNumber: function Lexer_getNumber() {
          var ch = this.currentChar;
          var eNotation = false;
          var divideBy = 0; // different from 0 if it's a floating point value
          var sign = 1;
    
          if (ch === 0x2D) { // '-'
            sign = -1;
            ch = this.nextChar();
    
            if (ch === 0x2D) { // '-'
              // Ignore double negative (this is consistent with Adobe Reader).
              ch = this.nextChar();
            }
          } else if (ch === 0x2B) { // '+'
            ch = this.nextChar();
          }
          if (ch === 0x2E) { // '.'
            divideBy = 10;
            ch = this.nextChar();
          }
          if (ch < 0x30 || ch > 0x39) { // '0' - '9'
            error('Invalid number: ' + String.fromCharCode(ch));
            return 0;
          }
    
          var baseValue = ch - 0x30; // '0'
          var powerValue = 0;
          var powerValueSign = 1;
    
          while ((ch = this.nextChar()) >= 0) {
            if (0x30 <= ch && ch <= 0x39) { // '0' - '9'
              var currentDigit = ch - 0x30; // '0'
              if (eNotation) { // We are after an 'e' or 'E'
                powerValue = powerValue * 10 + currentDigit;
              } else {
                if (divideBy !== 0) { // We are after a point
                  divideBy *= 10;
                }
                baseValue = baseValue * 10 + currentDigit;
              }
            } else if (ch === 0x2E) { // '.'
              if (divideBy === 0) {
                divideBy = 1;
              } else {
                // A number can have only one '.'
                break;
              }
            } else if (ch === 0x2D) { // '-'
              // ignore minus signs in the middle of numbers to match
              // Adobe's behavior
              warn('Badly formated number');
            } else if (ch === 0x45 || ch === 0x65) { // 'E', 'e'
              // 'E' can be either a scientific notation or the beginning of a new
              // operator
              ch = this.peekChar();
              if (ch === 0x2B || ch === 0x2D) { // '+', '-'
                powerValueSign = (ch === 0x2D) ? -1 : 1;
                this.nextChar(); // Consume the sign character
              } else if (ch < 0x30 || ch > 0x39) { // '0' - '9'
                // The 'E' must be the beginning of a new operator
                break;
              }
              eNotation = true;
            } else {
              // the last character doesn't belong to us
              break;
            }
          }
    
          if (divideBy !== 0) {
            baseValue /= divideBy;
          }
          if (eNotation) {
            baseValue *= Math.pow(10, powerValueSign * powerValue);
          }
          return sign * baseValue;