Quelle pdf.worker.mjs
Sprache: unbekannt
|
|
Spracherkennung für: .mjs vermutete Sprache: Unknown {[0] [0] [0]} [Methode: Schwerpunktbildung, einfache Gewichte, sechs Dimensionen]
/**
* @licstart The following is the entire license notice for the
* JavaScript code in this page
*
* Copyright 2024 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.
*
* @licend The above is the entire license notice for the
* JavaScript code in this page
*/
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, k ey)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = globalThis.pdfjsWorker = {};
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
WorkerMessageHandler: () => (/* reexport */ WorkerMessageHandler)
});
;// ./src/shared/util.js
const isNodeJS = false;
const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
const MAX_IMAGE_SIZE_TO_CACHE = 10e6;
const LINE_FACTOR = 1.35;
const LINE_DESCENT_FACTOR = 0.35;
const BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR;
const RenderingIntentFlag = {
ANY: 0x01,
DISPLAY: 0x02,
PRINT: 0x04,
SAVE: 0x08,
ANNOTATIONS_FORMS: 0x10,
ANNOTATIONS_STORAGE: 0x20,
ANNOTATIONS_DISABLE: 0x40,
IS_EDITING: 0x80,
OPLIST: 0x100
};
const AnnotationMode = {
DISABLE: 0,
ENABLE: 1,
ENABLE_FORMS: 2,
ENABLE_STORAGE: 3
};
const AnnotationEditorPrefix = "pdfjs_internal_editor_";
const AnnotationEditorType = {
DISABLE: -1,
NONE: 0,
FREETEXT: 3,
HIGHLIGHT: 9,
STAMP: 13,
INK: 15
};
const AnnotationEditorParamsType = {
RESIZE: 1,
CREATE: 2,
FREETEXT_SIZE: 11,
FREETEXT_COLOR: 12,
FREETEXT_OPACITY: 13,
INK_COLOR: 21,
INK_THICKNESS: 22,
INK_OPACITY: 23,
HIGHLIGHT_COLOR: 31,
HIGHLIGHT_DEFAULT_COLOR: 32,
HIGHLIGHT_THICKNESS: 33,
HIGHLIGHT_FREE: 34,
HIGHLIGHT_SHOW_ALL: 35,
DRAW_STEP: 41
};
const PermissionFlag = {
PRINT: 0x04,
MODIFY_CONTENTS: 0x08,
COPY: 0x10,
MODIFY_ANNOTATIONS: 0x20,
FILL_INTERACTIVE_FORMS: 0x100,
COPY_FOR_ACCESSIBILITY: 0x200,
ASSEMBLE: 0x400,
PRINT_HIGH_QUALITY: 0x800
};
const TextRenderingMode = {
FILL: 0,
STROKE: 1,
FILL_STROKE: 2,
INVISIBLE: 3,
FILL_ADD_TO_PATH: 4,
STROKE_ADD_TO_PATH: 5,
FILL_STROKE_ADD_TO_PATH: 6,
ADD_TO_PATH: 7,
FILL_STROKE_MASK: 3,
ADD_TO_PATH_FLAG: 4
};
const ImageKind = {
GRAYSCALE_1BPP: 1,
RGB_24BPP: 2,
RGBA_32BPP: 3
};
const AnnotationType = {
TEXT: 1,
LINK: 2,
FREETEXT: 3,
LINE: 4,
SQUARE: 5,
CIRCLE: 6,
POLYGON: 7,
POLYLINE: 8,
HIGHLIGHT: 9,
UNDERLINE: 10,
SQUIGGLY: 11,
STRIKEOUT: 12,
STAMP: 13,
CARET: 14,
INK: 15,
POPUP: 16,
FILEATTACHMENT: 17,
SOUND: 18,
MOVIE: 19,
WIDGET: 20,
SCREEN: 21,
PRINTERMARK: 22,
TRAPNET: 23,
WATERMARK: 24,
THREED: 25,
REDACT: 26
};
const AnnotationReplyType = {
GROUP: "Group",
REPLY: "R"
};
const AnnotationFlag = {
INVISIBLE: 0x01,
HIDDEN: 0x02,
PRINT: 0x04,
NOZOOM: 0x08,
NOROTATE: 0x10,
NOVIEW: 0x20,
READONLY: 0x40,
LOCKED: 0x80,
TOGGLENOVIEW: 0x100,
LOCKEDCONTENTS: 0x200
};
const AnnotationFieldFlag = {
READONLY: 0x0000001,
REQUIRED: 0x0000002,
NOEXPORT: 0x0000004,
MULTILINE: 0x0001000,
PASSWORD: 0x0002000,
NOTOGGLETOOFF: 0x0004000,
RADIO: 0x0008000,
PUSHBUTTON: 0x0010000,
COMBO: 0x0020000,
EDIT: 0x0040000,
SORT: 0x0080000,
FILESELECT: 0x0100000,
MULTISELECT: 0x0200000,
DONOTSPELLCHECK: 0x0400000,
DONOTSCROLL: 0x0800000,
COMB: 0x1000000,
RICHTEXT: 0x2000000,
RADIOSINUNISON: 0x2000000,
COMMITONSELCHANGE: 0x4000000
};
const AnnotationBorderStyleType = {
SOLID: 1,
DASHED: 2,
BEVELED: 3,
INSET: 4,
UNDERLINE: 5
};
const AnnotationActionEventType = {
E: "Mouse Enter",
X: "Mouse Exit",
D: "Mouse Down",
U: "Mouse Up",
Fo: "Focus",
Bl: "Blur",
PO: "PageOpen",
PC: "PageClose",
PV: "PageVisible",
PI: "PageInvisible",
K: "Keystroke",
F: "Format",
V: "Validate",
C: "Calculate"
};
const DocumentActionEventType = {
WC: "WillClose",
WS: "WillSave",
DS: "DidSave",
WP: "WillPrint",
DP: "DidPrint"
};
const PageActionEventType = {
O: "PageOpen",
C: "PageClose"
};
const VerbosityLevel = {
ERRORS: 0,
WARNINGS: 1,
INFOS: 5
};
const OPS = {
dependency: 1,
setLineWidth: 2,
setLineCap: 3,
setLineJoin: 4,
setMiterLimit: 5,
setDash: 6,
setRenderingIntent: 7,
setFlatness: 8,
setGState: 9,
save: 10,
restore: 11,
transform: 12,
moveTo: 13,
lineTo: 14,
curveTo: 15,
curveTo2: 16,
curveTo3: 17,
closePath: 18,
rectangle: 19,
stroke: 20,
closeStroke: 21,
fill: 22,
eoFill: 23,
fillStroke: 24,
eoFillStroke: 25,
closeFillStroke: 26,
closeEOFillStroke: 27,
endPath: 28,
clip: 29,
eoClip: 30,
beginText: 31,
endText: 32,
setCharSpacing: 33,
setWordSpacing: 34,
setHScale: 35,
setLeading: 36,
setFont: 37,
setTextRenderingMode: 38,
setTextRise: 39,
moveText: 40,
setLeadingMoveText: 41,
setTextMatrix: 42,
nextLine: 43,
showText: 44,
showSpacedText: 45,
nextLineShowText: 46,
nextLineSetSpacingShowText: 47,
setCharWidth: 48,
setCharWidthAndBounds: 49,
setStrokeColorSpace: 50,
setFillColorSpace: 51,
setStrokeColor: 52,
setStrokeColorN: 53,
setFillColor: 54,
setFillColorN: 55,
setStrokeGray: 56,
setFillGray: 57,
setStrokeRGBColor: 58,
setFillRGBColor: 59,
setStrokeCMYKColor: 60,
setFillCMYKColor: 61,
shadingFill: 62,
beginInlineImage: 63,
beginImageData: 64,
endInlineImage: 65,
paintXObject: 66,
markPoint: 67,
markPointProps: 68,
beginMarkedContent: 69,
beginMarkedContentProps: 70,
endMarkedContent: 71,
beginCompat: 72,
endCompat: 73,
paintFormXObjectBegin: 74,
paintFormXObjectEnd: 75,
beginGroup: 76,
endGroup: 77,
beginAnnotation: 80,
endAnnotation: 81,
paintImageMaskXObject: 83,
paintImageMaskXObjectGroup: 84,
paintImageXObject: 85,
paintInlineImageXObject: 86,
paintInlineImageXObjectGroup: 87,
paintImageXObjectRepeat: 88,
paintImageMaskXObjectRepeat: 89,
paintSolidColorImageMask: 90,
constructPath: 91,
setStrokeTransparent: 92,
setFillTransparent: 93
};
const PasswordResponses = {
NEED_PASSWORD: 1,
INCORRECT_PASSWORD: 2
};
let verbosity = VerbosityLevel.WARNINGS;
function setVerbosityLevel(level) {
if (Number.isInteger(level)) {
verbosity = level;
}
}
function getVerbosityLevel() {
return verbosity;
}
function info(msg) {
if (verbosity >= VerbosityLevel.INFOS) {
console.log(`Info: ${msg}`);
}
}
function warn(msg) {
if (verbosity >= VerbosityLevel.WARNINGS) {
console.log(`Warning: ${msg}`);
}
}
function unreachable(msg) {
throw new Error(msg);
}
function assert(cond, msg) {
if (!cond) {
unreachable(msg);
}
}
function _isValidProtocol(url) {
switch (url?.protocol) {
case "http:":
case "https:":
case "ftp:":
case "mailto:":
case "tel:":
return true;
default:
return false;
}
}
function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
if (!url) {
return null;
}
try {
if (options && typeof url === "string") {
if (options.addDefaultProtocol && url.startsWith("www.")) {
const dots = url.match(/\./g);
if (dots?.length >= 2) {
url = `http://${url}`;
}
}
if (options.tryConvertEncoding) {
try {
url = stringToUTF8String(url);
} catch {}
}
}
const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
if (_isValidProtocol(absoluteUrl)) {
return absoluteUrl;
}
} catch {}
return null;
}
function shadow(obj, prop, value, nonSerializable = false) {
Object.defineProperty(obj, prop, {
value,
enumerable: !nonSerializable,
configurable: true,
writable: false
});
return value;
}
const BaseException = function BaseExceptionClosure() {
function BaseException(message, name) {
this.message = message;
this.name = name;
}
BaseException.prototype = new Error();
BaseException.constructor = BaseException;
return BaseException;
}();
class PasswordException extends BaseException {
constructor(msg, code) {
super(msg, "PasswordException");
this.code = code;
}
}
class UnknownErrorException extends BaseException {
constructor(msg, details) {
super(msg, "UnknownErrorException");
this.details = details;
}
}
class InvalidPDFException extends BaseException {
constructor(msg) {
super(msg, "InvalidPDFException");
}
}
class ResponseException extends BaseException {
constructor(msg, status, missing) {
super(msg, "ResponseException");
this.status = status;
this.missing = missing;
}
}
class FormatError extends BaseException {
constructor(msg) {
super(msg, "FormatError");
}
}
class AbortException extends BaseException {
constructor(msg) {
super(msg, "AbortException");
}
}
function bytesToString(bytes) {
if (typeof bytes !== "object" || bytes?.length === undefined) {
unreachable("Invalid argument for bytesToString");
}
const length = bytes.length;
const MAX_ARGUMENT_COUNT = 8192;
if (length < MAX_ARGUMENT_COUNT) {
return String.fromCharCode.apply(null, bytes);
}
const strBuf = [];
for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
const chunk = bytes.subarray(i, chunkEnd);
strBuf.push(String.fromCharCode.apply(null, chunk));
}
return strBuf.join("");
}
function stringToBytes(str) {
if (typeof str !== "string") {
unreachable("Invalid argument for stringToBytes");
}
const length = str.length;
const bytes = new Uint8Array(length);
for (let i = 0; i < length; ++i) {
bytes[i] = str.charCodeAt(i) & 0xff;
}
return bytes;
}
function string32(value) {
return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
}
function objectSize(obj) {
return Object.keys(obj).length;
}
function objectFromMap(map) {
const obj = Object.create(null);
for (const [key, value] of map) {
obj[key] = value;
}
return obj;
}
function isLittleEndian() {
const buffer8 = new Uint8Array(4);
buffer8[0] = 1;
const view32 = new Uint32Array(buffer8.buffer, 0, 1);
return view32[0] === 1;
}
function isEvalSupported() {
try {
new Function("");
return true;
} catch {
return false;
}
}
class FeatureTest {
static get isLittleEndian() {
return shadow(this, "isLittleEndian", isLittleEndian());
}
static get isEvalSupported() {
return shadow(this, "isEvalSupported", isEvalSupported());
}
static get isOffscreenCanvasSupported() {
return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
}
static get isImageDecoderSupported() {
return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined");
}
static get platform() {
return shadow(this, "platform", {
isMac: navigator.platform.includes("Mac"),
isWindows: navigator.platform.includes("Win"),
isFirefox: true
});
}
static get isCSSRoundSupported() {
return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)"));
}
}
const hexNumbers = Array.from(Array(256).keys(), n => n.toString(16).padStart(2, "0"));
class Util {
static makeHexColor(r, g, b) {
return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
}
static scaleMinMax(transform, minMax) {
let temp;
if (transform[0]) {
if (transform[0] < 0) {
temp = minMax[0];
minMax[0] = minMax[2];
minMax[2] = temp;
}
minMax[0] *= transform[0];
minMax[2] *= transform[0];
if (transform[3] < 0) {
temp = minMax[1];
minMax[1] = minMax[3];
minMax[3] = temp;
}
minMax[1] *= transform[3];
minMax[3] *= transform[3];
} else {
temp = minMax[0];
minMax[0] = minMax[1];
minMax[1] = temp;
temp = minMax[2];
minMax[2] = minMax[3];
minMax[3] = temp;
if (transform[1] < 0) {
temp = minMax[1];
minMax[1] = minMax[3];
minMax[3] = temp;
}
minMax[1] *= transform[1];
minMax[3] *= transform[1];
if (transform[2] < 0) {
temp = minMax[0];
minMax[0] = minMax[2];
minMax[2] = temp;
}
minMax[0] *= transform[2];
minMax[2] *= transform[2];
}
minMax[0] += transform[4];
minMax[1] += transform[5];
minMax[2] += transform[4];
minMax[3] += transform[5];
}
static transform(m1, m2) {
return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
}
static applyTransform(p, m) {
const xt = p[0] * m[0] + p[1] * m[2] + m[4];
const yt = p[0] * m[1] + p[1] * m[3] + m[5];
return [xt, yt];
}
static applyInverseTransform(p, m) {
const d = m[0] * m[3] - m[1] * m[2];
const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
return [xt, yt];
}
static getAxialAlignedBoundingBox(r, m) {
const p1 = this.applyTransform(r, m);
const p2 = this.applyTransform(r.slice(2, 4), m);
const p3 = this.applyTransform([r[0], r[3]], m);
const p4 = this.applyTransform([r[2], r[1]], m);
return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
}
static inverseTransform(m) {
const d = m[0] * m[3] - m[1] * m[2];
return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
}
static singularValueDecompose2dScale(m) {
const transpose = [m[0], m[2], m[1], m[3]];
const a = m[0] * transpose[0] + m[1] * transpose[2];
const b = m[0] * transpose[1] + m[1] * transpose[3];
const c = m[2] * transpose[0] + m[3] * transpose[2];
const d = m[2] * transpose[1] + m[3] * transpose[3];
const first = (a + d) / 2;
const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
const sx = first + second || 1;
const sy = first - second || 1;
return [Math.sqrt(sx), Math.sqrt(sy)];
}
static normalizeRect(rect) {
const r = rect.slice(0);
if (rect[0] > rect[2]) {
r[0] = rect[2];
r[2] = rect[0];
}
if (rect[1] > rect[3]) {
r[1] = rect[3];
r[3] = rect[1];
}
return r;
}
static intersect(rect1, rect2) {
const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
if (xLow > xHigh) {
return null;
}
const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
if (yLow > yHigh) {
return null;
}
return [xLow, yLow, xHigh, yHigh];
}
static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, t, minMax) {
if (t <= 0 || t >= 1) {
return;
}
const mt = 1 - t;
const tt = t * t;
const ttt = tt * t;
const x = mt * (mt * (mt * x0 + 3 * t * x1) + 3 * tt * x2) + ttt * x3;
const y = mt * (mt * (mt * y0 + 3 * t * y1) + 3 * tt * y2) + ttt * y3;
minMax[0] = Math.min(minMax[0], x);
minMax[1] = Math.min(minMax[1], y);
minMax[2] = Math.max(minMax[2], x);
minMax[3] = Math.max(minMax[3], y);
}
static #getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, a, b, c, minMax) {
if (Math.abs(a) < 1e-12) {
if (Math.abs(b) >= 1e-12) {
this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, -c / b, minMax);
}
return;
}
const delta = b ** 2 - 4 * c * a;
if (delta < 0) {
return;
}
const sqrtDelta = Math.sqrt(delta);
const a2 = 2 * a;
this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b + sqrtDelta) / a2, minMax);
this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y2, y3, (-b - sqrtDelta) / a2, minMax);
}
static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
if (minMax) {
minMax[0] = Math.min(minMax[0], x0, x3);
minMax[1] = Math.min(minMax[1], y0, y3);
minMax[2] = Math.max(minMax[2], x0, x3);
minMax[3] = Math.max(minMax[3], y0, y3);
} else {
minMax = [Math.min(x0, x3), Math.min(y0, y3), Math.max(x0, x3), Math.max(y0, y3)];
}
this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax);
this.#getExtremum(x0, x1, x2, x3, y0, y1, y2, y3, 3 * (-y0 + 3 * (y1 - y2) + y3), 6 * (y0 - 2 * y1 + y2), 3 * (y1 - y0), minMax);
return minMax;
}
}
const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
function stringToPDFString(str) {
if (str[0] >= "\xEF") {
let encoding;
if (str[0] === "\xFE" && str[1] === "\xFF") {
encoding = "utf-16be";
if (str.length % 2 === 1) {
str = str.slice(0, -1);
}
} else if (str[0] === "\xFF" && str[1] === "\xFE") {
encoding = "utf-16le";
if (str.length % 2 === 1) {
str = str.slice(0, -1);
}
} else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
encoding = "utf-8";
}
if (encoding) {
try {
const decoder = new TextDecoder(encoding, {
fatal: true
});
const buffer = stringToBytes(str);
const decoded = decoder.decode(buffer);
if (!decoded.includes("\x1b")) {
return decoded;
}
return decoded.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g, "");
} catch (ex) {
warn(`stringToPDFString: "${ex}".`);
}
}
}
const strBuf = [];
for (let i = 0, ii = str.length; i < ii; i++) {
const charCode = str.charCodeAt(i);
if (charCode === 0x1b) {
while (++i < ii && str.charCodeAt(i) !== 0x1b) {}
continue;
}
const code = PDFStringTranslateTable[charCode];
strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
}
return strBuf.join("");
}
function stringToUTF8String(str) {
return decodeURIComponent(escape(str));
}
function utf8StringToString(str) {
return unescape(encodeURIComponent(str));
}
function isArrayEqual(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0, ii = arr1.length; i < ii; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
function getModificationDate(date = new Date()) {
const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
return buffer.join("");
}
let NormalizeRegex = null;
let NormalizationMap = null;
function normalizeUnicode(str) {
if (!NormalizeRegex) {
NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;
NormalizationMap = new Map([["ſt", "ſt"]]);
}
return str.replaceAll(NormalizeRegex, (_, p1, p2) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p2));
}
function getUuid() {
return crypto.randomUUID();
}
const AnnotationPrefix = "pdfjs_internal_id_";
function toHexUtil(arr) {
if (Uint8Array.prototype.toHex) {
return arr.toHex();
}
return Array.from(arr, num => hexNumbers[num]).join("");
}
function toBase64Util(arr) {
if (Uint8Array.prototype.toBase64) {
return arr.toBase64();
}
return btoa(bytesToString(arr));
}
function fromBase64Util(str) {
if (Uint8Array.fromBase64) {
return Uint8Array.fromBase64(str);
}
return stringToBytes(atob(str));
}
if (typeof Promise.try !== "function") {
Promise.try = function (fn, ...args) {
return new Promise(resolve => {
resolve(fn(...args));
});
};
}
;// ./src/core/primitives.js
const CIRCULAR_REF = Symbol("CIRCULAR_REF");
const EOF = Symbol("EOF");
let CmdCache = Object.create(null);
let NameCache = Object.create(null);
let RefCache = Object.create(null);
function clearPrimitiveCaches() {
CmdCache = Object.create(null);
NameCache = Object.create(null);
RefCache = Object.create(null);
}
class Name {
constructor(name) {
this.name = name;
}
static get(name) {
return NameCache[name] ||= new Name(name);
}
}
class Cmd {
constructor(cmd) {
this.cmd = cmd;
}
static get(cmd) {
return CmdCache[cmd] ||= new Cmd(cmd);
}
}
const nonSerializable = function nonSerializableClosure() {
return nonSerializable;
};
class Dict {
constructor(xref = null) {
this._map = new Map();
this.xref = xref;
this.objId = null;
this.suppressEncryption = false;
this.__nonSerializable__ = nonSerializable;
}
assignXref(newXref) {
this.xref = newXref;
}
get size() {
return this._map.size;
}
get(key1, key2, key3) {
let value = this._map.get(key1);
if (value === undefined && key2 !== undefined) {
value = this._map.get(key2);
if (value === undefined && key3 !== undefined) {
value = this._map.get(key3);
}
}
if (value instanceof Ref && this.xref) {
return this.xref.fetch(value, this.suppressEncryption);
}
return value;
}
async getAsync(key1, key2, key3) {
let value = this._map.get(key1);
if (value === undefined && key2 !== undefined) {
value = this._map.get(key2);
if (value === undefined && key3 !== undefined) {
value = this._map.get(key3);
}
}
if (value instanceof Ref && this.xref) {
return this.xref.fetchAsync(value, this.suppressEncryption);
}
return value;
}
getArray(key1, key2, key3) {
let value = this._map.get(key1);
if (value === undefined && key2 !== undefined) {
value = this._map.get(key2);
if (value === undefined && key3 !== undefined) {
value = this._map.get(key3);
}
}
if (value instanceof Ref && this.xref) {
value = this.xref.fetch(value, this.suppressEncryption);
}
if (Array.isArray(value)) {
value = value.slice();
for (let i = 0, ii = value.length; i < ii; i++) {
if (value[i] instanceof Ref && this.xref) {
value[i] = this.xref.fetch(value[i], this.suppressEncryption);
}
}
}
return value;
}
getRaw(key) {
return this._map.get(key);
}
getKeys() {
return [...this._map.keys()];
}
getRawValues() {
return [...this._map.values()];
}
set(key, value) {
this._map.set(key, value);
}
has(key) {
return this._map.has(key);
}
*[Symbol.iterator]() {
for (const [key, value] of this._map) {
yield [key, value instanceof Ref && this.xref ? this.xref.fetch(value, this.suppressEncryption) : value];
}
}
static get empty() {
const emptyDict = new Dict(null);
emptyDict.set = (key, value) => {
unreachable("Should not call `set` on the empty dictionary.");
};
return shadow(this, "empty", emptyDict);
}
static merge({
xref,
dictArray,
mergeSubDicts = false
}) {
const mergedDict = new Dict(xref),
properties = new Map();
for (const dict of dictArray) {
if (!(dict instanceof Dict)) {
continue;
}
for (const [key, value] of dict._map) {
let property = properties.get(key);
if (property === undefined) {
property = [];
properties.set(key, property);
} else if (!mergeSubDicts || !(value instanceof Dict)) {
continue;
}
property.push(value);
}
}
for (const [name, values] of properties) {
if (values.length === 1 || !(values[0] instanceof Dict)) {
mergedDict._map.set(name, values[0]);
continue;
}
const subDict = new Dict(xref);
for (const dict of values) {
for (const [key, value] of dict._map) {
if (!subDict._map.has(key)) {
subDict._map.set(key, value);
}
}
}
if (subDict.size > 0) {
mergedDict._map.set(name, subDict);
}
}
properties.clear();
return mergedDict.size > 0 ? mergedDict : Dict.empty;
}
clone() {
const dict = new Dict(this.xref);
for (const key of this.getKeys()) {
dict.set(key, this.getRaw(key));
}
return dict;
}
delete(key) {
delete this._map[key];
}
}
class Ref {
constructor(num, gen) {
this.num = num;
this.gen = gen;
}
toString() {
if (this.gen === 0) {
return `${this.num}R`;
}
return `${this.num}R${this.gen}`;
}
static fromString(str) {
const ref = RefCache[str];
if (ref) {
return ref;
}
const m = /^(\d+)R(\d*)$/.exec(str);
if (!m || m[1] === "0") {
return null;
}
return RefCache[str] = new Ref(parseInt(m[1]), !m[2] ? 0 : parseInt(m[2]));
}
static get(num, gen) {
const key = gen === 0 ? `${num}R` : `${num}R${gen}`;
return RefCache[key] ||= new Ref(num, gen);
}
}
class RefSet {
constructor(parent = null) {
this._set = new Set(parent?._set);
}
has(ref) {
return this._set.has(ref.toString());
}
put(ref) {
this._set.add(ref.toString());
}
remove(ref) {
this._set.delete(ref.toString());
}
[Symbol.iterator]() {
return this._set.values();
}
clear() {
this._set.clear();
}
}
class RefSetCache {
constructor() {
this._map = new Map();
}
get size() {
return this._map.size;
}
get(ref) {
return this._map.get(ref.toString());
}
has(ref) {
return this._map.has(ref.toString());
}
put(ref, obj) {
this._map.set(ref.toString(), obj);
}
putAlias(ref, aliasRef) {
this._map.set(ref.toString(), this.get(aliasRef));
}
[Symbol.iterator]() {
return this._map.values();
}
clear() {
this._map.clear();
}
*values() {
yield* this._map.values();
}
*items() {
for (const [ref, value] of this._map) {
yield [Ref.fromString(ref), value];
}
}
}
function isName(v, name) {
return v instanceof Name && (name === undefined || v.name === name);
}
function isCmd(v, cmd) {
return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
}
function isDict(v, type) {
return v instanceof Dict && (type === undefined || isName(v.get("Type"), type));
}
function isRefsEqual(v1, v2) {
return v1.num === v2.num && v1.gen === v2.gen;
}
;// ./src/core/base_stream.js
class BaseStream {
get length() {
unreachable("Abstract getter `length` accessed");
}
get isEmpty() {
unreachable("Abstract getter `isEmpty` accessed");
}
get isDataLoaded() {
return shadow(this, "isDataLoaded", true);
}
getByte() {
unreachable("Abstract method `getByte` called");
}
getBytes(length) {
unreachable("Abstract method `getBytes` called");
}
async getImageData(length, decoderOptions) {
return this.getBytes(length, decoderOptions);
}
async asyncGetBytes() {
unreachable("Abstract method `asyncGetBytes` called");
}
get isAsync() {
return false;
}
get isAsyncDecoder() {
return false;
}
get canAsyncDecodeImageFromBuffer() {
return false;
}
async getTransferableImage() {
return null;
}
peekByte() {
const peekedByte = this.getByte();
if (peekedByte !== -1) {
this.pos--;
}
return peekedByte;
}
peekBytes(length) {
const bytes = this.getBytes(length);
this.pos -= bytes.length;
return bytes;
}
getUint16() {
const b0 = this.getByte();
const b1 = this.getByte();
if (b0 === -1 || b1 === -1) {
return -1;
}
return (b0 << 8) + b1;
}
getInt32() {
const b0 = this.getByte();
const b1 = this.getByte();
const b2 = this.getByte();
const b3 = this.getByte();
return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
}
getByteRange(begin, end) {
unreachable("Abstract method `getByteRange` called");
}
getString(length) {
return bytesToString(this.getBytes(length));
}
skip(n) {
this.pos += n || 1;
}
reset() {
unreachable("Abstract method `reset` called");
}
moveStart() {
unreachable("Abstract method `moveStart` called");
}
makeSubStream(start, length, dict = null) {
unreachable("Abstract method `makeSubStream` called");
}
getBaseStreams() {
return null;
}
}
;// ./src/core/core_utils.js
const PDF_VERSION_REGEXP = /^[1-9]\.\d$/;
const MAX_INT_32 = 2 ** 31 - 1;
const MIN_INT_32 = -(2 ** 31);
function getLookupTableFactory(initializer) {
let lookup;
return function () {
if (initializer) {
lookup = Object.create(null);
initializer(lookup);
initializer = null;
}
return lookup;
};
}
class MissingDataException extends BaseException {
constructor(begin, end) {
super(`Missing data [${begin}, ${end})`, "MissingDataException");
this.begin = begin;
this.end = end;
}
}
class ParserEOFException extends BaseException {
constructor(msg) {
super(msg, "ParserEOFException");
}
}
class XRefEntryException extends BaseException {
constructor(msg) {
super(msg, "XRefEntryException");
}
}
class XRefParseException extends BaseException {
constructor(msg) {
super(msg, "XRefParseException");
}
}
function arrayBuffersToBytes(arr) {
const length = arr.length;
if (length === 0) {
return new Uint8Array(0);
}
if (length === 1) {
return new Uint8Array(arr[0]);
}
let dataLength = 0;
for (let i = 0; i < length; i++) {
dataLength += arr[i].byteLength;
}
const data = new Uint8Array(dataLength);
let pos = 0;
for (let i = 0; i < length; i++) {
const item = new Uint8Array(arr[i]);
data.set(item, pos);
pos += item.byteLength;
}
return data;
}
async function fetchBinaryData(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch file "${url}" with "${response.statusText}".`);
}
return new Uint8Array(await response.arrayBuffer());
}
function getInheritableProperty({
dict,
key,
getArray = false,
stopWhenFound = true
}) {
let values;
const visited = new RefSet();
while (dict instanceof Dict && !(dict.objId && visited.has(dict.objId))) {
if (dict.objId) {
visited.put(dict.objId);
}
const value = getArray ? dict.getArray(key) : dict.get(key);
if (value !== undefined) {
if (stopWhenFound) {
return value;
}
(values ||= []).push(value);
}
dict = dict.get("Parent");
}
return values;
}
function getParentToUpdate(dict, ref, xref) {
const visited = new RefSet();
const firstDict = dict;
const result = {
dict: null,
ref: null
};
while (dict instanceof Dict && !visited.has(ref)) {
visited.put(ref);
if (dict.has("T")) {
break;
}
ref = dict.getRaw("Parent");
if (!(ref instanceof Ref)) {
return result;
}
dict = xref.fetch(ref);
}
if (dict instanceof Dict && dict !== firstDict) {
result.dict = dict;
result.ref = ref;
}
return result;
}
const ROMAN_NUMBER_MAP = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
function toRomanNumerals(number, lowerCase = false) {
assert(Number.isInteger(number) && number > 0, "The number should be a positive integer.");
const roman = "M".repeat(number / 1000 | 0) + ROMAN_NUMBER_MAP[number % 1000 / 100 | 0] + ROMAN_NUMBER_MAP[10 + (number % 100 / 10 | 0)] + ROMAN_NUMBER_MAP[20 + number % 10];
return lowerCase ? roman.toLowerCase() : roman;
}
function log2(x) {
return x > 0 ? Math.ceil(Math.log2(x)) : 0;
}
function readInt8(data, offset) {
return data[offset] << 24 >> 24;
}
function readUint16(data, offset) {
return data[offset] << 8 | data[offset + 1];
}
function readUint32(data, offset) {
return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
}
function isWhiteSpace(ch) {
return ch === 0x20 || ch === 0x09 || ch === 0x0d || ch === 0x0a;
}
function isBooleanArray(arr, len) {
return Array.isArray(arr) && (len === null || arr.length === len) && arr.every(x => typeof x === "boolean");
}
function isNumberArray(arr, len) {
if (Array.isArray(arr)) {
return (len === null || arr.length === len) && arr.every(x => typeof x === "number");
}
return ArrayBuffer.isView(arr) && (arr.length === 0 || typeof arr[0] === "number") && (len === null || arr.length === len);
}
function lookupMatrix(arr, fallback) {
return isNumberArray(arr, 6) ? arr : fallback;
}
function lookupRect(arr, fallback) {
return isNumberArray(arr, 4) ? arr : fallback;
}
function lookupNormalRect(arr, fallback) {
return isNumberArray(arr, 4) ? Util.normalizeRect(arr) : fallback;
}
function parseXFAPath(path) {
const positionPattern = /(.+)\[(\d+)\]$/;
return path.split(".").map(component => {
const m = component.match(positionPattern);
if (m) {
return {
name: m[1],
pos: parseInt(m[2], 10)
};
}
return {
name: component,
pos: 0
};
});
}
function escapePDFName(str) {
const buffer = [];
let start = 0;
for (let i = 0, ii = str.length; i < ii; i++) {
const char = str.charCodeAt(i);
if (char < 0x21 || char > 0x7e || char === 0x23 || char === 0x28 || char === 0x29 || char === 0x3c || char === 0x3e || char === 0x5b || char === 0x5d || char === 0x7b || char === 0x7d || char === 0x2f || char === 0x25) {
if (start < i) {
buffer.push(str.substring(start, i));
}
buffer.push(`#${char.toString(16)}`);
start = i + 1;
}
}
if (buffer.length === 0) {
return str;
}
if (start < str.length) {
buffer.push(str.substring(start, str.length));
}
return buffer.join("");
}
function escapeString(str) {
return str.replaceAll(/([()\\\n\r])/g, match => {
if (match === "\n") {
return "\\n";
} else if (match === "\r") {
return "\\r";
}
return `\\${match}`;
});
}
function _collectJS(entry, xref, list, parents) {
if (!entry) {
return;
}
let parent = null;
if (entry instanceof Ref) {
if (parents.has(entry)) {
return;
}
parent = entry;
parents.put(parent);
entry = xref.fetch(entry);
}
if (Array.isArray(entry)) {
for (const element of entry) {
_collectJS(element, xref, list, parents);
}
} else if (entry instanceof Dict) {
if (isName(entry.get("S"), "JavaScript")) {
const js = entry.get("JS");
let code;
if (js instanceof BaseStream) {
code = js.getString();
} else if (typeof js === "string") {
code = js;
}
code &&= stringToPDFString(code).replaceAll("\x00", "");
if (code) {
list.push(code);
}
}
_collectJS(entry.getRaw("Next"), xref, list, parents);
}
if (parent) {
parents.remove(parent);
}
}
function collectActions(xref, dict, eventType) {
const actions = Object.create(null);
const additionalActionsDicts = getInheritableProperty({
dict,
key: "AA",
stopWhenFound: false
});
if (additionalActionsDicts) {
for (let i = additionalActionsDicts.length - 1; i >= 0; i--) {
const additionalActions = additionalActionsDicts[i];
if (!(additionalActions instanceof Dict)) {
continue;
}
for (const key of additionalActions.getKeys()) {
const action = eventType[key];
if (!action) {
continue;
}
const actionDict = additionalActions.getRaw(key);
const parents = new RefSet();
const list = [];
_collectJS(actionDict, xref, list, parents);
if (list.length > 0) {
actions[action] = list;
}
}
}
}
if (dict.has("A")) {
const actionDict = dict.get("A");
const parents = new RefSet();
const list = [];
_collectJS(actionDict, xref, list, parents);
if (list.length > 0) {
actions.Action = list;
}
}
return objectSize(actions) > 0 ? actions : null;
}
const XMLEntities = {
0x3c: "<",
0x3e: ">",
0x26: "&",
0x22: """,
0x27: "'"
};
function* codePointIter(str) {
for (let i = 0, ii = str.length; i < ii; i++) {
const char = str.codePointAt(i);
if (char > 0xd7ff && (char < 0xe000 || char > 0xfffd)) {
i++;
}
yield char;
}
}
function encodeToXmlString(str) {
const buffer = [];
let start = 0;
for (let i = 0, ii = str.length; i < ii; i++) {
const char = str.codePointAt(i);
if (0x20 <= char && char <= 0x7e) {
const entity = XMLEntities[char];
if (entity) {
if (start < i) {
buffer.push(str.substring(start, i));
}
buffer.push(entity);
start = i + 1;
}
} else {
if (start < i) {
buffer.push(str.substring(start, i));
}
buffer.push(`${char.toString(16).toUpperCase()};`);
if (char > 0xd7ff && (char < 0xe000 || char > 0xfffd)) {
i++;
}
start = i + 1;
}
}
if (buffer.length === 0) {
return str;
}
if (start < str.length) {
buffer.push(str.substring(start, str.length));
}
return buffer.join("");
}
function validateFontName(fontFamily, mustWarn = false) {
const m = /^("|').*("|')$/.exec(fontFamily);
if (m && m[1] === m[2]) {
const re = new RegExp(`[^\\\\]${m[1]}`);
if (re.test(fontFamily.slice(1, -1))) {
if (mustWarn) {
warn(`FontFamily contains unescaped ${m[1]}: ${fontFamily}.`);
}
return false;
}
} else {
for (const ident of fontFamily.split(/[ \t]+/)) {
if (/^(\d|(-(\d|-)))/.test(ident) || !/^[\w-\\]+$/.test(ident)) {
if (mustWarn) {
warn(`FontFamily contains invalid <custom-ident>: ${fontFamily}.`);
}
return false;
}
}
}
return true;
}
function validateCSSFont(cssFontInfo) {
const DEFAULT_CSS_FONT_OBLIQUE = "14";
const DEFAULT_CSS_FONT_WEIGHT = "400";
const CSS_FONT_WEIGHT_VALUES = new Set(["100", "200", "300", "400", "500", "600", "700", "800", "900", "1000", "normal", "bold", "bolder", "lighter"]);
const {
fontFamily,
fontWeight,
italicAngle
} = cssFontInfo;
if (!validateFontName(fontFamily, true)) {
return false;
}
const weight = fontWeight ? fontWeight.toString() : "";
cssFontInfo.fontWeight = CSS_FONT_WEIGHT_VALUES.has(weight) ? weight : DEFAULT_CSS_FONT_WEIGHT;
const angle = parseFloat(italicAngle);
cssFontInfo.italicAngle = isNaN(angle) || angle < -90 || angle > 90 ? DEFAULT_CSS_FONT_OBLIQUE : italicAngle.toString();
return true;
}
function recoverJsURL(str) {
const URL_OPEN_METHODS = ["app.launchURL", "window.open", "xfa.host.gotoURL"];
const regex = new RegExp("^\\s*(" + URL_OPEN_METHODS.join("|").replaceAll(".", "\\.") + ")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))", "i");
const jsUrl = regex.exec(str);
if (jsUrl?.[2]) {
return {
url: jsUrl[2],
newWindow: jsUrl[1] === "app.launchURL" && jsUrl[3] === "true"
};
}
return null;
}
function numberToString(value) {
if (Number.isInteger(value)) {
return value.toString();
}
const roundedValue = Math.round(value * 100);
if (roundedValue % 100 === 0) {
return (roundedValue / 100).toString();
}
if (roundedValue % 10 === 0) {
return value.toFixed(1);
}
return value.toFixed(2);
}
function getNewAnnotationsMap(annotationStorage) {
if (!annotationStorage) {
return null;
}
const newAnnotationsByPage = new Map();
for (const [key, value] of annotationStorage) {
if (!key.startsWith(AnnotationEditorPrefix)) {
continue;
}
let annotations = newAnnotationsByPage.get(value.pageIndex);
if (!annotations) {
annotations = [];
newAnnotationsByPage.set(value.pageIndex, annotations);
}
annotations.push(value);
}
return newAnnotationsByPage.size > 0 ? newAnnotationsByPage : null;
}
function stringToAsciiOrUTF16BE(str) {
return isAscii(str) ? str : stringToUTF16String(str, true);
}
function isAscii(str) {
return /^[\x00-\x7F]*$/.test(str);
}
function stringToUTF16HexString(str) {
const buf = [];
for (let i = 0, ii = str.length; i < ii; i++) {
const char = str.charCodeAt(i);
buf.push(hexNumbers[char >> 8 & 0xff], hexNumbers[char & 0xff]);
}
return buf.join("");
}
function stringToUTF16String(str, bigEndian = false) {
const buf = [];
if (bigEndian) {
buf.push("\xFE\xFF");
}
for (let i = 0, ii = str.length; i < ii; i++) {
const char = str.charCodeAt(i);
buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
}
return buf.join("");
}
function getRotationMatrix(rotation, width, height) {
switch (rotation) {
case 90:
return [0, 1, -1, 0, width, 0];
case 180:
return [-1, 0, 0, -1, width, height];
case 270:
return [0, -1, 1, 0, 0, height];
default:
throw new Error("Invalid rotation");
}
}
function getSizeInBytes(x) {
return Math.ceil(Math.ceil(Math.log2(1 + x)) / 8);
}
;// ./src/core/stream.js
class Stream extends BaseStream {
constructor(arrayBuffer, start, length, dict) {
super();
this.bytes = arrayBuffer instanceof Uint8Array ? arrayBuffer : new Uint8Array(arrayBuffer);
this.start = start || 0;
this.pos = this.start;
this.end = start + length || this.bytes.length;
this.dict = dict;
}
get length() {
return this.end - this.start;
}
get isEmpty() {
return this.length === 0;
}
getByte() {
if (this.pos >= this.end) {
return -1;
}
return this.bytes[this.pos++];
}
getBytes(length) {
const bytes = this.bytes;
const pos = this.pos;
const strEnd = this.end;
if (!length) {
return bytes.subarray(pos, strEnd);
}
let end = pos + length;
if (end > strEnd) {
end = strEnd;
}
this.pos = end;
return bytes.subarray(pos, end);
}
getByteRange(begin, end) {
if (begin < 0) {
begin = 0;
}
if (end > this.end) {
end = this.end;
}
return this.bytes.subarray(begin, end);
}
reset() {
this.pos = this.start;
}
moveStart() {
this.start = this.pos;
}
makeSubStream(start, length, dict = null) {
return new Stream(this.bytes.buffer, start, length, dict);
}
}
class StringStream extends Stream {
constructor(str) {
super(stringToBytes(str));
}
}
class NullStream extends Stream {
constructor() {
super(new Uint8Array(0));
}
}
;// ./src/core/chunked_stream.js
class ChunkedStream extends Stream {
constructor(length, chunkSize, manager) {
super(new Uint8Array(length), 0, length, null);
this.chunkSize = chunkSize;
this._loadedChunks = new Set();
this.numChunks = Math.ceil(length / chunkSize);
this.manager = manager;
this.progressiveDataLength = 0;
this.lastSuccessfulEnsureByteChunk = -1;
}
getMissingChunks() {
const chunks = [];
for (let chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
if (!this._loadedChunks.has(chunk)) {
chunks.push(chunk);
}
}
return chunks;
}
get numChunksLoaded() {
return this._loadedChunks.size;
}
get isDataLoaded() {
return this.numChunksLoaded === this.numChunks;
}
onReceiveData(begin, chunk) {
const chunkSize = this.chunkSize;
if (begin % chunkSize !== 0) {
throw new Error(`Bad begin offset: ${begin}`);
}
const end = begin + chunk.byteLength;
if (end % chunkSize !== 0 && end !== this.bytes.length) {
throw new Error(`Bad end offset: ${end}`);
}
this.bytes.set(new Uint8Array(chunk), begin);
const beginChunk = Math.floor(begin / chunkSize);
const endChunk = Math.floor((end - 1) / chunkSize) + 1;
for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
this._loadedChunks.add(curChunk);
}
}
onReceiveProgressiveData(data) {
let position = this.progressiveDataLength;
const beginChunk = Math.floor(position / this.chunkSize);
this.bytes.set(new Uint8Array(data), position);
position += data.byteLength;
this.progressiveDataLength = position;
const endChunk = position >= this.end ? this.numChunks : Math.floor(position / this.chunkSize);
for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
this._loadedChunks.add(curChunk);
}
}
ensureByte(pos) {
if (pos < this.progressiveDataLength) {
return;
}
const chunk = Math.floor(pos / this.chunkSize);
if (chunk > this.numChunks) {
return;
}
if (chunk === this.lastSuccessfulEnsureByteChunk) {
return;
}
if (!this._loadedChunks.has(chunk)) {
throw new MissingDataException(pos, pos + 1);
}
this.lastSuccessfulEnsureByteChunk = chunk;
}
ensureRange(begin, end) {
if (begin >= end) {
return;
}
if (end <= this.progressiveDataLength) {
return;
}
const beginChunk = Math.floor(begin / this.chunkSize);
if (beginChunk > this.numChunks) {
return;
}
const endChunk = Math.min(Math.floor((end - 1) / this.chunkSize) + 1, this.numChunks);
for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
if (!this._loadedChunks.has(chunk)) {
throw new MissingDataException(begin, end);
}
}
}
nextEmptyChunk(beginChunk) {
const numChunks = this.numChunks;
for (let i = 0; i < numChunks; ++i) {
const chunk = (beginChunk + i) % numChunks;
if (!this._loadedChunks.has(chunk)) {
return chunk;
}
}
return null;
}
hasChunk(chunk) {
return this._loadedChunks.has(chunk);
}
getByte() {
const pos = this.pos;
if (pos >= this.end) {
return -1;
}
if (pos >= this.progressiveDataLength) {
this.ensureByte(pos);
}
return this.bytes[this.pos++];
}
getBytes(length) {
const bytes = this.bytes;
const pos = this.pos;
const strEnd = this.end;
if (!length) {
if (strEnd > this.progressiveDataLength) {
this.ensureRange(pos, strEnd);
}
return bytes.subarray(pos, strEnd);
}
let end = pos + length;
if (end > strEnd) {
end = strEnd;
}
if (end > this.progressiveDataLength) {
this.ensureRange(pos, end);
}
this.pos = end;
return bytes.subarray(pos, end);
}
getByteRange(begin, end) {
if (begin < 0) {
begin = 0;
}
if (end > this.end) {
end = this.end;
}
if (end > this.progressiveDataLength) {
this.ensureRange(begin, end);
}
return this.bytes.subarray(begin, end);
}
makeSubStream(start, length, dict = null) {
if (length) {
if (start + length > this.progressiveDataLength) {
this.ensureRange(start, start + length);
}
} else if (start >= this.progressiveDataLength) {
this.ensureByte(start);
}
function ChunkedStreamSubstream() {}
ChunkedStreamSubstream.prototype = Object.create(this);
ChunkedStreamSubstream.prototype.getMissingChunks = function () {
const chunkSize = this.chunkSize;
const beginChunk = Math.floor(this.start / chunkSize);
const endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
const missingChunks = [];
for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
if (!this._loadedChunks.has(chunk)) {
missingChunks.push(chunk);
}
}
return missingChunks;
};
Object.defineProperty(ChunkedStreamSubstream.prototype, "isDataLoaded", {
get() {
if (this.numChunksLoaded === this.numChunks) {
return true;
}
return this.getMissingChunks().length === 0;
},
configurable: true
});
const subStream = new ChunkedStreamSubstream();
subStream.pos = subStream.start = start;
subStream.end = start + length || this.end;
subStream.dict = dict;
return subStream;
}
getBaseStreams() {
return [this];
}
}
class ChunkedStreamManager {
constructor(pdfNetworkStream, args) {
this.length = args.length;
this.chunkSize = args.rangeChunkSize;
this.stream = new ChunkedStream(this.length, this.chunkSize, this);
this.pdfNetworkStream = pdfNetworkStream;
this.disableAutoFetch = args.disableAutoFetch;
this.msgHandler = args.msgHandler;
this.currRequestId = 0;
this._chunksNeededByRequest = new Map();
this._requestsByChunk = new Map();
this._promisesByRequest = new Map();
this.progressiveDataLength = 0;
this.aborted = false;
this._loadedStreamCapability = Promise.withResolvers();
}
sendRequest(begin, end) {
const rangeReader = this.pdfNetworkStream.getRangeReader(begin, end);
if (!rangeReader.isStreamingSupported) {
rangeReader.onProgress = this.onProgress.bind(this);
}
let chunks = [],
loaded = 0;
return new Promise((resolve, reject) => {
const readChunk = ({
value,
done
}) => {
try {
if (done) {
const chunkData = arrayBuffersToBytes(chunks);
chunks = null;
resolve(chunkData);
return;
}
loaded += value.byteLength;
if (rangeReader.isStreamingSupported) {
this.onProgress({
loaded
});
}
chunks.push(value);
rangeReader.read().then(readChunk, reject);
} catch (e) {
reject(e);
}
};
rangeReader.read().then(readChunk, reject);
}).then(data => {
if (this.aborted) {
return;
}
this.onReceiveData({
chunk: data,
begin
});
});
}
requestAllChunks(noFetch = false) {
if (!noFetch) {
const missingChunks = this.stream.getMissingChunks();
this._requestChunks(missingChunks);
}
return this._loadedStreamCapability.promise;
}
_requestChunks(chunks) {
const requestId = this.currRequestId++;
const chunksNeeded = new Set();
this._chunksNeededByRequest.set(requestId, chunksNeeded);
for (const chunk of chunks) {
if (!this.stream.hasChunk(chunk)) {
chunksNeeded.add(chunk);
}
}
if (chunksNeeded.size === 0) {
return Promise.resolve();
}
const capability = Promise.withResolvers();
this._promisesByRequest.set(requestId, capability);
const chunksToRequest = [];
for (const chunk of chunksNeeded) {
let requestIds = this._requestsByChunk.get(chunk);
if (!requestIds) {
requestIds = [];
this._requestsByChunk.set(chunk, requestIds);
chunksToRequest.push(chunk);
}
requestIds.push(requestId);
}
if (chunksToRequest.length > 0) {
const groupedChunksToRequest = this.groupChunks(chunksToRequest);
for (const groupedChunk of groupedChunksToRequest) {
const begin = groupedChunk.beginChunk * this.chunkSize;
const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
this.sendRequest(begin, end).catch(capability.reject);
}
}
return capability.promise.catch(reason => {
if (this.aborted) {
return;
}
throw reason;
});
}
getStream() {
return this.stream;
}
requestRange(begin, end) {
end = Math.min(end, this.length);
const beginChunk = this.getBeginChunk(begin);
const endChunk = this.getEndChunk(end);
const chunks = [];
for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
chunks.push(chunk);
}
return this._requestChunks(chunks);
}
requestRanges(ranges = []) {
const chunksToRequest = [];
for (const range of ranges) {
const beginChunk = this.getBeginChunk(range.begin);
const endChunk = this.getEndChunk(range.end);
for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
if (!chunksToRequest.includes(chunk)) {
chunksToRequest.push(chunk);
}
}
}
chunksToRequest.sort(function (a, b) {
return a - b;
});
return this._requestChunks(chunksToRequest);
}
groupChunks(chunks) {
const groupedChunks = [];
let beginChunk = -1;
let prevChunk = -1;
for (let i = 0, ii = chunks.length; i < ii; ++i) {
const chunk = chunks[i];
if (beginChunk < 0) {
beginChunk = chunk;
}
if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
groupedChunks.push({
beginChunk,
endChunk: prevChunk + 1
});
beginChunk = chunk;
}
if (i + 1 === chunks.length) {
groupedChunks.push({
beginChunk,
endChunk: chunk + 1
});
}
prevChunk = chunk;
}
return groupedChunks;
}
onProgress(args) {
this.msgHandler.send("DocProgress", {
loaded: this.stream.numChunksLoaded * this.chunkSize + args.loaded,
total: this.length
});
}
onReceiveData(args) {
const chunk = args.chunk;
const isProgressive = args.begin === undefined;
const begin = isProgressive ? this.progressiveDataLength : args.begin;
const end = begin + chunk.byteLength;
const beginChunk = Math.floor(begin / this.chunkSize);
const endChunk = end < this.length ? Math.floor(end / this.chunkSize) : Math.ceil(end / this.chunkSize);
if (isProgressive) {
this.stream.onReceiveProgressiveData(chunk);
this.progressiveDataLength = end;
} else {
this.stream.onReceiveData(begin, chunk);
}
if (this.stream.isDataLoaded) {
this._loadedStreamCapability.resolve(this.stream);
}
const loadedRequests = [];
for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
const requestIds = this._requestsByChunk.get(curChunk);
if (!requestIds) {
continue;
}
this._requestsByChunk.delete(curChunk);
for (const requestId of requestIds) {
const chunksNeeded = this._chunksNeededByRequest.get(requestId);
if (chunksNeeded.has(curChunk)) {
chunksNeeded.delete(curChunk);
}
if (chunksNeeded.size > 0) {
continue;
}
loadedRequests.push(requestId);
}
}
if (!this.disableAutoFetch && this._requestsByChunk.size === 0) {
let nextEmptyChunk;
if (this.stream.numChunksLoaded === 1) {
const lastChunk = this.stream.numChunks - 1;
if (!this.stream.hasChunk(lastChunk)) {
nextEmptyChunk = lastChunk;
}
} else {
nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
}
if (Number.isInteger(nextEmptyChunk)) {
this._requestChunks([nextEmptyChunk]);
}
}
for (const requestId of loadedRequests) {
const capability = this._promisesByRequest.get(requestId);
this._promisesByRequest.delete(requestId);
capability.resolve();
}
this.msgHandler.send("DocProgress", {
loaded: this.stream.numChunksLoaded * this.chunkSize,
total: this.length
});
}
onError(err) {
this._loadedStreamCapability.reject(err);
}
getBeginChunk(begin) {
return Math.floor(begin / this.chunkSize);
}
getEndChunk(end) {
return Math.floor((end - 1) / this.chunkSize) + 1;
}
abort(reason) {
this.aborted = true;
this.pdfNetworkStream?.cancelAllRequests(reason);
for (const capability of this._promisesByRequest.values()) {
capability.reject(reason);
}
}
}
;// ./src/core/colorspace.js
function resizeRgbImage(src, dest, w1, h1, w2, h2, alpha01) {
const COMPONENTS = 3;
alpha01 = alpha01 !== 1 ? 0 : alpha01;
const xRatio = w1 / w2;
const yRatio = h1 / h2;
let newIndex = 0,
oldIndex;
const xScaled = new Uint16Array(w2);
const w1Scanline = w1 * COMPONENTS;
for (let i = 0; i < w2; i++) {
xScaled[i] = Math.floor(i * xRatio) * COMPONENTS;
}
for (let i = 0; i < h2; i++) {
const py = Math.floor(i * yRatio) * w1Scanline;
for (let j = 0; j < w2; j++) {
oldIndex = py + xScaled[j];
dest[newIndex++] = src[oldIndex++];
dest[newIndex++] = src[oldIndex++];
dest[newIndex++] = src[oldIndex++];
newIndex += alpha01;
}
}
}
function resizeRgbaImage(src, dest, w1, h1, w2, h2, alpha01) {
const xRatio = w1 / w2;
const yRatio = h1 / h2;
let newIndex = 0;
const xScaled = new Uint16Array(w2);
if (alpha01 === 1) {
for (let i = 0; i < w2; i++) {
xScaled[i] = Math.floor(i * xRatio);
}
const src32 = new Uint32Array(src.buffer);
const dest32 = new Uint32Array(dest.buffer);
const rgbMask = FeatureTest.isLittleEndian ? 0x00ffffff : 0xffffff00;
for (let i = 0; i < h2; i++) {
const buf = src32.subarray(Math.floor(i * yRatio) * w1);
for (let j = 0; j < w2; j++) {
dest32[newIndex++] |= buf[xScaled[j]] & rgbMask;
}
}
} else {
const COMPONENTS = 4;
const w1Scanline = w1 * COMPONENTS;
for (let i = 0; i < w2; i++) {
xScaled[i] = Math.floor(i * xRatio) * COMPONENTS;
}
for (let i = 0; i < h2; i++) {
const buf = src.subarray(Math.floor(i * yRatio) * w1Scanline);
for (let j = 0; j < w2; j++) {
const oldIndex = xScaled[j];
dest[newIndex++] = buf[oldIndex];
dest[newIndex++] = buf[oldIndex + 1];
dest[newIndex++] = buf[oldIndex + 2];
}
}
}
}
function copyRgbaImage(src, dest, alpha01) {
if (alpha01 === 1) {
const src32 = new Uint32Array(src.buffer);
const dest32 = new Uint32Array(dest.buffer);
const rgbMask = FeatureTest.isLittleEndian ? 0x00ffffff : 0xffffff00;
for (let i = 0, ii = src32.length; i < ii; i++) {
dest32[i] |= src32[i] & rgbMask;
}
} else {
let j = 0;
for (let i = 0, ii = src.length; i < ii; i += 4) {
dest[j++] = src[i];
dest[j++] = src[i + 1];
dest[j++] = src[i + 2];
}
}
}
class ColorSpace {
constructor(name, numComps) {
this.name = name;
this.numComps = numComps;
}
getRgb(src, srcOffset) {
const rgb = new Uint8ClampedArray(3);
this.getRgbItem(src, srcOffset, rgb, 0);
return rgb;
}
getRgbItem(src, srcOffset, dest, destOffset) {
unreachable("Should not call ColorSpace.getRgbItem");
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
unreachable("Should not call ColorSpace.getRgbBuffer");
}
getOutputLength(inputLength, alpha01) {
unreachable("Should not call ColorSpace.getOutputLength");
}
isPassthrough(bits) {
return false;
}
isDefaultDecode(decodeMap, bpc) {
return ColorSpace.isDefaultDecode(decodeMap, this.numComps);
}
fillRgb(dest, originalWidth, originalHeight, width, height, actualHeight, bpc, comps, alpha01) {
const count = originalWidth * originalHeight;
let rgbBuf = null;
const numComponentColors = 1 << bpc;
const needsResizing = originalHeight !== height || originalWidth !== width;
if (this.isPassthrough(bpc)) {
rgbBuf = comps;
} else if (this.numComps === 1 && count > numComponentColors && this.name !== "DeviceGray" && this.name !== "DeviceRGB") {
const allColors = bpc <= 8 ? new Uint8Array(numComponentColors) : new Uint16Array(numComponentColors);
for (let i = 0; i < numComponentColors; i++) {
allColors[i] = i;
}
const colorMap = new Uint8ClampedArray(numComponentColors * 3);
this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc, 0);
if (!needsResizing) {
let destPos = 0;
for (let i = 0; i < count; ++i) {
const key = comps[i] * 3;
dest[destPos++] = colorMap[key];
dest[destPos++] = colorMap[key + 1];
dest[destPos++] = colorMap[key + 2];
destPos += alpha01;
}
} else {
rgbBuf = new Uint8Array(count * 3);
let rgbPos = 0;
for (let i = 0; i < count; ++i) {
const key = comps[i] * 3;
rgbBuf[rgbPos++] = colorMap[key];
rgbBuf[rgbPos++] = colorMap[key + 1];
rgbBuf[rgbPos++] = colorMap[key + 2];
}
}
} else if (!needsResizing) {
this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc, alpha01);
} else {
rgbBuf = new Uint8ClampedArray(count * 3);
this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc, 0);
}
if (rgbBuf) {
if (needsResizing) {
resizeRgbImage(rgbBuf, dest, originalWidth, originalHeight, width, height, alpha01);
} else {
let destPos = 0,
rgbPos = 0;
for (let i = 0, ii = width * actualHeight; i < ii; i++) {
dest[destPos++] = rgbBuf[rgbPos++];
dest[destPos++] = rgbBuf[rgbPos++];
dest[destPos++] = rgbBuf[rgbPos++];
destPos += alpha01;
}
}
}
}
get usesZeroToOneRange() {
return shadow(this, "usesZeroToOneRange", true);
}
static _cache(cacheKey, xref, localColorSpaceCache, parsedColorSpace) {
if (!localColorSpaceCache) {
throw new Error('ColorSpace._cache - expected "localColorSpaceCache" argument.');
}
if (!parsedColorSpace) {
throw new Error('ColorSpace._cache - expected "parsedColorSpace" argument.');
}
let csName, csRef;
if (cacheKey instanceof Ref) {
csRef = cacheKey;
cacheKey = xref.fetch(cacheKey);
}
if (cacheKey instanceof Name) {
csName = cacheKey.name;
}
if (csName || csRef) {
localColorSpaceCache.set(csName, csRef, parsedColorSpace);
}
}
static getCached(cacheKey, xref, localColorSpaceCache) {
if (!localColorSpaceCache) {
throw new Error('ColorSpace.getCached - expected "localColorSpaceCache" argument.');
}
if (cacheKey instanceof Ref) {
const localColorSpace = localColorSpaceCache.getByRef(cacheKey);
if (localColorSpace) {
return localColorSpace;
}
try {
cacheKey = xref.fetch(cacheKey);
} catch (ex) {
if (ex instanceof MissingDataException) {
throw ex;
}
}
}
if (cacheKey instanceof Name) {
const localColorSpace = localColorSpaceCache.getByName(cacheKey.name);
if (localColorSpace) {
return localColorSpace;
}
}
return null;
}
static async parseAsync({
cs,
xref,
resources = null,
pdfFunctionFactory,
localColorSpaceCache
}) {
const parsedColorSpace = this._parse(cs, xref, resources, pdfFunctionFactory);
this._cache(cs, xref, localColorSpaceCache, parsedColorSpace);
return parsedColorSpace;
}
static parse({
cs,
xref,
resources = null,
pdfFunctionFactory,
localColorSpaceCache
}) {
const cachedColorSpace = this.getCached(cs, xref, localColorSpaceCache);
if (cachedColorSpace) {
return cachedColorSpace;
}
const parsedColorSpace = this._parse(cs, xref, resources, pdfFunctionFactory);
this._cache(cs, xref, localColorSpaceCache, parsedColorSpace);
return parsedColorSpace;
}
static _parse(cs, xref, resources = null, pdfFunctionFactory) {
cs = xref.fetchIfRef(cs);
if (cs instanceof Name) {
switch (cs.name) {
case "G":
case "DeviceGray":
return this.singletons.gray;
case "RGB":
case "DeviceRGB":
return this.singletons.rgb;
case "DeviceRGBA":
return this.singletons.rgba;
case "CMYK":
case "DeviceCMYK":
return this.singletons.cmyk;
case "Pattern":
return new PatternCS(null);
default:
if (resources instanceof Dict) {
const colorSpaces = resources.get("ColorSpace");
if (colorSpaces instanceof Dict) {
const resourcesCS = colorSpaces.get(cs.name);
if (resourcesCS) {
if (resourcesCS instanceof Name) {
return this._parse(resourcesCS, xref, resources, pdfFunctionFactory);
}
cs = resourcesCS;
break;
}
}
}
warn(`Unrecognized ColorSpace: ${cs.name}`);
return this.singletons.gray;
}
}
if (Array.isArray(cs)) {
const mode = xref.fetchIfRef(cs[0]).name;
let params, numComps, baseCS, whitePoint, blackPoint, gamma;
switch (mode) {
case "G":
case "DeviceGray":
return this.singletons.gray;
case "RGB":
case "DeviceRGB":
return this.singletons.rgb;
case "CMYK":
case "DeviceCMYK":
return this.singletons.cmyk;
case "CalGray":
params = xref.fetchIfRef(cs[1]);
whitePoint = params.getArray("WhitePoint");
blackPoint = params.getArray("BlackPoint");
gamma = params.get("Gamma");
return new CalGrayCS(whitePoint, blackPoint, gamma);
case "CalRGB":
params = xref.fetchIfRef(cs[1]);
whitePoint = params.getArray("WhitePoint");
blackPoint = params.getArray("BlackPoint");
gamma = params.getArray("Gamma");
const matrix = params.getArray("Matrix");
return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
case "ICCBased":
const stream = xref.fetchIfRef(cs[1]);
const dict = stream.dict;
numComps = dict.get("N");
const alt = dict.get("Alternate");
if (alt) {
const altCS = this._parse(alt, xref, resources, pdfFunctionFactory);
if (altCS.numComps === numComps) {
return altCS;
}
warn("ICCBased color space: Ignoring incorrect /Alternate entry.");
}
if (numComps === 1) {
return this.singletons.gray;
} else if (numComps === 3) {
return this.singletons.rgb;
} else if (numComps === 4) {
return this.singletons.cmyk;
}
break;
case "Pattern":
baseCS = cs[1] || null;
if (baseCS) {
baseCS = this._parse(baseCS, xref, resources, pdfFunctionFactory);
}
return new PatternCS(baseCS);
case "I":
case "Indexed":
baseCS = this._parse(cs[1], xref, resources, pdfFunctionFactory);
const hiVal = Math.max(0, Math.min(xref.fetchIfRef(cs[2]), 255));
const lookup = xref.fetchIfRef(cs[3]);
return new IndexedCS(baseCS, hiVal, lookup);
case "Separation":
case "DeviceN":
const name = xref.fetchIfRef(cs[1]);
numComps = Array.isArray(name) ? name.length : 1;
baseCS = this._parse(cs[2], xref, resources, pdfFunctionFactory);
const tintFn = pdfFunctionFactory.create(cs[3]);
return new AlternateCS(numComps, baseCS, tintFn);
case "Lab":
params = xref.fetchIfRef(cs[1]);
whitePoint = params.getArray("WhitePoint");
blackPoint = params.getArray("BlackPoint");
const range = params.getArray("Range");
return new LabCS(whitePoint, blackPoint, range);
default:
warn(`Unimplemented ColorSpace object: ${mode}`);
return this.singletons.gray;
}
}
warn(`Unrecognized ColorSpace object: ${cs}`);
return this.singletons.gray;
}
static isDefaultDecode(decode, numComps) {
if (!Array.isArray(decode)) {
return true;
}
if (numComps * 2 !== decode.length) {
warn("The decode map is not the correct length");
return true;
}
for (let i = 0, ii = decode.length; i < ii; i += 2) {
if (decode[i] !== 0 || decode[i + 1] !== 1) {
return false;
}
}
return true;
}
static get singletons() {
return shadow(this, "singletons", {
get gray() {
return shadow(this, "gray", new DeviceGrayCS());
},
get rgb() {
return shadow(this, "rgb", new DeviceRgbCS());
},
get rgba() {
return shadow(this, "rgba", new DeviceRgbaCS());
},
get cmyk() {
return shadow(this, "cmyk", new DeviceCmykCS());
}
});
}
}
class AlternateCS extends ColorSpace {
constructor(numComps, base, tintFn) {
super("Alternate", numComps);
this.base = base;
this.tintFn = tintFn;
this.tmpBuf = new Float32Array(base.numComps);
}
getRgbItem(src, srcOffset, dest, destOffset) {
const tmpBuf = this.tmpBuf;
this.tintFn(src, srcOffset, tmpBuf, 0);
this.base.getRgbItem(tmpBuf, 0, dest, destOffset);
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
const tintFn = this.tintFn;
const base = this.base;
const scale = 1 / ((1 << bits) - 1);
const baseNumComps = base.numComps;
const usesZeroToOneRange = base.usesZeroToOneRange;
const isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) && alpha01 === 0;
let pos = isPassthrough ? destOffset : 0;
const baseBuf = isPassthrough ? dest : new Uint8ClampedArray(baseNumComps * count);
const numComps = this.numComps;
const scaled = new Float32Array(numComps);
const tinted = new Float32Array(baseNumComps);
let i, j;
for (i = 0; i < count; i++) {
for (j = 0; j < numComps; j++) {
scaled[j] = src[srcOffset++] * scale;
}
tintFn(scaled, 0, tinted, 0);
if (usesZeroToOneRange) {
for (j = 0; j < baseNumComps; j++) {
baseBuf[pos++] = tinted[j] * 255;
}
} else {
base.getRgbItem(tinted, 0, baseBuf, pos);
pos += baseNumComps;
}
}
if (!isPassthrough) {
base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01);
}
}
getOutputLength(inputLength, alpha01) {
return this.base.getOutputLength(inputLength * this.base.numComps / this.numComps, alpha01);
}
}
class PatternCS extends ColorSpace {
constructor(baseCS) {
super("Pattern", null);
this.base = baseCS;
}
isDefaultDecode(decodeMap, bpc) {
unreachable("Should not call PatternCS.isDefaultDecode");
}
}
class IndexedCS extends ColorSpace {
constructor(base, highVal, lookup) {
super("Indexed", 1);
this.base = base;
const length = base.numComps * (highVal + 1);
this.lookup = new Uint8Array(length);
if (lookup instanceof BaseStream) {
const bytes = lookup.getBytes(length);
this.lookup.set(bytes);
} else if (typeof lookup === "string") {
for (let i = 0; i < length; ++i) {
this.lookup[i] = lookup.charCodeAt(i) & 0xff;
}
} else {
throw new FormatError(`IndexedCS - unrecognized lookup table: ${lookup}`);
}
}
getRgbItem(src, srcOffset, dest, destOffset) {
const numComps = this.base.numComps;
const start = src[srcOffset] * numComps;
this.base.getRgbBuffer(this.lookup, start, 1, dest, destOffset, 8, 0);
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
const base = this.base;
const numComps = base.numComps;
const outputDelta = base.getOutputLength(numComps, alpha01);
const lookup = this.lookup;
for (let i = 0; i < count; ++i) {
const lookupPos = src[srcOffset++] * numComps;
base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01);
destOffset += outputDelta;
}
}
getOutputLength(inputLength, alpha01) {
return this.base.getOutputLength(inputLength * this.base.numComps, alpha01);
}
isDefaultDecode(decodeMap, bpc) {
if (!Array.isArray(decodeMap)) {
return true;
}
if (decodeMap.length !== 2) {
warn("Decode map length is not correct");
return true;
}
if (!Number.isInteger(bpc) || bpc < 1) {
warn("Bits per component is not correct");
return true;
}
return decodeMap[0] === 0 && decodeMap[1] === (1 << bpc) - 1;
}
}
class DeviceGrayCS extends ColorSpace {
constructor() {
super("DeviceGray", 1);
}
getRgbItem(src, srcOffset, dest, destOffset) {
const c = src[srcOffset] * 255;
dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c;
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
const scale = 255 / ((1 << bits) - 1);
let j = srcOffset,
q = destOffset;
for (let i = 0; i < count; ++i) {
const c = scale * src[j++];
dest[q++] = c;
dest[q++] = c;
dest[q++] = c;
q += alpha01;
}
}
getOutputLength(inputLength, alpha01) {
return inputLength * (3 + alpha01);
}
}
class DeviceRgbCS extends ColorSpace {
constructor() {
super("DeviceRGB", 3);
}
getRgbItem(src, srcOffset, dest, destOffset) {
dest[destOffset] = src[srcOffset] * 255;
dest[destOffset + 1] = src[srcOffset + 1] * 255;
dest[destOffset + 2] = src[srcOffset + 2] * 255;
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
if (bits === 8 && alpha01 === 0) {
dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset);
return;
}
const scale = 255 / ((1 << bits) - 1);
let j = srcOffset,
q = destOffset;
for (let i = 0; i < count; ++i) {
dest[q++] = scale * src[j++];
dest[q++] = scale * src[j++];
dest[q++] = scale * src[j++];
q += alpha01;
}
}
getOutputLength(inputLength, alpha01) {
return inputLength * (3 + alpha01) / 3 | 0;
}
isPassthrough(bits) {
return bits === 8;
}
}
class DeviceRgbaCS extends ColorSpace {
constructor() {
super("DeviceRGBA", 4);
}
getOutputLength(inputLength, _alpha01) {
return inputLength * 4;
}
isPassthrough(bits) {
return bits === 8;
}
fillRgb(dest, originalWidth, originalHeight, width, height, actualHeight, bpc, comps, alpha01) {
if (originalHeight !== height || originalWidth !== width) {
resizeRgbaImage(comps, dest, originalWidth, originalHeight, width, height, alpha01);
} else {
copyRgbaImage(comps, dest, alpha01);
}
}
}
class DeviceCmykCS extends ColorSpace {
constructor() {
super("DeviceCMYK", 4);
}
#toRgb(src, srcOffset, srcScale, dest, destOffset) {
const c = src[srcOffset] * srcScale;
const m = src[srcOffset + 1] * srcScale;
const y = src[srcOffset + 2] * srcScale;
const k = src[srcOffset + 3] * srcScale;
dest[destOffset] = 255 + c * (-4.387332384609988 * c + 54.48615194189176 * m + 18.82290502165302 * y + 212.25662451639585 * k + -285.2331026137004) + m * (1.7149763477362134 * m - 5.6096736904047315 * y + -17.873870861415444 * k - 5.497006427196366) + y * (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) + k * (-21.86122147463605 * k - 189.48180835922747);
dest[destOffset + 1] = 255 + c * (8.841041422036149 * c + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k + -79.2970844816548) + m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) + y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) + k * (-20.737325471181034 * k - 187.80453709719578);
dest[destOffset + 2] = 255 + c * (0.8842522430003296 * c + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k + -14.183576799673286) + m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) + y * (0.03296041114873217 * y + 115.60384449646641 * k + -193.58209356861505) + k * (-22.33816807309886 * k - 180.12613974708367);
}
getRgbItem(src, srcOffset, dest, destOffset) {
this.#toRgb(src, srcOffset, 1, dest, destOffset);
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
const scale = 1 / ((1 << bits) - 1);
for (let i = 0; i < count; i++) {
this.#toRgb(src, srcOffset, scale, dest, destOffset);
srcOffset += 4;
destOffset += 3 + alpha01;
}
}
getOutputLength(inputLength, alpha01) {
return inputLength / 4 * (3 + alpha01) | 0;
}
}
class CalGrayCS extends ColorSpace {
constructor(whitePoint, blackPoint, gamma) {
super("CalGray", 1);
if (!whitePoint) {
throw new FormatError("WhitePoint missing - required for color space CalGray");
}
[this.XW, this.YW, this.ZW] = whitePoint;
[this.XB, this.YB, this.ZB] = blackPoint || [0, 0, 0];
this.G = gamma || 1;
if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
throw new FormatError(`Invalid WhitePoint components for ${this.name}, no fallback available`);
}
if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
info(`Invalid BlackPoint for ${this.name}, falling back to default.`);
this.XB = this.YB = this.ZB = 0;
}
if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) {
warn(`${this.name}, BlackPoint: XB: ${this.XB}, YB: ${this.YB}, ` + `ZB: ${this.ZB}, only default values are supported.`);
}
if (this.G < 1) {
info(`Invalid Gamma: ${this.G} for ${this.name}, falling back to default.`);
this.G = 1;
}
}
#toRgb(src, srcOffset, dest, destOffset, scale) {
const A = src[srcOffset] * scale;
const AG = A ** this.G;
const L = this.YW * AG;
const val = Math.max(295.8 * L ** 0.3333333333333333 - 40.8, 0);
dest[destOffset] = val;
dest[destOffset + 1] = val;
dest[destOffset + 2] = val;
}
getRgbItem(src, srcOffset, dest, destOffset) {
this.#toRgb(src, srcOffset, dest, destOffset, 1);
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
const scale = 1 / ((1 << bits) - 1);
for (let i = 0; i < count; ++i) {
this.#toRgb(src, srcOffset, dest, destOffset, scale);
srcOffset += 1;
destOffset += 3 + alpha01;
}
}
getOutputLength(inputLength, alpha01) {
return inputLength * (3 + alpha01);
}
}
class CalRGBCS extends ColorSpace {
static #BRADFORD_SCALE_MATRIX = new Float32Array([0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296]);
static #BRADFORD_SCALE_INVERSE_MATRIX = new Float32Array([0.9869929, -0.1470543, 0.1599627, 0.4323053, 0.5183603, 0.0492912, -0.0085287, 0.0400428, 0.9684867]);
static #SRGB_D65_XYZ_TO_RGB_MATRIX = new Float32Array([3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108, 0.0415560, 0.0556434, -0.2040259, 1.0572252]);
static #FLAT_WHITEPOINT_MATRIX = new Float32Array([1, 1, 1]);
static #tempNormalizeMatrix = new Float32Array(3);
static #tempConvertMatrix1 = new Float32Array(3);
static #tempConvertMatrix2 = new Float32Array(3);
static #DECODE_L_CONSTANT = ((8 + 16) / 116) ** 3 / 8.0;
constructor(whitePoint, blackPoint, gamma, matrix) {
super("CalRGB", 3);
if (!whitePoint) {
throw new FormatError("WhitePoint missing - required for color space CalRGB");
}
const [XW, YW, ZW] = this.whitePoint = whitePoint;
const [XB, YB, ZB] = this.blackPoint = blackPoint || new Float32Array(3);
[this.GR, this.GG, this.GB] = gamma || new Float32Array([1, 1, 1]);
[this.MXA, this.MYA, this.MZA, this.MXB, this.MYB, this.MZB, this.MXC, this.MYC, this.MZC] = matrix || new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);
if (XW < 0 || ZW < 0 || YW !== 1) {
throw new FormatError(`Invalid WhitePoint components for ${this.name}, no fallback available`);
}
if (XB < 0 || YB < 0 || ZB < 0) {
info(`Invalid BlackPoint for ${this.name} [${XB}, ${YB}, ${ZB}], ` + "falling back to default.");
this.blackPoint = new Float32Array(3);
}
if (this.GR < 0 || this.GG < 0 || this.GB < 0) {
info(`Invalid Gamma [${this.GR}, ${this.GG}, ${this.GB}] for ` + `${this.name}, falling back to default.`);
this.GR = this.GG = this.GB = 1;
}
}
#matrixProduct(a, b, result) {
result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
result[1] = a[3] * b[0] + a[4] * b[1] + a[5] * b[2];
result[2] = a[6] * b[0] + a[7] * b[1] + a[8] * b[2];
}
#toFlat(sourceWhitePoint, LMS, result) {
result[0] = LMS[0] * 1 / sourceWhitePoint[0];
result[1] = LMS[1] * 1 / sourceWhitePoint[1];
result[2] = LMS[2] * 1 / sourceWhitePoint[2];
}
#toD65(sourceWhitePoint, LMS, result) {
const D65X = 0.95047;
const D65Y = 1;
const D65Z = 1.08883;
result[0] = LMS[0] * D65X / sourceWhitePoint[0];
result[1] = LMS[1] * D65Y / sourceWhitePoint[1];
result[2] = LMS[2] * D65Z / sourceWhitePoint[2];
}
#sRGBTransferFunction(color) {
if (color <= 0.0031308) {
return this.#adjustToRange(0, 1, 12.92 * color);
}
if (color >= 0.99554525) {
return 1;
}
return this.#adjustToRange(0, 1, (1 + 0.055) * color ** (1 / 2.4) - 0.055);
}
#adjustToRange(min, max, value) {
return Math.max(min, Math.min(max, value));
}
#decodeL(L) {
if (L < 0) {
return -this.#decodeL(-L);
}
if (L > 8.0) {
return ((L + 16) / 116) ** 3;
}
return L * CalRGBCS.#DECODE_L_CONSTANT;
}
#compensateBlackPoint(sourceBlackPoint, XYZ_Flat, result) {
if (sourceBlackPoint[0] === 0 && sourceBlackPoint[1] === 0 && sourceBlackPoint[2] === 0) {
result[0] = XYZ_Flat[0];
result[1] = XYZ_Flat[1];
result[2] = XYZ_Flat[2];
return;
}
const zeroDecodeL = this.#decodeL(0);
const X_DST = zeroDecodeL;
const X_SRC = this.#decodeL(sourceBlackPoint[0]);
const Y_DST = zeroDecodeL;
const Y_SRC = this.#decodeL(sourceBlackPoint[1]);
const Z_DST = zeroDecodeL;
const Z_SRC = this.#decodeL(sourceBlackPoint[2]);
const X_Scale = (1 - X_DST) / (1 - X_SRC);
const X_Offset = 1 - X_Scale;
const Y_Scale = (1 - Y_DST) / (1 - Y_SRC);
const Y_Offset = 1 - Y_Scale;
const Z_Scale = (1 - Z_DST) / (1 - Z_SRC);
const Z_Offset = 1 - Z_Scale;
result[0] = XYZ_Flat[0] * X_Scale + X_Offset;
result[1] = XYZ_Flat[1] * Y_Scale + Y_Offset;
result[2] = XYZ_Flat[2] * Z_Scale + Z_Offset;
}
#normalizeWhitePointToFlat(sourceWhitePoint, XYZ_In, result) {
if (sourceWhitePoint[0] === 1 && sourceWhitePoint[2] === 1) {
result[0] = XYZ_In[0];
result[1] = XYZ_In[1];
result[2] = XYZ_In[2];
return;
}
const LMS = result;
this.#matrixProduct(CalRGBCS.#BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
const LMS_Flat = CalRGBCS.#tempNormalizeMatrix;
this.#toFlat(sourceWhitePoint, LMS, LMS_Flat);
this.#matrixProduct(CalRGBCS.#BRADFORD_SCALE_INVERSE_MATRIX, LMS_Flat, result);
}
#normalizeWhitePointToD65(sourceWhitePoint, XYZ_In, result) {
const LMS = result;
this.#matrixProduct(CalRGBCS.#BRADFORD_SCALE_MATRIX, XYZ_In, LMS);
const LMS_D65 = CalRGBCS.#tempNormalizeMatrix;
this.#toD65(sourceWhitePoint, LMS, LMS_D65);
this.#matrixProduct(CalRGBCS.#BRADFORD_SCALE_INVERSE_MATRIX, LMS_D65, result);
}
#toRgb(src, srcOffset, dest, destOffset, scale) {
const A = this.#adjustToRange(0, 1, src[srcOffset] * scale);
const B = this.#adjustToRange(0, 1, src[srcOffset + 1] * scale);
const C = this.#adjustToRange(0, 1, src[srcOffset + 2] * scale);
const AGR = A === 1 ? 1 : A ** this.GR;
const BGG = B === 1 ? 1 : B ** this.GG;
const CGB = C === 1 ? 1 : C ** this.GB;
const X = this.MXA * AGR + this.MXB * BGG + this.MXC * CGB;
const Y = this.MYA * AGR + this.MYB * BGG + this.MYC * CGB;
const Z = this.MZA * AGR + this.MZB * BGG + this.MZC * CGB;
const XYZ = CalRGBCS.#tempConvertMatrix1;
XYZ[0] = X;
XYZ[1] = Y;
XYZ[2] = Z;
const XYZ_Flat = CalRGBCS.#tempConvertMatrix2;
this.#normalizeWhitePointToFlat(this.whitePoint, XYZ, XYZ_Flat);
const XYZ_Black = CalRGBCS.#tempConvertMatrix1;
this.#compensateBlackPoint(this.blackPoint, XYZ_Flat, XYZ_Black);
const XYZ_D65 = CalRGBCS.#tempConvertMatrix2;
this.#normalizeWhitePointToD65(CalRGBCS.#FLAT_WHITEPOINT_MATRIX, XYZ_Black, XYZ_D65);
const SRGB = CalRGBCS.#tempConvertMatrix1;
this.#matrixProduct(CalRGBCS.#SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);
dest[destOffset] = this.#sRGBTransferFunction(SRGB[0]) * 255;
dest[destOffset + 1] = this.#sRGBTransferFunction(SRGB[1]) * 255;
dest[destOffset + 2] = this.#sRGBTransferFunction(SRGB[2]) * 255;
}
getRgbItem(src, srcOffset, dest, destOffset) {
this.#toRgb(src, srcOffset, dest, destOffset, 1);
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
const scale = 1 / ((1 << bits) - 1);
for (let i = 0; i < count; ++i) {
this.#toRgb(src, srcOffset, dest, destOffset, scale);
srcOffset += 3;
destOffset += 3 + alpha01;
}
}
getOutputLength(inputLength, alpha01) {
return inputLength * (3 + alpha01) / 3 | 0;
}
}
class LabCS extends ColorSpace {
constructor(whitePoint, blackPoint, range) {
super("Lab", 3);
if (!whitePoint) {
throw new FormatError("WhitePoint missing - required for color space Lab");
}
[this.XW, this.YW, this.ZW] = whitePoint;
[this.amin, this.amax, this.bmin, this.bmax] = range || [-100, 100, -100, 100];
[this.XB, this.YB, this.ZB] = blackPoint || [0, 0, 0];
if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) {
throw new FormatError("Invalid WhitePoint components, no fallback available");
}
if (this.XB < 0 || this.YB < 0 || this.ZB < 0) {
info("Invalid BlackPoint, falling back to default");
this.XB = this.YB = this.ZB = 0;
}
if (this.amin > this.amax || this.bmin > this.bmax) {
info("Invalid Range, falling back to defaults");
this.amin = -100;
this.amax = 100;
this.bmin = -100;
this.bmax = 100;
}
}
#fn_g(x) {
return x >= 6 / 29 ? x ** 3 : 108 / 841 * (x - 4 / 29);
}
#decode(value, high1, low2, high2) {
return low2 + value * (high2 - low2) / high1;
}
#toRgb(src, srcOffset, maxVal, dest, destOffset) {
let Ls = src[srcOffset];
let as = src[srcOffset + 1];
let bs = src[srcOffset + 2];
if (maxVal !== false) {
Ls = this.#decode(Ls, maxVal, 0, 100);
as = this.#decode(as, maxVal, this.amin, this.amax);
bs = this.#decode(bs, maxVal, this.bmin, this.bmax);
}
if (as > this.amax) {
as = this.amax;
} else if (as < this.amin) {
as = this.amin;
}
if (bs > this.bmax) {
bs = this.bmax;
} else if (bs < this.bmin) {
bs = this.bmin;
}
const M = (Ls + 16) / 116;
const L = M + as / 500;
const N = M - bs / 200;
const X = this.XW * this.#fn_g(L);
const Y = this.YW * this.#fn_g(M);
const Z = this.ZW * this.#fn_g(N);
let r, g, b;
if (this.ZW < 1) {
r = X * 3.1339 + Y * -1.617 + Z * -0.4906;
g = X * -0.9785 + Y * 1.916 + Z * 0.0333;
b = X * 0.072 + Y * -0.229 + Z * 1.4057;
} else {
r = X * 3.2406 + Y * -1.5372 + Z * -0.4986;
g = X * -0.9689 + Y * 1.8758 + Z * 0.0415;
b = X * 0.0557 + Y * -0.204 + Z * 1.057;
}
dest[destOffset] = Math.sqrt(r) * 255;
dest[destOffset + 1] = Math.sqrt(g) * 255;
dest[destOffset + 2] = Math.sqrt(b) * 255;
}
getRgbItem(src, srcOffset, dest, destOffset) {
this.#toRgb(src, srcOffset, false, dest, destOffset);
}
getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) {
const maxVal = (1 << bits) - 1;
for (let i = 0; i < count; i++) {
this.#toRgb(src, srcOffset, maxVal, dest, destOffset);
srcOffset += 3;
destOffset += 3 + alpha01;
}
}
getOutputLength(inputLength, alpha01) {
return inputLength * (3 + alpha01) / 3 | 0;
}
isDefaultDecode(decodeMap, bpc) {
return true;
}
get usesZeroToOneRange() {
return shadow(this, "usesZeroToOneRange", false);
}
}
;// ./src/core/binary_cmap.js
function hexToInt(a, size) {
let n = 0;
for (let i = 0; i <= size; i++) {
n = n << 8 | a[i];
}
return n >>> 0;
}
function hexToStr(a, size) {
if (size === 1) {
return String.fromCharCode(a[0], a[1]);
}
if (size === 3) {
return String.fromCharCode(a[0], a[1], a[2], a[3]);
}
return String.fromCharCode(...a.subarray(0, size + 1));
}
function addHex(a, b, size) {
let c = 0;
for (let i = size; i >= 0; i--) {
c += a[i] + b[i];
a[i] = c & 255;
c >>= 8;
}
}
function incHex(a, size) {
let c = 1;
for (let i = size; i >= 0 && c > 0; i--) {
c += a[i];
a[i] = c & 255;
c >>= 8;
}
}
const MAX_NUM_SIZE = 16;
const MAX_ENCODED_NUM_SIZE = 19;
class BinaryCMapStream {
constructor(data) {
this.buffer = data;
this.pos = 0;
this.end = data.length;
this.tmpBuf = new Uint8Array(MAX_ENCODED_NUM_SIZE);
}
readByte() {
if (this.pos >= this.end) {
return -1;
}
return this.buffer[this.pos++];
}
readNumber() {
let n = 0;
let last;
do {
const b = this.readByte();
if (b < 0) {
throw new FormatError("unexpected EOF in bcmap");
}
last = !(b & 0x80);
n = n << 7 | b & 0x7f;
} while (!last);
return n;
}
readSigned() {
const n = this.readNumber();
return n & 1 ? ~(n >>> 1) : n >>> 1;
}
readHex(num, size) {
num.set(this.buffer.subarray(this.pos, this.pos + size + 1));
this.pos += size + 1;
}
readHexNumber(num, size) {
let last;
const stack = this.tmpBuf;
let sp = 0;
do {
const b = this.readByte();
if (b < 0) {
throw new FormatError("unexpected EOF in bcmap");
}
last = !(b & 0x80);
stack[sp++] = b & 0x7f;
} while (!last);
let i = size,
buffer = 0,
bufferSize = 0;
while (i >= 0) {
while (bufferSize < 8 && stack.length > 0) {
buffer |= stack[--sp] << bufferSize;
bufferSize += 7;
}
num[i] = buffer & 255;
i--;
buffer >>= 8;
bufferSize -= 8;
}
}
readHexSigned(num, size) {
this.readHexNumber(num, size);
const sign = num[size] & 1 ? 255 : 0;
let c = 0;
for (let i = 0; i <= size; i++) {
c = (c & 1) << 8 | num[i];
num[i] = c >> 1 ^ sign;
}
}
readString() {
const len = this.readNumber(),
buf = new Array(len);
for (let i = 0; i < len; i++) {
buf[i] = this.readNumber();
}
return String.fromCharCode(...buf);
}
}
class BinaryCMapReader {
async process(data, cMap, extend) {
const stream = new BinaryCMapStream(data);
const header = stream.readByte();
cMap.vertical = !!(header & 1);
let useCMap = null;
const start = new Uint8Array(MAX_NUM_SIZE);
const end = new Uint8Array(MAX_NUM_SIZE);
const char = new Uint8Array(MAX_NUM_SIZE);
const charCode = new Uint8Array(MAX_NUM_SIZE);
const tmp = new Uint8Array(MAX_NUM_SIZE);
let code;
let b;
while ((b = stream.readByte()) >= 0) {
const type = b >> 5;
if (type === 7) {
switch (b & 0x1f) {
case 0:
stream.readString();
break;
case 1:
useCMap = stream.readString();
break;
}
continue;
}
const sequence = !!(b & 0x10);
const dataSize = b & 15;
if (dataSize + 1 > MAX_NUM_SIZE) {
throw new Error("BinaryCMapReader.process: Invalid dataSize.");
}
const ucs2DataSize = 1;
const subitemsCount = stream.readNumber();
switch (type) {
case 0:
stream.readHex(start, dataSize);
stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize);
cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize), hexToInt(end, dataSize));
for (let i = 1; i < subitemsCount; i++) {
incHex(end, dataSize);
stream.readHexNumber(start, dataSize);
addHex(start, end, dataSize);
stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize);
cMap.addCodespaceRange(dataSize + 1, hexToInt(start, dataSize), hexToInt(end, dataSize));
}
break;
case 1:
stream.readHex(start, dataSize);
stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize);
stream.readNumber();
for (let i = 1; i < subitemsCount; i++) {
incHex(end, dataSize);
stream.readHexNumber(start, dataSize);
addHex(start, end, dataSize);
stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize);
stream.readNumber();
}
break;
case 2:
stream.readHex(char, dataSize);
code = stream.readNumber();
cMap.mapOne(hexToInt(char, dataSize), code);
for (let i = 1; i < subitemsCount; i++) {
incHex(char, dataSize);
if (!sequence) {
stream.readHexNumber(tmp, dataSize);
addHex(char, tmp, dataSize);
}
code = stream.readSigned() + (code + 1);
cMap.mapOne(hexToInt(char, dataSize), code);
}
break;
case 3:
stream.readHex(start, dataSize);
stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize);
code = stream.readNumber();
cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize), code);
for (let i = 1; i < subitemsCount; i++) {
incHex(end, dataSize);
if (!sequence) {
stream.readHexNumber(start, dataSize);
addHex(start, end, dataSize);
} else {
start.set(end);
}
stream.readHexNumber(end, dataSize);
addHex(end, start, dataSize);
code = stream.readNumber();
cMap.mapCidRange(hexToInt(start, dataSize), hexToInt(end, dataSize), code);
}
break;
case 4:
stream.readHex(char, ucs2DataSize);
stream.readHex(charCode, dataSize);
cMap.mapOne(hexToInt(char, ucs2DataSize), hexToStr(charCode, dataSize));
for (let i = 1; i < subitemsCount; i++) {
incHex(char, ucs2DataSize);
if (!sequence) {
stream.readHexNumber(tmp, ucs2DataSize);
addHex(char, tmp, ucs2DataSize);
}
incHex(charCode, dataSize);
stream.readHexSigned(tmp, dataSize);
addHex(charCode, tmp, dataSize);
cMap.mapOne(hexToInt(char, ucs2DataSize), hexToStr(charCode, dataSize));
}
break;
case 5:
stream.readHex(start, ucs2DataSize);
stream.readHexNumber(end, ucs2DataSize);
addHex(end, start, ucs2DataSize);
stream.readHex(charCode, dataSize);
cMap.mapBfRange(hexToInt(start, ucs2DataSize), hexToInt(end, ucs2DataSize), hexToStr(charCode, dataSize));
for (let i = 1; i < subitemsCount; i++) {
incHex(end, ucs2DataSize);
if (!sequence) {
stream.readHexNumber(start, ucs2DataSize);
addHex(start, end, ucs2DataSize);
} else {
start.set(end);
}
stream.readHexNumber(end, ucs2DataSize);
addHex(end, start, ucs2DataSize);
stream.readHex(charCode, dataSize);
cMap.mapBfRange(hexToInt(start, ucs2DataSize), hexToInt(end, ucs2DataSize), hexToStr(charCode, dataSize));
}
break;
default:
throw new Error(`BinaryCMapReader.process - unknown type: ${type}`);
}
}
if (useCMap) {
return extend(useCMap);
}
return cMap;
}
}
;// ./src/core/decode_stream.js
const emptyBuffer = new Uint8Array(0);
class DecodeStream extends BaseStream {
constructor(maybeMinBufferLength) {
super();
this._rawMinBufferLength = maybeMinBufferLength || 0;
this.pos = 0;
this.bufferLength = 0;
this.eof = false;
this.buffer = emptyBuffer;
this.minBufferLength = 512;
if (maybeMinBufferLength) {
while (this.minBufferLength < maybeMinBufferLength) {
this.minBufferLength *= 2;
}
}
}
get isEmpty() {
while (!this.eof && this.bufferLength === 0) {
this.readBlock();
}
return this.bufferLength === 0;
}
ensureBuffer(requested) {
const buffer = this.buffer;
if (requested <= buffer.byteLength) {
return buffer;
}
let size = this.minBufferLength;
while (size < requested) {
size *= 2;
}
const buffer2 = new Uint8Array(size);
buffer2.set(buffer);
return this.buffer = buffer2;
}
getByte() {
const pos = this.pos;
while (this.bufferLength <= pos) {
if (this.eof) {
return -1;
}
this.readBlock();
}
return this.buffer[this.pos++];
}
getBytes(length, decoderOptions = null) {
const pos = this.pos;
let end;
if (length) {
this.ensureBuffer(pos + length);
end = pos + length;
while (!this.eof && this.bufferLength < end) {
this.readBlock(decoderOptions);
}
const bufEnd = this.bufferLength;
if (end > bufEnd) {
end = bufEnd;
}
} else {
while (!this.eof) {
this.readBlock(decoderOptions);
}
end = this.bufferLength;
}
this.pos = end;
return this.buffer.subarray(pos, end);
}
async getImageData(length, decoderOptions) {
if (!this.canAsyncDecodeImageFromBuffer) {
if (this.isAsyncDecoder) {
return this.decodeImage(null, decoderOptions);
}
return this.getBytes(length, decoderOptions);
}
const data = await this.stream.asyncGetBytes();
return this.decodeImage(data, decoderOptions);
}
reset() {
this.pos = 0;
}
makeSubStream(start, length, dict = null) {
if (length === undefined) {
while (!this.eof) {
this.readBlock();
}
} else {
const end = start + length;
while (this.bufferLength <= end && !this.eof) {
this.readBlock();
}
}
return new Stream(this.buffer, start, length, dict);
}
getBaseStreams() {
return this.str ? this.str.getBaseStreams() : null;
}
}
class StreamsSequenceStream extends DecodeStream {
constructor(streams, onError = null) {
streams = streams.filter(s => s instanceof BaseStream);
let maybeLength = 0;
for (const stream of streams) {
maybeLength += stream instanceof DecodeStream ? stream._rawMinBufferLength : stream.length;
}
super(maybeLength);
this.streams = streams;
this._onError = onError;
}
readBlock() {
const streams = this.streams;
if (streams.length === 0) {
this.eof = true;
return;
}
const stream = streams.shift();
let chunk;
try {
chunk = stream.getBytes();
} catch (reason) {
if (this._onError) {
this._onError(reason, stream.dict?.objId);
return;
}
throw reason;
}
const bufferLength = this.bufferLength;
const newLength = bufferLength + chunk.length;
const buffer = this.ensureBuffer(newLength);
buffer.set(chunk, bufferLength);
this.bufferLength = newLength;
}
getBaseStreams() {
const baseStreamsBuf = [];
for (const stream of this.streams) {
const baseStreams = stream.getBaseStreams();
if (baseStreams) {
baseStreamsBuf.push(...baseStreams);
}
}
return baseStreamsBuf.length > 0 ? baseStreamsBuf : null;
}
}
;// ./src/core/ascii_85_stream.js
class Ascii85Stream extends DecodeStream {
constructor(str, maybeLength) {
if (maybeLength) {
maybeLength *= 0.8;
}
super(maybeLength);
this.str = str;
this.dict = str.dict;
this.input = new Uint8Array(5);
}
readBlock() {
const TILDA_CHAR = 0x7e;
const Z_LOWER_CHAR = 0x7a;
const EOF = -1;
const str = this.str;
let c = str.getByte();
while (isWhiteSpace(c)) {
c = str.getByte();
}
if (c === EOF || c === TILDA_CHAR) {
this.eof = true;
return;
}
const bufferLength = this.bufferLength;
let buffer, i;
if (c === Z_LOWER_CHAR) {
buffer = this.ensureBuffer(bufferLength + 4);
for (i = 0; i < 4; ++i) {
buffer[bufferLength + i] = 0;
}
this.bufferLength += 4;
} else {
const input = this.input;
input[0] = c;
for (i = 1; i < 5; ++i) {
c = str.getByte();
while (isWhiteSpace(c)) {
c = str.getByte();
}
input[i] = c;
if (c === EOF || c === TILDA_CHAR) {
break;
}
}
buffer = this.ensureBuffer(bufferLength + i - 1);
this.bufferLength += i - 1;
if (i < 5) {
for (; i < 5; ++i) {
input[i] = 0x21 + 84;
}
this.eof = true;
}
let t = 0;
for (i = 0; i < 5; ++i) {
t = t * 85 + (input[i] - 0x21);
}
for (i = 3; i >= 0; --i) {
buffer[bufferLength + i] = t & 0xff;
t >>= 8;
}
}
}
}
;// ./src/core/ascii_hex_stream.js
class AsciiHexStream extends DecodeStream {
constructor(str, maybeLength) {
if (maybeLength) {
maybeLength *= 0.5;
}
super(maybeLength);
this.str = str;
this.dict = str.dict;
this.firstDigit = -1;
}
readBlock() {
const UPSTREAM_BLOCK_SIZE = 8000;
const bytes = this.str.getBytes(UPSTREAM_BLOCK_SIZE);
if (!bytes.length) {
this.eof = true;
return;
}
const maxDecodeLength = bytes.length + 1 >> 1;
const buffer = this.ensureBuffer(this.bufferLength + maxDecodeLength);
let bufferLength = this.bufferLength;
let firstDigit = this.firstDigit;
for (const ch of bytes) {
let digit;
if (ch >= 0x30 && ch <= 0x39) {
digit = ch & 0x0f;
} else if (ch >= 0x41 && ch <= 0x46 || ch >= 0x61 && ch <= 0x66) {
digit = (ch & 0x0f) + 9;
} else if (ch === 0x3e) {
this.eof = true;
break;
} else {
continue;
}
if (firstDigit < 0) {
firstDigit = digit;
} else {
buffer[bufferLength++] = firstDigit << 4 | digit;
firstDigit = -1;
}
}
if (firstDigit >= 0 && this.eof) {
buffer[bufferLength++] = firstDigit << 4;
firstDigit = -1;
}
this.firstDigit = firstDigit;
this.bufferLength = bufferLength;
}
}
;// ./src/core/ccitt.js
const ccittEOL = -2;
const ccittEOF = -1;
const twoDimPass = 0;
const twoDimHoriz = 1;
const twoDimVert0 = 2;
const twoDimVertR1 = 3;
const twoDimVertL1 = 4;
const twoDimVertR2 = 5;
const twoDimVertL2 = 6;
const twoDimVertR3 = 7;
const twoDimVertL3 = 8;
const twoDimTable = [[-1, -1], [-1, -1], [7, twoDimVertL3], [7, twoDimVertR3], [6, twoDimVertL2], [6, twoDimVertL2], [6, twoDimVertR2], [6, twoDimVertR2], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [4, twoDimPass], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimHoriz], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertL1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [3, twoDimVertR1], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0], [1, twoDimVert0]];
const whiteTable1 = [[-1, -1], [12, ccittEOL], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [11, 1792], [11, 1792], [12, 1984], [12, 2048], [12, 2112], [12, 2176], [12, 2240], [12, 2304], [11, 1856], [11, 1856], [11, 1920], [11, 1920], [12, 2368], [12, 2432], [12, 2496], [12, 2560]];
const whiteTable2 = [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [8, 29], [8, 29], [8, 30], [8, 30], [8, 45], [8, 45], [8, 46], [8, 46], [7, 22], [7, 22], [7, 22], [7, 22], [7, 23], [7, 23], [7, 23], [7, 23], [8, 47], [8, 47], [8, 48], [8, 48], [6, 13], [6, 13], [6, 13], [6, 13], [6, 13], [6, 13], [6, 13], [6, 13], [7, 20], [7, 20], [7, 20], [7, 20], [8, 33], [8, 33], [8, 34], [8, 34], [8, 35], [8, 35], [8, 36], [8, 36], [8, 37], [8, 37], [8, 38], [8, 38], [7, 19], [7, 19], [7, 19], [7, 19], [8, 31], [8, 31], [8, 32], [8, 32], [6, 1], [6, 1], [6, 1], [6, 1], [6, 1], [6, 1], [6, 1], [6, 1], [6, 12], [6, 12], [6, 12], [6, 12], [6, 12], [6, 12], [6, 12], [6, 12], [8, 53], [8, 53], [8, 54], [8, 54], [7, 26], [7, 26], [7, 26], [7, 26], [8, 39], [8, 39], [8, 40], [8, 40], [8, 41], [8, 41], [8, 42], [8, 42], [8, 43], [8, 43], [8, 44], [8, 44], [7, 21], [7, 21], [7, 21], [7, 21], [7, 28], [7, 28], [7, 28], [7, 28], [8, 61], [8, 61], [8, 62], [8, 62], [8, 63], [8, 63], [8, 0], [8, 0], [8, 320], [8, 320], [8, 384], [8, 384], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 10], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [5, 11], [7, 27], [7, 27], [7, 27], [7, 27], [8, 59], [8, 59], [8, 60], [8, 60], [9, 1472], [9, 1536], [9, 1600], [9, 1728], [7, 18], [7, 18], [7, 18], [7, 18], [7, 24], [7, 24], [7, 24], [7, 24], [8, 49], [8, 49], [8, 50], [8, 50], [8, 51], [8, 51], [8, 52], [8, 52], [7, 25], [7, 25], [7, 25], [7, 25], [8, 55], [8, 55], [8, 56], [8, 56], [8, 57], [8, 57], [8, 58], [8, 58], [6, 192], [6, 192], [6, 192], [6, 192], [6, 192], [6, 192], [6, 192], [6, 192], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [6, 1664], [8, 448], [8, 448], [8, 512], [8, 512], [9, 704], [9, 768], [8, 640], [8, 640], [8, 576], [8, 576], [9, 832], [9, 896], [9, 960], [9, 1024], [9, 1088], [9, 1152], [9, 1216], [9, 1280], [9, 1344], [9, 1408], [7, 256], [7, 256], [7, 256], [7, 256], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 2], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [4, 3], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 128], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 8], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [5, 9], [6, 16], [6, 16], [6, 16], [6, 16], [6, 16], [6, 16], [6, 16], [6, 16], [6, 17], [6, 17], [6, 17], [6, 17], [6, 17], [6, 17], [6, 17], [6, 17], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [6, 14], [6, 14], [6, 14], [6, 14], [6, 14], [6, 14], [6, 14], [6, 14], [6, 15], [6, 15], [6, 15], [6, 15], [6, 15], [6, 15], [6, 15], [6, 15], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [5, 64], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 6], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7], [4, 7]];
const blackTable1 = [[-1, -1], [-1, -1], [12, ccittEOL], [12, ccittEOL], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [-1, -1], [11, 1792], [11, 1792], [11, 1792], [11, 1792], [12, 1984], [12, 1984], [12, 2048], [12, 2048], [12, 2112], [12, 2112], [12, 2176], [12, 2176], [12, 2240], [12, 2240], [12, 2304], [12, 2304], [11, 1856], [11, 1856], [11, 1856], [11, 1856], [11, 1920], [11, 1920], [11, 1920], [11, 1920], [12, 2368], [12, 2368], [12, 2432], [12, 2432], [12, 2496], [12, 2496], [12, 2560], [12, 2560], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [10, 18], [12, 52], [12, 52], [13, 640], [13, 704], [13, 768], [13, 832], [12, 55], [12, 55], [12, 56], [12, 56], [13, 1280], [13, 1344], [13, 1408], [13, 1472], [12, 59], [12, 59], [12, 60], [12, 60], [13, 1536], [13, 1600], [11, 24], [11, 24], [11, 24], [11, 24], [11, 25], [11, 25], [11, 25], [11, 25], [13, 1664], [13, 1728], [12, 320], [12, 320], [12, 384], [12, 384], [12, 448], [12, 448], [13, 512], [13, 576], [12, 53], [12, 53], [12, 54], [12, 54], [13, 896], [13, 960], [13, 1024], [13, 1088], [13, 1152], [13, 1216], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64], [10, 64]];
const blackTable2 = [[8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [8, 13], [11, 23], [11, 23], [12, 50], [12, 51], [12, 44], [12, 45], [12, 46], [12, 47], [12, 57], [12, 58], [12, 61], [12, 256], [10, 16], [10, 16], [10, 16], [10, 16], [10, 17], [10, 17], [10, 17], [10, 17], [12, 48], [12, 49], [12, 62], [12, 63], [12, 30], [12, 31], [12, 32], [12, 33], [12, 40], [12, 41], [11, 22], [11, 22], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [8, 14], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 10], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [7, 11], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [9, 15], [12, 128], [12, 192], [12, 26], [12, 27], [12, 28], [12, 29], [11, 19], [11, 19], [11, 20], [11, 20], [12, 34], [12, 35], [12, 36], [12, 37], [12, 38], [12, 39], [11, 21], [11, 21], [12, 42], [12, 43], [10, 0], [10, 0], [10, 0], [10, 0], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12], [7, 12]];
const blackTable3 = [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [6, 9], [6, 8], [5, 7], [5, 7], [4, 6], [4, 6], [4, 6], [4, 6], [4, 5], [4, 5], [4, 5], [4, 5], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]];
class CCITTFaxDecoder {
constructor(source, options = {}) {
if (typeof source?.next !== "function") {
throw new Error('CCITTFaxDecoder - invalid "source" parameter.');
}
this.source = source;
this.eof = false;
this.encoding = options.K || 0;
this.eoline = options.EndOfLine || false;
this.byteAlign = options.EncodedByteAlign || false;
this.columns = options.Columns || 1728;
this.rows = options.Rows || 0;
this.eoblock = options.EndOfBlock ?? true;
this.black = options.BlackIs1 || false;
this.codingLine = new Uint32Array(this.columns + 1);
this.refLine = new Uint32Array(this.columns + 2);
this.codingLine[0] = this.columns;
this.codingPos = 0;
this.row = 0;
this.nextLine2D = this.encoding < 0;
this.inputBits = 0;
this.inputBuf = 0;
this.outputBits = 0;
this.rowsDone = false;
let code1;
while ((code1 = this._lookBits(12)) === 0) {
this._eatBits(1);
}
if (code1 === 1) {
this._eatBits(12);
}
if (this.encoding > 0) {
this.nextLine2D = !this._lookBits(1);
this._eatBits(1);
}
}
readNextChar() {
if (this.eof) {
return -1;
}
const refLine = this.refLine;
const codingLine = this.codingLine;
const columns = this.columns;
let refPos, blackPixels, bits, i;
if (this.outputBits === 0) {
if (this.rowsDone) {
this.eof = true;
}
if (this.eof) {
return -1;
}
this.err = false;
let code1, code2, code3;
if (this.nextLine2D) {
for (i = 0; codingLine[i] < columns; ++i) {
refLine[i] = codingLine[i];
}
refLine[i++] = columns;
refLine[i] = columns;
codingLine[0] = 0;
this.codingPos = 0;
refPos = 0;
blackPixels = 0;
while (codingLine[this.codingPos] < columns) {
code1 = this._getTwoDimCode();
switch (code1) {
case twoDimPass:
this._addPixels(refLine[refPos + 1], blackPixels);
if (refLine[refPos + 1] < columns) {
refPos += 2;
}
break;
case twoDimHoriz:
code1 = code2 = 0;
if (blackPixels) {
do {
code1 += code3 = this._getBlackCode();
} while (code3 >= 64);
do {
code2 += code3 = this._getWhiteCode();
} while (code3 >= 64);
} else {
do {
code1 += code3 = this._getWhiteCode();
} while (code3 >= 64);
do {
code2 += code3 = this._getBlackCode();
} while (code3 >= 64);
}
this._addPixels(codingLine[this.codingPos] + code1, blackPixels);
if (codingLine[this.codingPos] < columns) {
this._addPixels(codingLine[this.codingPos] + code2, blackPixels ^ 1);
}
while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
refPos += 2;
}
break;
case twoDimVertR3:
this._addPixels(refLine[refPos] + 3, blackPixels);
blackPixels ^= 1;
if (codingLine[this.codingPos] < columns) {
++refPos;
while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
refPos += 2;
}
}
break;
case twoDimVertR2:
this._addPixels(refLine[refPos] + 2, blackPixels);
blackPixels ^= 1;
if (codingLine[this.codingPos] < columns) {
++refPos;
while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
refPos += 2;
}
}
break;
case twoDimVertR1:
this._addPixels(refLine[refPos] + 1, blackPixels);
blackPixels ^= 1;
if (codingLine[this.codingPos] < columns) {
++refPos;
while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
refPos += 2;
}
}
break;
case twoDimVert0:
this._addPixels(refLine[refPos], blackPixels);
blackPixels ^= 1;
if (codingLine[this.codingPos] < columns) {
++refPos;
while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
refPos += 2;
}
}
break;
case twoDimVertL3:
this._addPixelsNeg(refLine[refPos] - 3, blackPixels);
blackPixels ^= 1;
if (codingLine[this.codingPos] < columns) {
if (refPos > 0) {
--refPos;
} else {
++refPos;
}
while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
refPos += 2;
}
}
break;
case twoDimVertL2:
this._addPixelsNeg(refLine[refPos] - 2, blackPixels);
blackPixels ^= 1;
if (codingLine[this.codingPos] < columns) {
if (refPos > 0) {
--refPos;
} else {
++refPos;
}
while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
refPos += 2;
}
}
break;
case twoDimVertL1:
this._addPixelsNeg(refLine[refPos] - 1, blackPixels);
blackPixels ^= 1;
if (codingLine[this.codingPos] < columns) {
if (refPos > 0) {
--refPos;
} else {
++refPos;
}
while (refLine[refPos] <= codingLine[this.codingPos] && refLine[refPos] < columns) {
refPos += 2;
}
}
break;
case ccittEOF:
this._addPixels(columns, 0);
this.eof = true;
break;
default:
info("bad 2d code");
this._addPixels(columns, 0);
this.err = true;
}
}
} else {
codingLine[0] = 0;
this.codingPos = 0;
blackPixels = 0;
while (codingLine[this.codingPos] < columns) {
code1 = 0;
if (blackPixels) {
do {
code1 += code3 = this._getBlackCode();
} while (code3 >= 64);
} else {
do {
code1 += code3 = this._getWhiteCode();
} while (code3 >= 64);
}
this._addPixels(codingLine[this.codingPos] + code1, blackPixels);
blackPixels ^= 1;
}
}
let gotEOL = false;
if (this.byteAlign) {
this.inputBits &= ~7;
}
if (!this.eoblock && this.row === this.rows - 1) {
this.rowsDone = true;
} else {
code1 = this._lookBits(12);
if (this.eoline) {
while (code1 !== ccittEOF && code1 !== 1) {
this._eatBits(1);
code1 = this._lookBits(12);
}
} else {
while (code1 === 0) {
this._eatBits(1);
code1 = this._lookBits(12);
}
}
if (code1 === 1) {
this._eatBits(12);
gotEOL = true;
} else if (code1 === ccittEOF) {
this.eof = true;
}
}
if (!this.eof && this.encoding > 0 && !this.rowsDone) {
this.nextLine2D = !this._lookBits(1);
this._eatBits(1);
}
if (this.eoblock && gotEOL && this.byteAlign) {
code1 = this._lookBits(12);
if (code1 === 1) {
this._eatBits(12);
if (this.encoding > 0) {
this._lookBits(1);
this._eatBits(1);
}
if (this.encoding >= 0) {
for (i = 0; i < 4; ++i) {
code1 = this._lookBits(12);
if (code1 !== 1) {
info("bad rtc code: " + code1);
}
this._eatBits(12);
if (this.encoding > 0) {
this._lookBits(1);
this._eatBits(1);
}
}
}
this.eof = true;
}
} else if (this.err && this.eoline) {
while (true) {
code1 = this._lookBits(13);
if (code1 === ccittEOF) {
this.eof = true;
return -1;
}
if (code1 >> 1 === 1) {
break;
}
this._eatBits(1);
}
this._eatBits(12);
if (this.encoding > 0) {
this._eatBits(1);
this.nextLine2D = !(code1 & 1);
}
}
this.outputBits = codingLine[0] > 0 ? codingLine[this.codingPos = 0] : codingLine[this.codingPos = 1];
this.row++;
}
let c;
if (this.outputBits >= 8) {
c = this.codingPos & 1 ? 0 : 0xff;
this.outputBits -= 8;
if (this.outputBits === 0 && codingLine[this.codingPos] < columns) {
this.codingPos++;
this.outputBits = codingLine[this.codingPos] - codingLine[this.codingPos - 1];
}
} else {
bits = 8;
c = 0;
do {
if (typeof this.outputBits !== "number") {
throw new FormatError('Invalid /CCITTFaxDecode data, "outputBits" must be a number.');
}
if (this.outputBits > bits) {
c <<= bits;
if (!(this.codingPos & 1)) {
c |= 0xff >> 8 - bits;
}
this.outputBits -= bits;
bits = 0;
} else {
c <<= this.outputBits;
if (!(this.codingPos & 1)) {
c |= 0xff >> 8 - this.outputBits;
}
bits -= this.outputBits;
this.outputBits = 0;
if (codingLine[this.codingPos] < columns) {
this.codingPos++;
this.outputBits = codingLine[this.codingPos] - codingLine[this.codingPos - 1];
} else if (bits > 0) {
c <<= bits;
bits = 0;
}
}
} while (bits);
}
if (this.black) {
c ^= 0xff;
}
return c;
}
_addPixels(a1, blackPixels) {
const codingLine = this.codingLine;
let codingPos = this.codingPos;
if (a1 > codingLine[codingPos]) {
if (a1 > this.columns) {
info("row is wrong length");
this.err = true;
a1 = this.columns;
}
if (codingPos & 1 ^ blackPixels) {
++codingPos;
}
codingLine[codingPos] = a1;
}
this.codingPos = codingPos;
}
_addPixelsNeg(a1, blackPixels) {
const codingLine = this.codingLine;
let codingPos = this.codingPos;
if (a1 > codingLine[codingPos]) {
if (a1 > this.columns) {
info("row is wrong length");
this.err = true;
a1 = this.columns;
}
if (codingPos & 1 ^ blackPixels) {
++codingPos;
}
codingLine[codingPos] = a1;
} else if (a1 < codingLine[codingPos]) {
if (a1 < 0) {
info("invalid code");
this.err = true;
a1 = 0;
}
while (codingPos > 0 && a1 < codingLine[codingPos - 1]) {
--codingPos;
}
codingLine[codingPos] = a1;
}
this.codingPos = codingPos;
}
_findTableCode(start, end, table, limit) {
const limitValue = limit || 0;
for (let i = start; i <= end; ++i) {
let code = this._lookBits(i);
if (code === ccittEOF) {
return [true, 1, false];
}
if (i < end) {
code <<= end - i;
}
if (!limitValue || code >= limitValue) {
const p = table[code - limitValue];
if (p[0] === i) {
this._eatBits(i);
return [true, p[1], true];
}
}
}
return [false, 0, false];
}
_getTwoDimCode() {
let code = 0;
let p;
if (this.eoblock) {
code = this._lookBits(7);
p = twoDimTable[code];
if (p?.[0] > 0) {
this._eatBits(p[0]);
return p[1];
}
} else {
const result = this._findTableCode(1, 7, twoDimTable);
if (result[0] && result[2]) {
return result[1];
}
}
info("Bad two dim code");
return ccittEOF;
}
_getWhiteCode() {
let code = 0;
let p;
if (this.eoblock) {
code = this._lookBits(12);
if (code === ccittEOF) {
return 1;
}
p = code >> 5 === 0 ? whiteTable1[code] : whiteTable2[code >> 3];
if (p[0] > 0) {
this._eatBits(p[0]);
return p[1];
}
} else {
let result = this._findTableCode(1, 9, whiteTable2);
if (result[0]) {
return result[1];
}
result = this._findTableCode(11, 12, whiteTable1);
if (result[0]) {
return result[1];
}
}
info("bad white code");
this._eatBits(1);
return 1;
}
_getBlackCode() {
let code, p;
if (this.eoblock) {
code = this._lookBits(13);
if (code === ccittEOF) {
return 1;
}
if (code >> 7 === 0) {
p = blackTable1[code];
} else if (code >> 9 === 0 && code >> 7 !== 0) {
p = blackTable2[(code >> 1) - 64];
} else {
p = blackTable3[code >> 7];
}
if (p[0] > 0) {
this._eatBits(p[0]);
return p[1];
}
} else {
let 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;
}
_lookBits(n) {
let c;
while (this.inputBits < n) {
if ((c = this.source.next()) === -1) {
if (this.inputBits === 0) {
return ccittEOF;
}
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;
}
_eatBits(n) {
if ((this.inputBits -= n) < 0) {
this.inputBits = 0;
}
}
}
;// ./src/core/ccitt_stream.js
class CCITTFaxStream extends DecodeStream {
constructor(str, maybeLength, params) {
super(maybeLength);
this.str = str;
this.dict = str.dict;
if (!(params instanceof Dict)) {
params = Dict.empty;
}
const source = {
next() {
return str.getByte();
}
};
this.ccittFaxDecoder = new CCITTFaxDecoder(source, {
K: params.get("K"),
EndOfLine: params.get("EndOfLine"),
EncodedByteAlign: params.get("EncodedByteAlign"),
Columns: params.get("Columns"),
Rows: params.get("Rows"),
EndOfBlock: params.get("EndOfBlock"),
BlackIs1: params.get("BlackIs1")
});
}
readBlock() {
while (!this.eof) {
const c = this.ccittFaxDecoder.readNextChar();
if (c === -1) {
this.eof = true;
return;
}
this.ensureBuffer(this.bufferLength + 1);
this.buffer[this.bufferLength++] = c;
}
}
}
;// ./src/core/flate_stream.js
const codeLenCodeMap = new Int32Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
const lengthDecode = new Int32Array([0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a, 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f, 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073, 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102]);
const distDecode = new Int32Array([0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d, 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1, 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01, 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001]);
const fixedLitCodeTab = [new Int32Array([0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0, 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0, 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0, 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0, 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8, 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8, 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8, 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4, 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4, 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4, 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc, 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec, 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc, 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2, 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2, 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2, 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca, 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea, 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da, 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6, 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6, 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6, 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce, 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee, 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de, 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe, 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1, 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1, 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1, 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1, 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9, 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9, 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9, 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5, 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5, 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5, 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd, 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed, 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd, 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3, 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3, 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3, 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb, 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb, 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db, 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7, 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7, 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7, 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf, 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef, 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df, 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff]), 9];
const fixedDistCodeTab = [new Int32Array([0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c, 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000, 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d, 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000]), 5];
class FlateStream extends DecodeStream {
constructor(str, maybeLength) {
super(maybeLength);
this.str = str;
this.dict = str.dict;
const cmf = str.getByte();
const flg = str.getByte();
if (cmf === -1 || flg === -1) {
throw new FormatError(`Invalid header in flate stream: ${cmf}, ${flg}`);
}
if ((cmf & 0x0f) !== 0x08) {
throw new FormatError(`Unknown compression method in flate stream: ${cmf}, ${flg}`);
}
if (((cmf << 8) + flg) % 31 !== 0) {
throw new FormatError(`Bad FCHECK in flate stream: ${cmf}, ${flg}`);
}
if (flg & 0x20) {
throw new FormatError(`FDICT bit set in flate stream: ${cmf}, ${flg}`);
}
this.codeSize = 0;
this.codeBuf = 0;
}
async getImageData(length, _decoderOptions) {
const data = await this.asyncGetBytes();
return data?.subarray(0, length) || this.getBytes(length);
}
async asyncGetBytes() {
this.str.reset();
const bytes = this.str.getBytes();
try {
const {
readable,
writable
} = new DecompressionStream("deflate");
const writer = writable.getWriter();
await writer.ready;
writer.write(bytes).then(async () => {
await writer.ready;
await writer.close();
}).catch(() => {});
const chunks = [];
let totalLength = 0;
for await (const chunk of readable) {
chunks.push(chunk);
totalLength += chunk.byteLength;
}
const data = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
data.set(chunk, offset);
offset += chunk.byteLength;
}
return data;
} catch {
this.str = new Stream(bytes, 2, bytes.length, this.str.dict);
this.reset();
return null;
}
}
get isAsync() {
return true;
}
getBits(bits) {
const str = this.str;
let codeSize = this.codeSize;
let codeBuf = this.codeBuf;
let b;
while (codeSize < bits) {
if ((b = str.getByte()) === -1) {
throw new FormatError("Bad encoding in flate stream");
}
codeBuf |= b << codeSize;
codeSize += 8;
}
b = codeBuf & (1 << bits) - 1;
this.codeBuf = codeBuf >> bits;
this.codeSize = codeSize -= bits;
return b;
}
getCode(table) {
const str = this.str;
const codes = table[0];
const maxLen = table[1];
let codeSize = this.codeSize;
let codeBuf = this.codeBuf;
let b;
while (codeSize < maxLen) {
if ((b = str.getByte()) === -1) {
break;
}
codeBuf |= b << codeSize;
codeSize += 8;
}
const code = codes[codeBuf & (1 << maxLen) - 1];
const codeLen = code >> 16;
const codeVal = code & 0xffff;
if (codeLen < 1 || codeSize < codeLen) {
throw new FormatError("Bad encoding in flate stream");
}
this.codeBuf = codeBuf >> codeLen;
this.codeSize = codeSize - codeLen;
return codeVal;
}
generateHuffmanTable(lengths) {
const n = lengths.length;
let maxLen = 0;
let i;
for (i = 0; i < n; ++i) {
if (lengths[i] > maxLen) {
maxLen = lengths[i];
}
}
const size = 1 << maxLen;
const codes = new Int32Array(size);
for (let len = 1, code = 0, skip = 2; len <= maxLen; ++len, code <<= 1, skip <<= 1) {
for (let val = 0; val < n; ++val) {
if (lengths[val] === len) {
let code2 = 0;
let t = code;
for (i = 0; i < len; ++i) {
code2 = code2 << 1 | t & 1;
t >>= 1;
}
for (i = code2; i < size; i += skip) {
codes[i] = len << 16 | val;
}
++code;
}
}
}
return [codes, maxLen];
}
#endsStreamOnError(err) {
info(err);
this.eof = true;
}
readBlock() {
let buffer, hdr, len;
const str = this.str;
try {
hdr = this.getBits(3);
} catch (ex) {
this.#endsStreamOnError(ex.message);
return;
}
if (hdr & 1) {
this.eof = true;
}
hdr >>= 1;
if (hdr === 0) {
let b;
if ((b = str.getByte()) === -1) {
this.#endsStreamOnError("Bad block header in flate stream");
return;
}
let blockLen = b;
if ((b = str.getByte()) === -1) {
this.#endsStreamOnError("Bad block header in flate stream");
return;
}
blockLen |= b << 8;
if ((b = str.getByte()) === -1) {
this.#endsStreamOnError("Bad block header in flate stream");
return;
}
let check = b;
if ((b = str.getByte()) === -1) {
this.#endsStreamOnError("Bad block header in flate stream");
return;
}
check |= b << 8;
if (check !== (~blockLen & 0xffff) && (blockLen !== 0 || check !== 0)) {
throw new FormatError("Bad uncompressed block length in flate stream");
}
this.codeBuf = 0;
this.codeSize = 0;
const bufferLength = this.bufferLength,
end = bufferLength + blockLen;
buffer = this.ensureBuffer(end);
this.bufferLength = end;
if (blockLen === 0) {
if (str.peekByte() === -1) {
this.eof = true;
}
} else {
const block = str.getBytes(blockLen);
buffer.set(block, bufferLength);
if (block.length < blockLen) {
this.eof = true;
}
}
return;
}
let litCodeTable;
let distCodeTable;
if (hdr === 1) {
litCodeTable = fixedLitCodeTab;
distCodeTable = fixedDistCodeTab;
} else if (hdr === 2) {
const numLitCodes = this.getBits(5) + 257;
const numDistCodes = this.getBits(5) + 1;
const numCodeLenCodes = this.getBits(4) + 4;
const codeLenCodeLengths = new Uint8Array(codeLenCodeMap.length);
let i;
for (i = 0; i < numCodeLenCodes; ++i) {
codeLenCodeLengths[codeLenCodeMap[i]] = this.getBits(3);
}
const codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths);
len = 0;
i = 0;
const codes = numLitCodes + numDistCodes;
const codeLengths = new Uint8Array(codes);
let bitsLength, bitsOffset, what;
while (i < codes) {
const code = this.getCode(codeLenCodeTab);
if (code === 16) {
bitsLength = 2;
bitsOffset = 3;
what = len;
} else if (code === 17) {
bitsLength = 3;
bitsOffset = 3;
what = len = 0;
} else if (code === 18) {
bitsLength = 7;
bitsOffset = 11;
what = len = 0;
} else {
codeLengths[i++] = len = code;
continue;
}
let repeatLength = this.getBits(bitsLength) + bitsOffset;
while (repeatLength-- > 0) {
codeLengths[i++] = what;
}
}
litCodeTable = this.generateHuffmanTable(codeLengths.subarray(0, numLitCodes));
distCodeTable = this.generateHuffmanTable(codeLengths.subarray(numLitCodes, codes));
} else {
throw new FormatError("Unknown block type in flate stream");
}
buffer = this.buffer;
let limit = buffer ? buffer.length : 0;
let pos = this.bufferLength;
while (true) {
let code1 = this.getCode(litCodeTable);
if (code1 < 256) {
if (pos + 1 >= limit) {
buffer = this.ensureBuffer(pos + 1);
limit = buffer.length;
}
buffer[pos++] = code1;
continue;
}
if (code1 === 256) {
this.bufferLength = pos;
return;
}
code1 -= 257;
code1 = lengthDecode[code1];
let code2 = code1 >> 16;
if (code2 > 0) {
code2 = this.getBits(code2);
}
len = (code1 & 0xffff) + code2;
code1 = this.getCode(distCodeTable);
code1 = distDecode[code1];
code2 = code1 >> 16;
if (code2 > 0) {
code2 = this.getBits(code2);
}
const dist = (code1 & 0xffff) + code2;
if (pos + len >= limit) {
buffer = this.ensureBuffer(pos + len);
limit = buffer.length;
}
for (let k = 0; k < len; ++k, ++pos) {
buffer[pos] = buffer[pos - dist];
}
}
}
}
;// ./src/core/arithmetic_decoder.js
const QeTable = [{
qe: 0x5601,
nmps: 1,
nlps: 1,
switchFlag: 1
}, {
qe: 0x3401,
nmps: 2,
nlps: 6,
switchFlag: 0
}, {
qe: 0x1801,
nmps: 3,
nlps: 9,
switchFlag: 0
}, {
qe: 0x0ac1,
nmps: 4,
nlps: 12,
switchFlag: 0
}, {
qe: 0x0521,
nmps: 5,
nlps: 29,
switchFlag: 0
}, {
qe: 0x0221,
nmps: 38,
nlps: 33,
switchFlag: 0
}, {
qe: 0x5601,
nmps: 7,
nlps: 6,
switchFlag: 1
}, {
qe: 0x5401,
nmps: 8,
nlps: 14,
switchFlag: 0
}, {
qe: 0x4801,
nmps: 9,
nlps: 14,
switchFlag: 0
}, {
qe: 0x3801,
nmps: 10,
nlps: 14,
switchFlag: 0
}, {
qe: 0x3001,
nmps: 11,
nlps: 17,
switchFlag: 0
}, {
qe: 0x2401,
nmps: 12,
nlps: 18,
switchFlag: 0
}, {
qe: 0x1c01,
nmps: 13,
nlps: 20,
switchFlag: 0
}, {
qe: 0x1601,
nmps: 29,
nlps: 21,
switchFlag: 0
}, {
qe: 0x5601,
nmps: 15,
nlps: 14,
switchFlag: 1
}, {
qe: 0x5401,
nmps: 16,
nlps: 14,
switchFlag: 0
}, {
qe: 0x5101,
nmps: 17,
nlps: 15,
switchFlag: 0
}, {
qe: 0x4801,
nmps: 18,
nlps: 16,
switchFlag: 0
}, {
qe: 0x3801,
nmps: 19,
nlps: 17,
switchFlag: 0
}, {
qe: 0x3401,
nmps: 20,
nlps: 18,
switchFlag: 0
}, {
qe: 0x3001,
nmps: 21,
nlps: 19,
switchFlag: 0
}, {
qe: 0x2801,
nmps: 22,
nlps: 19,
switchFlag: 0
}, {
qe: 0x2401,
nmps: 23,
nlps: 20,
switchFlag: 0
}, {
qe: 0x2201,
nmps: 24,
nlps: 21,
switchFlag: 0
}, {
qe: 0x1c01,
nmps: 25,
nlps: 22,
switchFlag: 0
}, {
qe: 0x1801,
nmps: 26,
nlps: 23,
switchFlag: 0
}, {
qe: 0x1601,
nmps: 27,
nlps: 24,
switchFlag: 0
}, {
qe: 0x1401,
nmps: 28,
nlps: 25,
switchFlag: 0
}, {
qe: 0x1201,
nmps: 29,
nlps: 26,
switchFlag: 0
}, {
qe: 0x1101,
nmps: 30,
nlps: 27,
switchFlag: 0
}, {
qe: 0x0ac1,
nmps: 31,
nlps: 28,
switchFlag: 0
}, {
qe: 0x09c1,
nmps: 32,
nlps: 29,
switchFlag: 0
}, {
qe: 0x08a1,
nmps: 33,
nlps: 30,
switchFlag: 0
}, {
qe: 0x0521,
nmps: 34,
nlps: 31,
switchFlag: 0
}, {
qe: 0x0441,
nmps: 35,
nlps: 32,
switchFlag: 0
}, {
qe: 0x02a1,
nmps: 36,
nlps: 33,
switchFlag: 0
}, {
qe: 0x0221,
nmps: 37,
nlps: 34,
switchFlag: 0
}, {
qe: 0x0141,
nmps: 38,
nlps: 35,
switchFlag: 0
}, {
qe: 0x0111,
nmps: 39,
nlps: 36,
switchFlag: 0
}, {
qe: 0x0085,
nmps: 40,
nlps: 37,
switchFlag: 0
}, {
qe: 0x0049,
nmps: 41,
nlps: 38,
switchFlag: 0
}, {
qe: 0x0025,
nmps: 42,
nlps: 39,
switchFlag: 0
}, {
qe: 0x0015,
nmps: 43,
nlps: 40,
switchFlag: 0
}, {
qe: 0x0009,
nmps: 44,
nlps: 41,
switchFlag: 0
}, {
qe: 0x0005,
nmps: 45,
nlps: 42,
switchFlag: 0
}, {
qe: 0x0001,
nmps: 45,
nlps: 43,
switchFlag: 0
}, {
qe: 0x5601,
nmps: 46,
nlps: 46,
switchFlag: 0
}];
class ArithmeticDecoder {
constructor(data, start, end) {
this.data = data;
this.bp = start;
this.dataEnd = end;
this.chigh = data[start];
this.clow = 0;
this.byteIn();
this.chigh = this.chigh << 7 & 0xffff | this.clow >> 9 & 0x7f;
this.clow = this.clow << 7 & 0xffff;
this.ct -= 7;
this.a = 0x8000;
}
byteIn() {
const data = this.data;
let bp = this.bp;
if (data[bp] === 0xff) {
if (data[bp + 1] > 0x8f) {
this.clow += 0xff00;
this.ct = 8;
} else {
bp++;
this.clow += data[bp] << 9;
this.ct = 7;
this.bp = bp;
}
} else {
bp++;
this.clow += bp < this.dataEnd ? data[bp] << 8 : 0xff00;
this.ct = 8;
this.bp = bp;
}
if (this.clow > 0xffff) {
this.chigh += this.clow >> 16;
this.clow &= 0xffff;
}
}
readBit(contexts, pos) {
let cx_index = contexts[pos] >> 1,
cx_mps = contexts[pos] & 1;
const qeTableIcx = QeTable[cx_index];
const qeIcx = qeTableIcx.qe;
let d;
let a = this.a - qeIcx;
if (this.chigh < qeIcx) {
if (a < qeIcx) {
a = qeIcx;
d = cx_mps;
cx_index = qeTableIcx.nmps;
} else {
a = qeIcx;
d = 1 ^ cx_mps;
if (qeTableIcx.switchFlag === 1) {
cx_mps = d;
}
cx_index = qeTableIcx.nlps;
}
} else {
this.chigh -= qeIcx;
if ((a & 0x8000) !== 0) {
this.a = a;
return cx_mps;
}
if (a < qeIcx) {
d = 1 ^ cx_mps;
if (qeTableIcx.switchFlag === 1) {
cx_mps = d;
}
cx_index = qeTableIcx.nlps;
} else {
d = cx_mps;
cx_index = qeTableIcx.nmps;
}
}
do {
if (this.ct === 0) {
this.byteIn();
}
a <<= 1;
this.chigh = this.chigh << 1 & 0xffff | this.clow >> 15 & 1;
this.clow = this.clow << 1 & 0xffff;
this.ct--;
} while ((a & 0x8000) === 0);
this.a = a;
contexts[pos] = cx_index << 1 | cx_mps;
return d;
}
}
;// ./src/core/jbig2.js
class Jbig2Error extends BaseException {
constructor(msg) {
super(msg, "Jbig2Error");
}
}
class ContextCache {
getContexts(id) {
if (id in this) {
return this[id];
}
return this[id] = new Int8Array(1 << 16);
}
}
class DecodingContext {
constructor(data, start, end) {
this.data = data;
this.start = start;
this.end = end;
}
get decoder() {
const decoder = new ArithmeticDecoder(this.data, this.start, this.end);
return shadow(this, "decoder", decoder);
}
get contextCache() {
const cache = new ContextCache();
return shadow(this, "contextCache", cache);
}
}
function decodeInteger(contextCache, procedure, decoder) {
const contexts = contextCache.getContexts(procedure);
let prev = 1;
function readBits(length) {
let v = 0;
for (let i = 0; i < length; i++) {
const bit = decoder.readBit(contexts, prev);
prev = prev < 256 ? prev << 1 | bit : (prev << 1 | bit) & 511 | 256;
v = v << 1 | bit;
}
return v >>> 0;
}
const sign = readBits(1);
const value = readBits(1) ? readBits(1) ? readBits(1) ? readBits(1) ? readBits(1) ? readBits(32) + 4436 : readBits(12) + 340 : readBits(8) + 84 : readBits(6) + 20 : readBits(4) + 4 : readBits(2);
let signedValue;
if (sign === 0) {
signedValue = value;
} else if (value > 0) {
signedValue = -value;
}
if (signedValue >= MIN_INT_32 && signedValue <= MAX_INT_32) {
return signedValue;
}
return null;
}
function decodeIAID(contextCache, decoder, codeLength) {
const contexts = contextCache.getContexts("IAID");
let prev = 1;
for (let i = 0; i < codeLength; i++) {
const bit = decoder.readBit(contexts, prev);
prev = prev << 1 | bit;
}
if (codeLength < 31) {
return prev & (1 << codeLength) - 1;
}
return prev & 0x7fffffff;
}
const SegmentTypes = ["SymbolDictionary", null, null, null, "IntermediateTextRegion", null, "ImmediateTextRegion", "ImmediateLosslessTextRegion", null, null, null, null, null, null, null, null, "PatternDictionary", null, null, null, "IntermediateHalftoneRegion", null, "ImmediateHalftoneRegion", "ImmediateLosslessHalftoneRegion", null, null, null, null, null, null, null, null, null, null, null, null, "IntermediateGenericRegion", null, "ImmediateGenericRegion", "ImmediateLosslessGenericRegion", "IntermediateGenericRefinementRegion", null, "ImmediateGenericRefinementRegion", "ImmediateLosslessGenericRefinementRegion", null, null, null, null, "PageInformation", "EndOfPage", "EndOfStripe", "EndOfFile", "Profiles", "Tables", null, null, null, null, null, null, null, null, "Extension"];
const CodingTemplates = [[{
x: -1,
y: -2
}, {
x: 0,
y: -2
}, {
x: 1,
y: -2
}, {
x: -2,
y: -1
}, {
x: -1,
y: -1
}, {
x: 0,
y: -1
}, {
x: 1,
y: -1
}, {
x: 2,
y: -1
}, {
x: -4,
y: 0
}, {
x: -3,
y: 0
}, {
x: -2,
y: 0
}, {
x: -1,
y: 0
}], [{
x: -1,
y: -2
}, {
x: 0,
y: -2
}, {
x: 1,
y: -2
}, {
x: 2,
y: -2
}, {
x: -2,
y: -1
}, {
x: -1,
y: -1
}, {
x: 0,
y: -1
}, {
x: 1,
y: -1
}, {
x: 2,
y: -1
}, {
x: -3,
y: 0
}, {
x: -2,
y: 0
}, {
x: -1,
y: 0
}], [{
x: -1,
y: -2
}, {
x: 0,
y: -2
}, {
x: 1,
y: -2
}, {
x: -2,
y: -1
}, {
x: -1,
y: -1
}, {
x: 0,
y: -1
}, {
x: 1,
y: -1
}, {
x: -2,
y: 0
}, {
x: -1,
y: 0
}], [{
x: -3,
y: -1
}, {
x: -2,
y: -1
}, {
x: -1,
y: -1
}, {
x: 0,
y: -1
}, {
x: 1,
y: -1
}, {
x: -4,
y: 0
}, {
x: -3,
y: 0
}, {
x: -2,
y: 0
}, {
x: -1,
y: 0
}]];
const RefinementTemplates = [{
coding: [{
x: 0,
y: -1
}, {
x: 1,
y: -1
}, {
x: -1,
y: 0
}],
reference: [{
x: 0,
y: -1
}, {
x: 1,
y: -1
}, {
x: -1,
y: 0
}, {
x: 0,
y: 0
}, {
x: 1,
y: 0
}, {
x: -1,
y: 1
}, {
x: 0,
y: 1
}, {
x: 1,
y: 1
}]
}, {
coding: [{
x: -1,
y: -1
}, {
x: 0,
y: -1
}, {
x: 1,
y: -1
}, {
x: -1,
y: 0
}],
reference: [{
x: 0,
y: -1
}, {
x: -1,
y: 0
}, {
x: 0,
y: 0
}, {
x: 1,
y: 0
}, {
x: 0,
y: 1
}, {
x: 1,
y: 1
}]
}];
const ReusedContexts = [0x9b25, 0x0795, 0x00e5, 0x0195];
const RefinementReusedContexts = [0x0020, 0x0008];
function decodeBitmapTemplate0(width, height, decodingContext) {
const decoder = decodingContext.decoder;
const contexts = decodingContext.contextCache.getContexts("GB");
const bitmap = [];
let contextLabel, i, j, pixel, row, row1, row2;
const OLD_PIXEL_MASK = 0x7bf7;
for (i = 0; i < height; i++) {
row = bitmap[i] = new Uint8Array(width);
row1 = i < 1 ? row : bitmap[i - 1];
row2 = i < 2 ? row : bitmap[i - 2];
contextLabel = row2[0] << 13 | row2[1] << 12 | row2[2] << 11 | row1[0] << 7 | row1[1] << 6 | row1[2] << 5 | row1[3] << 4;
for (j = 0; j < width; j++) {
row[j] = pixel = decoder.readBit(contexts, contextLabel);
contextLabel = (contextLabel & OLD_PIXEL_MASK) << 1 | (j + 3 < width ? row2[j + 3] << 11 : 0) | (j + 4 < width ? row1[j + 4] << 4 : 0) | pixel;
}
}
return bitmap;
}
function decodeBitmap(mmr, width, height, templateIndex, prediction, skip, at, decodingContext) {
if (mmr) {
const input = new Reader(decodingContext.data, decodingContext.start, decodingContext.end);
return decodeMMRBitmap(input, width, height, false);
}
if (templateIndex === 0 && !skip && !prediction && at.length === 4 && at[0].x === 3 && at[0].y === -1 && at[1].x === -3 && at[1].y === -1 && at[2].x === 2 && at[2].y === -2 && at[3].x === -2 && at[3].y === -2) {
return decodeBitmapTemplate0(width, height, decodingContext);
}
const useskip = !!skip;
const template = CodingTemplates[templateIndex].concat(at);
template.sort(function (a, b) {
return a.y - b.y || a.x - b.x;
});
const templateLength = template.length;
const templateX = new Int8Array(templateLength);
const templateY = new Int8Array(templateLength);
const changingTemplateEntries = [];
let reuseMask = 0,
minX = 0,
maxX = 0,
minY = 0;
let c, k;
for (k = 0; k < templateLength; k++) {
templateX[k] = template[k].x;
templateY[k] = template[k].y;
minX = Math.min(minX, template[k].x);
maxX = Math.max(maxX, template[k].x);
minY = Math.min(minY, template[k].y);
if (k < templateLength - 1 && template[k].y === template[k + 1].y && template[k].x === template[k + 1].x - 1) {
reuseMask |= 1 << templateLength - 1 - k;
} else {
changingTemplateEntries.push(k);
}
}
const changingEntriesLength = changingTemplateEntries.length;
const changingTemplateX = new Int8Array(changingEntriesLength);
const changingTemplateY = new Int8Array(changingEntriesLength);
const changingTemplateBit = new Uint16Array(changingEntriesLength);
for (c = 0; c < changingEntriesLength; c++) {
k = changingTemplateEntries[c];
changingTemplateX[c] = template[k].x;
changingTemplateY[c] = template[k].y;
changingTemplateBit[c] = 1 << templateLength - 1 - k;
}
const sbb_left = -minX;
const sbb_top = -minY;
const sbb_right = width - maxX;
const pseudoPixelContext = ReusedContexts[templateIndex];
let row = new Uint8Array(width);
const bitmap = [];
const decoder = decodingContext.decoder;
const contexts = decodingContext.contextCache.getContexts("GB");
let ltp = 0,
j,
i0,
j0,
contextLabel = 0,
bit,
shift;
for (let i = 0; i < height; i++) {
if (prediction) {
const sltp = decoder.readBit(contexts, pseudoPixelContext);
ltp ^= sltp;
if (ltp) {
bitmap.push(row);
continue;
}
}
row = new Uint8Array(row);
bitmap.push(row);
for (j = 0; j < width; j++) {
if (useskip && skip[i][j]) {
row[j] = 0;
continue;
}
if (j >= sbb_left && j < sbb_right && i >= sbb_top) {
contextLabel = contextLabel << 1 & reuseMask;
for (k = 0; k < changingEntriesLength; k++) {
i0 = i + changingTemplateY[k];
j0 = j + changingTemplateX[k];
bit = bitmap[i0][j0];
if (bit) {
bit = changingTemplateBit[k];
contextLabel |= bit;
}
}
} else {
contextLabel = 0;
shift = templateLength - 1;
for (k = 0; k < templateLength; k++, shift--) {
j0 = j + templateX[k];
if (j0 >= 0 && j0 < width) {
i0 = i + templateY[k];
if (i0 >= 0) {
bit = bitmap[i0][j0];
if (bit) {
contextLabel |= bit << shift;
}
}
}
}
}
const pixel = decoder.readBit(contexts, contextLabel);
row[j] = pixel;
}
}
return bitmap;
}
function decodeRefinement(width, height, templateIndex, referenceBitmap, offsetX, offsetY, prediction, at, decodingContext) {
let codingTemplate = RefinementTemplates[templateIndex].coding;
if (templateIndex === 0) {
codingTemplate = codingTemplate.concat([at[0]]);
}
const codingTemplateLength = codingTemplate.length;
const codingTemplateX = new Int32Array(codingTemplateLength);
const codingTemplateY = new Int32Array(codingTemplateLength);
let k;
for (k = 0; k < codingTemplateLength; k++) {
codingTemplateX[k] = codingTemplate[k].x;
codingTemplateY[k] = codingTemplate[k].y;
}
let referenceTemplate = RefinementTemplates[templateIndex].reference;
if (templateIndex === 0) {
referenceTemplate = referenceTemplate.concat([at[1]]);
}
const referenceTemplateLength = referenceTemplate.length;
const referenceTemplateX = new Int32Array(referenceTemplateLength);
const referenceTemplateY = new Int32Array(referenceTemplateLength);
for (k = 0; k < referenceTemplateLength; k++) {
referenceTemplateX[k] = referenceTemplate[k].x;
referenceTemplateY[k] = referenceTemplate[k].y;
}
const referenceWidth = referenceBitmap[0].length;
const referenceHeight = referenceBitmap.length;
const pseudoPixelContext = RefinementReusedContexts[templateIndex];
const bitmap = [];
const decoder = decodingContext.decoder;
const contexts = decodingContext.contextCache.getContexts("GR");
let ltp = 0;
for (let i = 0; i < height; i++) {
if (prediction) {
const sltp = decoder.readBit(contexts, pseudoPixelContext);
ltp ^= sltp;
if (ltp) {
throw new Jbig2Error("prediction is not supported");
}
}
const row = new Uint8Array(width);
bitmap.push(row);
for (let j = 0; j < width; j++) {
let i0, j0;
let contextLabel = 0;
for (k = 0; k < codingTemplateLength; k++) {
i0 = i + codingTemplateY[k];
j0 = j + codingTemplateX[k];
if (i0 < 0 || j0 < 0 || j0 >= width) {
contextLabel <<= 1;
} else {
contextLabel = contextLabel << 1 | bitmap[i0][j0];
}
}
for (k = 0; k < referenceTemplateLength; k++) {
i0 = i + referenceTemplateY[k] - offsetY;
j0 = j + referenceTemplateX[k] - offsetX;
if (i0 < 0 || i0 >= referenceHeight || j0 < 0 || j0 >= referenceWidth) {
contextLabel <<= 1;
} else {
contextLabel = contextLabel << 1 | referenceBitmap[i0][j0];
}
}
const pixel = decoder.readBit(contexts, contextLabel);
row[j] = pixel;
}
}
return bitmap;
}
function decodeSymbolDictionary(huffman, refinement, symbols, numberOfNewSymbols, numberOfExportedSymbols, huffmanTables, templateIndex, at, refinementTemplateIndex, refinementAt, decodingContext, huffmanInput) {
if (huffman && refinement) {
throw new Jbig2Error("symbol refinement with Huffman is not supported");
}
const newSymbols = [];
let currentHeight = 0;
let symbolCodeLength = log2(symbols.length + numberOfNewSymbols);
const decoder = decodingContext.decoder;
const contextCache = decodingContext.contextCache;
let tableB1, symbolWidths;
if (huffman) {
tableB1 = getStandardTable(1);
symbolWidths = [];
symbolCodeLength = Math.max(symbolCodeLength, 1);
}
while (newSymbols.length < numberOfNewSymbols) {
const deltaHeight = huffman ? huffmanTables.tableDeltaHeight.decode(huffmanInput) : decodeInteger(contextCache, "IADH", decoder);
currentHeight += deltaHeight;
let currentWidth = 0,
totalWidth = 0;
const firstSymbol = huffman ? symbolWidths.length : 0;
while (true) {
const deltaWidth = huffman ? huffmanTables.tableDeltaWidth.decode(huffmanInput) : decodeInteger(contextCache, "IADW", decoder);
if (deltaWidth === null) {
break;
}
currentWidth += deltaWidth;
totalWidth += currentWidth;
let bitmap;
if (refinement) {
const numberOfInstances = decodeInteger(contextCache, "IAAI", decoder);
if (numberOfInstances > 1) {
bitmap = decodeTextRegion(huffman, refinement, currentWidth, currentHeight, 0, numberOfInstances, 1, symbols.concat(newSymbols), symbolCodeLength, 0, 0, 1, 0, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext, 0, huffmanInput);
} else {
const symbolId = decodeIAID(contextCache, decoder, symbolCodeLength);
const rdx = decodeInteger(contextCache, "IARDX", decoder);
const rdy = decodeInteger(contextCache, "IARDY", decoder);
const symbol = symbolId < symbols.length ? symbols[symbolId] : newSymbols[symbolId - symbols.length];
bitmap = decodeRefinement(currentWidth, currentHeight, refinementTemplateIndex, symbol, rdx, rdy, false, refinementAt, decodingContext);
}
newSymbols.push(bitmap);
} else if (huffman) {
symbolWidths.push(currentWidth);
} else {
bitmap = decodeBitmap(false, currentWidth, currentHeight, templateIndex, false, null, at, decodingContext);
newSymbols.push(bitmap);
}
}
if (huffman && !refinement) {
const bitmapSize = huffmanTables.tableBitmapSize.decode(huffmanInput);
huffmanInput.byteAlign();
let collectiveBitmap;
if (bitmapSize === 0) {
collectiveBitmap = readUncompressedBitmap(huffmanInput, totalWidth, currentHeight);
} else {
const originalEnd = huffmanInput.end;
const bitmapEnd = huffmanInput.position + bitmapSize;
huffmanInput.end = bitmapEnd;
collectiveBitmap = decodeMMRBitmap(huffmanInput, totalWidth, currentHeight, false);
huffmanInput.end = originalEnd;
huffmanInput.position = bitmapEnd;
}
const numberOfSymbolsDecoded = symbolWidths.length;
if (firstSymbol === numberOfSymbolsDecoded - 1) {
newSymbols.push(collectiveBitmap);
} else {
let i,
y,
xMin = 0,
xMax,
bitmapWidth,
symbolBitmap;
for (i = firstSymbol; i < numberOfSymbolsDecoded; i++) {
bitmapWidth = symbolWidths[i];
xMax = xMin + bitmapWidth;
symbolBitmap = [];
for (y = 0; y < currentHeight; y++) {
symbolBitmap.push(collectiveBitmap[y].subarray(xMin, xMax));
}
newSymbols.push(symbolBitmap);
xMin = xMax;
}
}
}
}
const exportedSymbols = [],
flags = [];
let currentFlag = false,
i,
ii;
const totalSymbolsLength = symbols.length + numberOfNewSymbols;
while (flags.length < totalSymbolsLength) {
let runLength = huffman ? tableB1.decode(huffmanInput) : decodeInteger(contextCache, "IAEX", decoder);
while (runLength--) {
flags.push(currentFlag);
}
currentFlag = !currentFlag;
}
for (i = 0, ii = symbols.length; i < ii; i++) {
if (flags[i]) {
exportedSymbols.push(symbols[i]);
}
}
for (let j = 0; j < numberOfNewSymbols; i++, j++) {
if (flags[i]) {
exportedSymbols.push(newSymbols[j]);
}
}
return exportedSymbols;
}
function decodeTextRegion(huffman, refinement, width, height, defaultPixelValue, numberOfSymbolInstances, stripSize, inputSymbols, symbolCodeLength, transposed, dsOffset, referenceCorner, combinationOperator, huffmanTables, refinementTemplateIndex, refinementAt, decodingContext, logStripSize, huffmanInput) {
if (huffman && refinement) {
throw new Jbig2Error("refinement with Huffman is not supported");
}
const bitmap = [];
let i, row;
for (i = 0; i < height; i++) {
row = new Uint8Array(width);
if (defaultPixelValue) {
for (let j = 0; j < width; j++) {
row[j] = defaultPixelValue;
}
}
bitmap.push(row);
}
const decoder = decodingContext.decoder;
const contextCache = decodingContext.contextCache;
let stripT = huffman ? -huffmanTables.tableDeltaT.decode(huffmanInput) : -decodeInteger(contextCache, "IADT", decoder);
let firstS = 0;
i = 0;
while (i < numberOfSymbolInstances) {
const deltaT = huffman ? huffmanTables.tableDeltaT.decode(huffmanInput) : decodeInteger(contextCache, "IADT", decoder);
stripT += deltaT;
const deltaFirstS = huffman ? huffmanTables.tableFirstS.decode(huffmanInput) : decodeInteger(contextCache, "IAFS", decoder);
firstS += deltaFirstS;
let currentS = firstS;
do {
let currentT = 0;
if (stripSize > 1) {
currentT = huffman ? huffmanInput.readBits(logStripSize) : decodeInteger(contextCache, "IAIT", decoder);
}
const t = stripSize * stripT + currentT;
const symbolId = huffman ? huffmanTables.symbolIDTable.decode(huffmanInput) : decodeIAID(contextCache, decoder, symbolCodeLength);
const applyRefinement = refinement && (huffman ? huffmanInput.readBit() : decodeInteger(contextCache, "IARI", decoder));
let symbolBitmap = inputSymbols[symbolId];
let symbolWidth = symbolBitmap[0].length;
let symbolHeight = symbolBitmap.length;
if (applyRefinement) {
const rdw = decodeInteger(contextCache, "IARDW", decoder);
const rdh = decodeInteger(contextCache, "IARDH", decoder);
const rdx = decodeInteger(contextCache, "IARDX", decoder);
const rdy = decodeInteger(contextCache, "IARDY", decoder);
symbolWidth += rdw;
symbolHeight += rdh;
symbolBitmap = decodeRefinement(symbolWidth, symbolHeight, refinementTemplateIndex, symbolBitmap, (rdw >> 1) + rdx, (rdh >> 1) + rdy, false, refinementAt, decodingContext);
}
let increment = 0;
if (!transposed) {
if (referenceCorner > 1) {
currentS += symbolWidth - 1;
} else {
increment = symbolWidth - 1;
}
} else if (!(referenceCorner & 1)) {
currentS += symbolHeight - 1;
} else {
increment = symbolHeight - 1;
}
const offsetT = t - (referenceCorner & 1 ? 0 : symbolHeight - 1);
const offsetS = currentS - (referenceCorner & 2 ? symbolWidth - 1 : 0);
let s2, t2, symbolRow;
if (transposed) {
for (s2 = 0; s2 < symbolHeight; s2++) {
row = bitmap[offsetS + s2];
if (!row) {
continue;
}
symbolRow = symbolBitmap[s2];
const maxWidth = Math.min(width - offsetT, symbolWidth);
switch (combinationOperator) {
case 0:
for (t2 = 0; t2 < maxWidth; t2++) {
row[offsetT + t2] |= symbolRow[t2];
}
break;
case 2:
for (t2 = 0; t2 < maxWidth; t2++) {
row[offsetT + t2] ^= symbolRow[t2];
}
break;
default:
throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
}
}
} else {
for (t2 = 0; t2 < symbolHeight; t2++) {
row = bitmap[offsetT + t2];
if (!row) {
continue;
}
symbolRow = symbolBitmap[t2];
switch (combinationOperator) {
case 0:
for (s2 = 0; s2 < symbolWidth; s2++) {
row[offsetS + s2] |= symbolRow[s2];
}
break;
case 2:
for (s2 = 0; s2 < symbolWidth; s2++) {
row[offsetS + s2] ^= symbolRow[s2];
}
break;
default:
throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
}
}
}
i++;
const deltaS = huffman ? huffmanTables.tableDeltaS.decode(huffmanInput) : decodeInteger(contextCache, "IADS", decoder);
if (deltaS === null) {
break;
}
currentS += increment + deltaS + dsOffset;
} while (true);
}
return bitmap;
}
function decodePatternDictionary(mmr, patternWidth, patternHeight, maxPatternIndex, template, decodingContext) {
const at = [];
if (!mmr) {
at.push({
x: -patternWidth,
y: 0
});
if (template === 0) {
at.push({
x: -3,
y: -1
}, {
x: 2,
y: -2
}, {
x: -2,
y: -2
});
}
}
const collectiveWidth = (maxPatternIndex + 1) * patternWidth;
const collectiveBitmap = decodeBitmap(mmr, collectiveWidth, patternHeight, template, false, null, at, decodingContext);
const patterns = [];
for (let i = 0; i <= maxPatternIndex; i++) {
const patternBitmap = [];
const xMin = patternWidth * i;
const xMax = xMin + patternWidth;
for (let y = 0; y < patternHeight; y++) {
patternBitmap.push(collectiveBitmap[y].subarray(xMin, xMax));
}
patterns.push(patternBitmap);
}
return patterns;
}
function decodeHalftoneRegion(mmr, patterns, template, regionWidth, regionHeight, defaultPixelValue, enableSkip, combinationOperator, gridWidth, gridHeight, gridOffsetX, gridOffsetY, gridVectorX, gridVectorY, decodingContext) {
const skip = null;
if (enableSkip) {
throw new Jbig2Error("skip is not supported");
}
if (combinationOperator !== 0) {
throw new Jbig2Error(`operator "${combinationOperator}" is not supported in halftone region`);
}
const regionBitmap = [];
let i, j, row;
for (i = 0; i < regionHeight; i++) {
row = new Uint8Array(regionWidth);
if (defaultPixelValue) {
for (j = 0; j < regionWidth; j++) {
row[j] = defaultPixelValue;
}
}
regionBitmap.push(row);
}
const numberOfPatterns = patterns.length;
const pattern0 = patterns[0];
const patternWidth = pattern0[0].length,
patternHeight = pattern0.length;
const bitsPerValue = log2(numberOfPatterns);
const at = [];
if (!mmr) {
at.push({
x: template <= 1 ? 3 : 2,
y: -1
});
if (template === 0) {
at.push({
x: -3,
y: -1
}, {
x: 2,
y: -2
}, {
x: -2,
y: -2
});
}
}
const grayScaleBitPlanes = [];
let mmrInput, bitmap;
if (mmr) {
mmrInput = new Reader(decodingContext.data, decodingContext.start, decodingContext.end);
}
for (i = bitsPerValue - 1; i >= 0; i--) {
if (mmr) {
bitmap = decodeMMRBitmap(mmrInput, gridWidth, gridHeight, true);
} else {
bitmap = decodeBitmap(false, gridWidth, gridHeight, template, false, skip, at, decodingContext);
}
grayScaleBitPlanes[i] = bitmap;
}
let mg, ng, bit, patternIndex, patternBitmap, x, y, patternRow, regionRow;
for (mg = 0; mg < gridHeight; mg++) {
for (ng = 0; ng < gridWidth; ng++) {
bit = 0;
patternIndex = 0;
for (j = bitsPerValue - 1; j >= 0; j--) {
bit ^= grayScaleBitPlanes[j][mg][ng];
patternIndex |= bit << j;
}
patternBitmap = patterns[patternIndex];
x = gridOffsetX + mg * gridVectorY + ng * gridVectorX >> 8;
y = gridOffsetY + mg * gridVectorX - ng * gridVectorY >> 8;
if (x >= 0 && x + patternWidth <= regionWidth && y >= 0 && y + patternHeight <= regionHeight) {
for (i = 0; i < patternHeight; i++) {
regionRow = regionBitmap[y + i];
patternRow = patternBitmap[i];
for (j = 0; j < patternWidth; j++) {
regionRow[x + j] |= patternRow[j];
}
}
} else {
let regionX, regionY;
for (i = 0; i < patternHeight; i++) {
regionY = y + i;
if (regionY < 0 || regionY >= regionHeight) {
continue;
}
regionRow = regionBitmap[regionY];
patternRow = patternBitmap[i];
for (j = 0; j < patternWidth; j++) {
regionX = x + j;
if (regionX >= 0 && regionX < regionWidth) {
regionRow[regionX] |= patternRow[j];
}
}
}
}
}
}
return regionBitmap;
}
function readSegmentHeader(data, start) {
const segmentHeader = {};
segmentHeader.number = readUint32(data, start);
const flags = data[start + 4];
const segmentType = flags & 0x3f;
if (!SegmentTypes[segmentType]) {
throw new Jbig2Error("invalid segment type: " + segmentType);
}
segmentHeader.type = segmentType;
segmentHeader.typeName = SegmentTypes[segmentType];
segmentHeader.deferredNonRetain = !!(flags & 0x80);
const pageAssociationFieldSize = !!(flags & 0x40);
const referredFlags = data[start + 5];
let referredToCount = referredFlags >> 5 & 7;
const retainBits = [referredFlags & 31];
let position = start + 6;
if (referredFlags === 7) {
referredToCount = readUint32(data, position - 1) & 0x1fffffff;
position += 3;
let bytes = referredToCount + 7 >> 3;
retainBits[0] = data[position++];
while (--bytes > 0) {
retainBits.push(data[position++]);
}
} else if (referredFlags === 5 || referredFlags === 6) {
throw new Jbig2Error("invalid referred-to flags");
}
segmentHeader.retainBits = retainBits;
let referredToSegmentNumberSize = 4;
if (segmentHeader.number <= 256) {
referredToSegmentNumberSize = 1;
} else if (segmentHeader.number <= 65536) {
referredToSegmentNumberSize = 2;
}
const referredTo = [];
let i, ii;
for (i = 0; i < referredToCount; i++) {
let number;
if (referredToSegmentNumberSize === 1) {
number = data[position];
} else if (referredToSegmentNumberSize === 2) {
number = readUint16(data, position);
} else {
number = readUint32(data, position);
}
referredTo.push(number);
position += referredToSegmentNumberSize;
}
segmentHeader.referredTo = referredTo;
if (!pageAssociationFieldSize) {
segmentHeader.pageAssociation = data[position++];
} else {
segmentHeader.pageAssociation = readUint32(data, position);
position += 4;
}
segmentHeader.length = readUint32(data, position);
position += 4;
if (segmentHeader.length === 0xffffffff) {
if (segmentType === 38) {
const genericRegionInfo = readRegionSegmentInformation(data, position);
const genericRegionSegmentFlags = data[position + RegionSegmentInformationFieldLength];
const genericRegionMmr = !!(genericRegionSegmentFlags & 1);
const searchPatternLength = 6;
const searchPattern = new Uint8Array(searchPatternLength);
if (!genericRegionMmr) {
searchPattern[0] = 0xff;
searchPattern[1] = 0xac;
}
searchPattern[2] = genericRegionInfo.height >>> 24 & 0xff;
searchPattern[3] = genericRegionInfo.height >> 16 & 0xff;
searchPattern[4] = genericRegionInfo.height >> 8 & 0xff;
searchPattern[5] = genericRegionInfo.height & 0xff;
for (i = position, ii = data.length; i < ii; i++) {
let j = 0;
while (j < searchPatternLength && searchPattern[j] === data[i + j]) {
j++;
}
if (j === searchPatternLength) {
segmentHeader.length = i + searchPatternLength;
break;
}
}
if (segmentHeader.length === 0xffffffff) {
throw new Jbig2Error("segment end was not found");
}
} else {
throw new Jbig2Error("invalid unknown segment length");
}
}
segmentHeader.headerEnd = position;
return segmentHeader;
}
function readSegments(header, data, start, end) {
const segments = [];
let position = start;
while (position < end) {
const segmentHeader = readSegmentHeader(data, position);
position = segmentHeader.headerEnd;
const segment = {
header: segmentHeader,
data
};
if (!header.randomAccess) {
segment.start = position;
position += segmentHeader.length;
segment.end = position;
}
segments.push(segment);
if (segmentHeader.type === 51) {
break;
}
}
if (header.randomAccess) {
for (let i = 0, ii = segments.length; i < ii; i++) {
segments[i].start = position;
position += segments[i].header.length;
segments[i].end = position;
}
}
return segments;
}
function readRegionSegmentInformation(data, start) {
return {
width: readUint32(data, start),
height: readUint32(data, start + 4),
x: readUint32(data, start + 8),
y: readUint32(data, start + 12),
combinationOperator: data[start + 16] & 7
};
}
const RegionSegmentInformationFieldLength = 17;
function processSegment(segment, visitor) {
const header = segment.header;
const data = segment.data,
end = segment.end;
let position = segment.start;
let args, at, i, atLength;
switch (header.type) {
case 0:
const dictionary = {};
const dictionaryFlags = readUint16(data, position);
dictionary.huffman = !!(dictionaryFlags & 1);
dictionary.refinement = !!(dictionaryFlags & 2);
dictionary.huffmanDHSelector = dictionaryFlags >> 2 & 3;
dictionary.huffmanDWSelector = dictionaryFlags >> 4 & 3;
dictionary.bitmapSizeSelector = dictionaryFlags >> 6 & 1;
dictionary.aggregationInstancesSelector = dictionaryFlags >> 7 & 1;
dictionary.bitmapCodingContextUsed = !!(dictionaryFlags & 256);
dictionary.bitmapCodingContextRetained = !!(dictionaryFlags & 512);
dictionary.template = dictionaryFlags >> 10 & 3;
dictionary.refinementTemplate = dictionaryFlags >> 12 & 1;
position += 2;
if (!dictionary.huffman) {
atLength = dictionary.template === 0 ? 4 : 1;
at = [];
for (i = 0; i < atLength; i++) {
at.push({
x: readInt8(data, position),
y: readInt8(data, position + 1)
});
position += 2;
}
dictionary.at = at;
}
if (dictionary.refinement && !dictionary.refinementTemplate) {
at = [];
for (i = 0; i < 2; i++) {
at.push({
x: readInt8(data, position),
y: readInt8(data, position + 1)
});
position += 2;
}
dictionary.refinementAt = at;
}
dictionary.numberOfExportedSymbols = readUint32(data, position);
position += 4;
dictionary.numberOfNewSymbols = readUint32(data, position);
position += 4;
args = [dictionary, header.number, header.referredTo, data, position, end];
break;
case 6:
case 7:
const textRegion = {};
textRegion.info = readRegionSegmentInformation(data, position);
position += RegionSegmentInformationFieldLength;
const textRegionSegmentFlags = readUint16(data, position);
position += 2;
textRegion.huffman = !!(textRegionSegmentFlags & 1);
textRegion.refinement = !!(textRegionSegmentFlags & 2);
textRegion.logStripSize = textRegionSegmentFlags >> 2 & 3;
textRegion.stripSize = 1 << textRegion.logStripSize;
textRegion.referenceCorner = textRegionSegmentFlags >> 4 & 3;
textRegion.transposed = !!(textRegionSegmentFlags & 64);
textRegion.combinationOperator = textRegionSegmentFlags >> 7 & 3;
textRegion.defaultPixelValue = textRegionSegmentFlags >> 9 & 1;
textRegion.dsOffset = textRegionSegmentFlags << 17 >> 27;
textRegion.refinementTemplate = textRegionSegmentFlags >> 15 & 1;
if (textRegion.huffman) {
const textRegionHuffmanFlags = readUint16(data, position);
position += 2;
textRegion.huffmanFS = textRegionHuffmanFlags & 3;
textRegion.huffmanDS = textRegionHuffmanFlags >> 2 & 3;
textRegion.huffmanDT = textRegionHuffmanFlags >> 4 & 3;
textRegion.huffmanRefinementDW = textRegionHuffmanFlags >> 6 & 3;
textRegion.huffmanRefinementDH = textRegionHuffmanFlags >> 8 & 3;
textRegion.huffmanRefinementDX = textRegionHuffmanFlags >> 10 & 3;
textRegion.huffmanRefinementDY = textRegionHuffmanFlags >> 12 & 3;
textRegion.huffmanRefinementSizeSelector = !!(textRegionHuffmanFlags & 0x4000);
}
if (textRegion.refinement && !textRegion.refinementTemplate) {
at = [];
for (i = 0; i < 2; i++) {
at.push({
x: readInt8(data, position),
y: readInt8(data, position + 1)
});
position += 2;
}
textRegion.refinementAt = at;
}
textRegion.numberOfSymbolInstances = readUint32(data, position);
position += 4;
args = [textRegion, header.referredTo, data, position, end];
break;
case 16:
const patternDictionary = {};
const patternDictionaryFlags = data[position++];
patternDictionary.mmr = !!(patternDictionaryFlags & 1);
patternDictionary.template = patternDictionaryFlags >> 1 & 3;
patternDictionary.patternWidth = data[position++];
patternDictionary.patternHeight = data[position++];
patternDictionary.maxPatternIndex = readUint32(data, position);
position += 4;
args = [patternDictionary, header.number, data, position, end];
break;
case 22:
case 23:
const halftoneRegion = {};
halftoneRegion.info = readRegionSegmentInformation(data, position);
position += RegionSegmentInformationFieldLength;
const halftoneRegionFlags = data[position++];
halftoneRegion.mmr = !!(halftoneRegionFlags & 1);
halftoneRegion.template = halftoneRegionFlags >> 1 & 3;
halftoneRegion.enableSkip = !!(halftoneRegionFlags & 8);
halftoneRegion.combinationOperator = halftoneRegionFlags >> 4 & 7;
halftoneRegion.defaultPixelValue = halftoneRegionFlags >> 7 & 1;
halftoneRegion.gridWidth = readUint32(data, position);
position += 4;
halftoneRegion.gridHeight = readUint32(data, position);
position += 4;
halftoneRegion.gridOffsetX = readUint32(data, position) & 0xffffffff;
position += 4;
halftoneRegion.gridOffsetY = readUint32(data, position) & 0xffffffff;
position += 4;
halftoneRegion.gridVectorX = readUint16(data, position);
position += 2;
halftoneRegion.gridVectorY = readUint16(data, position);
position += 2;
args = [halftoneRegion, header.referredTo, data, position, end];
break;
case 38:
case 39:
const genericRegion = {};
genericRegion.info = readRegionSegmentInformation(data, position);
position += RegionSegmentInformationFieldLength;
const genericRegionSegmentFlags = data[position++];
genericRegion.mmr = !!(genericRegionSegmentFlags & 1);
genericRegion.template = genericRegionSegmentFlags >> 1 & 3;
genericRegion.prediction = !!(genericRegionSegmentFlags & 8);
if (!genericRegion.mmr) {
atLength = genericRegion.template === 0 ? 4 : 1;
at = [];
for (i = 0; i < atLength; i++) {
at.push({
x: readInt8(data, position),
y: readInt8(data, position + 1)
});
position += 2;
}
genericRegion.at = at;
}
args = [genericRegion, data, position, end];
break;
case 48:
const pageInfo = {
width: readUint32(data, position),
height: readUint32(data, position + 4),
resolutionX: readUint32(data, position + 8),
resolutionY: readUint32(data, position + 12)
};
if (pageInfo.height === 0xffffffff) {
delete pageInfo.height;
}
const pageSegmentFlags = data[position + 16];
readUint16(data, position + 17);
pageInfo.lossless = !!(pageSegmentFlags & 1);
pageInfo.refinement = !!(pageSegmentFlags & 2);
pageInfo.defaultPixelValue = pageSegmentFlags >> 2 & 1;
pageInfo.combinationOperator = pageSegmentFlags >> 3 & 3;
pageInfo.requiresBuffer = !!(pageSegmentFlags & 32);
pageInfo.combinationOperatorOverride = !!(pageSegmentFlags & 64);
args = [pageInfo];
break;
case 49:
break;
case 50:
break;
case 51:
break;
case 53:
args = [header.number, data, position, end];
break;
case 62:
break;
default:
throw new Jbig2Error(`segment type ${header.typeName}(${header.type}) is not implemented`);
}
const callbackName = "on" + header.typeName;
if (callbackName in visitor) {
visitor[callbackName].apply(visitor, args);
}
}
function processSegments(segments, visitor) {
for (let i = 0, ii = segments.length; i < ii; i++) {
processSegment(segments[i], visitor);
}
}
function parseJbig2Chunks(chunks) {
const visitor = new SimpleSegmentVisitor();
for (let i = 0, ii = chunks.length; i < ii; i++) {
const chunk = chunks[i];
const segments = readSegments({}, chunk.data, chunk.start, chunk.end);
processSegments(segments, visitor);
}
return visitor.buffer;
}
function parseJbig2(data) {
throw new Error("Not implemented: parseJbig2");
}
class SimpleSegmentVisitor {
onPageInformation(info) {
this.currentPageInfo = info;
const rowSize = info.width + 7 >> 3;
const buffer = new Uint8ClampedArray(rowSize * info.height);
if (info.defaultPixelValue) {
buffer.fill(0xff);
}
this.buffer = buffer;
}
drawBitmap(regionInfo, bitmap) {
const pageInfo = this.currentPageInfo;
const width = regionInfo.width,
height = regionInfo.height;
const rowSize = pageInfo.width + 7 >> 3;
const combinationOperator = pageInfo.combinationOperatorOverride ? regionInfo.combinationOperator : pageInfo.combinationOperator;
const buffer = this.buffer;
const mask0 = 128 >> (regionInfo.x & 7);
let offset0 = regionInfo.y * rowSize + (regionInfo.x >> 3);
let i, j, mask, offset;
switch (combinationOperator) {
case 0:
for (i = 0; i < height; i++) {
mask = mask0;
offset = offset0;
for (j = 0; j < width; j++) {
if (bitmap[i][j]) {
buffer[offset] |= mask;
}
mask >>= 1;
if (!mask) {
mask = 128;
offset++;
}
}
offset0 += rowSize;
}
break;
case 2:
for (i = 0; i < height; i++) {
mask = mask0;
offset = offset0;
for (j = 0; j < width; j++) {
if (bitmap[i][j]) {
buffer[offset] ^= mask;
}
mask >>= 1;
if (!mask) {
mask = 128;
offset++;
}
}
offset0 += rowSize;
}
break;
default:
throw new Jbig2Error(`operator ${combinationOperator} is not supported`);
}
}
onImmediateGenericRegion(region, data, start, end) {
const regionInfo = region.info;
const decodingContext = new DecodingContext(data, start, end);
const bitmap = decodeBitmap(region.mmr, regionInfo.width, regionInfo.height, region.template, region.prediction, null, region.at, decodingContext);
this.drawBitmap(regionInfo, bitmap);
}
onImmediateLosslessGenericRegion() {
this.onImmediateGenericRegion(...arguments);
}
onSymbolDictionary(dictionary, currentSegment, referredSegments, data, start, end) {
let huffmanTables, huffmanInput;
if (dictionary.huffman) {
huffmanTables = getSymbolDictionaryHuffmanTables(dictionary, referredSegments, this.customTables);
huffmanInput = new Reader(data, start, end);
}
let symbols = this.symbols;
if (!symbols) {
this.symbols = symbols = {};
}
const inputSymbols = [];
for (const referredSegment of referredSegments) {
const referredSymbols = symbols[referredSegment];
if (referredSymbols) {
inputSymbols.push(...referredSymbols);
}
}
const decodingContext = new DecodingContext(data, start, end);
symbols[currentSegment] = decodeSymbolDictionary(dictionary.huffman, dictionary.refinement, inputSymbols, dictionary.numberOfNewSymbols, dictionary.numberOfExportedSym | |