diff --git a/.codeclimate.yml b/.codeclimate.yml
new file mode 100644
index 000000000..49b146d7c
--- /dev/null
+++ b/.codeclimate.yml
@@ -0,0 +1,30 @@
+---
+engines:
+ csslint:
+ enabled: true
+ duplication:
+ enabled: true
+ config:
+ languages:
+ - javascript
+ eslint:
+ enabled: true
+ config:
+ config: .eslintrc.js
+ fixme:
+ enabled: true
+ratings:
+ paths:
+ - "**.css"
+ - "**.js"
+exclude_paths:
+- assets/**/*
+- data/**/*
+- dist/**/*
+- examples/**/*
+- external/**/*
+- deprecated/**/*
+- specs/**/*
+- src/controls/**/*
+- gulpfile.js
+- karma.conf.js
diff --git a/.csslintrc b/.csslintrc
new file mode 100644
index 000000000..aacba956e
--- /dev/null
+++ b/.csslintrc
@@ -0,0 +1,2 @@
+--exclude-exts=.min.css
+--ignore=adjoining-classes,box-model,ids,order-alphabetical,unqualified-attributes
diff --git a/.eslintignore b/.eslintignore
new file mode 100644
index 000000000..96212a359
--- /dev/null
+++ b/.eslintignore
@@ -0,0 +1 @@
+**/*{.,-}min.js
diff --git a/.eslintrc.js b/.eslintrc.js
new file mode 100644
index 000000000..c81c686f5
--- /dev/null
+++ b/.eslintrc.js
@@ -0,0 +1,219 @@
+module.exports = {
+ "parserOptions": {
+ "ecmaVersion": 6,
+ "sourceType": "module",
+ "ecmaFeatures": {
+ "modules": true
+ },
+
+ },
+ "env": {
+ "browser": true,
+ "es6": true,
+ "node": true
+ },
+ "globals": {
+ "THREE": false
+ },
+ // http://eslint.org/docs/rules/
+ "rules": {
+ "comma-dangle": [2, "never"],
+ "no-cond-assign": 2,
+ "no-console": 0,
+ "no-constant-condition": 2,
+ "no-control-regex": 2,
+ "no-debugger": 2,
+ "no-dupe-args": 2,
+ "no-dupe-keys": 2,
+ "no-duplicate-case": 2,
+ "no-empty": 2,
+ "no-empty-character-class": 2,
+ "no-ex-assign": 2,
+ "no-extra-boolean-cast": 2,
+ "no-extra-parens": 0,
+ "no-extra-semi": 2,
+ "no-func-assign": 2,
+ "no-inner-declarations": [2, "functions"],
+ "no-invalid-regexp": 2,
+ "no-irregular-whitespace": 2,
+ "no-negated-in-lhs": 2,
+ "no-obj-calls": 2,
+ "no-regex-spaces": 2,
+ "no-sparse-arrays": 2,
+ "no-unexpected-multiline": 2,
+ "no-unreachable": 2,
+ "use-isnan": 2,
+ "valid-jsdoc": 0,
+ "valid-typeof": 2,
+
+ // Best Practices,
+ "accessor-pairs": 2,
+ "block-scoped-var": 0,
+ "complexity": [2, 6],
+ "consistent-return": 0,
+ "curly": 0,
+ "default-case": 0,
+ "dot-location": 0,
+ "dot-notation": 0,
+ "eqeqeq": 2,
+ "guard-for-in": 2,
+ "no-alert": 2,
+ "no-caller": 2,
+ "no-case-declarations": 2,
+ "no-div-regex": 2,
+ "no-else-return": 0,
+ "no-empty-pattern": 2,
+ "no-eq-null": 2,
+ "no-eval": 2,
+ "no-extend-native": 2,
+ "no-extra-bind": 2,
+ "no-fallthrough": 2,
+ "no-floating-decimal": 0,
+ "no-implicit-coercion": 0,
+ "no-implied-eval": 2,
+ "no-invalid-this": 0,
+ "no-iterator": 2,
+ "no-labels": 0,
+ "no-lone-blocks": 2,
+ "no-loop-func": 2,
+ "no-magic-number": 0,
+ "no-multi-spaces": 0,
+ "no-multi-str": 0,
+ "no-native-reassign": 2,
+ "no-new-func": 2,
+ "no-new-wrappers": 2,
+ "no-new": 2,
+ "no-octal-escape": 2,
+ "no-octal": 2,
+ "no-proto": 2,
+ "no-redeclare": 2,
+ "no-return-assign": 2,
+ "no-script-url": 2,
+ "no-self-compare": 2,
+ "no-sequences": 0,
+ "no-throw-literal": 0,
+ "no-unused-expressions": 2,
+ "no-useless-call": 2,
+ "no-useless-concat": 2,
+ "no-void": 2,
+ "no-warning-comments": 0,
+ "no-with": 2,
+ "radix": 2,
+ "vars-on-top": 0,
+ "wrap-iife": 2,
+ "yoda": 0,
+
+ // Strict,
+ "strict": 0,
+
+ // Variables,
+ "init-declarations": 0,
+ "no-catch-shadow": 2,
+ "no-delete-var": 2,
+ "no-label-var": 2,
+ "no-shadow-restricted-names": 2,
+ "no-shadow": 0,
+ "no-undef-init": 0,
+ "no-undef": 2,
+ "no-undefined": 0,
+ "no-unused-vars": 0,
+ "no-use-before-define": 0,
+
+ // Node.js and CommonJS,
+ "callback-return": 2,
+ "global-require": 2,
+ "handle-callback-err": 2,
+ "no-mixed-requires": 0,
+ "no-new-require": 0,
+ "no-path-concat": 2,
+ "no-process-exit": 2,
+ "no-restricted-modules": 0,
+ "no-sync": 0,
+
+ // Stylistic Issues,
+ "array-bracket-spacing": 0,
+ "block-spacing": 0,
+ "brace-style": 0,
+ "camelcase": 0,
+ "comma-spacing": 0,
+ "comma-style": 0,
+ "computed-property-spacing": 0,
+ "consistent-this": 0,
+ "eol-last": 0,
+ "func-names": 0,
+ "func-style": 0,
+ "id-length": 0,
+ "id-match": 0,
+ "indent": 0,
+ "jsx-quotes": 0,
+ "key-spacing": 0,
+ "linebreak-style": 0,
+ "lines-around-comment": 0,
+ "max-depth": 0,
+ "max-len": 0,
+ "max-nested-callbacks": 0,
+ "max-params": 0,
+ "max-statements": [2, 30],
+ "new-cap": 0,
+ "new-parens": 0,
+ "newline-after-var": 0,
+ "no-array-constructor": 0,
+ "no-bitwise": 0,
+ "no-continue": 0,
+ "no-inline-comments": 0,
+ "no-lonely-if": 0,
+ "no-mixed-spaces-and-tabs": 0,
+ "no-multiple-empty-lines": 0,
+ "no-negated-condition": 0,
+ "no-nested-ternary": 0,
+ "no-new-object": 0,
+ "no-plusplus": 0,
+ "no-restricted-syntax": 0,
+ "no-spaced-func": 0,
+ "no-ternary": 0,
+ "no-trailing-spaces": 0,
+ "no-underscore-dangle": 0,
+ "no-unneeded-ternary": 0,
+ "object-curly-spacing": 0,
+ "one-var": 0,
+ "operator-assignment": 0,
+ "operator-linebreak": 0,
+ "padded-blocks": 0,
+ "quote-props": 0,
+ "quotes": 0,
+ "require-jsdoc": 0,
+ "semi-spacing": 0,
+ "semi": 0,
+ "sort-vars": 0,
+ "space-after-keywords": 0,
+ "space-before-blocks": 0,
+ "space-before-function-paren": 0,
+ "space-before-keywords": 0,
+ "space-in-parens": 0,
+ "space-infix-ops": 0,
+ "space-return-throw-case": 0,
+ "space-unary-ops": 0,
+ "spaced-comment": 0,
+ "wrap-regex": 0,
+
+ // ECMAScript 6,
+ "arrow-body-style": 0,
+ "arrow-parens": 0,
+ "arrow-spacing": 0,
+ "constructor-super": 0,
+ "generator-star-spacing": 0,
+ "no-arrow-condition": 0,
+ "no-class-assign": 0,
+ "no-const-assign": 0,
+ "no-dupe-class-members": 0,
+ "no-this-before-super": 0,
+ "no-var": 0,
+ "object-shorthand": 0,
+ "prefer-arrow-callback": 0,
+ "prefer-const": 0,
+ "prefer-reflect": 0,
+ "prefer-spread": 0,
+ "prefer-template": 0,
+ "require-yield": 0
+ }
+}
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..bf732f556
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,9 @@
+.DS_STORE
+.publish
+.sass-cache
+.tmp
+bower_components
+build-old
+deprecated
+gh-pages
+node_modules
diff --git a/.jscsrc b/.jscsrc
new file mode 100644
index 000000000..ebc0e58f3
--- /dev/null
+++ b/.jscsrc
@@ -0,0 +1,8 @@
+{
+ "preset": "google",
+ "requireCurlyBraces": null,
+ "validateLineBreaks" : "LF",
+ "validateIndentation" : 2,
+ "excludeFiles" : ["node_modules/**", "bower_components/**"],
+ "esnext": true
+}
\ No newline at end of file
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 000000000..1269488f7
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1 @@
+data
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 000000000..d8875361e
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,15 @@
+language: node_js
+node_js:
+ - "5.4"
+ - "5.6"
+cache:
+ directories:
+ - node_modules
+before_script:
+ - npm install -g gulp
+script:
+ - gulp test
+ - gulp build
+ - gulp
+notifications:
+ slack: fnndsc:UohaXDsjFDVqZj5IfdC88XRa
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..d52295937
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 FNNDSC / CHB
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
diff --git a/README.md b/README.md
new file mode 100644
index 000000000..87fd23582
--- /dev/null
+++ b/README.md
@@ -0,0 +1,358 @@
+**WARNING: AMI is not ready for production yet.** (Alpha release scheduled in first 15 days of April 2016 - almost there :)
+[](https://travis-ci.org/FNNDSC/ami)
+[](https://codeclimate.com/github/FNNDSC/ami)
+[](http://slack.babymri.org)
+[](https://www.npmjs.com/package/ami.js)
+[](https://www.npmjs.com/package/ami.js)
+
+
+#
AMI JS ToolKit
+> AMI Medical Imaging (AMI) JS ToolKit for THREEJS
+
+### Content
+
+1. [Lessons](#lessons)
+2. [Advanced examples](#advanced)
+2. [Features](#features)
+3. [Usage](#usage)
+4. [Pre-requisites](#pre-requisites)
+5. [Use with NPM](#npm)
+6. [Use compiled version](#compiled)
+7. [API Documentation](https://fnndsc.github.io/ami/doc)
+8. [Developer corner](https://fnndsc.github.io/ami/doc)
+9. [Credits](#credits)
+
+## Lessons
+
+
+
+
+
+
+
+
+ |
+
+
+ Lesson 00: Load
+
+
+ Load DICOM Data and get a nice Series/Stack/Frame structure.
+
+ |
+
+
+
+
+
+
+
+ |
+
+
+ Lesson 01: Visualize 3D
+
+
+ Look at the data we loaded in 3D.
+
+ |
+
+
+
+
+
+
+
+
+
+ |
+
+
+ Lesson 02: Mesh
+
+
+ Add a mesh to the scene.
+
+ |
+
+
+
+
+
+
+
+ |
+
+
+ Lesson 03: Visualize 2D
+
+
+ Look at the data in 2D.
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+ Lesson 04: Labelmap
+
+
+ Label maps - coming soon.
+
+ |
+
+
+
+
+
+
+
+ |
+
+
+ Lesson 05: TRK
+
+
+ TRK - coming soon.
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+ Lesson 06: Volume Rendering
+
+
+ Volume Rendering - coming soon.
+
+ |
+
+
+
+
+
+
+
+ |
+
+
+ Lesson 07: Lookup tables
+
+
+ Lookup Tables - coming soon.
+
+ |
+
+
+
+## Advanced
+
+See it live [there](https://fnndsc.github.io/ami)!
+
+## Features
+:white_check_mark: READY - :large_orange_diamond: IN PROGRESS OR LIMITED SUPPORT - :x: ON ROADMAP
+#### Capabilities
+:white_check_mark: 2D Visulization
+
+:white_check_mark: 3D Visualization
+
+:white_check_mark: Volume Rendering
+
+:white_check_mark: Lookup Tables
+
+:large_orange_diamond: Label Maps
+
+#### Widgets
+
+:large_orange_diamond: Probe (2D/3D)
+
+:large_orange_diamond: Ruler (2D/3D)
+
+:large_orange_diamond: Angle (2D/3D)
+
+:large_orange_diamond: Orientation (2D/3D)
+
+#### Volumes
+
+:white_check_mark: Dicom
+
+:white_check_mark: NRRD
+
+:large_orange_diamond: Nifti
+
+:x: MGH/MGZ
+
+:x: JPEG
+
+#### Meshes
+
+:white_check_mark: VTK (THREEJS)
+
+:white_check_mark: STL (THREEJS)
+
+:large_orange_diamond: TRK
+
+:x: CURV
+
+:x: FSM
+
+## Usage
+
+If you know how to use THREEJS, you already know out to use AMI. Learn about THREEJS then checkout the lessons, examples and the API to dive in!
+
+## Pre-requisites
+
+### THREEJS
+Make sure that you are loading THREEJS your index.html **BEFORE** AMI.
+```
+
+```
+
+### Promise polyfills (for older browsers)
+Follow the instructions from [babel's wiki](http://babeljs.io/docs/usage/polyfill/) or just use one of the many Promise polyfill available out there.
+
+**NOT FOR PRODUCTION**: available for convenience at:
+```
+
+```
+
+## NPM
+
+### Installation
+
+
+```
+npm install ami.js
+```
+
+Note that you might need to include [babel](https://github.com/babel/babel) and [glslify](https://github.com/stackgl/glslify) transforms in you build (browserify, webpack, etc.) process.
+```
+...
+browserify(
+ {entries: [entry],
+ debug: true
+ })
+ .transform(babelify, {"presets": ["es2015"]})
+ .transform(glslify)
+ .bundle()
+...
+```
+
+### Usage
+
+```
+let AMI = require('ami.js');
+window.console.log(AMI);
+
+// Ready to rock
+```
+
+## Compiled
+
+### Installation
+Add AMI in your index.html after THREEJS.
+```
+...
+
+
+...
+```
+
+### Usage
+```
+let AMI = AMI.default;
+window.console.log(AMI);
+
+// Ready to rock
+```
+
+## Developer corner
+Get the source code and related packages.
+```
+$> git clone https://github.com/FNNDSC/ami.git
+$> cd ami
+$> npm install
+```
+
+Default task (runs tests, documentation, etc. and create a directory ready to be pushed as gh-page)
+```
+$> gulp
+```
+
+To run examples (browserify/babelify/glslify the example)
+```
+$> gulp examples --
+
+# for instance to run the geometries_slice example
+
+$> gulp examples --geometries_slices
+```
+
+To run lessons (runs example against compiled ami.js)
+```
+$> gulp lessons --
+
+# for instance to run lesson 00
+
+$> gulp lessons --00
+```
+
+Build standalone library to build/
+```
+$> gulp build
+```
+
+Tests
+```
+$> gulp test
+```
+
+Documentation
+```
+$> gulp doc
+```
+
+# Credits
+
+##### [THREEJS](https://github.com/mrdoob/three.js/)
+* Base components such as Vectors, Matrices and Objects3D.
+* HTML template for example page.
+* Author(s): [mrdoob](https://github.com/mrdoob)
+
+##### [DicomParser](https://github.com/chafey/dicomParser)
+* DICOM parsing relies on it.
+* Author(s): [chafey](https://github.com/chafey)
+
+##### [CornerstoneWADOImageLoader](https://github.com/chafey/cornerstoneWADOImageLoader)
+* Was used to figure out how to use the dicom parser properly.
+* Author(s): [chafey](https://github.com/chafey)
+
+##### [NIFTI-Reader-JS](https://github.com/rii-mango/NIFTI-Reader-JS)
+* Nifti parsing relies on it.
+* Author(s): [rii-mango](https://github.com/rii-mango)
+
+##### [JPEGLosslessDecoderJS](https://github.com/rii-mango/JPEGLosslessDecoderJS)
+* JPEG Lossless Decoder for DICOM images
+* Author(s): [rii-mango](https://github.com/rii-mango)
+
+##### [Image-JPEG2000](https://github.com/OHIF/image-JPEG2000)
+* JPEG 2000 Decoder for DICOM images
+* Author(s): [jpambrun](https://github.com/jpambrun), [mozilla](https://github.com/mozilla/pdf.js/)
+
+##### [Pako](https://github.com/nodeca/pako)
+* GZ file decompression
+* Author(s): [nodeca](https://github.com/nodeca)
diff --git a/assets/A.svg b/assets/A.svg
new file mode 100644
index 000000000..eb97a40c9
--- /dev/null
+++ b/assets/A.svg
@@ -0,0 +1,110 @@
+
+
+
+
diff --git a/assets/V.svg b/assets/V.svg
new file mode 100644
index 000000000..b09d895f2
--- /dev/null
+++ b/assets/V.svg
@@ -0,0 +1,110 @@
+
+
+
+
diff --git a/assets/V_flat_icon.png b/assets/V_flat_icon.png
new file mode 100644
index 000000000..15429b64d
Binary files /dev/null and b/assets/V_flat_icon.png differ
diff --git a/assets/flat_icon.xcf b/assets/flat_icon.xcf
new file mode 100644
index 000000000..1a6132066
Binary files /dev/null and b/assets/flat_icon.xcf differ
diff --git a/bower.json b/bower.json
new file mode 100644
index 000000000..5eab07901
--- /dev/null
+++ b/bower.json
@@ -0,0 +1,5 @@
+{
+ "name": "vjs",
+ "version": "0.0.0",
+ "dependencies": {}
+}
diff --git a/data/dicom/MELANIX.dcm.tar b/data/dicom/MELANIX.dcm.tar
new file mode 100644
index 000000000..07a2424b3
Binary files /dev/null and b/data/dicom/MELANIX.dcm.tar differ
diff --git a/data/dicom/MR-MONO2-8-16x-heart.dcm.tar b/data/dicom/MR-MONO2-8-16x-heart.dcm.tar
new file mode 100644
index 000000000..3030fb0bd
Binary files /dev/null and b/data/dicom/MR-MONO2-8-16x-heart.dcm.tar differ
diff --git a/data/dicom/US-RGB-8-epicard.dcm.tar b/data/dicom/US-RGB-8-epicard.dcm.tar
new file mode 100644
index 000000000..629645c6e
Binary files /dev/null and b/data/dicom/US-RGB-8-epicard.dcm.tar differ
diff --git a/data/dicom/US-RGB-8-esopecho.dcm.tar b/data/dicom/US-RGB-8-esopecho.dcm.tar
new file mode 100644
index 000000000..8fe696d60
Binary files /dev/null and b/data/dicom/US-RGB-8-esopecho.dcm.tar differ
diff --git a/data/dicom/dcm.seg.andrei.tar b/data/dicom/dcm.seg.andrei.tar
new file mode 100644
index 000000000..a5eb1157e
Binary files /dev/null and b/data/dicom/dcm.seg.andrei.tar differ
diff --git a/data/dicom/mi2b2.dcm.tar b/data/dicom/mi2b2.dcm.tar
new file mode 100644
index 000000000..c79cb38f2
Binary files /dev/null and b/data/dicom/mi2b2.dcm.tar differ
diff --git a/data/dicom/monochrome2.dcm.tar b/data/dicom/monochrome2.dcm.tar
new file mode 100644
index 000000000..f7eccb679
Binary files /dev/null and b/data/dicom/monochrome2.dcm.tar differ
diff --git a/dist/ami.js b/dist/ami.js
new file mode 100644
index 000000000..80f087457
--- /dev/null
+++ b/dist/ami.js
@@ -0,0 +1,29024 @@
+(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AMI = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && !codeLengths[length - 1])
+ length--;
+ code.push({children: [], index: 0});
+ var p = code[0], q;
+ for (i = 0; i < length; i++) {
+ for (j = 0; j < codeLengths[i]; j++) {
+ p = code.pop();
+ p.children[p.index] = values[k];
+ while (p.index > 0) {
+ p = code.pop();
+ }
+ p.index++;
+ code.push(p);
+ while (code.length <= i) {
+ code.push(q = {children: [], index: 0});
+ p.children[p.index] = q.children;
+ p = q;
+ }
+ k++;
+ }
+ if (i + 1 < length) {
+ // p here points to last code
+ code.push(q = {children: [], index: 0});
+ p.children[p.index] = q.children;
+ p = q;
+ }
+ }
+ return code[0].children;
+ }
+
+ function getBlockBufferOffset(component, row, col) {
+ return 64 * ((component.blocksPerLine + 1) * row + col);
+ }
+
+ function decodeScan(data, offset,
+ frame, components, resetInterval,
+ spectralStart, spectralEnd,
+ successivePrev, successive) {
+ var precision = frame.precision;
+ var samplesPerLine = frame.samplesPerLine;
+ var scanLines = frame.scanLines;
+ var mcusPerLine = frame.mcusPerLine;
+ var progressive = frame.progressive;
+ var maxH = frame.maxH, maxV = frame.maxV;
+
+ var startOffset = offset, bitsData = 0, bitsCount = 0;
+
+ function readBit() {
+ if (bitsCount > 0) {
+ bitsCount--;
+ return (bitsData >> bitsCount) & 1;
+ }
+ bitsData = data[offset++];
+ if (bitsData == 0xFF) {
+ var nextByte = data[offset++];
+ if (nextByte) {
+ throw "unexpected marker: " + ((bitsData << 8) | nextByte).toString(16);
+ }
+ // unstuff 0
+ }
+ bitsCount = 7;
+ return bitsData >>> 7;
+ }
+
+ function decodeHuffman(tree) {
+ var node = tree;
+ var bit;
+ while ((bit = readBit()) !== null) {
+ node = node[bit];
+ if (typeof node === 'number')
+ return node;
+ if (typeof node !== 'object')
+ throw "invalid huffman sequence";
+ }
+ return null;
+ }
+
+ function receive(length) {
+ var n = 0;
+ while (length > 0) {
+ var bit = readBit();
+ if (bit === null)
+ return;
+ n = (n << 1) | bit;
+ length--;
+ }
+ return n;
+ }
+
+ function receiveAndExtend(length) {
+ var n = receive(length);
+ if (n >= 1 << (length - 1))
+ return n;
+ return n + (-1 << length) + 1;
+ }
+
+ function decodeBaseline(component, offset) {
+ var t = decodeHuffman(component.huffmanTableDC);
+ var diff = t === 0 ? 0 : receiveAndExtend(t);
+ component.blockData[offset] = (component.pred += diff);
+ var k = 1;
+ while (k < 64) {
+ var rs = decodeHuffman(component.huffmanTableAC);
+ var s = rs & 15, r = rs >> 4;
+ if (s === 0) {
+ if (r < 15)
+ break;
+ k += 16;
+ continue;
+ }
+ k += r;
+ var z = dctZigZag[k];
+ component.blockData[offset + z] = receiveAndExtend(s);
+ k++;
+ }
+ }
+
+ function decodeDCFirst(component, offset) {
+ var t = decodeHuffman(component.huffmanTableDC);
+ var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
+ component.blockData[offset] = (component.pred += diff);
+ }
+
+ function decodeDCSuccessive(component, offset) {
+ component.blockData[offset] |= readBit() << successive;
+ }
+
+ var eobrun = 0;
+ function decodeACFirst(component, offset) {
+ if (eobrun > 0) {
+ eobrun--;
+ return;
+ }
+ var k = spectralStart, e = spectralEnd;
+ while (k <= e) {
+ var rs = decodeHuffman(component.huffmanTableAC);
+ var s = rs & 15, r = rs >> 4;
+ if (s === 0) {
+ if (r < 15) {
+ eobrun = receive(r) + (1 << r) - 1;
+ break;
+ }
+ k += 16;
+ continue;
+ }
+ k += r;
+ var z = dctZigZag[k];
+ component.blockData[offset + z] = receiveAndExtend(s) * (1 << successive);
+ k++;
+ }
+ }
+
+ var successiveACState = 0, successiveACNextValue;
+ function decodeACSuccessive(component, offset) {
+ var k = spectralStart, e = spectralEnd, r = 0;
+ while (k <= e) {
+ var z = dctZigZag[k];
+ switch (successiveACState) {
+ case 0: // initial state
+ var rs = decodeHuffman(component.huffmanTableAC);
+ var s = rs & 15;
+ r = rs >> 4;
+ if (s === 0) {
+ if (r < 15) {
+ eobrun = receive(r) + (1 << r);
+ successiveACState = 4;
+ } else {
+ r = 16;
+ successiveACState = 1;
+ }
+ } else {
+ if (s !== 1)
+ throw "invalid ACn encoding";
+ successiveACNextValue = receiveAndExtend(s);
+ successiveACState = r ? 2 : 3;
+ }
+ continue;
+ case 1: // skipping r zero items
+ case 2:
+ if (component.blockData[offset + z]) {
+ component.blockData[offset + z] += (readBit() << successive);
+ } else {
+ r--;
+ if (r === 0)
+ successiveACState = successiveACState == 2 ? 3 : 0;
+ }
+ break;
+ case 3: // set value for a zero item
+ if (component.blockData[offset + z]) {
+ component.blockData[offset + z] += (readBit() << successive);
+ } else {
+ component.blockData[offset + z] = successiveACNextValue << successive;
+ successiveACState = 0;
+ }
+ break;
+ case 4: // eob
+ if (component.blockData[offset + z]) {
+ component.blockData[offset + z] += (readBit() << successive);
+ }
+ break;
+ }
+ k++;
+ }
+ if (successiveACState === 4) {
+ eobrun--;
+ if (eobrun === 0)
+ successiveACState = 0;
+ }
+ }
+
+ function decodeMcu(component, decode, mcu, row, col) {
+ var mcuRow = (mcu / mcusPerLine) | 0;
+ var mcuCol = mcu % mcusPerLine;
+ var blockRow = mcuRow * component.v + row;
+ var blockCol = mcuCol * component.h + col;
+ var offset = getBlockBufferOffset(component, blockRow, blockCol);
+ decode(component, offset);
+ }
+
+ function decodeBlock(component, decode, mcu) {
+ var blockRow = (mcu / component.blocksPerLine) | 0;
+ var blockCol = mcu % component.blocksPerLine;
+ var offset = getBlockBufferOffset(component, blockRow, blockCol);
+ decode(component, offset);
+ }
+
+ var componentsLength = components.length;
+ var component, i, j, k, n;
+ var decodeFn;
+ if (progressive) {
+ if (spectralStart === 0)
+ decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
+ else
+ decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
+ } else {
+ decodeFn = decodeBaseline;
+ }
+
+ var mcu = 0, marker;
+ var mcuExpected;
+ if (componentsLength == 1) {
+ mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
+ } else {
+ mcuExpected = mcusPerLine * frame.mcusPerColumn;
+ }
+ if (!resetInterval) {
+ resetInterval = mcuExpected;
+ }
+
+ var h, v;
+ while (mcu < mcuExpected) {
+ // reset interval stuff
+ for (i = 0; i < componentsLength; i++) {
+ components[i].pred = 0;
+ }
+ eobrun = 0;
+
+ if (componentsLength == 1) {
+ component = components[0];
+ for (n = 0; n < resetInterval; n++) {
+ decodeBlock(component, decodeFn, mcu);
+ mcu++;
+ }
+ } else {
+ for (n = 0; n < resetInterval; n++) {
+ for (i = 0; i < componentsLength; i++) {
+ component = components[i];
+ h = component.h;
+ v = component.v;
+ for (j = 0; j < v; j++) {
+ for (k = 0; k < h; k++) {
+ decodeMcu(component, decodeFn, mcu, j, k);
+ }
+ }
+ }
+ mcu++;
+ }
+ }
+
+ // find marker
+ bitsCount = 0;
+ marker = (data[offset] << 8) | data[offset + 1];
+ if (marker <= 0xFF00) {
+ throw "marker was not found";
+ }
+
+ if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
+ offset += 2;
+ } else {
+ break;
+ }
+ }
+
+ return offset - startOffset;
+ }
+
+ // A port of poppler's IDCT method which in turn is taken from:
+ // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
+ // "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
+ // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
+ // 988-991.
+ function quantizeAndInverse(component, blockBufferOffset, p) {
+ var qt = component.quantizationTable;
+ var v0, v1, v2, v3, v4, v5, v6, v7, t;
+ var i;
+
+ // dequant
+ for (i = 0; i < 64; i++) {
+ p[i] = component.blockData[blockBufferOffset + i] * qt[i];
+ }
+
+ // inverse DCT on rows
+ for (i = 0; i < 8; ++i) {
+ var row = 8 * i;
+
+ // check for all-zero AC coefficients
+ if (p[1 + row] === 0 && p[2 + row] === 0 && p[3 + row] === 0 &&
+ p[4 + row] === 0 && p[5 + row] === 0 && p[6 + row] === 0 &&
+ p[7 + row] === 0) {
+ t = (dctSqrt2 * p[0 + row] + 512) >> 10;
+ p[0 + row] = t;
+ p[1 + row] = t;
+ p[2 + row] = t;
+ p[3 + row] = t;
+ p[4 + row] = t;
+ p[5 + row] = t;
+ p[6 + row] = t;
+ p[7 + row] = t;
+ continue;
+ }
+
+ // stage 4
+ v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;
+ v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;
+ v2 = p[2 + row];
+ v3 = p[6 + row];
+ v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;
+ v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;
+ v5 = p[3 + row] << 4;
+ v6 = p[5 + row] << 4;
+
+ // stage 3
+ t = (v0 - v1 + 1) >> 1;
+ v0 = (v0 + v1 + 1) >> 1;
+ v1 = t;
+ t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;
+ v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;
+ v3 = t;
+ t = (v4 - v6 + 1) >> 1;
+ v4 = (v4 + v6 + 1) >> 1;
+ v6 = t;
+ t = (v7 + v5 + 1) >> 1;
+ v5 = (v7 - v5 + 1) >> 1;
+ v7 = t;
+
+ // stage 2
+ t = (v0 - v3 + 1) >> 1;
+ v0 = (v0 + v3 + 1) >> 1;
+ v3 = t;
+ t = (v1 - v2 + 1) >> 1;
+ v1 = (v1 + v2 + 1) >> 1;
+ v2 = t;
+ t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
+ v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
+ v7 = t;
+ t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
+ v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
+ v6 = t;
+
+ // stage 1
+ p[0 + row] = v0 + v7;
+ p[7 + row] = v0 - v7;
+ p[1 + row] = v1 + v6;
+ p[6 + row] = v1 - v6;
+ p[2 + row] = v2 + v5;
+ p[5 + row] = v2 - v5;
+ p[3 + row] = v3 + v4;
+ p[4 + row] = v3 - v4;
+ }
+
+ // inverse DCT on columns
+ for (i = 0; i < 8; ++i) {
+ var col = i;
+
+ // check for all-zero AC coefficients
+ if (p[1 * 8 + col] === 0 && p[2 * 8 + col] === 0 && p[3 * 8 + col] === 0 &&
+ p[4 * 8 + col] === 0 && p[5 * 8 + col] === 0 && p[6 * 8 + col] === 0 &&
+ p[7 * 8 + col] === 0) {
+ t = (dctSqrt2 * p[i + 0] + 8192) >> 14;
+ p[0 * 8 + col] = t;
+ p[1 * 8 + col] = t;
+ p[2 * 8 + col] = t;
+ p[3 * 8 + col] = t;
+ p[4 * 8 + col] = t;
+ p[5 * 8 + col] = t;
+ p[6 * 8 + col] = t;
+ p[7 * 8 + col] = t;
+ continue;
+ }
+
+ // stage 4
+ v0 = (dctSqrt2 * p[0 * 8 + col] + 2048) >> 12;
+ v1 = (dctSqrt2 * p[4 * 8 + col] + 2048) >> 12;
+ v2 = p[2 * 8 + col];
+ v3 = p[6 * 8 + col];
+ v4 = (dctSqrt1d2 * (p[1 * 8 + col] - p[7 * 8 + col]) + 2048) >> 12;
+ v7 = (dctSqrt1d2 * (p[1 * 8 + col] + p[7 * 8 + col]) + 2048) >> 12;
+ v5 = p[3 * 8 + col];
+ v6 = p[5 * 8 + col];
+
+ // stage 3
+ t = (v0 - v1 + 1) >> 1;
+ v0 = (v0 + v1 + 1) >> 1;
+ v1 = t;
+ t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;
+ v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;
+ v3 = t;
+ t = (v4 - v6 + 1) >> 1;
+ v4 = (v4 + v6 + 1) >> 1;
+ v6 = t;
+ t = (v7 + v5 + 1) >> 1;
+ v5 = (v7 - v5 + 1) >> 1;
+ v7 = t;
+
+ // stage 2
+ t = (v0 - v3 + 1) >> 1;
+ v0 = (v0 + v3 + 1) >> 1;
+ v3 = t;
+ t = (v1 - v2 + 1) >> 1;
+ v1 = (v1 + v2 + 1) >> 1;
+ v2 = t;
+ t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;
+ v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;
+ v7 = t;
+ t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;
+ v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;
+ v6 = t;
+
+ // stage 1
+ p[0 * 8 + col] = v0 + v7;
+ p[7 * 8 + col] = v0 - v7;
+ p[1 * 8 + col] = v1 + v6;
+ p[6 * 8 + col] = v1 - v6;
+ p[2 * 8 + col] = v2 + v5;
+ p[5 * 8 + col] = v2 - v5;
+ p[3 * 8 + col] = v3 + v4;
+ p[4 * 8 + col] = v3 - v4;
+ }
+
+ // convert to 8-bit integers
+ for (i = 0; i < 64; ++i) {
+ var index = blockBufferOffset + i;
+ var q = p[i];
+ q = (q <= -2056 / component.bitConversion) ? 0 :
+ (q >= 2024 / component.bitConversion) ? 255 / component.bitConversion :
+ (q + 2056 / component.bitConversion) >> 4;
+ component.blockData[index] = q;
+ }
+ }
+
+ function buildComponentData(frame, component) {
+ var lines = [];
+ var blocksPerLine = component.blocksPerLine;
+ var blocksPerColumn = component.blocksPerColumn;
+ var samplesPerLine = blocksPerLine << 3;
+ var computationBuffer = new Int32Array(64);
+
+ var i, j, ll = 0;
+ for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
+ for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
+ var offset = getBlockBufferOffset(component, blockRow, blockCol);
+ quantizeAndInverse(component, offset, computationBuffer);
+ }
+ }
+ return component.blockData;
+ }
+
+ function clampToUint8(a) {
+ return a <= 0 ? 0 : a >= 255 ? 255 : a | 0;
+ }
+
+ constructor.prototype = {
+ load: function load(path) {
+ var handleData = (function (data) {
+ this.parse(data);
+ if (this.onload)
+ this.onload();
+ }).bind(this);
+
+ if (path.indexOf("data:") > -1) {
+ var offset = path.indexOf("base64,") + 7;
+ var data = atob(path.substring(offset));
+ var arr = new Uint8Array(data.length);
+ for (var i = data.length - 1; i >= 0; i--) {
+ arr[i] = data.charCodeAt(i);
+ }
+ handleData(data);
+ } else {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", path, true);
+ xhr.responseType = "arraybuffer";
+ xhr.onload = (function () {
+ // TODO catch parse error
+ var data = new Uint8Array(xhr.response);
+ handleData(data);
+ }).bind(this);
+ xhr.send(null);
+ }
+ },
+ parse: function parse(data) {
+
+ function readUint16() {
+ var value = (data[offset] << 8) | data[offset + 1];
+ offset += 2;
+ return value;
+ }
+
+ function readDataBlock() {
+ var length = readUint16();
+ var array = data.subarray(offset, offset + length - 2);
+ offset += array.length;
+ return array;
+ }
+
+ function prepareComponents(frame) {
+ var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / frame.maxH);
+ var mcusPerColumn = Math.ceil(frame.scanLines / 8 / frame.maxV);
+ for (var i = 0; i < frame.components.length; i++) {
+ component = frame.components[i];
+ var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / frame.maxH);
+ var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / frame.maxV);
+ var blocksPerLineForMcu = mcusPerLine * component.h;
+ var blocksPerColumnForMcu = mcusPerColumn * component.v;
+
+ var blocksBufferSize = 64 * blocksPerColumnForMcu * (blocksPerLineForMcu + 1);
+ component.blockData = new Int16Array(blocksBufferSize);
+ component.blocksPerLine = blocksPerLine;
+ component.blocksPerColumn = blocksPerColumn;
+ }
+ frame.mcusPerLine = mcusPerLine;
+ frame.mcusPerColumn = mcusPerColumn;
+ }
+
+ var offset = 0, length = data.length;
+ var jfif = null;
+ var adobe = null;
+ var pixels = null;
+ var frame, resetInterval;
+ var quantizationTables = [];
+ var huffmanTablesAC = [], huffmanTablesDC = [];
+ var fileMarker = readUint16();
+ if (fileMarker != 0xFFD8) { // SOI (Start of Image)
+ throw "SOI not found";
+ }
+
+ fileMarker = readUint16();
+ while (fileMarker != 0xFFD9) { // EOI (End of image)
+ var i, j, l;
+ switch (fileMarker) {
+ case 0xFFE0: // APP0 (Application Specific)
+ case 0xFFE1: // APP1
+ case 0xFFE2: // APP2
+ case 0xFFE3: // APP3
+ case 0xFFE4: // APP4
+ case 0xFFE5: // APP5
+ case 0xFFE6: // APP6
+ case 0xFFE7: // APP7
+ case 0xFFE8: // APP8
+ case 0xFFE9: // APP9
+ case 0xFFEA: // APP10
+ case 0xFFEB: // APP11
+ case 0xFFEC: // APP12
+ case 0xFFED: // APP13
+ case 0xFFEE: // APP14
+ case 0xFFEF: // APP15
+ case 0xFFFE: // COM (Comment)
+ var appData = readDataBlock();
+
+ if (fileMarker === 0xFFE0) {
+ if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&
+ appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
+ jfif = {
+ version: {major: appData[5], minor: appData[6]},
+ densityUnits: appData[7],
+ xDensity: (appData[8] << 8) | appData[9],
+ yDensity: (appData[10] << 8) | appData[11],
+ thumbWidth: appData[12],
+ thumbHeight: appData[13],
+ thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
+ };
+ }
+ }
+ // TODO APP1 - Exif
+ if (fileMarker === 0xFFEE) {
+ if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&
+ appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
+ adobe = {
+ version: appData[6],
+ flags0: (appData[7] << 8) | appData[8],
+ flags1: (appData[9] << 8) | appData[10],
+ transformCode: appData[11]
+ };
+ }
+ }
+ break;
+
+ case 0xFFDB: // DQT (Define Quantization Tables)
+ var quantizationTablesLength = readUint16();
+ var quantizationTablesEnd = quantizationTablesLength + offset - 2;
+ while (offset < quantizationTablesEnd) {
+ var quantizationTableSpec = data[offset++];
+ var tableData = new Int32Array(64);
+ if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
+ for (j = 0; j < 64; j++) {
+ var z = dctZigZag[j];
+ tableData[z] = data[offset++];
+ }
+ } else if ((quantizationTableSpec >> 4) === 1) { //16 bit
+ for (j = 0; j < 64; j++) {
+ var zz = dctZigZag[j];
+ tableData[zz] = readUint16();
+ }
+ } else
+ throw "DQT: invalid table spec";
+ quantizationTables[quantizationTableSpec & 15] = tableData;
+ }
+ break;
+
+ case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
+ case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
+ case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)
+ if (frame) {
+ throw "Only single frame JPEGs supported";
+ }
+ readUint16(); // skip data length
+ frame = {};
+ frame.extended = (fileMarker === 0xFFC1);
+ frame.progressive = (fileMarker === 0xFFC2);
+ frame.precision = data[offset++];
+ frame.scanLines = readUint16();
+ frame.samplesPerLine = readUint16();
+ frame.components = [];
+ frame.componentIds = {};
+ var componentsCount = data[offset++], componentId;
+ var maxH = 0, maxV = 0;
+ for (i = 0; i < componentsCount; i++) {
+ componentId = data[offset];
+ var h = data[offset + 1] >> 4;
+ var v = data[offset + 1] & 15;
+ if (maxH < h)
+ maxH = h;
+ if (maxV < v)
+ maxV = v;
+ var qId = data[offset + 2];
+ l = frame.components.push({
+ h: h,
+ v: v,
+ quantizationTable: quantizationTables[qId],
+ quantizationTableId: qId,
+ bitConversion: 255 / ((1 << frame.precision) - 1)
+ });
+ frame.componentIds[componentId] = l - 1;
+ offset += 3;
+ }
+ frame.maxH = maxH;
+ frame.maxV = maxV;
+ prepareComponents(frame);
+ break;
+
+ case 0xFFC4: // DHT (Define Huffman Tables)
+ var huffmanLength = readUint16();
+ for (i = 2; i < huffmanLength; ) {
+ var huffmanTableSpec = data[offset++];
+ var codeLengths = new Uint8Array(16);
+ var codeLengthSum = 0;
+ for (j = 0; j < 16; j++, offset++)
+ codeLengthSum += (codeLengths[j] = data[offset]);
+ var huffmanValues = new Uint8Array(codeLengthSum);
+ for (j = 0; j < codeLengthSum; j++, offset++)
+ huffmanValues[j] = data[offset];
+ i += 17 + codeLengthSum;
+
+ ((huffmanTableSpec >> 4) === 0 ?
+ huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =
+ buildHuffmanTable(codeLengths, huffmanValues);
+ }
+ break;
+
+ case 0xFFDD: // DRI (Define Restart Interval)
+ readUint16(); // skip data length
+ resetInterval = readUint16();
+ break;
+
+ case 0xFFDA: // SOS (Start of Scan)
+ var scanLength = readUint16();
+ var selectorsCount = data[offset++];
+ var components = [], component;
+ for (i = 0; i < selectorsCount; i++) {
+ var componentIndex = frame.componentIds[data[offset++]];
+ component = frame.components[componentIndex];
+ var tableSpec = data[offset++];
+ component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
+ component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
+ components.push(component);
+ }
+ var spectralStart = data[offset++];
+ var spectralEnd = data[offset++];
+ var successiveApproximation = data[offset++];
+ var processed = decodeScan(data, offset,
+ frame, components, resetInterval,
+ spectralStart, spectralEnd,
+ successiveApproximation >> 4, successiveApproximation & 15);
+ offset += processed;
+ break;
+ default:
+ if (data[offset - 3] == 0xFF &&
+ data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
+ // could be incorrect encoding -- last 0xFF byte of the previous
+ // block was eaten by the encoder
+ offset -= 3;
+ break;
+ }
+ throw "unknown JPEG marker " + fileMarker.toString(16);
+ }
+ fileMarker = readUint16();
+ }
+
+ this.width = frame.samplesPerLine;
+ this.height = frame.scanLines;
+ this.jfif = jfif;
+ this.adobe = adobe;
+ this.components = [];
+ switch (frame.components.length)
+ {
+ case 1:
+ this.colorspace = ColorSpace.Grayscale;
+ break;
+ case 3:
+ if (this.adobe)
+ this.colorspace = ColorSpace.AdobeRGB;
+ else
+ this.colorspace = ColorSpace.RGB;
+ break;
+ case 4:
+ this.colorspace = ColorSpace.CYMK;
+ break;
+ default:
+ this.colorspace = ColorSpace.Unknown;
+ }
+ for (var i = 0; i < frame.components.length; i++) {
+ var component = frame.components[i];
+ if (!component.quantizationTable && component.quantizationTableId !== null)
+ component.quantizationTable = quantizationTables[component.quantizationTableId];
+ this.components.push({
+ output: buildComponentData(frame, component),
+ scaleX: component.h / frame.maxH,
+ scaleY: component.v / frame.maxV,
+ blocksPerLine: component.blocksPerLine,
+ blocksPerColumn: component.blocksPerColumn,
+ bitConversion: component.bitConversion
+ });
+ }
+ },
+ getData16: function getData16(width, height) {
+ if (this.components.length !== 1)
+ throw 'Unsupported color mode';
+ var scaleX = this.width / width, scaleY = this.height / height;
+
+ var component, componentScaleX, componentScaleY;
+ var x, y, i;
+ var offset = 0;
+ var numComponents = this.components.length;
+ var dataLength = width * height * numComponents;
+ var data = new Uint16Array(dataLength);
+ var componentLine;
+
+ // lineData is reused for all components. Assume first component is
+ // the biggest
+ var lineData = new Uint16Array((this.components[0].blocksPerLine << 3) *
+ this.components[0].blocksPerColumn * 8);
+
+ // First construct image data ...
+ for (i = 0; i < numComponents; i++) {
+ component = this.components[i];
+ var blocksPerLine = component.blocksPerLine;
+ var blocksPerColumn = component.blocksPerColumn;
+ var samplesPerLine = blocksPerLine << 3;
+
+ var j, k, ll = 0;
+ var lineOffset = 0;
+ for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
+ var scanLine = blockRow << 3;
+ for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
+ var bufferOffset = getBlockBufferOffset(component, blockRow, blockCol);
+ var offset = 0, sample = blockCol << 3;
+ for (j = 0; j < 8; j++) {
+ var lineOffset = (scanLine + j) * samplesPerLine;
+ for (k = 0; k < 8; k++) {
+ lineData[lineOffset + sample + k] =
+ component.output[bufferOffset + offset++];
+ }
+ }
+ }
+ }
+
+ componentScaleX = component.scaleX * scaleX;
+ componentScaleY = component.scaleY * scaleY;
+ offset = i;
+
+ var cx, cy;
+ var index;
+ for (y = 0; y < height; y++) {
+ for (x = 0; x < width; x++) {
+ cy = 0 | (y * componentScaleY);
+ cx = 0 | (x * componentScaleX);
+ index = cy * samplesPerLine + cx;
+ data[offset] = lineData[index];
+ offset += numComponents;
+ }
+ }
+ }
+ return data;
+ },
+ getData: function getData(width, height) {
+ var scaleX = this.width / width, scaleY = this.height / height;
+
+ var component, componentScaleX, componentScaleY;
+ var x, y, i;
+ var offset = 0;
+ var Y, Cb, Cr, K, C, M, Ye, R, G, B;
+ var colorTransform;
+ var numComponents = this.components.length;
+ var dataLength = width * height * numComponents;
+ var data = new Uint8Array(dataLength);
+ var componentLine;
+
+ // lineData is reused for all components. Assume first component is
+ // the biggest
+ var lineData = new Uint8Array((this.components[0].blocksPerLine << 3) *
+ this.components[0].blocksPerColumn * 8);
+
+ // First construct image data ...
+ for (i = 0; i < numComponents; i++) {
+ component = this.components[i];
+ var blocksPerLine = component.blocksPerLine;
+ var blocksPerColumn = component.blocksPerColumn;
+ var samplesPerLine = blocksPerLine << 3;
+
+ var j, k, ll = 0;
+ var lineOffset = 0;
+ for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
+ var scanLine = blockRow << 3;
+ for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
+ var bufferOffset = getBlockBufferOffset(component, blockRow, blockCol);
+ var offset = 0, sample = blockCol << 3;
+ for (j = 0; j < 8; j++) {
+ var lineOffset = (scanLine + j) * samplesPerLine;
+ for (k = 0; k < 8; k++) {
+ lineData[lineOffset + sample + k] =
+ component.output[bufferOffset + offset++] * component.bitConversion;
+ }
+ }
+ }
+ }
+
+ componentScaleX = component.scaleX * scaleX;
+ componentScaleY = component.scaleY * scaleY;
+ offset = i;
+
+ var cx, cy;
+ var index;
+ for (y = 0; y < height; y++) {
+ for (x = 0; x < width; x++) {
+ cy = 0 | (y * componentScaleY);
+ cx = 0 | (x * componentScaleX);
+ index = cy * samplesPerLine + cx;
+ data[offset] = lineData[index];
+ offset += numComponents;
+ }
+ }
+ }
+
+ // ... then transform colors, if necessary
+ switch (numComponents) {
+ case 1:
+ case 2:
+ break;
+ // no color conversion for one or two compoenents
+
+ case 3:
+ // The default transform for three components is true
+ colorTransform = true;
+ // The adobe transform marker overrides any previous setting
+ if (this.adobe && this.adobe.transformCode)
+ colorTransform = true;
+ else if (typeof this.colorTransform !== 'undefined')
+ colorTransform = !!this.colorTransform;
+
+ if (colorTransform) {
+ for (i = 0; i < dataLength; i += numComponents) {
+ Y = data[i ];
+ Cb = data[i + 1];
+ Cr = data[i + 2];
+
+ R = clampToUint8(Y - 179.456 + 1.402 * Cr);
+ G = clampToUint8(Y + 135.459 - 0.344 * Cb - 0.714 * Cr);
+ B = clampToUint8(Y - 226.816 + 1.772 * Cb);
+
+ data[i ] = R;
+ data[i + 1] = G;
+ data[i + 2] = B;
+ }
+ }
+ break;
+ case 4:
+ if (!this.adobe)
+ throw 'Unsupported color mode (4 components)';
+ // The default transform for four components is false
+ colorTransform = false;
+ // The adobe transform marker overrides any previous setting
+ if (this.adobe && this.adobe.transformCode)
+ colorTransform = true;
+ else if (typeof this.colorTransform !== 'undefined')
+ colorTransform = !!this.colorTransform;
+
+ if (colorTransform) {
+ for (i = 0; i < dataLength; i += numComponents) {
+ Y = data[i];
+ Cb = data[i + 1];
+ Cr = data[i + 2];
+
+ C = clampToUint8(434.456 - Y - 1.402 * Cr);
+ M = clampToUint8(119.541 - Y + 0.344 * Cb + 0.714 * Cr);
+ Y = clampToUint8(481.816 - Y - 1.772 * Cb);
+
+ data[i ] = C;
+ data[i + 1] = M;
+ data[i + 2] = Y;
+ // K is unchanged
+ }
+ }
+ break;
+ default:
+ throw 'Unsupported color mode';
+ }
+ return data;
+ }
+ };
+
+ return constructor;
+})();
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = JpegImage;
+}
+},{}],2:[function(require,module,exports){
+/*! image-JPEG2000 - v0.3.1 - 2015-08-26 | https://github.com/OHIF/image-JPEG2000 */
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
+/* Copyright 2012 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/* globals ArithmeticDecoder, globalScope, log2, readUint16, readUint32,
+ info, warn */
+
+'use strict';
+
+var JpxImage = (function JpxImageClosure() {
+ // Table E.1
+ var SubbandsGainLog2 = {
+ 'LL': 0,
+ 'LH': 1,
+ 'HL': 1,
+ 'HH': 2
+ };
+ function JpxImage() {
+ this.failOnCorruptedImage = false;
+ }
+ JpxImage.prototype = {
+ parse: function JpxImage_parse(data) {
+
+ var head = readUint16(data, 0);
+ // No box header, immediate start of codestream (SOC)
+ if (head === 0xFF4F) {
+ this.parseCodestream(data, 0, data.length);
+ return;
+ }
+
+ var position = 0, length = data.length;
+ while (position < length) {
+ var headerSize = 8;
+ var lbox = readUint32(data, position);
+ var tbox = readUint32(data, position + 4);
+ position += headerSize;
+ if (lbox === 1) {
+ // XLBox: read UInt64 according to spec.
+ // JavaScript's int precision of 53 bit should be sufficient here.
+ lbox = readUint32(data, position) * 4294967296 +
+ readUint32(data, position + 4);
+ position += 8;
+ headerSize += 8;
+ }
+ if (lbox === 0) {
+ lbox = length - position + headerSize;
+ }
+ if (lbox < headerSize) {
+ throw new Error('JPX Error: Invalid box field size');
+ }
+ var dataLength = lbox - headerSize;
+ var jumpDataLength = true;
+ switch (tbox) {
+ case 0x6A703268: // 'jp2h'
+ jumpDataLength = false; // parsing child boxes
+ break;
+ case 0x636F6C72: // 'colr'
+ // Colorspaces are not used, the CS from the PDF is used.
+ var method = data[position];
+ var precedence = data[position + 1];
+ var approximation = data[position + 2];
+ if (method === 1) {
+ // enumerated colorspace
+ var colorspace = readUint32(data, position + 3);
+ switch (colorspace) {
+ case 16: // this indicates a sRGB colorspace
+ case 17: // this indicates a grayscale colorspace
+ case 18: // this indicates a YUV colorspace
+ break;
+ default:
+ warn('Unknown colorspace ' + colorspace);
+ break;
+ }
+ } else if (method === 2) {
+ info('ICC profile not supported');
+ }
+ break;
+ case 0x6A703263: // 'jp2c'
+ this.parseCodestream(data, position, position + dataLength);
+ break;
+ case 0x6A502020: // 'jP\024\024'
+ if (0x0d0a870a !== readUint32(data, position)) {
+ warn('Invalid JP2 signature');
+ }
+ break;
+ // The following header types are valid but currently not used:
+ case 0x6A501A1A: // 'jP\032\032'
+ case 0x66747970: // 'ftyp'
+ case 0x72726571: // 'rreq'
+ case 0x72657320: // 'res '
+ case 0x69686472: // 'ihdr'
+ break;
+ default:
+ var headerType = String.fromCharCode((tbox >> 24) & 0xFF,
+ (tbox >> 16) & 0xFF,
+ (tbox >> 8) & 0xFF,
+ tbox & 0xFF);
+ warn('Unsupported header type ' + tbox + ' (' + headerType + ')');
+ break;
+ }
+ if (jumpDataLength) {
+ position += dataLength;
+ }
+ }
+ },
+ parseImageProperties: function JpxImage_parseImageProperties(stream) {
+ var newByte = stream.getByte();
+ while (newByte >= 0) {
+ var oldByte = newByte;
+ newByte = stream.getByte();
+ var code = (oldByte << 8) | newByte;
+ // Image and tile size (SIZ)
+ if (code === 0xFF51) {
+ stream.skip(4);
+ var Xsiz = stream.getInt32() >>> 0; // Byte 4
+ var Ysiz = stream.getInt32() >>> 0; // Byte 8
+ var XOsiz = stream.getInt32() >>> 0; // Byte 12
+ var YOsiz = stream.getInt32() >>> 0; // Byte 16
+ stream.skip(16);
+ var Csiz = stream.getUint16(); // Byte 36
+ this.width = Xsiz - XOsiz;
+ this.height = Ysiz - YOsiz;
+ this.componentsCount = Csiz;
+ // Results are always returned as Uint8Arrays
+ this.bitsPerComponent = 8;
+ return;
+ }
+ }
+ throw new Error('JPX Error: No size marker found in JPX stream');
+ },
+ parseCodestream: function JpxImage_parseCodestream(data, start, end) {
+ var context = {};
+ try {
+ var doNotRecover = false;
+ var position = start;
+ while (position + 1 < end) {
+ var code = readUint16(data, position);
+ position += 2;
+
+ var length = 0, j, sqcd, spqcds, spqcdSize, scalarExpounded, tile;
+ switch (code) {
+ case 0xFF4F: // Start of codestream (SOC)
+ context.mainHeader = true;
+ break;
+ case 0xFFD9: // End of codestream (EOC)
+ break;
+ case 0xFF51: // Image and tile size (SIZ)
+ length = readUint16(data, position);
+ var siz = {};
+ siz.Xsiz = readUint32(data, position + 4);
+ siz.Ysiz = readUint32(data, position + 8);
+ siz.XOsiz = readUint32(data, position + 12);
+ siz.YOsiz = readUint32(data, position + 16);
+ siz.XTsiz = readUint32(data, position + 20);
+ siz.YTsiz = readUint32(data, position + 24);
+ siz.XTOsiz = readUint32(data, position + 28);
+ siz.YTOsiz = readUint32(data, position + 32);
+ var componentsCount = readUint16(data, position + 36);
+ siz.Csiz = componentsCount;
+ var components = [];
+ j = position + 38;
+ for (var i = 0; i < componentsCount; i++) {
+ var component = {
+ precision: (data[j] & 0x7F) + 1,
+ isSigned: !!(data[j] & 0x80),
+ XRsiz: data[j + 1],
+ YRsiz: data[j + 1]
+ };
+ calculateComponentDimensions(component, siz);
+ components.push(component);
+ }
+ context.SIZ = siz;
+ context.components = components;
+ calculateTileGrids(context, components);
+ context.QCC = [];
+ context.COC = [];
+ break;
+ case 0xFF5C: // Quantization default (QCD)
+ length = readUint16(data, position);
+ var qcd = {};
+ j = position + 2;
+ sqcd = data[j++];
+ switch (sqcd & 0x1F) {
+ case 0:
+ spqcdSize = 8;
+ scalarExpounded = true;
+ break;
+ case 1:
+ spqcdSize = 16;
+ scalarExpounded = false;
+ break;
+ case 2:
+ spqcdSize = 16;
+ scalarExpounded = true;
+ break;
+ default:
+ throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
+ }
+ qcd.noQuantization = (spqcdSize === 8);
+ qcd.scalarExpounded = scalarExpounded;
+ qcd.guardBits = sqcd >> 5;
+ spqcds = [];
+ while (j < length + position) {
+ var spqcd = {};
+ if (spqcdSize === 8) {
+ spqcd.epsilon = data[j++] >> 3;
+ spqcd.mu = 0;
+ } else {
+ spqcd.epsilon = data[j] >> 3;
+ spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
+ j += 2;
+ }
+ spqcds.push(spqcd);
+ }
+ qcd.SPqcds = spqcds;
+ if (context.mainHeader) {
+ context.QCD = qcd;
+ } else {
+ context.currentTile.QCD = qcd;
+ context.currentTile.QCC = [];
+ }
+ break;
+ case 0xFF5D: // Quantization component (QCC)
+ length = readUint16(data, position);
+ var qcc = {};
+ j = position + 2;
+ var cqcc;
+ if (context.SIZ.Csiz < 257) {
+ cqcc = data[j++];
+ } else {
+ cqcc = readUint16(data, j);
+ j += 2;
+ }
+ sqcd = data[j++];
+ switch (sqcd & 0x1F) {
+ case 0:
+ spqcdSize = 8;
+ scalarExpounded = true;
+ break;
+ case 1:
+ spqcdSize = 16;
+ scalarExpounded = false;
+ break;
+ case 2:
+ spqcdSize = 16;
+ scalarExpounded = true;
+ break;
+ default:
+ throw new Error('JPX Error: Invalid SQcd value ' + sqcd);
+ }
+ qcc.noQuantization = (spqcdSize === 8);
+ qcc.scalarExpounded = scalarExpounded;
+ qcc.guardBits = sqcd >> 5;
+ spqcds = [];
+ while (j < (length + position)) {
+ spqcd = {};
+ if (spqcdSize === 8) {
+ spqcd.epsilon = data[j++] >> 3;
+ spqcd.mu = 0;
+ } else {
+ spqcd.epsilon = data[j] >> 3;
+ spqcd.mu = ((data[j] & 0x7) << 8) | data[j + 1];
+ j += 2;
+ }
+ spqcds.push(spqcd);
+ }
+ qcc.SPqcds = spqcds;
+ if (context.mainHeader) {
+ context.QCC[cqcc] = qcc;
+ } else {
+ context.currentTile.QCC[cqcc] = qcc;
+ }
+ break;
+ case 0xFF52: // Coding style default (COD)
+ length = readUint16(data, position);
+ var cod = {};
+ j = position + 2;
+ var scod = data[j++];
+ cod.entropyCoderWithCustomPrecincts = !!(scod & 1);
+ cod.sopMarkerUsed = !!(scod & 2);
+ cod.ephMarkerUsed = !!(scod & 4);
+ cod.progressionOrder = data[j++];
+ cod.layersCount = readUint16(data, j);
+ j += 2;
+ cod.multipleComponentTransform = data[j++];
+
+ cod.decompositionLevelsCount = data[j++];
+ cod.xcb = (data[j++] & 0xF) + 2;
+ cod.ycb = (data[j++] & 0xF) + 2;
+ var blockStyle = data[j++];
+ cod.selectiveArithmeticCodingBypass = !!(blockStyle & 1);
+ cod.resetContextProbabilities = !!(blockStyle & 2);
+ cod.terminationOnEachCodingPass = !!(blockStyle & 4);
+ cod.verticalyStripe = !!(blockStyle & 8);
+ cod.predictableTermination = !!(blockStyle & 16);
+ cod.segmentationSymbolUsed = !!(blockStyle & 32);
+ cod.reversibleTransformation = data[j++];
+ if (cod.entropyCoderWithCustomPrecincts) {
+ var precinctsSizes = [];
+ while (j < length + position) {
+ var precinctsSize = data[j++];
+ precinctsSizes.push({
+ PPx: precinctsSize & 0xF,
+ PPy: precinctsSize >> 4
+ });
+ }
+ cod.precinctsSizes = precinctsSizes;
+ }
+ var unsupported = [];
+ if (cod.selectiveArithmeticCodingBypass) {
+ unsupported.push('selectiveArithmeticCodingBypass');
+ }
+ if (cod.resetContextProbabilities) {
+ unsupported.push('resetContextProbabilities');
+ }
+ if (cod.terminationOnEachCodingPass) {
+ unsupported.push('terminationOnEachCodingPass');
+ }
+ if (cod.verticalyStripe) {
+ unsupported.push('verticalyStripe');
+ }
+ if (cod.predictableTermination) {
+ unsupported.push('predictableTermination');
+ }
+ if (unsupported.length > 0) {
+ doNotRecover = true;
+ throw new Error('JPX Error: Unsupported COD options (' +
+ unsupported.join(', ') + ')');
+ }
+ if (context.mainHeader) {
+ context.COD = cod;
+ } else {
+ context.currentTile.COD = cod;
+ context.currentTile.COC = [];
+ }
+ break;
+ case 0xFF90: // Start of tile-part (SOT)
+ length = readUint16(data, position);
+ tile = {};
+ tile.index = readUint16(data, position + 2);
+ tile.length = readUint32(data, position + 4);
+ tile.dataEnd = tile.length + position - 2;
+ tile.partIndex = data[position + 8];
+ tile.partsCount = data[position + 9];
+
+ context.mainHeader = false;
+ if (tile.partIndex === 0) {
+ // reset component specific settings
+ tile.COD = context.COD;
+ tile.COC = context.COC.slice(0); // clone of the global COC
+ tile.QCD = context.QCD;
+ tile.QCC = context.QCC.slice(0); // clone of the global COC
+ }
+ context.currentTile = tile;
+ break;
+ case 0xFF93: // Start of data (SOD)
+ tile = context.currentTile;
+ if (tile.partIndex === 0) {
+ initializeTile(context, tile.index);
+ buildPackets(context);
+ }
+
+ // moving to the end of the data
+ length = tile.dataEnd - position;
+ parseTilePackets(context, data, position, length);
+ break;
+ case 0xFF55: // Tile-part lengths, main header (TLM)
+ case 0xFF57: // Packet length, main header (PLM)
+ case 0xFF58: // Packet length, tile-part header (PLT)
+ case 0xFF64: // Comment (COM)
+ length = readUint16(data, position);
+ // skipping content
+ break;
+ case 0xFF53: // Coding style component (COC)
+ throw new Error('JPX Error: Codestream code 0xFF53 (COC) is ' +
+ 'not implemented');
+ default:
+ throw new Error('JPX Error: Unknown codestream code: ' +
+ code.toString(16));
+ }
+ position += length;
+ }
+ } catch (e) {
+ if (doNotRecover || this.failOnCorruptedImage) {
+ throw e;
+ } else {
+ warn('Trying to recover from ' + e.message);
+ }
+ }
+ this.tiles = transformComponents(context);
+ this.width = context.SIZ.Xsiz - context.SIZ.XOsiz;
+ this.height = context.SIZ.Ysiz - context.SIZ.YOsiz;
+ this.componentsCount = context.SIZ.Csiz;
+ }
+ };
+ function calculateComponentDimensions(component, siz) {
+ // Section B.2 Component mapping
+ component.x0 = Math.ceil(siz.XOsiz / component.XRsiz);
+ component.x1 = Math.ceil(siz.Xsiz / component.XRsiz);
+ component.y0 = Math.ceil(siz.YOsiz / component.YRsiz);
+ component.y1 = Math.ceil(siz.Ysiz / component.YRsiz);
+ component.width = component.x1 - component.x0;
+ component.height = component.y1 - component.y0;
+ }
+ function calculateTileGrids(context, components) {
+ var siz = context.SIZ;
+ // Section B.3 Division into tile and tile-components
+ var tile, tiles = [];
+ var numXtiles = Math.ceil((siz.Xsiz - siz.XTOsiz) / siz.XTsiz);
+ var numYtiles = Math.ceil((siz.Ysiz - siz.YTOsiz) / siz.YTsiz);
+ for (var q = 0; q < numYtiles; q++) {
+ for (var p = 0; p < numXtiles; p++) {
+ tile = {};
+ tile.tx0 = Math.max(siz.XTOsiz + p * siz.XTsiz, siz.XOsiz);
+ tile.ty0 = Math.max(siz.YTOsiz + q * siz.YTsiz, siz.YOsiz);
+ tile.tx1 = Math.min(siz.XTOsiz + (p + 1) * siz.XTsiz, siz.Xsiz);
+ tile.ty1 = Math.min(siz.YTOsiz + (q + 1) * siz.YTsiz, siz.Ysiz);
+ tile.width = tile.tx1 - tile.tx0;
+ tile.height = tile.ty1 - tile.ty0;
+ tile.components = [];
+ tiles.push(tile);
+ }
+ }
+ context.tiles = tiles;
+
+ var componentsCount = siz.Csiz;
+ for (var i = 0, ii = componentsCount; i < ii; i++) {
+ var component = components[i];
+ for (var j = 0, jj = tiles.length; j < jj; j++) {
+ var tileComponent = {};
+ tile = tiles[j];
+ tileComponent.tcx0 = Math.ceil(tile.tx0 / component.XRsiz);
+ tileComponent.tcy0 = Math.ceil(tile.ty0 / component.YRsiz);
+ tileComponent.tcx1 = Math.ceil(tile.tx1 / component.XRsiz);
+ tileComponent.tcy1 = Math.ceil(tile.ty1 / component.YRsiz);
+ tileComponent.width = tileComponent.tcx1 - tileComponent.tcx0;
+ tileComponent.height = tileComponent.tcy1 - tileComponent.tcy0;
+ tile.components[i] = tileComponent;
+ }
+ }
+ }
+ function getBlocksDimensions(context, component, r) {
+ var codOrCoc = component.codingStyleParameters;
+ var result = {};
+ if (!codOrCoc.entropyCoderWithCustomPrecincts) {
+ result.PPx = 15;
+ result.PPy = 15;
+ } else {
+ result.PPx = codOrCoc.precinctsSizes[r].PPx;
+ result.PPy = codOrCoc.precinctsSizes[r].PPy;
+ }
+ // calculate codeblock size as described in section B.7
+ result.xcb_ = (r > 0 ? Math.min(codOrCoc.xcb, result.PPx - 1) :
+ Math.min(codOrCoc.xcb, result.PPx));
+ result.ycb_ = (r > 0 ? Math.min(codOrCoc.ycb, result.PPy - 1) :
+ Math.min(codOrCoc.ycb, result.PPy));
+ return result;
+ }
+ function buildPrecincts(context, resolution, dimensions) {
+ // Section B.6 Division resolution to precincts
+ var precinctWidth = 1 << dimensions.PPx;
+ var precinctHeight = 1 << dimensions.PPy;
+ // Jasper introduces codeblock groups for mapping each subband codeblocks
+ // to precincts. Precinct partition divides a resolution according to width
+ // and height parameters. The subband that belongs to the resolution level
+ // has a different size than the level, unless it is the zero resolution.
+
+ // From Jasper documentation: jpeg2000.pdf, section K: Tier-2 coding:
+ // The precinct partitioning for a particular subband is derived from a
+ // partitioning of its parent LL band (i.e., the LL band at the next higher
+ // resolution level)... The LL band associated with each resolution level is
+ // divided into precincts... Each of the resulting precinct regions is then
+ // mapped into its child subbands (if any) at the next lower resolution
+ // level. This is accomplished by using the coordinate transformation
+ // (u, v) = (ceil(x/2), ceil(y/2)) where (x, y) and (u, v) are the
+ // coordinates of a point in the LL band and child subband, respectively.
+ var isZeroRes = resolution.resLevel === 0;
+ var precinctWidthInSubband = 1 << (dimensions.PPx + (isZeroRes ? 0 : -1));
+ var precinctHeightInSubband = 1 << (dimensions.PPy + (isZeroRes ? 0 : -1));
+ var numprecinctswide = (resolution.trx1 > resolution.trx0 ?
+ Math.ceil(resolution.trx1 / precinctWidth) -
+ Math.floor(resolution.trx0 / precinctWidth) : 0);
+ var numprecinctshigh = (resolution.try1 > resolution.try0 ?
+ Math.ceil(resolution.try1 / precinctHeight) -
+ Math.floor(resolution.try0 / precinctHeight) : 0);
+ var numprecincts = numprecinctswide * numprecinctshigh;
+
+ resolution.precinctParameters = {
+ precinctWidth: precinctWidth,
+ precinctHeight: precinctHeight,
+ numprecinctswide: numprecinctswide,
+ numprecinctshigh: numprecinctshigh,
+ numprecincts: numprecincts,
+ precinctWidthInSubband: precinctWidthInSubband,
+ precinctHeightInSubband: precinctHeightInSubband
+ };
+ }
+ function buildCodeblocks(context, subband, dimensions) {
+ // Section B.7 Division sub-band into code-blocks
+ var xcb_ = dimensions.xcb_;
+ var ycb_ = dimensions.ycb_;
+ var codeblockWidth = 1 << xcb_;
+ var codeblockHeight = 1 << ycb_;
+ var cbx0 = subband.tbx0 >> xcb_;
+ var cby0 = subband.tby0 >> ycb_;
+ var cbx1 = (subband.tbx1 + codeblockWidth - 1) >> xcb_;
+ var cby1 = (subband.tby1 + codeblockHeight - 1) >> ycb_;
+ var precinctParameters = subband.resolution.precinctParameters;
+ var codeblocks = [];
+ var precincts = [];
+ var i, j, codeblock, precinctNumber;
+ for (j = cby0; j < cby1; j++) {
+ for (i = cbx0; i < cbx1; i++) {
+ codeblock = {
+ cbx: i,
+ cby: j,
+ tbx0: codeblockWidth * i,
+ tby0: codeblockHeight * j,
+ tbx1: codeblockWidth * (i + 1),
+ tby1: codeblockHeight * (j + 1)
+ };
+
+ codeblock.tbx0_ = Math.max(subband.tbx0, codeblock.tbx0);
+ codeblock.tby0_ = Math.max(subband.tby0, codeblock.tby0);
+ codeblock.tbx1_ = Math.min(subband.tbx1, codeblock.tbx1);
+ codeblock.tby1_ = Math.min(subband.tby1, codeblock.tby1);
+
+ // Calculate precinct number for this codeblock, codeblock position
+ // should be relative to its subband, use actual dimension and position
+ // See comment about codeblock group width and height
+ var pi = Math.floor((codeblock.tbx0_ - subband.tbx0) /
+ precinctParameters.precinctWidthInSubband);
+ var pj = Math.floor((codeblock.tby0_ - subband.tby0) /
+ precinctParameters.precinctHeightInSubband);
+ precinctNumber = pi + (pj * precinctParameters.numprecinctswide);
+
+ codeblock.precinctNumber = precinctNumber;
+ codeblock.subbandType = subband.type;
+ codeblock.Lblock = 3;
+
+ if (codeblock.tbx1_ <= codeblock.tbx0_ ||
+ codeblock.tby1_ <= codeblock.tby0_) {
+ continue;
+ }
+ codeblocks.push(codeblock);
+ // building precinct for the sub-band
+ var precinct = precincts[precinctNumber];
+ if (precinct !== undefined) {
+ if (i < precinct.cbxMin) {
+ precinct.cbxMin = i;
+ } else if (i > precinct.cbxMax) {
+ precinct.cbxMax = i;
+ }
+ if (j < precinct.cbyMin) {
+ precinct.cbxMin = j;
+ } else if (j > precinct.cbyMax) {
+ precinct.cbyMax = j;
+ }
+ } else {
+ precincts[precinctNumber] = precinct = {
+ cbxMin: i,
+ cbyMin: j,
+ cbxMax: i,
+ cbyMax: j
+ };
+ }
+ codeblock.precinct = precinct;
+ }
+ }
+ subband.codeblockParameters = {
+ codeblockWidth: xcb_,
+ codeblockHeight: ycb_,
+ numcodeblockwide: cbx1 - cbx0 + 1,
+ numcodeblockhigh: cby1 - cby0 + 1
+ };
+ subband.codeblocks = codeblocks;
+ subband.precincts = precincts;
+ }
+ function createPacket(resolution, precinctNumber, layerNumber) {
+ var precinctCodeblocks = [];
+ // Section B.10.8 Order of info in packet
+ var subbands = resolution.subbands;
+ // sub-bands already ordered in 'LL', 'HL', 'LH', and 'HH' sequence
+ for (var i = 0, ii = subbands.length; i < ii; i++) {
+ var subband = subbands[i];
+ var codeblocks = subband.codeblocks;
+ for (var j = 0, jj = codeblocks.length; j < jj; j++) {
+ var codeblock = codeblocks[j];
+ if (codeblock.precinctNumber !== precinctNumber) {
+ continue;
+ }
+ precinctCodeblocks.push(codeblock);
+ }
+ }
+ return {
+ layerNumber: layerNumber,
+ codeblocks: precinctCodeblocks
+ };
+ }
+ function LayerResolutionComponentPositionIterator(context) {
+ var siz = context.SIZ;
+ var tileIndex = context.currentTile.index;
+ var tile = context.tiles[tileIndex];
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
+ var componentsCount = siz.Csiz;
+ var maxDecompositionLevelsCount = 0;
+ for (var q = 0; q < componentsCount; q++) {
+ maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
+ tile.components[q].codingStyleParameters.decompositionLevelsCount);
+ }
+
+ var l = 0, r = 0, i = 0, k = 0;
+
+ this.nextPacket = function JpxImage_nextPacket() {
+ // Section B.12.1.1 Layer-resolution-component-position
+ for (; l < layersCount; l++) {
+ for (; r <= maxDecompositionLevelsCount; r++) {
+ for (; i < componentsCount; i++) {
+ var component = tile.components[i];
+ if (r > component.codingStyleParameters.decompositionLevelsCount) {
+ continue;
+ }
+
+ var resolution = component.resolutions[r];
+ var numprecincts = resolution.precinctParameters.numprecincts;
+ for (; k < numprecincts;) {
+ var packet = createPacket(resolution, k, l);
+ k++;
+ return packet;
+ }
+ k = 0;
+ }
+ i = 0;
+ }
+ r = 0;
+ }
+ };
+ }
+ function ResolutionLayerComponentPositionIterator(context) {
+ var siz = context.SIZ;
+ var tileIndex = context.currentTile.index;
+ var tile = context.tiles[tileIndex];
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
+ var componentsCount = siz.Csiz;
+ var maxDecompositionLevelsCount = 0;
+ for (var q = 0; q < componentsCount; q++) {
+ maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
+ tile.components[q].codingStyleParameters.decompositionLevelsCount);
+ }
+
+ var r = 0, l = 0, i = 0, k = 0;
+
+ this.nextPacket = function JpxImage_nextPacket() {
+ // Section B.12.1.2 Resolution-layer-component-position
+ for (; r <= maxDecompositionLevelsCount; r++) {
+ for (; l < layersCount; l++) {
+ for (; i < componentsCount; i++) {
+ var component = tile.components[i];
+ if (r > component.codingStyleParameters.decompositionLevelsCount) {
+ continue;
+ }
+
+ var resolution = component.resolutions[r];
+ var numprecincts = resolution.precinctParameters.numprecincts;
+ for (; k < numprecincts;) {
+ var packet = createPacket(resolution, k, l);
+ k++;
+ return packet;
+ }
+ k = 0;
+ }
+ i = 0;
+ }
+ l = 0;
+ }
+ };
+ }
+ function ResolutionPositionComponentLayerIterator(context) {
+ var siz = context.SIZ;
+ var tileIndex = context.currentTile.index;
+ var tile = context.tiles[tileIndex];
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
+ var componentsCount = siz.Csiz;
+ var l, r, c, p;
+ var maxDecompositionLevelsCount = 0;
+ for (c = 0; c < componentsCount; c++) {
+ var component = tile.components[c];
+ maxDecompositionLevelsCount = Math.max(maxDecompositionLevelsCount,
+ component.codingStyleParameters.decompositionLevelsCount);
+ }
+ var maxNumPrecinctsInLevel = new Int32Array(
+ maxDecompositionLevelsCount + 1);
+ for (r = 0; r <= maxDecompositionLevelsCount; ++r) {
+ var maxNumPrecincts = 0;
+ for (c = 0; c < componentsCount; ++c) {
+ var resolutions = tile.components[c].resolutions;
+ if (r < resolutions.length) {
+ maxNumPrecincts = Math.max(maxNumPrecincts,
+ resolutions[r].precinctParameters.numprecincts);
+ }
+ }
+ maxNumPrecinctsInLevel[r] = maxNumPrecincts;
+ }
+ l = 0;
+ r = 0;
+ c = 0;
+ p = 0;
+
+ this.nextPacket = function JpxImage_nextPacket() {
+ // Section B.12.1.3 Resolution-position-component-layer
+ for (; r <= maxDecompositionLevelsCount; r++) {
+ for (; p < maxNumPrecinctsInLevel[r]; p++) {
+ for (; c < componentsCount; c++) {
+ var component = tile.components[c];
+ if (r > component.codingStyleParameters.decompositionLevelsCount) {
+ continue;
+ }
+ var resolution = component.resolutions[r];
+ var numprecincts = resolution.precinctParameters.numprecincts;
+ if (p >= numprecincts) {
+ continue;
+ }
+ for (; l < layersCount;) {
+ var packet = createPacket(resolution, p, l);
+ l++;
+ return packet;
+ }
+ l = 0;
+ }
+ c = 0;
+ }
+ p = 0;
+ }
+ };
+ }
+ function PositionComponentResolutionLayerIterator(context) {
+ var siz = context.SIZ;
+ var tileIndex = context.currentTile.index;
+ var tile = context.tiles[tileIndex];
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
+ var componentsCount = siz.Csiz;
+ var precinctsSizes = getPrecinctSizesInImageScale(tile);
+ var precinctsIterationSizes = precinctsSizes;
+ var l = 0, r = 0, c = 0, px = 0, py = 0;
+
+ this.nextPacket = function JpxImage_nextPacket() {
+ // Section B.12.1.4 Position-component-resolution-layer
+ for (; py < precinctsIterationSizes.maxNumHigh; py++) {
+ for (; px < precinctsIterationSizes.maxNumWide; px++) {
+ for (; c < componentsCount; c++) {
+ var component = tile.components[c];
+ var decompositionLevelsCount =
+ component.codingStyleParameters.decompositionLevelsCount;
+ for (; r <= decompositionLevelsCount; r++) {
+ var resolution = component.resolutions[r];
+ var sizeInImageScale =
+ precinctsSizes.components[c].resolutions[r];
+ var k = getPrecinctIndexIfExist(
+ px,
+ py,
+ sizeInImageScale,
+ precinctsIterationSizes,
+ resolution);
+ if (k === null) {
+ continue;
+ }
+ for (; l < layersCount;) {
+ var packet = createPacket(resolution, k, l);
+ l++;
+ return packet;
+ }
+ l = 0;
+ }
+ r = 0;
+ }
+ c = 0;
+ }
+ px = 0;
+ }
+ };
+ }
+ function ComponentPositionResolutionLayerIterator(context) {
+ var siz = context.SIZ;
+ var tileIndex = context.currentTile.index;
+ var tile = context.tiles[tileIndex];
+ var layersCount = tile.codingStyleDefaultParameters.layersCount;
+ var componentsCount = siz.Csiz;
+ var precinctsSizes = getPrecinctSizesInImageScale(tile);
+ var l = 0, r = 0, c = 0, px = 0, py = 0;
+
+ this.nextPacket = function JpxImage_nextPacket() {
+ // Section B.12.1.5 Component-position-resolution-layer
+ for (; c < componentsCount; ++c) {
+ var component = tile.components[c];
+ var precinctsIterationSizes = precinctsSizes.components[c];
+ var decompositionLevelsCount =
+ component.codingStyleParameters.decompositionLevelsCount;
+ for (; py < precinctsIterationSizes.maxNumHigh; py++) {
+ for (; px < precinctsIterationSizes.maxNumWide; px++) {
+ for (; r <= decompositionLevelsCount; r++) {
+ var resolution = component.resolutions[r];
+ var sizeInImageScale = precinctsIterationSizes.resolutions[r];
+ var k = getPrecinctIndexIfExist(
+ px,
+ py,
+ sizeInImageScale,
+ precinctsIterationSizes,
+ resolution);
+ if (k === null) {
+ continue;
+ }
+ for (; l < layersCount;) {
+ var packet = createPacket(resolution, k, l);
+ l++;
+ return packet;
+ }
+ l = 0;
+ }
+ r = 0;
+ }
+ px = 0;
+ }
+ py = 0;
+ }
+ };
+ }
+ function getPrecinctIndexIfExist(
+ pxIndex, pyIndex, sizeInImageScale, precinctIterationSizes, resolution) {
+ var posX = pxIndex * precinctIterationSizes.minWidth;
+ var posY = pyIndex * precinctIterationSizes.minHeight;
+ if (posX % sizeInImageScale.width !== 0 ||
+ posY % sizeInImageScale.height !== 0) {
+ return null;
+ }
+ var startPrecinctRowIndex =
+ (posY / sizeInImageScale.width) *
+ resolution.precinctParameters.numprecinctswide;
+ return (posX / sizeInImageScale.height) + startPrecinctRowIndex;
+ }
+ function getPrecinctSizesInImageScale(tile) {
+ var componentsCount = tile.components.length;
+ var minWidth = Number.MAX_VALUE;
+ var minHeight = Number.MAX_VALUE;
+ var maxNumWide = 0;
+ var maxNumHigh = 0;
+ var sizePerComponent = new Array(componentsCount);
+ for (var c = 0; c < componentsCount; c++) {
+ var component = tile.components[c];
+ var decompositionLevelsCount =
+ component.codingStyleParameters.decompositionLevelsCount;
+ var sizePerResolution = new Array(decompositionLevelsCount + 1);
+ var minWidthCurrentComponent = Number.MAX_VALUE;
+ var minHeightCurrentComponent = Number.MAX_VALUE;
+ var maxNumWideCurrentComponent = 0;
+ var maxNumHighCurrentComponent = 0;
+ var scale = 1;
+ for (var r = decompositionLevelsCount; r >= 0; --r) {
+ var resolution = component.resolutions[r];
+ var widthCurrentResolution =
+ scale * resolution.precinctParameters.precinctWidth;
+ var heightCurrentResolution =
+ scale * resolution.precinctParameters.precinctHeight;
+ minWidthCurrentComponent = Math.min(
+ minWidthCurrentComponent,
+ widthCurrentResolution);
+ minHeightCurrentComponent = Math.min(
+ minHeightCurrentComponent,
+ heightCurrentResolution);
+ maxNumWideCurrentComponent = Math.max(maxNumWideCurrentComponent,
+ resolution.precinctParameters.numprecinctswide);
+ maxNumHighCurrentComponent = Math.max(maxNumHighCurrentComponent,
+ resolution.precinctParameters.numprecinctshigh);
+ sizePerResolution[r] = {
+ width: widthCurrentResolution,
+ height: heightCurrentResolution
+ };
+ scale <<= 1;
+ }
+ minWidth = Math.min(minWidth, minWidthCurrentComponent);
+ minHeight = Math.min(minHeight, minHeightCurrentComponent);
+ maxNumWide = Math.max(maxNumWide, maxNumWideCurrentComponent);
+ maxNumHigh = Math.max(maxNumHigh, maxNumHighCurrentComponent);
+ sizePerComponent[c] = {
+ resolutions: sizePerResolution,
+ minWidth: minWidthCurrentComponent,
+ minHeight: minHeightCurrentComponent,
+ maxNumWide: maxNumWideCurrentComponent,
+ maxNumHigh: maxNumHighCurrentComponent
+ };
+ }
+ return {
+ components: sizePerComponent,
+ minWidth: minWidth,
+ minHeight: minHeight,
+ maxNumWide: maxNumWide,
+ maxNumHigh: maxNumHigh
+ };
+ }
+ function buildPackets(context) {
+ var siz = context.SIZ;
+ var tileIndex = context.currentTile.index;
+ var tile = context.tiles[tileIndex];
+ var componentsCount = siz.Csiz;
+ // Creating resolutions and sub-bands for each component
+ for (var c = 0; c < componentsCount; c++) {
+ var component = tile.components[c];
+ var decompositionLevelsCount =
+ component.codingStyleParameters.decompositionLevelsCount;
+ // Section B.5 Resolution levels and sub-bands
+ var resolutions = [];
+ var subbands = [];
+ for (var r = 0; r <= decompositionLevelsCount; r++) {
+ var blocksDimensions = getBlocksDimensions(context, component, r);
+ var resolution = {};
+ var scale = 1 << (decompositionLevelsCount - r);
+ resolution.trx0 = Math.ceil(component.tcx0 / scale);
+ resolution.try0 = Math.ceil(component.tcy0 / scale);
+ resolution.trx1 = Math.ceil(component.tcx1 / scale);
+ resolution.try1 = Math.ceil(component.tcy1 / scale);
+ resolution.resLevel = r;
+ buildPrecincts(context, resolution, blocksDimensions);
+ resolutions.push(resolution);
+
+ var subband;
+ if (r === 0) {
+ // one sub-band (LL) with last decomposition
+ subband = {};
+ subband.type = 'LL';
+ subband.tbx0 = Math.ceil(component.tcx0 / scale);
+ subband.tby0 = Math.ceil(component.tcy0 / scale);
+ subband.tbx1 = Math.ceil(component.tcx1 / scale);
+ subband.tby1 = Math.ceil(component.tcy1 / scale);
+ subband.resolution = resolution;
+ buildCodeblocks(context, subband, blocksDimensions);
+ subbands.push(subband);
+ resolution.subbands = [subband];
+ } else {
+ var bscale = 1 << (decompositionLevelsCount - r + 1);
+ var resolutionSubbands = [];
+ // three sub-bands (HL, LH and HH) with rest of decompositions
+ subband = {};
+ subband.type = 'HL';
+ subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
+ subband.tby0 = Math.ceil(component.tcy0 / bscale);
+ subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
+ subband.tby1 = Math.ceil(component.tcy1 / bscale);
+ subband.resolution = resolution;
+ buildCodeblocks(context, subband, blocksDimensions);
+ subbands.push(subband);
+ resolutionSubbands.push(subband);
+
+ subband = {};
+ subband.type = 'LH';
+ subband.tbx0 = Math.ceil(component.tcx0 / bscale);
+ subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
+ subband.tbx1 = Math.ceil(component.tcx1 / bscale);
+ subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
+ subband.resolution = resolution;
+ buildCodeblocks(context, subband, blocksDimensions);
+ subbands.push(subband);
+ resolutionSubbands.push(subband);
+
+ subband = {};
+ subband.type = 'HH';
+ subband.tbx0 = Math.ceil(component.tcx0 / bscale - 0.5);
+ subband.tby0 = Math.ceil(component.tcy0 / bscale - 0.5);
+ subband.tbx1 = Math.ceil(component.tcx1 / bscale - 0.5);
+ subband.tby1 = Math.ceil(component.tcy1 / bscale - 0.5);
+ subband.resolution = resolution;
+ buildCodeblocks(context, subband, blocksDimensions);
+ subbands.push(subband);
+ resolutionSubbands.push(subband);
+
+ resolution.subbands = resolutionSubbands;
+ }
+ }
+ component.resolutions = resolutions;
+ component.subbands = subbands;
+ }
+ // Generate the packets sequence
+ var progressionOrder = tile.codingStyleDefaultParameters.progressionOrder;
+ switch (progressionOrder) {
+ case 0:
+ tile.packetsIterator =
+ new LayerResolutionComponentPositionIterator(context);
+ break;
+ case 1:
+ tile.packetsIterator =
+ new ResolutionLayerComponentPositionIterator(context);
+ break;
+ case 2:
+ tile.packetsIterator =
+ new ResolutionPositionComponentLayerIterator(context);
+ break;
+ case 3:
+ tile.packetsIterator =
+ new PositionComponentResolutionLayerIterator(context);
+ break;
+ case 4:
+ tile.packetsIterator =
+ new ComponentPositionResolutionLayerIterator(context);
+ break;
+ default:
+ throw new Error('JPX Error: Unsupported progression order ' +
+ progressionOrder);
+ }
+ }
+ function parseTilePackets(context, data, offset, dataLength) {
+ var position = 0;
+ var buffer, bufferSize = 0, skipNextBit = false;
+ function readBits(count) {
+ while (bufferSize < count) {
+ if(offset + position >= data.length){
+ throw new Error("Unexpected EOF");
+ }
+ var b = data[offset + position];
+ position++;
+ if (skipNextBit) {
+ buffer = (buffer << 7) | b;
+ bufferSize += 7;
+ skipNextBit = false;
+ } else {
+ buffer = (buffer << 8) | b;
+ bufferSize += 8;
+ }
+ if (b === 0xFF) {
+ skipNextBit = true;
+ }
+ }
+ bufferSize -= count;
+ return (buffer >>> bufferSize) & ((1 << count) - 1);
+ }
+ function skipMarkerIfEqual(value) {
+ if (data[offset + position - 1] === 0xFF &&
+ data[offset + position] === value) {
+ skipBytes(1);
+ return true;
+ } else if (data[offset + position] === 0xFF &&
+ data[offset + position + 1] === value) {
+ skipBytes(2);
+ return true;
+ }
+ return false;
+ }
+ function skipBytes(count) {
+ position += count;
+ }
+ function alignToByte() {
+ bufferSize = 0;
+ if (skipNextBit) {
+ position++;
+ skipNextBit = false;
+ }
+ }
+ function readCodingpasses() {
+ if (readBits(1) === 0) {
+ return 1;
+ }
+ if (readBits(1) === 0) {
+ return 2;
+ }
+ var value = readBits(2);
+ if (value < 3) {
+ return value + 3;
+ }
+ value = readBits(5);
+ if (value < 31) {
+ return value + 6;
+ }
+ value = readBits(7);
+ return value + 37;
+ }
+ var tileIndex = context.currentTile.index;
+ var tile = context.tiles[tileIndex];
+ var sopMarkerUsed = context.COD.sopMarkerUsed;
+ var ephMarkerUsed = context.COD.ephMarkerUsed;
+ var packetsIterator = tile.packetsIterator;
+ while (position < dataLength) {
+ try{
+ alignToByte();
+ if (sopMarkerUsed && skipMarkerIfEqual(0x91)) {
+ // Skip also marker segment length and packet sequence ID
+ skipBytes(4);
+ }
+ var packet = packetsIterator.nextPacket();
+ if (packet === undefined) {
+ //No more packets. Stream is probably truncated.
+ return;
+ }
+ if (!readBits(1)) {
+ continue;
+ }
+ var layerNumber = packet.layerNumber;
+ var queue = [], codeblock;
+ for (var i = 0, ii = packet.codeblocks.length; i < ii; i++) {
+ codeblock = packet.codeblocks[i];
+ var precinct = codeblock.precinct;
+ var codeblockColumn = codeblock.cbx - precinct.cbxMin;
+ var codeblockRow = codeblock.cby - precinct.cbyMin;
+ var codeblockIncluded = false;
+ var firstTimeInclusion = false;
+ var valueReady;
+ if (codeblock['included'] !== undefined) {
+ codeblockIncluded = !!readBits(1);
+ } else {
+ // reading inclusion tree
+ precinct = codeblock.precinct;
+ var inclusionTree, zeroBitPlanesTree;
+ if (precinct['inclusionTree'] !== undefined) {
+ inclusionTree = precinct.inclusionTree;
+ } else {
+ // building inclusion and zero bit-planes trees
+ var width = precinct.cbxMax - precinct.cbxMin + 1;
+ var height = precinct.cbyMax - precinct.cbyMin + 1;
+ inclusionTree = new InclusionTree(width, height);
+ zeroBitPlanesTree = new TagTree(width, height);
+ precinct.inclusionTree = inclusionTree;
+ precinct.zeroBitPlanesTree = zeroBitPlanesTree;
+ }
+
+ inclusionTree.reset(codeblockColumn, codeblockRow, layerNumber);
+ while (true) {
+ if (position >= data.length) {
+ return;
+ }
+ if (inclusionTree.isAboveThreshold()){
+ break;
+ }
+ if (inclusionTree.isKnown()) {
+ inclusionTree.nextLevel();
+ continue;
+ }
+ if (readBits(1)) {
+ inclusionTree.setKnown();
+ if (inclusionTree.isLeaf()) {
+ codeblock.included = true;
+ codeblockIncluded = firstTimeInclusion = true;
+ break;
+ } else {
+ inclusionTree.nextLevel();
+ }
+ } else {
+ inclusionTree.incrementValue();
+ }
+ }
+ }
+ if (!codeblockIncluded) {
+ continue;
+ }
+ if (firstTimeInclusion) {
+ zeroBitPlanesTree = precinct.zeroBitPlanesTree;
+ zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
+ while (true) {
+ if (position >= data.length) {
+ return;
+ }
+ if (readBits(1)) {
+ valueReady = !zeroBitPlanesTree.nextLevel();
+ if (valueReady) {
+ break;
+ }
+ } else {
+ zeroBitPlanesTree.incrementValue();
+ }
+ }
+ codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
+ }
+ var codingpasses = readCodingpasses();
+ while (readBits(1)) {
+ codeblock.Lblock++;
+ }
+ var codingpassesLog2 = log2(codingpasses);
+ // rounding down log2
+ var bits = ((codingpasses < (1 << codingpassesLog2)) ?
+ codingpassesLog2 - 1 : codingpassesLog2) + codeblock.Lblock;
+ var codedDataLength = readBits(bits);
+ queue.push({
+ codeblock: codeblock,
+ codingpasses: codingpasses,
+ dataLength: codedDataLength
+ });
+ }
+ alignToByte();
+ if (ephMarkerUsed) {
+ skipMarkerIfEqual(0x92);
+ }
+ while (queue.length > 0) {
+ var packetItem = queue.shift();
+ codeblock = packetItem.codeblock;
+ if (codeblock['data'] === undefined) {
+ codeblock.data = [];
+ }
+ codeblock.data.push({
+ data: data,
+ start: offset + position,
+ end: offset + position + packetItem.dataLength,
+ codingpasses: packetItem.codingpasses
+ });
+ position += packetItem.dataLength;
+ }
+ } catch (e) {
+ return;
+ }
+ }
+ return position;
+ }
+ function copyCoefficients(coefficients, levelWidth, levelHeight, subband,
+ delta, mb, reversible, segmentationSymbolUsed) {
+ var x0 = subband.tbx0;
+ var y0 = subband.tby0;
+ var width = subband.tbx1 - subband.tbx0;
+ var codeblocks = subband.codeblocks;
+ var right = subband.type.charAt(0) === 'H' ? 1 : 0;
+ var bottom = subband.type.charAt(1) === 'H' ? levelWidth : 0;
+
+ for (var i = 0, ii = codeblocks.length; i < ii; ++i) {
+ var codeblock = codeblocks[i];
+ var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
+ var blockHeight = codeblock.tby1_ - codeblock.tby0_;
+ if (blockWidth === 0 || blockHeight === 0) {
+ continue;
+ }
+ if (codeblock['data'] === undefined) {
+ continue;
+ }
+
+ var bitModel, currentCodingpassType;
+ bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
+ codeblock.zeroBitPlanes, mb);
+ currentCodingpassType = 2; // first bit plane starts from cleanup
+
+ // collect data
+ var data = codeblock.data, totalLength = 0, codingpasses = 0;
+ var j, jj, dataItem;
+ for (j = 0, jj = data.length; j < jj; j++) {
+ dataItem = data[j];
+ totalLength += dataItem.end - dataItem.start;
+ codingpasses += dataItem.codingpasses;
+ }
+ var encodedData = new Int16Array(totalLength);
+ var position = 0;
+ for (j = 0, jj = data.length; j < jj; j++) {
+ dataItem = data[j];
+ var chunk = dataItem.data.subarray(dataItem.start, dataItem.end);
+ encodedData.set(chunk, position);
+ position += chunk.length;
+ }
+ // decoding the item
+ var decoder = new ArithmeticDecoder(encodedData, 0, totalLength);
+ bitModel.setDecoder(decoder);
+
+ for (j = 0; j < codingpasses; j++) {
+ switch (currentCodingpassType) {
+ case 0:
+ bitModel.runSignificancePropogationPass();
+ break;
+ case 1:
+ bitModel.runMagnitudeRefinementPass();
+ break;
+ case 2:
+ bitModel.runCleanupPass();
+ if (segmentationSymbolUsed) {
+ bitModel.checkSegmentationSymbol();
+ }
+ break;
+ }
+ currentCodingpassType = (currentCodingpassType + 1) % 3;
+ }
+
+ var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width;
+ var sign = bitModel.coefficentsSign;
+ var magnitude = bitModel.coefficentsMagnitude;
+ var bitsDecoded = bitModel.bitsDecoded;
+ var magnitudeCorrection = reversible ? 0 : 0.5;
+ var k, n, nb;
+ position = 0;
+ // Do the interleaving of Section F.3.3 here, so we do not need
+ // to copy later. LL level is not interleaved, just copied.
+ var interleave = (subband.type !== 'LL');
+ for (j = 0; j < blockHeight; j++) {
+ var row = (offset / width) | 0; // row in the non-interleaved subband
+ var levelOffset = 2 * row * (levelWidth - width) + right + bottom;
+ for (k = 0; k < blockWidth; k++) {
+ n = magnitude[position];
+ if (n !== 0) {
+ n = (n + magnitudeCorrection) * delta;
+ if (sign[position] !== 0) {
+ n = -n;
+ }
+ nb = bitsDecoded[position];
+ var pos = interleave ? (levelOffset + (offset << 1)) : offset;
+ if (reversible && (nb >= mb)) {
+ coefficients[pos] = n;
+ } else {
+ coefficients[pos] = n * (1 << (mb - nb));
+ }
+ }
+ offset++;
+ position++;
+ }
+ offset += width - blockWidth;
+ }
+ }
+ }
+ function transformTile(context, tile, c) {
+ var component = tile.components[c];
+ var codingStyleParameters = component.codingStyleParameters;
+ var quantizationParameters = component.quantizationParameters;
+ var decompositionLevelsCount =
+ codingStyleParameters.decompositionLevelsCount;
+ var spqcds = quantizationParameters.SPqcds;
+ var scalarExpounded = quantizationParameters.scalarExpounded;
+ var guardBits = quantizationParameters.guardBits;
+ var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed;
+ var precision = context.components[c].precision;
+
+ var reversible = codingStyleParameters.reversibleTransformation;
+ var transform = (reversible ? new ReversibleTransform() :
+ new IrreversibleTransform());
+
+ var subbandCoefficients = [];
+ var b = 0;
+ for (var i = 0; i <= decompositionLevelsCount; i++) {
+ var resolution = component.resolutions[i];
+
+ var width = resolution.trx1 - resolution.trx0;
+ var height = resolution.try1 - resolution.try0;
+ // Allocate space for the whole sublevel.
+ var coefficients = new Float32Array(width * height);
+
+ for (var j = 0, jj = resolution.subbands.length; j < jj; j++) {
+ var mu, epsilon;
+ if (!scalarExpounded) {
+ // formula E-5
+ mu = spqcds[0].mu;
+ epsilon = spqcds[0].epsilon + (i > 0 ? 1 - i : 0);
+ } else {
+ mu = spqcds[b].mu;
+ epsilon = spqcds[b].epsilon;
+ b++;
+ }
+
+ var subband = resolution.subbands[j];
+ var gainLog2 = SubbandsGainLog2[subband.type];
+
+ // calulate quantization coefficient (Section E.1.1.1)
+ var delta = (reversible ? 1 :
+ Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048));
+ var mb = (guardBits + epsilon - 1);
+
+ // In the first resolution level, copyCoefficients will fill the
+ // whole array with coefficients. In the succeding passes,
+ // copyCoefficients will consecutively fill in the values that belong
+ // to the interleaved positions of the HL, LH, and HH coefficients.
+ // The LL coefficients will then be interleaved in Transform.iterate().
+ copyCoefficients(coefficients, width, height, subband, delta, mb,
+ reversible, segmentationSymbolUsed);
+ }
+ subbandCoefficients.push({
+ width: width,
+ height: height,
+ items: coefficients
+ });
+ }
+
+ var result = transform.calculate(subbandCoefficients,
+ component.tcx0, component.tcy0);
+ return {
+ left: component.tcx0,
+ top: component.tcy0,
+ width: result.width,
+ height: result.height,
+ items: result.items
+ };
+ }
+ function transformComponents(context) {
+ var siz = context.SIZ;
+ var components = context.components;
+ var componentsCount = siz.Csiz;
+ var resultImages = [];
+ for (var i = 0, ii = context.tiles.length; i < ii; i++) {
+ var tile = context.tiles[i];
+ var transformedTiles = [];
+ var c;
+ for (c = 0; c < componentsCount; c++) {
+ transformedTiles[c] = transformTile(context, tile, c);
+ }
+ var tile0 = transformedTiles[0];
+ var isSigned = components[0].isSigned;
+ if (isSigned) {
+ var out = new Int16Array(tile0.items.length * componentsCount);
+ } else {
+ var out = new Uint16Array(tile0.items.length * componentsCount);
+ }
+ var result = {
+ left: tile0.left,
+ top: tile0.top,
+ width: tile0.width,
+ height: tile0.height,
+ items: out
+ };
+
+ // Section G.2.2 Inverse multi component transform
+ var shift, offset, max, min, maxK;
+ var pos = 0, j, jj, y0, y1, y2, r, g, b, k, val;
+ if (tile.codingStyleDefaultParameters.multipleComponentTransform) {
+ var fourComponents = componentsCount === 4;
+ var y0items = transformedTiles[0].items;
+ var y1items = transformedTiles[1].items;
+ var y2items = transformedTiles[2].items;
+ var y3items = fourComponents ? transformedTiles[3].items : null;
+
+ // HACK: The multiple component transform formulas below assume that
+ // all components have the same precision. With this in mind, we
+ // compute shift and offset only once.
+ shift = components[0].precision - 8;
+ offset = (128 << shift) + 0.5;
+ max = 255 * (1 << shift);
+ maxK = max * 0.5;
+ min = -maxK;
+
+ var component0 = tile.components[0];
+ var alpha01 = componentsCount - 3;
+ jj = y0items.length;
+ if (!component0.codingStyleParameters.reversibleTransformation) {
+ // inverse irreversible multiple component transform
+ for (j = 0; j < jj; j++, pos += alpha01) {
+ y0 = y0items[j] + offset;
+ y1 = y1items[j];
+ y2 = y2items[j];
+ r = y0 + 1.402 * y2;
+ g = y0 - 0.34413 * y1 - 0.71414 * y2;
+ b = y0 + 1.772 * y1;
+ out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
+ out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
+ out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
+ }
+ } else {
+ // inverse reversible multiple component transform
+ for (j = 0; j < jj; j++, pos += alpha01) {
+ y0 = y0items[j] + offset;
+ y1 = y1items[j];
+ y2 = y2items[j];
+ g = y0 - ((y2 + y1) >> 2);
+ r = g + y2;
+ b = g + y1;
+ out[pos++] = r <= 0 ? 0 : r >= max ? 255 : r >> shift;
+ out[pos++] = g <= 0 ? 0 : g >= max ? 255 : g >> shift;
+ out[pos++] = b <= 0 ? 0 : b >= max ? 255 : b >> shift;
+ }
+ }
+ if (fourComponents) {
+ for (j = 0, pos = 3; j < jj; j++, pos += 4) {
+ k = y3items[j];
+ out[pos] = k <= min ? 0 : k >= maxK ? 255 : (k + offset) >> shift;
+ }
+ }
+ } else { // no multi-component transform
+ for (c = 0; c < componentsCount; c++) {
+ if (components[c].precision === 8){
+ var items = transformedTiles[c].items;
+ shift = components[c].precision - 8;
+ offset = (128 << shift) + 0.5;
+ max = (127.5 * (1 << shift));
+ min = -max;
+ for (pos = c, j = 0, jj = items.length; j < jj; j++) {
+ val = items[j];
+ out[pos] = val <= min ? 0 :
+ val >= max ? 255 : (val + offset) >> shift;
+ pos += componentsCount;
+ }
+ }else{
+ var isSigned = components[c].isSigned;
+ var items = transformedTiles[c].items;
+
+ if(isSigned){
+ for (pos = c, j = 0, jj = items.length; j < jj; j++) {
+ out[pos] = items[j];
+ pos += componentsCount;
+ }
+ }else{
+ shift = components[c].precision - 8;
+ offset = (128 << shift) + 0.5;
+ var precisionMax = Math.pow(2,components[c].precision)-1;
+ for (pos = c, j = 0, jj = items.length; j < jj; j++) {
+ val = items[j];
+ out[pos] = Math.max(Math.min((val + offset),precisionMax),0);
+ pos += componentsCount;
+ }
+ }
+ }
+ }
+ }
+ resultImages.push(result);
+ }
+ return resultImages;
+ }
+ function initializeTile(context, tileIndex) {
+ var siz = context.SIZ;
+ var componentsCount = siz.Csiz;
+ var tile = context.tiles[tileIndex];
+ for (var c = 0; c < componentsCount; c++) {
+ var component = tile.components[c];
+ var qcdOrQcc = (context.currentTile.QCC[c] !== undefined ?
+ context.currentTile.QCC[c] : context.currentTile.QCD);
+ component.quantizationParameters = qcdOrQcc;
+ var codOrCoc = (context.currentTile.COC[c] !== undefined ?
+ context.currentTile.COC[c] : context.currentTile.COD);
+ component.codingStyleParameters = codOrCoc;
+ }
+ tile.codingStyleDefaultParameters = context.currentTile.COD;
+ }
+
+ // Section B.10.2 Tag trees
+ var TagTree = (function TagTreeClosure() {
+ function TagTree(width, height) {
+ var levelsLength = log2(Math.max(width, height)) + 1;
+ this.levels = [];
+ for (var i = 0; i < levelsLength; i++) {
+ var level = {
+ width: width,
+ height: height,
+ items: []
+ };
+ this.levels.push(level);
+ width = Math.ceil(width / 2);
+ height = Math.ceil(height / 2);
+ }
+ }
+ TagTree.prototype = {
+ reset: function TagTree_reset(i, j) {
+ var currentLevel = 0, value = 0, level;
+ while (currentLevel < this.levels.length) {
+ level = this.levels[currentLevel];
+ var index = i + j * level.width;
+ if (level.items[index] !== undefined) {
+ value = level.items[index];
+ break;
+ }
+ level.index = index;
+ i >>= 1;
+ j >>= 1;
+ currentLevel++;
+ }
+ currentLevel--;
+ level = this.levels[currentLevel];
+ level.items[level.index] = value;
+ this.currentLevel = currentLevel;
+ delete this.value;
+ },
+ incrementValue: function TagTree_incrementValue() {
+ var level = this.levels[this.currentLevel];
+ level.items[level.index]++;
+ },
+ nextLevel: function TagTree_nextLevel() {
+ var currentLevel = this.currentLevel;
+ var level = this.levels[currentLevel];
+ var value = level.items[level.index];
+ currentLevel--;
+ if (currentLevel < 0) {
+ this.value = value;
+ return false;
+ }
+
+ this.currentLevel = currentLevel;
+ level = this.levels[currentLevel];
+ level.items[level.index] = value;
+ return true;
+ }
+ };
+ return TagTree;
+ })();
+
+ var InclusionTree = (function InclusionTreeClosure() {
+ function InclusionTree(width, height) {
+ var levelsLength = log2(Math.max(width, height)) + 1;
+ this.levels = [];
+ for (var i = 0; i < levelsLength; i++) {
+ var items = new Uint8Array(width * height);
+ var status = new Uint8Array(width * height);
+ for (var j = 0, jj = items.length; j < jj; j++) {
+ items[j] = 0;
+ status[j] = 0;
+ }
+
+ var level = {
+ width: width,
+ height: height,
+ items: items,
+ status: status
+ };
+ this.levels.push(level);
+
+ width = Math.ceil(width / 2);
+ height = Math.ceil(height / 2);
+ }
+ }
+ InclusionTree.prototype = {
+ reset: function InclusionTree_reset(i, j, stopValue) {
+ this.currentStopValue = stopValue;
+ var currentLevel = 0;
+ while (currentLevel < this.levels.length) {
+ var level = this.levels[currentLevel];
+ var index = i + j * level.width;
+ level.index = index;
+
+ i >>= 1;
+ j >>= 1;
+ currentLevel++;
+ }
+
+ this.currentLevel = this.levels.length - 1;
+ this.minValue =this.levels[this.currentLevel].items[0];
+ return;
+ },
+ incrementValue: function InclusionTree_incrementValue() {
+ var level = this.levels[this.currentLevel];
+ level.items[level.index] = level.items[level.index] + 1;
+ if(level.items[level.index] > this.minValue) {
+ this.minValue = level.items[level.index];
+ }
+ },
+ nextLevel: function InclusionTree_nextLevel() {
+ var currentLevel = this.currentLevel;
+ currentLevel--;
+ if (currentLevel < 0) {
+ return false;
+ } else {
+ this.currentLevel = currentLevel;
+ var level = this.levels[currentLevel];
+ if(level.items[level.index] < this.minValue) {
+ level.items[level.index] = this.minValue;
+ }else if (level.items[level.index] > this.minValue) {
+ this.minValue = level.items[level.index];
+ }
+ return true;
+ }
+ },
+ isLeaf: function InclusionTree_isLeaf(){
+ return (this.currentLevel === 0);
+ },
+ isAboveThreshold: function InclusionTree_isAboveThreshold(){
+ var levelindex = this.currentLevel;
+ var level = this.levels[levelindex];
+ return (level.items[level.index] > this.currentStopValue);
+ },
+ isKnown: function InclusionTree_isKnown(){
+ var levelindex = this.currentLevel;
+ var level = this.levels[levelindex];
+ return (level.status[level.index] > 0);
+ },
+ setKnown: function InclusionTree_setKnown(){
+ var levelindex = this.currentLevel;
+ var level = this.levels[levelindex];
+ level.status[level.index] = 1;
+ return;
+ }
+
+ };
+ return InclusionTree;
+ })();
+
+ // Section D. Coefficient bit modeling
+ var BitModel = (function BitModelClosure() {
+ var UNIFORM_CONTEXT = 17;
+ var RUNLENGTH_CONTEXT = 18;
+ // Table D-1
+ // The index is binary presentation: 0dddvvhh, ddd - sum of Di (0..4),
+ // vv - sum of Vi (0..2), and hh - sum of Hi (0..2)
+ var LLAndLHContextsLabel = new Uint8Array([
+ 0, 5, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 1, 6, 8, 0, 3, 7, 8, 0, 4,
+ 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6,
+ 8, 0, 3, 7, 8, 0, 4, 7, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 3, 7, 8, 0, 4, 7, 8
+ ]);
+ var HLContextLabel = new Uint8Array([
+ 0, 3, 4, 0, 5, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 1, 3, 4, 0, 6, 7, 7, 0, 8,
+ 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3,
+ 4, 0, 6, 7, 7, 0, 8, 8, 8, 0, 0, 0, 0, 0, 2, 3, 4, 0, 6, 7, 7, 0, 8, 8, 8
+ ]);
+ var HHContextLabel = new Uint8Array([
+ 0, 1, 2, 0, 1, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 3, 4, 5, 0, 4, 5, 5, 0, 5,
+ 5, 5, 0, 0, 0, 0, 0, 6, 7, 7, 0, 7, 7, 7, 0, 7, 7, 7, 0, 0, 0, 0, 0, 8, 8,
+ 8, 0, 8, 8, 8, 0, 8, 8, 8, 0, 0, 0, 0, 0, 8, 8, 8, 0, 8, 8, 8, 0, 8, 8, 8
+ ]);
+
+ function BitModel(width, height, subband, zeroBitPlanes, mb) {
+ this.width = width;
+ this.height = height;
+
+ this.contextLabelTable = (subband === 'HH' ? HHContextLabel :
+ (subband === 'HL' ? HLContextLabel : LLAndLHContextsLabel));
+
+ var coefficientCount = width * height;
+
+ // coefficients outside the encoding region treated as insignificant
+ // add border state cells for significanceState
+ this.neighborsSignificance = new Uint8Array(coefficientCount);
+ this.coefficentsSign = new Uint8Array(coefficientCount);
+ this.coefficentsMagnitude = mb > 14 ? new Uint32Array(coefficientCount) :
+ mb > 6 ? new Uint16Array(coefficientCount) :
+ new Uint8Array(coefficientCount);
+ this.processingFlags = new Uint8Array(coefficientCount);
+
+ var bitsDecoded = new Uint8Array(coefficientCount);
+ if (zeroBitPlanes !== 0) {
+ for (var i = 0; i < coefficientCount; i++) {
+ bitsDecoded[i] = zeroBitPlanes;
+ }
+ }
+ this.bitsDecoded = bitsDecoded;
+
+ this.reset();
+ }
+
+ BitModel.prototype = {
+ setDecoder: function BitModel_setDecoder(decoder) {
+ this.decoder = decoder;
+ },
+ reset: function BitModel_reset() {
+ // We have 17 contexts that are accessed via context labels,
+ // plus the uniform and runlength context.
+ this.contexts = new Int8Array(19);
+
+ // Contexts are packed into 1 byte:
+ // highest 7 bits carry the index, lowest bit carries mps
+ this.contexts[0] = (4 << 1) | 0;
+ this.contexts[UNIFORM_CONTEXT] = (46 << 1) | 0;
+ this.contexts[RUNLENGTH_CONTEXT] = (3 << 1) | 0;
+ },
+ setNeighborsSignificance:
+ function BitModel_setNeighborsSignificance(row, column, index) {
+ var neighborsSignificance = this.neighborsSignificance;
+ var width = this.width, height = this.height;
+ var left = (column > 0);
+ var right = (column + 1 < width);
+ var i;
+
+ if (row > 0) {
+ i = index - width;
+ if (left) {
+ neighborsSignificance[i - 1] += 0x10;
+ }
+ if (right) {
+ neighborsSignificance[i + 1] += 0x10;
+ }
+ neighborsSignificance[i] += 0x04;
+ }
+
+ if (row + 1 < height) {
+ i = index + width;
+ if (left) {
+ neighborsSignificance[i - 1] += 0x10;
+ }
+ if (right) {
+ neighborsSignificance[i + 1] += 0x10;
+ }
+ neighborsSignificance[i] += 0x04;
+ }
+
+ if (left) {
+ neighborsSignificance[index - 1] += 0x01;
+ }
+ if (right) {
+ neighborsSignificance[index + 1] += 0x01;
+ }
+ neighborsSignificance[index] |= 0x80;
+ },
+ runSignificancePropogationPass:
+ function BitModel_runSignificancePropogationPass() {
+ var decoder = this.decoder;
+ var width = this.width, height = this.height;
+ var coefficentsMagnitude = this.coefficentsMagnitude;
+ var coefficentsSign = this.coefficentsSign;
+ var neighborsSignificance = this.neighborsSignificance;
+ var processingFlags = this.processingFlags;
+ var contexts = this.contexts;
+ var labels = this.contextLabelTable;
+ var bitsDecoded = this.bitsDecoded;
+ var processedInverseMask = ~1;
+ var processedMask = 1;
+ var firstMagnitudeBitMask = 2;
+
+ for (var i0 = 0; i0 < height; i0 += 4) {
+ for (var j = 0; j < width; j++) {
+ var index = i0 * width + j;
+ for (var i1 = 0; i1 < 4; i1++, index += width) {
+ var i = i0 + i1;
+ if (i >= height) {
+ break;
+ }
+ // clear processed flag first
+ processingFlags[index] &= processedInverseMask;
+
+ if (coefficentsMagnitude[index] ||
+ !neighborsSignificance[index]) {
+ continue;
+ }
+
+ var contextLabel = labels[neighborsSignificance[index]];
+ var decision = decoder.readBit(contexts, contextLabel);
+ if (decision) {
+ var sign = this.decodeSignBit(i, j, index);
+ coefficentsSign[index] = sign;
+ coefficentsMagnitude[index] = 1;
+ this.setNeighborsSignificance(i, j, index);
+ processingFlags[index] |= firstMagnitudeBitMask;
+ }
+ bitsDecoded[index]++;
+ processingFlags[index] |= processedMask;
+ }
+ }
+ }
+ },
+ decodeSignBit: function BitModel_decodeSignBit(row, column, index) {
+ var width = this.width, height = this.height;
+ var coefficentsMagnitude = this.coefficentsMagnitude;
+ var coefficentsSign = this.coefficentsSign;
+ var contribution, sign0, sign1, significance1;
+ var contextLabel, decoded;
+
+ // calculate horizontal contribution
+ significance1 = (column > 0 && coefficentsMagnitude[index - 1] !== 0);
+ if (column + 1 < width && coefficentsMagnitude[index + 1] !== 0) {
+ sign1 = coefficentsSign[index + 1];
+ if (significance1) {
+ sign0 = coefficentsSign[index - 1];
+ contribution = 1 - sign1 - sign0;
+ } else {
+ contribution = 1 - sign1 - sign1;
+ }
+ } else if (significance1) {
+ sign0 = coefficentsSign[index - 1];
+ contribution = 1 - sign0 - sign0;
+ } else {
+ contribution = 0;
+ }
+ var horizontalContribution = 3 * contribution;
+
+ // calculate vertical contribution and combine with the horizontal
+ significance1 = (row > 0 && coefficentsMagnitude[index - width] !== 0);
+ if (row + 1 < height && coefficentsMagnitude[index + width] !== 0) {
+ sign1 = coefficentsSign[index + width];
+ if (significance1) {
+ sign0 = coefficentsSign[index - width];
+ contribution = 1 - sign1 - sign0 + horizontalContribution;
+ } else {
+ contribution = 1 - sign1 - sign1 + horizontalContribution;
+ }
+ } else if (significance1) {
+ sign0 = coefficentsSign[index - width];
+ contribution = 1 - sign0 - sign0 + horizontalContribution;
+ } else {
+ contribution = horizontalContribution;
+ }
+
+ if (contribution >= 0) {
+ contextLabel = 9 + contribution;
+ decoded = this.decoder.readBit(this.contexts, contextLabel);
+ } else {
+ contextLabel = 9 - contribution;
+ decoded = this.decoder.readBit(this.contexts, contextLabel) ^ 1;
+ }
+ return decoded;
+ },
+ runMagnitudeRefinementPass:
+ function BitModel_runMagnitudeRefinementPass() {
+ var decoder = this.decoder;
+ var width = this.width, height = this.height;
+ var coefficentsMagnitude = this.coefficentsMagnitude;
+ var neighborsSignificance = this.neighborsSignificance;
+ var contexts = this.contexts;
+ var bitsDecoded = this.bitsDecoded;
+ var processingFlags = this.processingFlags;
+ var processedMask = 1;
+ var firstMagnitudeBitMask = 2;
+ var length = width * height;
+ var width4 = width * 4;
+
+ for (var index0 = 0, indexNext; index0 < length; index0 = indexNext) {
+ indexNext = Math.min(length, index0 + width4);
+ for (var j = 0; j < width; j++) {
+ for (var index = index0 + j; index < indexNext; index += width) {
+
+ // significant but not those that have just become
+ if (!coefficentsMagnitude[index] ||
+ (processingFlags[index] & processedMask) !== 0) {
+ continue;
+ }
+
+ var contextLabel = 16;
+ if ((processingFlags[index] & firstMagnitudeBitMask) !== 0) {
+ processingFlags[index] ^= firstMagnitudeBitMask;
+ // first refinement
+ var significance = neighborsSignificance[index] & 127;
+ contextLabel = significance === 0 ? 15 : 14;
+ }
+
+ var bit = decoder.readBit(contexts, contextLabel);
+ coefficentsMagnitude[index] =
+ (coefficentsMagnitude[index] << 1) | bit;
+ bitsDecoded[index]++;
+ processingFlags[index] |= processedMask;
+ }
+ }
+ }
+ },
+ runCleanupPass: function BitModel_runCleanupPass() {
+ var decoder = this.decoder;
+ var width = this.width, height = this.height;
+ var neighborsSignificance = this.neighborsSignificance;
+ var coefficentsMagnitude = this.coefficentsMagnitude;
+ var coefficentsSign = this.coefficentsSign;
+ var contexts = this.contexts;
+ var labels = this.contextLabelTable;
+ var bitsDecoded = this.bitsDecoded;
+ var processingFlags = this.processingFlags;
+ var processedMask = 1;
+ var firstMagnitudeBitMask = 2;
+ var oneRowDown = width;
+ var twoRowsDown = width * 2;
+ var threeRowsDown = width * 3;
+ var iNext;
+ for (var i0 = 0; i0 < height; i0 = iNext) {
+ iNext = Math.min(i0 + 4, height);
+ var indexBase = i0 * width;
+ var checkAllEmpty = i0 + 3 < height;
+ for (var j = 0; j < width; j++) {
+ var index0 = indexBase + j;
+ // using the property: labels[neighborsSignificance[index]] === 0
+ // when neighborsSignificance[index] === 0
+ var allEmpty = (checkAllEmpty &&
+ processingFlags[index0] === 0 &&
+ processingFlags[index0 + oneRowDown] === 0 &&
+ processingFlags[index0 + twoRowsDown] === 0 &&
+ processingFlags[index0 + threeRowsDown] === 0 &&
+ neighborsSignificance[index0] === 0 &&
+ neighborsSignificance[index0 + oneRowDown] === 0 &&
+ neighborsSignificance[index0 + twoRowsDown] === 0 &&
+ neighborsSignificance[index0 + threeRowsDown] === 0);
+ var i1 = 0, index = index0;
+ var i = i0, sign;
+ if (allEmpty) {
+ var hasSignificantCoefficent =
+ decoder.readBit(contexts, RUNLENGTH_CONTEXT);
+ if (!hasSignificantCoefficent) {
+ bitsDecoded[index0]++;
+ bitsDecoded[index0 + oneRowDown]++;
+ bitsDecoded[index0 + twoRowsDown]++;
+ bitsDecoded[index0 + threeRowsDown]++;
+ continue; // next column
+ }
+ i1 = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
+ decoder.readBit(contexts, UNIFORM_CONTEXT);
+ if (i1 !== 0) {
+ i = i0 + i1;
+ index += i1 * width;
+ }
+
+ sign = this.decodeSignBit(i, j, index);
+ coefficentsSign[index] = sign;
+ coefficentsMagnitude[index] = 1;
+ this.setNeighborsSignificance(i, j, index);
+ processingFlags[index] |= firstMagnitudeBitMask;
+
+ index = index0;
+ for (var i2 = i0; i2 <= i; i2++, index += width) {
+ bitsDecoded[index]++;
+ }
+
+ i1++;
+ }
+ for (i = i0 + i1; i < iNext; i++, index += width) {
+ if (coefficentsMagnitude[index] ||
+ (processingFlags[index] & processedMask) !== 0) {
+ continue;
+ }
+
+ var contextLabel = labels[neighborsSignificance[index]];
+ var decision = decoder.readBit(contexts, contextLabel);
+ if (decision === 1) {
+ sign = this.decodeSignBit(i, j, index);
+ coefficentsSign[index] = sign;
+ coefficentsMagnitude[index] = 1;
+ this.setNeighborsSignificance(i, j, index);
+ processingFlags[index] |= firstMagnitudeBitMask;
+ }
+ bitsDecoded[index]++;
+ }
+ }
+ }
+ },
+ checkSegmentationSymbol: function BitModel_checkSegmentationSymbol() {
+ var decoder = this.decoder;
+ var contexts = this.contexts;
+ var symbol = (decoder.readBit(contexts, UNIFORM_CONTEXT) << 3) |
+ (decoder.readBit(contexts, UNIFORM_CONTEXT) << 2) |
+ (decoder.readBit(contexts, UNIFORM_CONTEXT) << 1) |
+ decoder.readBit(contexts, UNIFORM_CONTEXT);
+ if (symbol !== 0xA) {
+ throw new Error('JPX Error: Invalid segmentation symbol');
+ }
+ }
+ };
+
+ return BitModel;
+ })();
+
+ // Section F, Discrete wavelet transformation
+ var Transform = (function TransformClosure() {
+ function Transform() {}
+
+ Transform.prototype.calculate =
+ function transformCalculate(subbands, u0, v0) {
+ var ll = subbands[0];
+ for (var i = 1, ii = subbands.length; i < ii; i++) {
+ ll = this.iterate(ll, subbands[i], u0, v0);
+ }
+ return ll;
+ };
+ Transform.prototype.extend = function extend(buffer, offset, size) {
+ // Section F.3.7 extending... using max extension of 4
+ var i1 = offset - 1, j1 = offset + 1;
+ var i2 = offset + size - 2, j2 = offset + size;
+ buffer[i1--] = buffer[j1++];
+ buffer[j2++] = buffer[i2--];
+ buffer[i1--] = buffer[j1++];
+ buffer[j2++] = buffer[i2--];
+ buffer[i1--] = buffer[j1++];
+ buffer[j2++] = buffer[i2--];
+ buffer[i1] = buffer[j1];
+ buffer[j2] = buffer[i2];
+ };
+ Transform.prototype.iterate = function Transform_iterate(ll, hl_lh_hh,
+ u0, v0) {
+ var llWidth = ll.width, llHeight = ll.height, llItems = ll.items;
+ var width = hl_lh_hh.width;
+ var height = hl_lh_hh.height;
+ var items = hl_lh_hh.items;
+ var i, j, k, l, u, v;
+
+ // Interleave LL according to Section F.3.3
+ for (k = 0, i = 0; i < llHeight; i++) {
+ l = i * 2 * width;
+ for (j = 0; j < llWidth; j++, k++, l += 2) {
+ items[l] = llItems[k];
+ }
+ }
+ // The LL band is not needed anymore.
+ llItems = ll.items = null;
+
+ var bufferPadding = 4;
+ var rowBuffer = new Float32Array(width + 2 * bufferPadding);
+
+ // Section F.3.4 HOR_SR
+ if (width === 1) {
+ // if width = 1, when u0 even keep items as is, when odd divide by 2
+ if ((u0 & 1) !== 0) {
+ for (v = 0, k = 0; v < height; v++, k += width) {
+ items[k] *= 0.5;
+ }
+ }
+ } else {
+ for (v = 0, k = 0; v < height; v++, k += width) {
+ rowBuffer.set(items.subarray(k, k + width), bufferPadding);
+
+ this.extend(rowBuffer, bufferPadding, width);
+ this.filter(rowBuffer, bufferPadding, width);
+
+ items.set(
+ rowBuffer.subarray(bufferPadding, bufferPadding + width),
+ k);
+ }
+ }
+
+ // Accesses to the items array can take long, because it may not fit into
+ // CPU cache and has to be fetched from main memory. Since subsequent
+ // accesses to the items array are not local when reading columns, we
+ // have a cache miss every time. To reduce cache misses, get up to
+ // 'numBuffers' items at a time and store them into the individual
+ // buffers. The colBuffers should be small enough to fit into CPU cache.
+ var numBuffers = 16;
+ var colBuffers = [];
+ for (i = 0; i < numBuffers; i++) {
+ colBuffers.push(new Float32Array(height + 2 * bufferPadding));
+ }
+ var b, currentBuffer = 0;
+ ll = bufferPadding + height;
+
+ // Section F.3.5 VER_SR
+ if (height === 1) {
+ // if height = 1, when v0 even keep items as is, when odd divide by 2
+ if ((v0 & 1) !== 0) {
+ for (u = 0; u < width; u++) {
+ items[u] *= 0.5;
+ }
+ }
+ } else {
+ for (u = 0; u < width; u++) {
+ // if we ran out of buffers, copy several image columns at once
+ if (currentBuffer === 0) {
+ numBuffers = Math.min(width - u, numBuffers);
+ for (k = u, l = bufferPadding; l < ll; k += width, l++) {
+ for (b = 0; b < numBuffers; b++) {
+ colBuffers[b][l] = items[k + b];
+ }
+ }
+ currentBuffer = numBuffers;
+ }
+
+ currentBuffer--;
+ var buffer = colBuffers[currentBuffer];
+ this.extend(buffer, bufferPadding, height);
+ this.filter(buffer, bufferPadding, height);
+
+ // If this is last buffer in this group of buffers, flush all buffers.
+ if (currentBuffer === 0) {
+ k = u - numBuffers + 1;
+ for (l = bufferPadding; l < ll; k += width, l++) {
+ for (b = 0; b < numBuffers; b++) {
+ items[k + b] = colBuffers[b][l];
+ }
+ }
+ }
+ }
+ }
+
+ return {
+ width: width,
+ height: height,
+ items: items
+ };
+ };
+ return Transform;
+ })();
+
+ // Section 3.8.2 Irreversible 9-7 filter
+ var IrreversibleTransform = (function IrreversibleTransformClosure() {
+ function IrreversibleTransform() {
+ Transform.call(this);
+ }
+
+ IrreversibleTransform.prototype = Object.create(Transform.prototype);
+ IrreversibleTransform.prototype.filter =
+ function irreversibleTransformFilter(x, offset, length) {
+ var len = length >> 1;
+ offset = offset | 0;
+ var j, n, current, next;
+
+ var alpha = -1.586134342059924;
+ var beta = -0.052980118572961;
+ var gamma = 0.882911075530934;
+ var delta = 0.443506852043971;
+ var K = 1.230174104914001;
+ var K_ = 1 / K;
+
+ // step 1 is combined with step 3
+
+ // step 2
+ j = offset - 3;
+ for (n = len + 4; n--; j += 2) {
+ x[j] *= K_;
+ }
+
+ // step 1 & 3
+ j = offset - 2;
+ current = delta * x[j -1];
+ for (n = len + 3; n--; j += 2) {
+ next = delta * x[j + 1];
+ x[j] = K * x[j] - current - next;
+ if (n--) {
+ j += 2;
+ current = delta * x[j + 1];
+ x[j] = K * x[j] - current - next;
+ } else {
+ break;
+ }
+ }
+
+ // step 4
+ j = offset - 1;
+ current = gamma * x[j - 1];
+ for (n = len + 2; n--; j += 2) {
+ next = gamma * x[j + 1];
+ x[j] -= current + next;
+ if (n--) {
+ j += 2;
+ current = gamma * x[j + 1];
+ x[j] -= current + next;
+ } else {
+ break;
+ }
+ }
+
+ // step 5
+ j = offset;
+ current = beta * x[j - 1];
+ for (n = len + 1; n--; j += 2) {
+ next = beta * x[j + 1];
+ x[j] -= current + next;
+ if (n--) {
+ j += 2;
+ current = beta * x[j + 1];
+ x[j] -= current + next;
+ } else {
+ break;
+ }
+ }
+
+ // step 6
+ if (len !== 0) {
+ j = offset + 1;
+ current = alpha * x[j - 1];
+ for (n = len; n--; j += 2) {
+ next = alpha * x[j + 1];
+ x[j] -= current + next;
+ if (n--) {
+ j += 2;
+ current = alpha * x[j + 1];
+ x[j] -= current + next;
+ } else {
+ break;
+ }
+ }
+ }
+ };
+
+ return IrreversibleTransform;
+ })();
+
+ // Section 3.8.1 Reversible 5-3 filter
+ var ReversibleTransform = (function ReversibleTransformClosure() {
+ function ReversibleTransform() {
+ Transform.call(this);
+ }
+
+ ReversibleTransform.prototype = Object.create(Transform.prototype);
+ ReversibleTransform.prototype.filter =
+ function reversibleTransformFilter(x, offset, length) {
+ var len = length >> 1;
+ offset = offset | 0;
+ var j, n;
+
+ for (j = offset, n = len + 1; n--; j += 2) {
+ x[j] -= (x[j - 1] + x[j + 1] + 2) >> 2;
+ }
+
+ for (j = offset + 1, n = len; n--; j += 2) {
+ x[j] += (x[j - 1] + x[j + 1]) >> 1;
+ }
+ };
+
+ return ReversibleTransform;
+ })();
+
+ return JpxImage;
+})();
+
+
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
+/* Copyright 2012 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+'use strict';
+
+/* This class implements the QM Coder decoding as defined in
+ * JPEG 2000 Part I Final Committee Draft Version 1.0
+ * Annex C.3 Arithmetic decoding procedure
+ * available at http://www.jpeg.org/public/fcd15444-1.pdf
+ *
+ * The arithmetic decoder is used in conjunction with context models to decode
+ * JPEG2000 and JBIG2 streams.
+ */
+var ArithmeticDecoder = (function ArithmeticDecoderClosure() {
+ // Table C-2
+ var 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}
+ ];
+
+ // C.3.5 Initialisation of the decoder (INITDEC)
+ function ArithmeticDecoder(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;
+ }
+
+ ArithmeticDecoder.prototype = {
+ // C.3.4 Compressed data input (BYTEIN)
+ byteIn: function ArithmeticDecoder_byteIn() {
+ var data = this.data;
+ var bp = this.bp;
+ if (data[bp] === 0xFF) {
+ var b1 = data[bp + 1];
+ if (b1 > 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;
+ }
+ },
+ // C.3.2 Decoding a decision (DECODE)
+ readBit: function ArithmeticDecoder_readBit(contexts, pos) {
+ // contexts are packed into 1 byte:
+ // highest 7 bits carry cx.index, lowest bit carries cx.mps
+ var cx_index = contexts[pos] >> 1, cx_mps = contexts[pos] & 1;
+ var qeTableIcx = QeTable[cx_index];
+ var qeIcx = qeTableIcx.qe;
+ var d;
+ var a = this.a - qeIcx;
+
+ if (this.chigh < qeIcx) {
+ // exchangeLps
+ 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;
+ }
+ // exchangeMps
+ 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;
+ }
+ }
+ // C.3.3 renormD;
+ 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;
+ }
+ };
+
+ return ArithmeticDecoder;
+})();
+
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
+/* Copyright 2012 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
+ Promise */
+
+'use strict';
+
+var globalScope = (typeof window === 'undefined') ? this : window;
+
+var isWorker = (typeof window === 'undefined');
+
+var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
+
+var 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
+};
+
+var ImageKind = {
+ GRAYSCALE_1BPP: 1,
+ RGB_24BPP: 2,
+ RGBA_32BPP: 3
+};
+
+var AnnotationType = {
+ WIDGET: 1,
+ TEXT: 2,
+ LINK: 3
+};
+
+var StreamType = {
+ UNKNOWN: 0,
+ FLATE: 1,
+ LZW: 2,
+ DCT: 3,
+ JPX: 4,
+ JBIG: 5,
+ A85: 6,
+ AHX: 7,
+ CCF: 8,
+ RL: 9
+};
+
+var FontType = {
+ UNKNOWN: 0,
+ TYPE1: 1,
+ TYPE1C: 2,
+ CIDFONTTYPE0: 3,
+ CIDFONTTYPE0C: 4,
+ TRUETYPE: 5,
+ CIDFONTTYPE2: 6,
+ TYPE3: 7,
+ OPENTYPE: 8,
+ TYPE0: 9,
+ MMTYPE1: 10
+};
+
+// The global PDFJS object exposes the API
+// In production, it will be declared outside a global wrapper
+// In development, it will be declared here
+if (!globalScope.PDFJS) {
+ globalScope.PDFJS = {};
+}
+
+globalScope.PDFJS.pdfBug = false;
+
+PDFJS.VERBOSITY_LEVELS = {
+ errors: 0,
+ warnings: 1,
+ infos: 5
+};
+
+// All the possible operations for an operator list.
+var OPS = PDFJS.OPS = {
+ // Intentionally start from 1 so it is easy to spot bad operators that will be
+ // 0's.
+ 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,
+ beginAnnotations: 78,
+ endAnnotations: 79,
+ beginAnnotation: 80,
+ endAnnotation: 81,
+ paintJpegXObject: 82,
+ paintImageMaskXObject: 83,
+ paintImageMaskXObjectGroup: 84,
+ paintImageXObject: 85,
+ paintInlineImageXObject: 86,
+ paintInlineImageXObjectGroup: 87,
+ paintImageXObjectRepeat: 88,
+ paintImageMaskXObjectRepeat: 89,
+ paintSolidColorImageMask: 90,
+ constructPath: 91
+};
+
+// A notice for devs. These are good for things that are helpful to devs, such
+// as warning that Workers were disabled, which is important to devs but not
+// end users.
+function info(msg) {
+ if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
+ console.log('Info: ' + msg);
+ }
+}
+
+// Non-fatal warnings.
+function warn(msg) {
+ if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
+ console.log('Warning: ' + msg);
+ }
+}
+
+// Fatal errors that should trigger the fallback UI and halt execution by
+// throwing an exception.
+function error(msg) {
+ // If multiple arguments were passed, pass them all to the log function.
+ if (arguments.length > 1) {
+ var logArguments = ['Error:'];
+ logArguments.push.apply(logArguments, arguments);
+ console.log.apply(console, logArguments);
+ // Join the arguments into a single string for the lines below.
+ msg = [].join.call(arguments, ' ');
+ } else {
+ console.log('Error: ' + msg);
+ }
+ console.log(backtrace());
+ UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
+ throw new Error(msg);
+}
+
+function backtrace() {
+ try {
+ throw new Error();
+ } catch (e) {
+ return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
+ }
+}
+
+function assert(cond, msg) {
+ if (!cond) {
+ error(msg);
+ }
+}
+
+var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
+ unknown: 'unknown',
+ forms: 'forms',
+ javaScript: 'javaScript',
+ smask: 'smask',
+ shadingPattern: 'shadingPattern',
+ font: 'font'
+};
+
+var UnsupportedManager = PDFJS.UnsupportedManager =
+ (function UnsupportedManagerClosure() {
+ var listeners = [];
+ return {
+ listen: function (cb) {
+ listeners.push(cb);
+ },
+ notify: function (featureId) {
+ warn('Unsupported feature "' + featureId + '"');
+ for (var i = 0, ii = listeners.length; i < ii; i++) {
+ listeners[i](featureId);
+ }
+ }
+ };
+})();
+
+// Combines two URLs. The baseUrl shall be absolute URL. If the url is an
+// absolute URL, it will be returned as is.
+function combineUrl(baseUrl, url) {
+ if (!url) {
+ return baseUrl;
+ }
+ if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
+ return url;
+ }
+ var i;
+ if (url.charAt(0) === '/') {
+ // absolute path
+ i = baseUrl.indexOf('://');
+ if (url.charAt(1) === '/') {
+ ++i;
+ } else {
+ i = baseUrl.indexOf('/', i + 3);
+ }
+ return baseUrl.substring(0, i) + url;
+ } else {
+ // relative path
+ var pathLength = baseUrl.length;
+ i = baseUrl.lastIndexOf('#');
+ pathLength = i >= 0 ? i : pathLength;
+ i = baseUrl.lastIndexOf('?', pathLength);
+ pathLength = i >= 0 ? i : pathLength;
+ var prefixLength = baseUrl.lastIndexOf('/', pathLength);
+ return baseUrl.substring(0, prefixLength + 1) + url;
+ }
+}
+
+// Validates if URL is safe and allowed, e.g. to avoid XSS.
+function isValidUrl(url, allowRelative) {
+ if (!url) {
+ return false;
+ }
+ // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
+ // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
+ var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
+ if (!protocol) {
+ return allowRelative;
+ }
+ protocol = protocol[0].toLowerCase();
+ switch (protocol) {
+ case 'http':
+ case 'https':
+ case 'ftp':
+ case 'mailto':
+ case 'tel':
+ return true;
+ default:
+ return false;
+ }
+}
+PDFJS.isValidUrl = isValidUrl;
+
+function shadow(obj, prop, value) {
+ Object.defineProperty(obj, prop, { value: value,
+ enumerable: true,
+ configurable: true,
+ writable: false });
+ return value;
+}
+PDFJS.shadow = shadow;
+
+var PasswordResponses = PDFJS.PasswordResponses = {
+ NEED_PASSWORD: 1,
+ INCORRECT_PASSWORD: 2
+};
+
+var PasswordException = (function PasswordExceptionClosure() {
+ function PasswordException(msg, code) {
+ this.name = 'PasswordException';
+ this.message = msg;
+ this.code = code;
+ }
+
+ PasswordException.prototype = new Error();
+ PasswordException.constructor = PasswordException;
+
+ return PasswordException;
+})();
+PDFJS.PasswordException = PasswordException;
+
+var UnknownErrorException = (function UnknownErrorExceptionClosure() {
+ function UnknownErrorException(msg, details) {
+ this.name = 'UnknownErrorException';
+ this.message = msg;
+ this.details = details;
+ }
+
+ UnknownErrorException.prototype = new Error();
+ UnknownErrorException.constructor = UnknownErrorException;
+
+ return UnknownErrorException;
+})();
+PDFJS.UnknownErrorException = UnknownErrorException;
+
+var InvalidPDFException = (function InvalidPDFExceptionClosure() {
+ function InvalidPDFException(msg) {
+ this.name = 'InvalidPDFException';
+ this.message = msg;
+ }
+
+ InvalidPDFException.prototype = new Error();
+ InvalidPDFException.constructor = InvalidPDFException;
+
+ return InvalidPDFException;
+})();
+PDFJS.InvalidPDFException = InvalidPDFException;
+
+var MissingPDFException = (function MissingPDFExceptionClosure() {
+ function MissingPDFException(msg) {
+ this.name = 'MissingPDFException';
+ this.message = msg;
+ }
+
+ MissingPDFException.prototype = new Error();
+ MissingPDFException.constructor = MissingPDFException;
+
+ return MissingPDFException;
+})();
+PDFJS.MissingPDFException = MissingPDFException;
+
+var UnexpectedResponseException =
+ (function UnexpectedResponseExceptionClosure() {
+ function UnexpectedResponseException(msg, status) {
+ this.name = 'UnexpectedResponseException';
+ this.message = msg;
+ this.status = status;
+ }
+
+ UnexpectedResponseException.prototype = new Error();
+ UnexpectedResponseException.constructor = UnexpectedResponseException;
+
+ return UnexpectedResponseException;
+})();
+PDFJS.UnexpectedResponseException = UnexpectedResponseException;
+
+var NotImplementedException = (function NotImplementedExceptionClosure() {
+ function NotImplementedException(msg) {
+ this.message = msg;
+ }
+
+ NotImplementedException.prototype = new Error();
+ NotImplementedException.prototype.name = 'NotImplementedException';
+ NotImplementedException.constructor = NotImplementedException;
+
+ return NotImplementedException;
+})();
+
+var MissingDataException = (function MissingDataExceptionClosure() {
+ function MissingDataException(begin, end) {
+ this.begin = begin;
+ this.end = end;
+ this.message = 'Missing data [' + begin + ', ' + end + ')';
+ }
+
+ MissingDataException.prototype = new Error();
+ MissingDataException.prototype.name = 'MissingDataException';
+ MissingDataException.constructor = MissingDataException;
+
+ return MissingDataException;
+})();
+
+var XRefParseException = (function XRefParseExceptionClosure() {
+ function XRefParseException(msg) {
+ this.message = msg;
+ }
+
+ XRefParseException.prototype = new Error();
+ XRefParseException.prototype.name = 'XRefParseException';
+ XRefParseException.constructor = XRefParseException;
+
+ return XRefParseException;
+})();
+
+
+function bytesToString(bytes) {
+ assert(bytes !== null && typeof bytes === 'object' &&
+ bytes.length !== undefined, 'Invalid argument for bytesToString');
+ var length = bytes.length;
+ var MAX_ARGUMENT_COUNT = 8192;
+ if (length < MAX_ARGUMENT_COUNT) {
+ return String.fromCharCode.apply(null, bytes);
+ }
+ var strBuf = [];
+ for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
+ var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
+ var chunk = bytes.subarray(i, chunkEnd);
+ strBuf.push(String.fromCharCode.apply(null, chunk));
+ }
+ return strBuf.join('');
+}
+
+function stringToBytes(str) {
+ assert(typeof str === 'string', 'Invalid argument for stringToBytes');
+ var length = str.length;
+ var bytes = new Uint8Array(length);
+ for (var 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 log2(x) {
+ var n = 1, i = 0;
+ while (x > n) {
+ n <<= 1;
+ i++;
+ }
+ return i;
+}
+
+function readInt8(data, start) {
+ return (data[start] << 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;
+}
+
+// Lazy test the endianness of the platform
+// NOTE: This will be 'true' for simulated TypedArrays
+function isLittleEndian() {
+ var buffer8 = new Uint8Array(2);
+ buffer8[0] = 1;
+ var buffer16 = new Uint16Array(buffer8.buffer);
+ return (buffer16[0] === 1);
+}
+
+Object.defineProperty(PDFJS, 'isLittleEndian', {
+ configurable: true,
+ get: function PDFJS_isLittleEndian() {
+ return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
+ }
+});
+
+//#if !(FIREFOX || MOZCENTRAL || B2G || CHROME)
+//// Lazy test if the userAgant support CanvasTypedArrays
+function hasCanvasTypedArrays() {
+ var canvas = document.createElement('canvas');
+ canvas.width = canvas.height = 1;
+ var ctx = canvas.getContext('2d');
+ var imageData = ctx.createImageData(1, 1);
+ return (typeof imageData.data.buffer !== 'undefined');
+}
+
+Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
+ configurable: true,
+ get: function PDFJS_hasCanvasTypedArrays() {
+ return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
+ }
+});
+
+var Uint32ArrayView = (function Uint32ArrayViewClosure() {
+
+ function Uint32ArrayView(buffer, length) {
+ this.buffer = buffer;
+ this.byteLength = buffer.length;
+ this.length = length === undefined ? (this.byteLength >> 2) : length;
+ ensureUint32ArrayViewProps(this.length);
+ }
+ Uint32ArrayView.prototype = Object.create(null);
+
+ var uint32ArrayViewSetters = 0;
+ function createUint32ArrayProp(index) {
+ return {
+ get: function () {
+ var buffer = this.buffer, offset = index << 2;
+ return (buffer[offset] | (buffer[offset + 1] << 8) |
+ (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
+ },
+ set: function (value) {
+ var buffer = this.buffer, offset = index << 2;
+ buffer[offset] = value & 255;
+ buffer[offset + 1] = (value >> 8) & 255;
+ buffer[offset + 2] = (value >> 16) & 255;
+ buffer[offset + 3] = (value >>> 24) & 255;
+ }
+ };
+ }
+
+ function ensureUint32ArrayViewProps(length) {
+ while (uint32ArrayViewSetters < length) {
+ Object.defineProperty(Uint32ArrayView.prototype,
+ uint32ArrayViewSetters,
+ createUint32ArrayProp(uint32ArrayViewSetters));
+ uint32ArrayViewSetters++;
+ }
+ }
+
+ return Uint32ArrayView;
+})();
+//#else
+//PDFJS.hasCanvasTypedArrays = true;
+//#endif
+
+var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
+
+var Util = PDFJS.Util = (function UtilClosure() {
+ function Util() {}
+
+ var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
+
+ // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
+ // creating many intermediate strings.
+ Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
+ rgbBuf[1] = r;
+ rgbBuf[3] = g;
+ rgbBuf[5] = b;
+ return rgbBuf.join('');
+ };
+
+ // Concatenates two transformation matrices together and returns the result.
+ Util.transform = function Util_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]
+ ];
+ };
+
+ // For 2d affine transforms
+ Util.applyTransform = function Util_applyTransform(p, m) {
+ var xt = p[0] * m[0] + p[1] * m[2] + m[4];
+ var yt = p[0] * m[1] + p[1] * m[3] + m[5];
+ return [xt, yt];
+ };
+
+ Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
+ var d = m[0] * m[3] - m[1] * m[2];
+ var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
+ var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
+ return [xt, yt];
+ };
+
+ // Applies the transform to the rectangle and finds the minimum axially
+ // aligned bounding box.
+ Util.getAxialAlignedBoundingBox =
+ function Util_getAxialAlignedBoundingBox(r, m) {
+
+ var p1 = Util.applyTransform(r, m);
+ var p2 = Util.applyTransform(r.slice(2, 4), m);
+ var p3 = Util.applyTransform([r[0], r[3]], m);
+ var p4 = Util.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])
+ ];
+ };
+
+ Util.inverseTransform = function Util_inverseTransform(m) {
+ var 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];
+ };
+
+ // Apply a generic 3d matrix M on a 3-vector v:
+ // | a b c | | X |
+ // | d e f | x | Y |
+ // | g h i | | Z |
+ // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
+ // with v as [X,Y,Z]
+ Util.apply3dTransform = function Util_apply3dTransform(m, v) {
+ return [
+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
+ m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
+ m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
+ ];
+ };
+
+ // This calculation uses Singular Value Decomposition.
+ // The SVD can be represented with formula A = USV. We are interested in the
+ // matrix S here because it represents the scale values.
+ Util.singularValueDecompose2dScale =
+ function Util_singularValueDecompose2dScale(m) {
+
+ var transpose = [m[0], m[2], m[1], m[3]];
+
+ // Multiply matrix m with its transpose.
+ var a = m[0] * transpose[0] + m[1] * transpose[2];
+ var b = m[0] * transpose[1] + m[1] * transpose[3];
+ var c = m[2] * transpose[0] + m[3] * transpose[2];
+ var d = m[2] * transpose[1] + m[3] * transpose[3];
+
+ // Solve the second degree polynomial to get roots.
+ var first = (a + d) / 2;
+ var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
+ var sx = first + second || 1;
+ var sy = first - second || 1;
+
+ // Scale values are the square roots of the eigenvalues.
+ return [Math.sqrt(sx), Math.sqrt(sy)];
+ };
+
+ // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
+ // For coordinate systems whose origin lies in the bottom-left, this
+ // means normalization to (BL,TR) ordering. For systems with origin in the
+ // top-left, this means (TL,BR) ordering.
+ Util.normalizeRect = function Util_normalizeRect(rect) {
+ var r = rect.slice(0); // clone rect
+ 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;
+ };
+
+ // Returns a rectangle [x1, y1, x2, y2] corresponding to the
+ // intersection of rect1 and rect2. If no intersection, returns 'false'
+ // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
+ Util.intersect = function Util_intersect(rect1, rect2) {
+ function compare(a, b) {
+ return a - b;
+ }
+
+ // Order points along the axes
+ var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
+ orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
+ result = [];
+
+ rect1 = Util.normalizeRect(rect1);
+ rect2 = Util.normalizeRect(rect2);
+
+ // X: first and second points belong to different rectangles?
+ if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
+ (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
+ // Intersection must be between second and third points
+ result[0] = orderedX[1];
+ result[2] = orderedX[2];
+ } else {
+ return false;
+ }
+
+ // Y: first and second points belong to different rectangles?
+ if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
+ (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
+ // Intersection must be between second and third points
+ result[1] = orderedY[1];
+ result[3] = orderedY[2];
+ } else {
+ return false;
+ }
+
+ return result;
+ };
+
+ Util.sign = function Util_sign(num) {
+ return num < 0 ? -1 : 1;
+ };
+
+ Util.appendToArray = function Util_appendToArray(arr1, arr2) {
+ Array.prototype.push.apply(arr1, arr2);
+ };
+
+ Util.prependToArray = function Util_prependToArray(arr1, arr2) {
+ Array.prototype.unshift.apply(arr1, arr2);
+ };
+
+ Util.extendObj = function extendObj(obj1, obj2) {
+ for (var key in obj2) {
+ obj1[key] = obj2[key];
+ }
+ };
+
+ Util.getInheritableProperty = function Util_getInheritableProperty(dict,
+ name) {
+ while (dict && !dict.has(name)) {
+ dict = dict.get('Parent');
+ }
+ if (!dict) {
+ return null;
+ }
+ return dict.get(name);
+ };
+
+ Util.inherit = function Util_inherit(sub, base, prototype) {
+ sub.prototype = Object.create(base.prototype);
+ sub.prototype.constructor = sub;
+ for (var prop in prototype) {
+ sub.prototype[prop] = prototype[prop];
+ }
+ };
+
+ Util.loadScript = function Util_loadScript(src, callback) {
+ var script = document.createElement('script');
+ var loaded = false;
+ script.setAttribute('src', src);
+ if (callback) {
+ script.onload = function() {
+ if (!loaded) {
+ callback();
+ }
+ loaded = true;
+ };
+ }
+ document.getElementsByTagName('head')[0].appendChild(script);
+ };
+
+ return Util;
+})();
+
+/**
+ * PDF page viewport created based on scale, rotation and offset.
+ * @class
+ * @alias PDFJS.PageViewport
+ */
+var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
+ /**
+ * @constructor
+ * @private
+ * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
+ * @param scale {number} scale of the viewport.
+ * @param rotation {number} rotations of the viewport in degrees.
+ * @param offsetX {number} offset X
+ * @param offsetY {number} offset Y
+ * @param dontFlip {boolean} if true, axis Y will not be flipped.
+ */
+ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
+ this.viewBox = viewBox;
+ this.scale = scale;
+ this.rotation = rotation;
+ this.offsetX = offsetX;
+ this.offsetY = offsetY;
+
+ // creating transform to convert pdf coordinate system to the normal
+ // canvas like coordinates taking in account scale and rotation
+ var centerX = (viewBox[2] + viewBox[0]) / 2;
+ var centerY = (viewBox[3] + viewBox[1]) / 2;
+ var rotateA, rotateB, rotateC, rotateD;
+ rotation = rotation % 360;
+ rotation = rotation < 0 ? rotation + 360 : rotation;
+ switch (rotation) {
+ case 180:
+ rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
+ break;
+ case 90:
+ rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
+ break;
+ case 270:
+ rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
+ break;
+ //case 0:
+ default:
+ rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
+ break;
+ }
+
+ if (dontFlip) {
+ rotateC = -rotateC; rotateD = -rotateD;
+ }
+
+ var offsetCanvasX, offsetCanvasY;
+ var width, height;
+ if (rotateA === 0) {
+ offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
+ offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
+ width = Math.abs(viewBox[3] - viewBox[1]) * scale;
+ height = Math.abs(viewBox[2] - viewBox[0]) * scale;
+ } else {
+ offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
+ offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
+ width = Math.abs(viewBox[2] - viewBox[0]) * scale;
+ height = Math.abs(viewBox[3] - viewBox[1]) * scale;
+ }
+ // creating transform for the following operations:
+ // translate(-centerX, -centerY), rotate and flip vertically,
+ // scale, and translate(offsetCanvasX, offsetCanvasY)
+ this.transform = [
+ rotateA * scale,
+ rotateB * scale,
+ rotateC * scale,
+ rotateD * scale,
+ offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
+ offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
+ ];
+
+ this.width = width;
+ this.height = height;
+ this.fontScale = scale;
+ }
+ PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
+ /**
+ * Clones viewport with additional properties.
+ * @param args {Object} (optional) If specified, may contain the 'scale' or
+ * 'rotation' properties to override the corresponding properties in
+ * the cloned viewport.
+ * @returns {PDFJS.PageViewport} Cloned viewport.
+ */
+ clone: function PageViewPort_clone(args) {
+ args = args || {};
+ var scale = 'scale' in args ? args.scale : this.scale;
+ var rotation = 'rotation' in args ? args.rotation : this.rotation;
+ return new PageViewport(this.viewBox.slice(), scale, rotation,
+ this.offsetX, this.offsetY, args.dontFlip);
+ },
+ /**
+ * Converts PDF point to the viewport coordinates. For examples, useful for
+ * converting PDF location into canvas pixel coordinates.
+ * @param x {number} X coordinate.
+ * @param y {number} Y coordinate.
+ * @returns {Object} Object that contains 'x' and 'y' properties of the
+ * point in the viewport coordinate space.
+ * @see {@link convertToPdfPoint}
+ * @see {@link convertToViewportRectangle}
+ */
+ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
+ return Util.applyTransform([x, y], this.transform);
+ },
+ /**
+ * Converts PDF rectangle to the viewport coordinates.
+ * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
+ * @returns {Array} Contains corresponding coordinates of the rectangle
+ * in the viewport coordinate space.
+ * @see {@link convertToViewportPoint}
+ */
+ convertToViewportRectangle:
+ function PageViewport_convertToViewportRectangle(rect) {
+ var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
+ var br = Util.applyTransform([rect[2], rect[3]], this.transform);
+ return [tl[0], tl[1], br[0], br[1]];
+ },
+ /**
+ * Converts viewport coordinates to the PDF location. For examples, useful
+ * for converting canvas pixel location into PDF one.
+ * @param x {number} X coordinate.
+ * @param y {number} Y coordinate.
+ * @returns {Object} Object that contains 'x' and 'y' properties of the
+ * point in the PDF coordinate space.
+ * @see {@link convertToViewportPoint}
+ */
+ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
+ return Util.applyInverseTransform([x, y], this.transform);
+ }
+ };
+ return PageViewport;
+})();
+
+var 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) {
+ var i, n = str.length, strBuf = [];
+ if (str[0] === '\xFE' && str[1] === '\xFF') {
+ // UTF16BE BOM
+ for (i = 2; i < n; i += 2) {
+ strBuf.push(String.fromCharCode(
+ (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
+ }
+ } else {
+ for (i = 0; i < n; ++i) {
+ var code = PDFStringTranslateTable[str.charCodeAt(i)];
+ strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
+ }
+ }
+ return strBuf.join('');
+}
+
+function stringToUTF8String(str) {
+ return decodeURIComponent(escape(str));
+}
+
+function isEmptyObj(obj) {
+ for (var key in obj) {
+ return false;
+ }
+ return true;
+}
+
+function isBool(v) {
+ return typeof v === 'boolean';
+}
+
+function isInt(v) {
+ return typeof v === 'number' && ((v | 0) === v);
+}
+
+function isNum(v) {
+ return typeof v === 'number';
+}
+
+function isString(v) {
+ return typeof v === 'string';
+}
+
+function isNull(v) {
+ return v === null;
+}
+
+function isName(v) {
+ return v instanceof Name;
+}
+
+function isCmd(v, cmd) {
+ return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
+}
+
+function isDict(v, type) {
+ if (!(v instanceof Dict)) {
+ return false;
+ }
+ if (!type) {
+ return true;
+ }
+ var dictType = v.get('Type');
+ return isName(dictType) && dictType.name === type;
+}
+
+function isArray(v) {
+ return v instanceof Array;
+}
+
+function isStream(v) {
+ return typeof v === 'object' && v !== null && v.getBytes !== undefined;
+}
+
+function isArrayBuffer(v) {
+ return typeof v === 'object' && v !== null && v.byteLength !== undefined;
+}
+
+function isRef(v) {
+ return v instanceof Ref;
+}
+
+/**
+ * Promise Capability object.
+ *
+ * @typedef {Object} PromiseCapability
+ * @property {Promise} promise - A promise object.
+ * @property {function} resolve - Fullfills the promise.
+ * @property {function} reject - Rejects the promise.
+ */
+
+/**
+ * Creates a promise capability object.
+ * @alias PDFJS.createPromiseCapability
+ *
+ * @return {PromiseCapability} A capability object contains:
+ * - a Promise, resolve and reject methods.
+ */
+function createPromiseCapability() {
+ var capability = {};
+ capability.promise = new Promise(function (resolve, reject) {
+ capability.resolve = resolve;
+ capability.reject = reject;
+ });
+ return capability;
+}
+
+PDFJS.createPromiseCapability = createPromiseCapability;
+
+/**
+ * Polyfill for Promises:
+ * The following promise implementation tries to generally implement the
+ * Promise/A+ spec. Some notable differences from other promise libaries are:
+ * - There currently isn't a seperate deferred and promise object.
+ * - Unhandled rejections eventually show an error if they aren't handled.
+ *
+ * Based off of the work in:
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
+ */
+(function PromiseClosure() {
+ if (globalScope.Promise) {
+ // Promises existing in the DOM/Worker, checking presence of all/resolve
+ if (typeof globalScope.Promise.all !== 'function') {
+ globalScope.Promise.all = function (iterable) {
+ var count = 0, results = [], resolve, reject;
+ var promise = new globalScope.Promise(function (resolve_, reject_) {
+ resolve = resolve_;
+ reject = reject_;
+ });
+ iterable.forEach(function (p, i) {
+ count++;
+ p.then(function (result) {
+ results[i] = result;
+ count--;
+ if (count === 0) {
+ resolve(results);
+ }
+ }, reject);
+ });
+ if (count === 0) {
+ resolve(results);
+ }
+ return promise;
+ };
+ }
+ if (typeof globalScope.Promise.resolve !== 'function') {
+ globalScope.Promise.resolve = function (value) {
+ return new globalScope.Promise(function (resolve) { resolve(value); });
+ };
+ }
+ if (typeof globalScope.Promise.reject !== 'function') {
+ globalScope.Promise.reject = function (reason) {
+ return new globalScope.Promise(function (resolve, reject) {
+ reject(reason);
+ });
+ };
+ }
+ if (typeof globalScope.Promise.prototype.catch !== 'function') {
+ globalScope.Promise.prototype.catch = function (onReject) {
+ return globalScope.Promise.prototype.then(undefined, onReject);
+ };
+ }
+ return;
+ }
+//#if !MOZCENTRAL
+ var STATUS_PENDING = 0;
+ var STATUS_RESOLVED = 1;
+ var STATUS_REJECTED = 2;
+
+ // In an attempt to avoid silent exceptions, unhandled rejections are
+ // tracked and if they aren't handled in a certain amount of time an
+ // error is logged.
+ var REJECTION_TIMEOUT = 500;
+
+ var HandlerManager = {
+ handlers: [],
+ running: false,
+ unhandledRejections: [],
+ pendingRejectionCheck: false,
+
+ scheduleHandlers: function scheduleHandlers(promise) {
+ if (promise._status === STATUS_PENDING) {
+ return;
+ }
+
+ this.handlers = this.handlers.concat(promise._handlers);
+ promise._handlers = [];
+
+ if (this.running) {
+ return;
+ }
+ this.running = true;
+
+ setTimeout(this.runHandlers.bind(this), 0);
+ },
+
+ runHandlers: function runHandlers() {
+ var RUN_TIMEOUT = 1; // ms
+ var timeoutAt = Date.now() + RUN_TIMEOUT;
+ while (this.handlers.length > 0) {
+ var handler = this.handlers.shift();
+
+ var nextStatus = handler.thisPromise._status;
+ var nextValue = handler.thisPromise._value;
+
+ try {
+ if (nextStatus === STATUS_RESOLVED) {
+ if (typeof handler.onResolve === 'function') {
+ nextValue = handler.onResolve(nextValue);
+ }
+ } else if (typeof handler.onReject === 'function') {
+ nextValue = handler.onReject(nextValue);
+ nextStatus = STATUS_RESOLVED;
+
+ if (handler.thisPromise._unhandledRejection) {
+ this.removeUnhandeledRejection(handler.thisPromise);
+ }
+ }
+ } catch (ex) {
+ nextStatus = STATUS_REJECTED;
+ nextValue = ex;
+ }
+
+ handler.nextPromise._updateStatus(nextStatus, nextValue);
+ if (Date.now() >= timeoutAt) {
+ break;
+ }
+ }
+
+ if (this.handlers.length > 0) {
+ setTimeout(this.runHandlers.bind(this), 0);
+ return;
+ }
+
+ this.running = false;
+ },
+
+ addUnhandledRejection: function addUnhandledRejection(promise) {
+ this.unhandledRejections.push({
+ promise: promise,
+ time: Date.now()
+ });
+ this.scheduleRejectionCheck();
+ },
+
+ removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
+ promise._unhandledRejection = false;
+ for (var i = 0; i < this.unhandledRejections.length; i++) {
+ if (this.unhandledRejections[i].promise === promise) {
+ this.unhandledRejections.splice(i);
+ i--;
+ }
+ }
+ },
+
+ scheduleRejectionCheck: function scheduleRejectionCheck() {
+ if (this.pendingRejectionCheck) {
+ return;
+ }
+ this.pendingRejectionCheck = true;
+ setTimeout(function rejectionCheck() {
+ this.pendingRejectionCheck = false;
+ var now = Date.now();
+ for (var i = 0; i < this.unhandledRejections.length; i++) {
+ if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
+ var unhandled = this.unhandledRejections[i].promise._value;
+ var msg = 'Unhandled rejection: ' + unhandled;
+ if (unhandled.stack) {
+ msg += '\n' + unhandled.stack;
+ }
+ warn(msg);
+ this.unhandledRejections.splice(i);
+ i--;
+ }
+ }
+ if (this.unhandledRejections.length) {
+ this.scheduleRejectionCheck();
+ }
+ }.bind(this), REJECTION_TIMEOUT);
+ }
+ };
+
+ function Promise(resolver) {
+ this._status = STATUS_PENDING;
+ this._handlers = [];
+ try {
+ resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
+ } catch (e) {
+ this._reject(e);
+ }
+ }
+ /**
+ * Builds a promise that is resolved when all the passed in promises are
+ * resolved.
+ * @param {array} array of data and/or promises to wait for.
+ * @return {Promise} New dependant promise.
+ */
+ Promise.all = function Promise_all(promises) {
+ var resolveAll, rejectAll;
+ var deferred = new Promise(function (resolve, reject) {
+ resolveAll = resolve;
+ rejectAll = reject;
+ });
+ var unresolved = promises.length;
+ var results = [];
+ if (unresolved === 0) {
+ resolveAll(results);
+ return deferred;
+ }
+ function reject(reason) {
+ if (deferred._status === STATUS_REJECTED) {
+ return;
+ }
+ results = [];
+ rejectAll(reason);
+ }
+ for (var i = 0, ii = promises.length; i < ii; ++i) {
+ var promise = promises[i];
+ var resolve = (function(i) {
+ return function(value) {
+ if (deferred._status === STATUS_REJECTED) {
+ return;
+ }
+ results[i] = value;
+ unresolved--;
+ if (unresolved === 0) {
+ resolveAll(results);
+ }
+ };
+ })(i);
+ if (Promise.isPromise(promise)) {
+ promise.then(resolve, reject);
+ } else {
+ resolve(promise);
+ }
+ }
+ return deferred;
+ };
+
+ /**
+ * Checks if the value is likely a promise (has a 'then' function).
+ * @return {boolean} true if value is thenable
+ */
+ Promise.isPromise = function Promise_isPromise(value) {
+ return value && typeof value.then === 'function';
+ };
+
+ /**
+ * Creates resolved promise
+ * @param value resolve value
+ * @returns {Promise}
+ */
+ Promise.resolve = function Promise_resolve(value) {
+ return new Promise(function (resolve) { resolve(value); });
+ };
+
+ /**
+ * Creates rejected promise
+ * @param reason rejection value
+ * @returns {Promise}
+ */
+ Promise.reject = function Promise_reject(reason) {
+ return new Promise(function (resolve, reject) { reject(reason); });
+ };
+
+ Promise.prototype = {
+ _status: null,
+ _value: null,
+ _handlers: null,
+ _unhandledRejection: null,
+
+ _updateStatus: function Promise__updateStatus(status, value) {
+ if (this._status === STATUS_RESOLVED ||
+ this._status === STATUS_REJECTED) {
+ return;
+ }
+
+ if (status === STATUS_RESOLVED &&
+ Promise.isPromise(value)) {
+ value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
+ this._updateStatus.bind(this, STATUS_REJECTED));
+ return;
+ }
+
+ this._status = status;
+ this._value = value;
+
+ if (status === STATUS_REJECTED && this._handlers.length === 0) {
+ this._unhandledRejection = true;
+ HandlerManager.addUnhandledRejection(this);
+ }
+
+ HandlerManager.scheduleHandlers(this);
+ },
+
+ _resolve: function Promise_resolve(value) {
+ this._updateStatus(STATUS_RESOLVED, value);
+ },
+
+ _reject: function Promise_reject(reason) {
+ this._updateStatus(STATUS_REJECTED, reason);
+ },
+
+ then: function Promise_then(onResolve, onReject) {
+ var nextPromise = new Promise(function (resolve, reject) {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ this._handlers.push({
+ thisPromise: this,
+ onResolve: onResolve,
+ onReject: onReject,
+ nextPromise: nextPromise
+ });
+ HandlerManager.scheduleHandlers(this);
+ return nextPromise;
+ },
+
+ catch: function Promise_catch(onReject) {
+ return this.then(undefined, onReject);
+ }
+ };
+
+ globalScope.Promise = Promise;
+//#else
+//throw new Error('DOM Promise is not present');
+//#endif
+})();
+
+var StatTimer = (function StatTimerClosure() {
+ function rpad(str, pad, length) {
+ while (str.length < length) {
+ str += pad;
+ }
+ return str;
+ }
+ function StatTimer() {
+ this.started = {};
+ this.times = [];
+ this.enabled = true;
+ }
+ StatTimer.prototype = {
+ time: function StatTimer_time(name) {
+ if (!this.enabled) {
+ return;
+ }
+ if (name in this.started) {
+ warn('Timer is already running for ' + name);
+ }
+ this.started[name] = Date.now();
+ },
+ timeEnd: function StatTimer_timeEnd(name) {
+ if (!this.enabled) {
+ return;
+ }
+ if (!(name in this.started)) {
+ warn('Timer has not been started for ' + name);
+ }
+ this.times.push({
+ 'name': name,
+ 'start': this.started[name],
+ 'end': Date.now()
+ });
+ // Remove timer from started so it can be called again.
+ delete this.started[name];
+ },
+ toString: function StatTimer_toString() {
+ var i, ii;
+ var times = this.times;
+ var out = '';
+ // Find the longest name for padding purposes.
+ var longest = 0;
+ for (i = 0, ii = times.length; i < ii; ++i) {
+ var name = times[i]['name'];
+ if (name.length > longest) {
+ longest = name.length;
+ }
+ }
+ for (i = 0, ii = times.length; i < ii; ++i) {
+ var span = times[i];
+ var duration = span.end - span.start;
+ out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
+ }
+ return out;
+ }
+ };
+ return StatTimer;
+})();
+
+PDFJS.createBlob = function createBlob(data, contentType) {
+ if (typeof Blob !== 'undefined') {
+ return new Blob([data], { type: contentType });
+ }
+ // Blob builder is deprecated in FF14 and removed in FF18.
+ var bb = new MozBlobBuilder();
+ bb.append(data);
+ return bb.getBlob(contentType);
+};
+
+PDFJS.createObjectURL = (function createObjectURLClosure() {
+ // Blob/createObjectURL is not available, falling back to data schema.
+ var digits =
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
+
+ return function createObjectURL(data, contentType) {
+ if (!PDFJS.disableCreateObjectURL &&
+ typeof URL !== 'undefined' && URL.createObjectURL) {
+ var blob = PDFJS.createBlob(data, contentType);
+ return URL.createObjectURL(blob);
+ }
+
+ var buffer = 'data:' + contentType + ';base64,';
+ for (var i = 0, ii = data.length; i < ii; i += 3) {
+ var b1 = data[i] & 0xFF;
+ var b2 = data[i + 1] & 0xFF;
+ var b3 = data[i + 2] & 0xFF;
+ var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
+ var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
+ var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
+ buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
+ }
+ return buffer;
+ };
+})();
+
+function MessageHandler(name, comObj) {
+ this.name = name;
+ this.comObj = comObj;
+ this.callbackIndex = 1;
+ this.postMessageTransfers = true;
+ var callbacksCapabilities = this.callbacksCapabilities = {};
+ var ah = this.actionHandler = {};
+
+ ah['console_log'] = [function ahConsoleLog(data) {
+ console.log.apply(console, data);
+ }];
+ ah['console_error'] = [function ahConsoleError(data) {
+ console.error.apply(console, data);
+ }];
+ ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
+ UnsupportedManager.notify(data);
+ }];
+
+ comObj.onmessage = function messageHandlerComObjOnMessage(event) {
+ var data = event.data;
+ if (data.isReply) {
+ var callbackId = data.callbackId;
+ if (data.callbackId in callbacksCapabilities) {
+ var callback = callbacksCapabilities[callbackId];
+ delete callbacksCapabilities[callbackId];
+ if ('error' in data) {
+ callback.reject(data.error);
+ } else {
+ callback.resolve(data.data);
+ }
+ } else {
+ error('Cannot resolve callback ' + callbackId);
+ }
+ } else if (data.action in ah) {
+ var action = ah[data.action];
+ if (data.callbackId) {
+ Promise.resolve().then(function () {
+ return action[0].call(action[1], data.data);
+ }).then(function (result) {
+ comObj.postMessage({
+ isReply: true,
+ callbackId: data.callbackId,
+ data: result
+ });
+ }, function (reason) {
+ comObj.postMessage({
+ isReply: true,
+ callbackId: data.callbackId,
+ error: reason
+ });
+ });
+ } else {
+ action[0].call(action[1], data.data);
+ }
+ } else {
+ error('Unknown action from worker: ' + data.action);
+ }
+ };
+}
+
+MessageHandler.prototype = {
+ on: function messageHandlerOn(actionName, handler, scope) {
+ var ah = this.actionHandler;
+ if (ah[actionName]) {
+ error('There is already an actionName called "' + actionName + '"');
+ }
+ ah[actionName] = [handler, scope];
+ },
+ /**
+ * Sends a message to the comObj to invoke the action with the supplied data.
+ * @param {String} actionName Action to call.
+ * @param {JSON} data JSON data to send.
+ * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
+ */
+ send: function messageHandlerSend(actionName, data, transfers) {
+ var message = {
+ action: actionName,
+ data: data
+ };
+ this.postMessage(message, transfers);
+ },
+ /**
+ * Sends a message to the comObj to invoke the action with the supplied data.
+ * Expects that other side will callback with the response.
+ * @param {String} actionName Action to call.
+ * @param {JSON} data JSON data to send.
+ * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
+ * @returns {Promise} Promise to be resolved with response data.
+ */
+ sendWithPromise:
+ function messageHandlerSendWithPromise(actionName, data, transfers) {
+ var callbackId = this.callbackIndex++;
+ var message = {
+ action: actionName,
+ data: data,
+ callbackId: callbackId
+ };
+ var capability = createPromiseCapability();
+ this.callbacksCapabilities[callbackId] = capability;
+ try {
+ this.postMessage(message, transfers);
+ } catch (e) {
+ capability.reject(e);
+ }
+ return capability.promise;
+ },
+ /**
+ * Sends raw message to the comObj.
+ * @private
+ * @param message {Object} Raw message.
+ * @param transfers List of transfers/ArrayBuffers, or undefined.
+ */
+ postMessage: function (message, transfers) {
+ if (transfers && this.postMessageTransfers) {
+ this.comObj.postMessage(message, transfers);
+ } else {
+ this.comObj.postMessage(message);
+ }
+ }
+};
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = JpxImage;
+}
+
+function loadJpegStream(id, imageUrl, objs) {
+ var img = new Image();
+ img.onload = (function loadJpegStream_onloadClosure() {
+ objs.resolve(id, img);
+ });
+ img.onerror = (function loadJpegStream_onerrorClosure() {
+ objs.resolve(id, null);
+ warn('Error during JPEG image loading');
+ });
+ img.src = imageUrl;
+}
+},{}],3:[function(require,module,exports){
+// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
+//
+// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
+//
+// Originally from narwhal.js (http://narwhaljs.org)
+// Copyright (c) 2009 Thomas Robinson <280north.com>
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the 'Software'), to
+// deal in the Software without restriction, including without limitation the
+// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+// sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+// when used in node, this will actually load the util module we depend on
+// versus loading the builtin util module as happens otherwise
+// this is a bug in node module loading as far as I am concerned
+var util = require('util/');
+
+var pSlice = Array.prototype.slice;
+var hasOwn = Object.prototype.hasOwnProperty;
+
+// 1. The assert module provides functions that throw
+// AssertionError's when particular conditions are not met. The
+// assert module must conform to the following interface.
+
+var assert = module.exports = ok;
+
+// 2. The AssertionError is defined in assert.
+// new assert.AssertionError({ message: message,
+// actual: actual,
+// expected: expected })
+
+assert.AssertionError = function AssertionError(options) {
+ this.name = 'AssertionError';
+ this.actual = options.actual;
+ this.expected = options.expected;
+ this.operator = options.operator;
+ if (options.message) {
+ this.message = options.message;
+ this.generatedMessage = false;
+ } else {
+ this.message = getMessage(this);
+ this.generatedMessage = true;
+ }
+ var stackStartFunction = options.stackStartFunction || fail;
+
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, stackStartFunction);
+ }
+ else {
+ // non v8 browsers so we can have a stacktrace
+ var err = new Error();
+ if (err.stack) {
+ var out = err.stack;
+
+ // try to strip useless frames
+ var fn_name = stackStartFunction.name;
+ var idx = out.indexOf('\n' + fn_name);
+ if (idx >= 0) {
+ // once we have located the function frame
+ // we need to strip out everything before it (and its line)
+ var next_line = out.indexOf('\n', idx + 1);
+ out = out.substring(next_line + 1);
+ }
+
+ this.stack = out;
+ }
+ }
+};
+
+// assert.AssertionError instanceof Error
+util.inherits(assert.AssertionError, Error);
+
+function replacer(key, value) {
+ if (util.isUndefined(value)) {
+ return '' + value;
+ }
+ if (util.isNumber(value) && !isFinite(value)) {
+ return value.toString();
+ }
+ if (util.isFunction(value) || util.isRegExp(value)) {
+ return value.toString();
+ }
+ return value;
+}
+
+function truncate(s, n) {
+ if (util.isString(s)) {
+ return s.length < n ? s : s.slice(0, n);
+ } else {
+ return s;
+ }
+}
+
+function getMessage(self) {
+ return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
+ self.operator + ' ' +
+ truncate(JSON.stringify(self.expected, replacer), 128);
+}
+
+// At present only the three keys mentioned above are used and
+// understood by the spec. Implementations or sub modules can pass
+// other keys to the AssertionError's constructor - they will be
+// ignored.
+
+// 3. All of the following functions must throw an AssertionError
+// when a corresponding condition is not met, with a message that
+// may be undefined if not provided. All assertion methods provide
+// both the actual and expected values to the assertion error for
+// display purposes.
+
+function fail(actual, expected, message, operator, stackStartFunction) {
+ throw new assert.AssertionError({
+ message: message,
+ actual: actual,
+ expected: expected,
+ operator: operator,
+ stackStartFunction: stackStartFunction
+ });
+}
+
+// EXTENSION! allows for well behaved errors defined elsewhere.
+assert.fail = fail;
+
+// 4. Pure assertion tests whether a value is truthy, as determined
+// by !!guard.
+// assert.ok(guard, message_opt);
+// This statement is equivalent to assert.equal(true, !!guard,
+// message_opt);. To test strictly for the value true, use
+// assert.strictEqual(true, guard, message_opt);.
+
+function ok(value, message) {
+ if (!value) fail(value, true, message, '==', assert.ok);
+}
+assert.ok = ok;
+
+// 5. The equality assertion tests shallow, coercive equality with
+// ==.
+// assert.equal(actual, expected, message_opt);
+
+assert.equal = function equal(actual, expected, message) {
+ if (actual != expected) fail(actual, expected, message, '==', assert.equal);
+};
+
+// 6. The non-equality assertion tests for whether two objects are not equal
+// with != assert.notEqual(actual, expected, message_opt);
+
+assert.notEqual = function notEqual(actual, expected, message) {
+ if (actual == expected) {
+ fail(actual, expected, message, '!=', assert.notEqual);
+ }
+};
+
+// 7. The equivalence assertion tests a deep equality relation.
+// assert.deepEqual(actual, expected, message_opt);
+
+assert.deepEqual = function deepEqual(actual, expected, message) {
+ if (!_deepEqual(actual, expected)) {
+ fail(actual, expected, message, 'deepEqual', assert.deepEqual);
+ }
+};
+
+function _deepEqual(actual, expected) {
+ // 7.1. All identical values are equivalent, as determined by ===.
+ if (actual === expected) {
+ return true;
+
+ } else if (util.isBuffer(actual) && util.isBuffer(expected)) {
+ if (actual.length != expected.length) return false;
+
+ for (var i = 0; i < actual.length; i++) {
+ if (actual[i] !== expected[i]) return false;
+ }
+
+ return true;
+
+ // 7.2. If the expected value is a Date object, the actual value is
+ // equivalent if it is also a Date object that refers to the same time.
+ } else if (util.isDate(actual) && util.isDate(expected)) {
+ return actual.getTime() === expected.getTime();
+
+ // 7.3 If the expected value is a RegExp object, the actual value is
+ // equivalent if it is also a RegExp object with the same source and
+ // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
+ } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
+ return actual.source === expected.source &&
+ actual.global === expected.global &&
+ actual.multiline === expected.multiline &&
+ actual.lastIndex === expected.lastIndex &&
+ actual.ignoreCase === expected.ignoreCase;
+
+ // 7.4. Other pairs that do not both pass typeof value == 'object',
+ // equivalence is determined by ==.
+ } else if (!util.isObject(actual) && !util.isObject(expected)) {
+ return actual == expected;
+
+ // 7.5 For all other Object pairs, including Array objects, equivalence is
+ // determined by having the same number of owned properties (as verified
+ // with Object.prototype.hasOwnProperty.call), the same set of keys
+ // (although not necessarily the same order), equivalent values for every
+ // corresponding key, and an identical 'prototype' property. Note: this
+ // accounts for both named and indexed properties on Arrays.
+ } else {
+ return objEquiv(actual, expected);
+ }
+}
+
+function isArguments(object) {
+ return Object.prototype.toString.call(object) == '[object Arguments]';
+}
+
+function objEquiv(a, b) {
+ if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
+ return false;
+ // an identical 'prototype' property.
+ if (a.prototype !== b.prototype) return false;
+ // if one is a primitive, the other must be same
+ if (util.isPrimitive(a) || util.isPrimitive(b)) {
+ return a === b;
+ }
+ var aIsArgs = isArguments(a),
+ bIsArgs = isArguments(b);
+ if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
+ return false;
+ if (aIsArgs) {
+ a = pSlice.call(a);
+ b = pSlice.call(b);
+ return _deepEqual(a, b);
+ }
+ var ka = objectKeys(a),
+ kb = objectKeys(b),
+ key, i;
+ // having the same number of owned properties (keys incorporates
+ // hasOwnProperty)
+ if (ka.length != kb.length)
+ return false;
+ //the same set of keys (although not necessarily the same order),
+ ka.sort();
+ kb.sort();
+ //~~~cheap key test
+ for (i = ka.length - 1; i >= 0; i--) {
+ if (ka[i] != kb[i])
+ return false;
+ }
+ //equivalent values for every corresponding key, and
+ //~~~possibly expensive deep test
+ for (i = ka.length - 1; i >= 0; i--) {
+ key = ka[i];
+ if (!_deepEqual(a[key], b[key])) return false;
+ }
+ return true;
+}
+
+// 8. The non-equivalence assertion tests for any deep inequality.
+// assert.notDeepEqual(actual, expected, message_opt);
+
+assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
+ if (_deepEqual(actual, expected)) {
+ fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
+ }
+};
+
+// 9. The strict equality assertion tests strict equality, as determined by ===.
+// assert.strictEqual(actual, expected, message_opt);
+
+assert.strictEqual = function strictEqual(actual, expected, message) {
+ if (actual !== expected) {
+ fail(actual, expected, message, '===', assert.strictEqual);
+ }
+};
+
+// 10. The strict non-equality assertion tests for strict inequality, as
+// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
+
+assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
+ if (actual === expected) {
+ fail(actual, expected, message, '!==', assert.notStrictEqual);
+ }
+};
+
+function expectedException(actual, expected) {
+ if (!actual || !expected) {
+ return false;
+ }
+
+ if (Object.prototype.toString.call(expected) == '[object RegExp]') {
+ return expected.test(actual);
+ } else if (actual instanceof expected) {
+ return true;
+ } else if (expected.call({}, actual) === true) {
+ return true;
+ }
+
+ return false;
+}
+
+function _throws(shouldThrow, block, expected, message) {
+ var actual;
+
+ if (util.isString(expected)) {
+ message = expected;
+ expected = null;
+ }
+
+ try {
+ block();
+ } catch (e) {
+ actual = e;
+ }
+
+ message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
+ (message ? ' ' + message : '.');
+
+ if (shouldThrow && !actual) {
+ fail(actual, expected, 'Missing expected exception' + message);
+ }
+
+ if (!shouldThrow && expectedException(actual, expected)) {
+ fail(actual, expected, 'Got unwanted exception' + message);
+ }
+
+ if ((shouldThrow && actual && expected &&
+ !expectedException(actual, expected)) || (!shouldThrow && actual)) {
+ throw actual;
+ }
+}
+
+// 11. Expected to throw an error:
+// assert.throws(block, Error_opt, message_opt);
+
+assert.throws = function(block, /*optional*/error, /*optional*/message) {
+ _throws.apply(this, [true].concat(pSlice.call(arguments)));
+};
+
+// EXTENSION! This is annoying to write outside this module.
+assert.doesNotThrow = function(block, /*optional*/message) {
+ _throws.apply(this, [false].concat(pSlice.call(arguments)));
+};
+
+assert.ifError = function(err) { if (err) {throw err;}};
+
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) {
+ if (hasOwn.call(obj, key)) keys.push(key);
+ }
+ return keys;
+};
+
+},{"util/":47}],4:[function(require,module,exports){
+'use strict';
+
+// VARIABLES //
+
+var FLOAT32_VIEW = new Float32Array( 1 );
+var UINT32_VIEW = new Uint32Array( FLOAT32_VIEW.buffer );
+
+// 1 11111111 00000000000000000000000 => 4286578688 => 0xff800000 (see IEEE 754-2008)
+var NINF = 0xff800000;
+
+// Set the ArrayBuffer bit sequence:
+UINT32_VIEW[ 0 ] = NINF;
+
+
+// EXPORTS //
+
+module.exports = FLOAT32_VIEW[ 0 ];
+
+},{}],5:[function(require,module,exports){
+'use strict';
+
+// VARIABLES //
+
+var FLOAT32_VIEW = new Float32Array( 1 );
+var UINT32_VIEW = new Uint32Array( FLOAT32_VIEW.buffer );
+
+// 0 11111111 00000000000000000000000 => 2139095040 => 0x7f800000 (see IEEE 754-2008)
+var PINF = 0x7f800000;
+
+// Set the ArrayBuffer bit sequence:
+UINT32_VIEW[ 0 ] = PINF;
+
+
+// EXPORTS //
+
+module.exports = FLOAT32_VIEW[ 0 ];
+
+},{}],6:[function(require,module,exports){
+/*! dicom-parser - v1.1.0 - 2015-07-20 | (c) 2014 Chris Hafey | https://github.com/chafey/dicomParser */
+(function (root, factory) {
+
+ // node.js
+ if (typeof module !== 'undefined' && module.exports) {
+ module.exports = factory();
+ }
+ else if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module.
+ define([], factory);
+ } else {
+ // Browser globals
+ if(typeof cornerstone === 'undefined'){
+ dicomParser = {};
+
+ // meteor
+ if (typeof Package !== 'undefined') {
+ root.dicomParser = dicomParser;
+ }
+ }
+ dicomParser = factory();
+ }
+}(this, function () {
+
+ /**
+ * Parses a DICOM P10 byte array and returns a DataSet object with the parsed elements. If the options
+ * argument is supplied and it contains the untilTag property, parsing will stop once that
+ * tag is encoutered. This can be used to parse partial byte streams.
+ *
+ * @param byteArray the byte array
+ * @param options object to control parsing behavior (optional)
+ * @returns {DataSet}
+ * @throws error if an error occurs while parsing. The exception object will contain a property dataSet with the
+ * elements successfully parsed before the error.
+ */
+var dicomParser = (function(dicomParser) {
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ dicomParser.parseDicom = function(byteArray, options) {
+
+ if(byteArray === undefined)
+ {
+ throw "dicomParser.parseDicom: missing required parameter 'byteArray'";
+ }
+
+ var littleEndianByteStream = new dicomParser.ByteStream(dicomParser.littleEndianByteArrayParser, byteArray);
+
+ function readPrefix()
+ {
+ littleEndianByteStream.seek(128);
+ var prefix = littleEndianByteStream.readFixedString(4);
+ if(prefix !== "DICM")
+ {
+ throw "dicomParser.parseDicom: DICM prefix not found at location 132";
+ }
+ }
+
+ function readPart10Header()
+ {
+ // Per the DICOM standard, the header is always encoded in Explicit VR Little Endian (see PS3.10, section 7.1)
+ // so use littleEndianByteStream throughout this method regardless of the transfer syntax
+ readPrefix();
+
+ var warnings = [];
+ var elements = {};
+ while(littleEndianByteStream.position < littleEndianByteStream.byteArray.length) {
+ var position = littleEndianByteStream.position;
+ var element = dicomParser.readDicomElementExplicit(littleEndianByteStream, warnings);
+ if(element.tag > 'x0002ffff') {
+ littleEndianByteStream.position = position;
+ break;
+ }
+ // Cache the littleEndianByteArrayParser for meta header elements, since the rest of the data set may be big endian
+ // and this parser will be needed later if the meta header values are to be read.
+ element.parser = dicomParser.littleEndianByteArrayParser;
+ elements[element.tag] = element;
+ }
+ var metaHeaderDataSet = new dicomParser.DataSet(littleEndianByteStream.byteArrayParser, littleEndianByteStream.byteArray, elements);
+ metaHeaderDataSet.warnings = littleEndianByteStream.warnings;
+ return metaHeaderDataSet;
+ }
+
+ function readTransferSyntax(metaHeaderDataSet) {
+ if(metaHeaderDataSet.elements.x00020010 === undefined) {
+ throw 'dicomParser.parseDicom: missing required meta header attribute 0002,0010';
+ }
+ var transferSyntaxElement = metaHeaderDataSet.elements.x00020010;
+ return dicomParser.readFixedString(littleEndianByteStream.byteArray, transferSyntaxElement.dataOffset, transferSyntaxElement.length);
+ }
+
+ function isExplicit(transferSyntax) {
+ if(transferSyntax === '1.2.840.10008.1.2') // implicit little endian
+ {
+ return false;
+ }
+ // all other transfer syntaxes should be explicit
+ return true;
+ }
+
+ function getDataSetByteStream(transferSyntax) {
+ if(transferSyntax === '1.2.840.10008.1.2.2') // explicit big endian
+ {
+ return new dicomParser.ByteStream(dicomParser.bigEndianByteArrayParser, byteArray, littleEndianByteStream.position);
+ }
+ else
+ {
+ // all other transfer syntaxes are little endian; only the pixel encoding differs
+ // make a new stream so the metaheader warnings don't come along for the ride
+ return new dicomParser.ByteStream(dicomParser.littleEndianByteArrayParser, byteArray, littleEndianByteStream.position);
+ }
+ }
+
+ function mergeDataSets(metaHeaderDataSet, instanceDataSet)
+ {
+ for (var propertyName in metaHeaderDataSet.elements)
+ {
+ if(metaHeaderDataSet.elements.hasOwnProperty(propertyName))
+ {
+ instanceDataSet.elements[propertyName] = metaHeaderDataSet.elements[propertyName];
+ }
+ }
+ if (metaHeaderDataSet.warnings !== undefined) {
+ instanceDataSet.warnings = metaHeaderDataSet.warnings.concat(instanceDataSet.warnings);
+ }
+ return instanceDataSet;
+ }
+
+ function readDataSet(metaHeaderDataSet)
+ {
+ var transferSyntax = readTransferSyntax(metaHeaderDataSet);
+ var explicit = isExplicit(transferSyntax);
+ var dataSetByteStream = getDataSetByteStream(transferSyntax);
+
+ var elements = {};
+ var dataSet = new dicomParser.DataSet(dataSetByteStream.byteArrayParser, dataSetByteStream.byteArray, elements);
+ dataSet.warnings = dataSetByteStream.warnings;
+
+ try{
+ if(explicit) {
+ dicomParser.parseDicomDataSetExplicit(dataSet, dataSetByteStream, dataSetByteStream.byteArray.length, options);
+ }
+ else
+ {
+ dicomParser.parseDicomDataSetImplicit(dataSet, dataSetByteStream, dataSetByteStream.byteArray.length, options);
+ }
+ }
+ catch(e) {
+ var ex = {
+ exception: e,
+ dataSet: dataSet
+ };
+ throw ex;
+ }
+ return dataSet;
+ }
+
+ // main function here
+ function parseTheByteStream() {
+ var metaHeaderDataSet = readPart10Header();
+
+ var dataSet = readDataSet(metaHeaderDataSet);
+
+ return mergeDataSets(metaHeaderDataSet, dataSet);
+ }
+
+ // This is where we actually start parsing
+ return parseTheByteStream();
+ };
+
+ return dicomParser;
+})(dicomParser);
+
+var dicomParser = (function (dicomParser) {
+ "use strict";
+
+ if (dicomParser === undefined) {
+ dicomParser = {};
+ }
+
+ /**
+ * converts an explicit dataSet to a javascript object
+ * @param dataSet
+ * @param options
+ */
+ dicomParser.explicitDataSetToJS = function (dataSet, options) {
+
+ if(dataSet === undefined) {
+ throw 'dicomParser.explicitDataSetToJS: missing required parameter dataSet';
+ }
+
+ options = options || {
+ omitPrivateAttibutes: true, // true if private elements should be omitted
+ maxElementLength : 128 // maximum element length to try and convert to string format
+ };
+
+ var result = {
+
+ };
+
+ for(var tag in dataSet.elements) {
+ var element = dataSet.elements[tag];
+
+ // skip this element if it a private element and our options specify that we should
+ if(options.omitPrivateAttibutes === true && dicomParser.isPrivateTag(tag))
+ {
+ continue;
+ }
+
+ if(element.items) {
+ // handle sequences
+ var sequenceItems = [];
+ for(var i=0; i < element.items.length; i++) {
+ sequenceItems.push(dicomParser.explicitDataSetToJS(element.items[i].dataSet, options));
+ }
+ result[tag] = sequenceItems;
+ } else {
+ var asString;
+ asString = undefined;
+ if(element.length < options.maxElementLength) {
+ asString = dicomParser.explicitElementToString(dataSet, element);
+ }
+
+ if(asString !== undefined) {
+ result[tag] = asString;
+ } else {
+ result[tag] = {
+ dataOffset: element.dataOffset,
+ length : element.length
+ };
+ }
+ }
+ }
+
+ return result;
+ };
+
+
+ return dicomParser;
+}(dicomParser));
+var dicomParser = (function (dicomParser) {
+ "use strict";
+
+ if (dicomParser === undefined) {
+ dicomParser = {};
+ }
+
+ /**
+ * Converts an explicit VR element to a string or undefined if it is not possible to convert.
+ * Throws an error if an implicit element is supplied
+ * @param dataSet
+ * @param element
+ * @returns {*}
+ */
+ dicomParser.explicitElementToString = function(dataSet, element)
+ {
+ if(dataSet === undefined || element === undefined) {
+ throw 'dicomParser.explicitElementToString: missing required parameters';
+ }
+ if(element.vr === undefined) {
+ throw 'dicomParser.explicitElementToString: cannot convert implicit element to string';
+ }
+ var vr = element.vr;
+ var tag = element.tag;
+
+ var textResult;
+
+ function multiElementToString(numItems, func) {
+ var result = "";
+ for(var i=0; i < numItems; i++) {
+ if(i !== 0) {
+ result += '/';
+ }
+ result += func.call(dataSet, tag).toString();
+ }
+ return result;
+ }
+
+ if(dicomParser.isStringVr(vr) === true)
+ {
+ textResult = dataSet.string(tag);
+ }
+ else if (vr == 'AT') {
+ var num = dataSet.uint32(tag);
+ if(num === undefined) {
+ return undefined;
+ }
+ if (num < 0)
+ {
+ num = 0xFFFFFFFF + num + 1;
+ }
+
+ return 'x' + num.toString(16).toUpperCase();
+ }
+ else if (vr == 'US')
+ {
+ textResult = multiElementToString(element.length / 2, dataSet.uint16);
+ }
+ else if(vr === 'SS')
+ {
+ textResult = multiElementToString(element.length / 2, dataSet.int16);
+ }
+ else if (vr == 'UL')
+ {
+ textResult = multiElementToString(element.length / 4, dataSet.uint32);
+ }
+ else if(vr === 'SL')
+ {
+ textResult = multiElementToString(element.length / 4, dataSet.int32);
+ }
+ else if(vr == 'FD')
+ {
+ textResult = multiElementToString(element.length / 8, dataSet.int32);
+ }
+ else if(vr == 'FL')
+ {
+ textResult = multiElementToString(element.length / 4, dataSet.float);
+ }
+
+ return textResult;
+ };
+ return dicomParser;
+}(dicomParser));
+/**
+ * Utility functions for dealing with DICOM
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ var stringVrs = {
+ AE: true,
+ AS: true,
+ AT: false,
+ CS: true,
+ DA: true,
+ DS: true,
+ DT: true,
+ FL: false,
+ FD: false,
+ IS: true,
+ LO: true,
+ LT: true,
+ OB: false,
+ OD: false,
+ OF: false,
+ OW: false,
+ PN: true,
+ SH: true,
+ SL: false,
+ SQ: false,
+ SS: false,
+ ST: true,
+ TM: true,
+ UI: true,
+ UL: false,
+ UN: undefined, // dunno
+ UR: true,
+ US: false,
+ UT: true
+ };
+
+ /**
+ * Tests to see if vr is a string or not.
+ * @param vr
+ * @returns true if string, false it not string, undefined if unknown vr or UN type
+ */
+ dicomParser.isStringVr = function(vr)
+ {
+ return stringVrs[vr];
+ };
+
+ /**
+ * Tests to see if a given tag in the format xggggeeee is a private tag or not
+ * @param tag
+ * @returns {boolean}
+ */
+ dicomParser.isPrivateTag = function(tag)
+ {
+ var lastGroupDigit = parseInt(tag[4]);
+ var groupIsOdd = (lastGroupDigit % 2) === 1;
+ return groupIsOdd;
+ };
+
+ /**
+ * Parses a PN formatted string into a javascript object with properties for givenName, familyName, middleName, prefix and suffix
+ * @param personName a string in the PN VR format
+ * @param index
+ * @returns {*} javascript object with properties for givenName, familyName, middleName, prefix and suffix or undefined if no element or data
+ */
+ dicomParser.parsePN = function(personName) {
+ if(personName === undefined) {
+ return undefined;
+ }
+ var stringValues = personName.split('^');
+ return {
+ familyName: stringValues[0],
+ givenName: stringValues[1],
+ middleName: stringValues[2],
+ prefix: stringValues[3],
+ suffix: stringValues[4]
+ };
+ };
+
+ /**
+ * Parses a DA formatted string into a Javascript object
+ * @param date a string in the DA VR format
+ * @returns {*} Javascript object with properties year, month and day or undefined if not present or not 8 bytes long
+ */
+ dicomParser.parseDA = function(date)
+ {
+ if(date && date.length === 8)
+ {
+ var yyyy = parseInt(date.substring(0, 4), 10);
+ var mm = parseInt(date.substring(4, 6), 10);
+ var dd = parseInt(date.substring(6, 8), 10);
+
+ return {
+ year: yyyy,
+ month: mm,
+ day: dd
+ };
+ }
+ return undefined;
+ };
+
+ /**
+ * Parses a TM formatted string into a javascript object with properties for hours, minutes, seconds and fractionalSeconds
+ * @param time a string in the TM VR format
+ * @returns {*} javascript object with properties for hours, minutes, seconds and fractionalSeconds or undefined if no element or data. Missing fields are set to undefined
+ */
+ dicomParser.parseTM = function(time) {
+
+ if (time.length >= 2) // must at least have HH
+ {
+ // 0123456789
+ // HHMMSS.FFFFFF
+ var hh = parseInt(time.substring(0, 2), 10);
+ var mm = time.length >= 4 ? parseInt(time.substring(2, 4), 10) : undefined;
+ var ss = time.length >= 6 ? parseInt(time.substring(4, 6), 10) : undefined;
+ var ffffff = time.length >= 8 ? parseInt(time.substring(7, 13), 10) : undefined;
+
+ return {
+ hours: hh,
+ minutes: mm,
+ seconds: ss,
+ fractionalSeconds: ffffff
+ };
+ }
+ return undefined;
+ };
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Functionality for extracting encapsulated pixel data
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ function getPixelDataFromFragments(byteStream, fragments, bufferSize)
+ {
+ // if there is only one fragment, return a view on this array to avoid copying
+ if(fragments.length === 1) {
+ return new Uint8Array(byteStream.byteArray.buffer, fragments[0].dataOffset, fragments[0].length);
+ }
+
+ // more than one fragment, combine all of the fragments into one buffer
+ var pixelData = new Uint8Array(bufferSize);
+ var pixelDataIndex = 0;
+ for(var i=0; i < fragments.length; i++) {
+ var fragmentOffset = fragments[i].dataOffset;
+ for(var j=0; j < fragments[i].length; j++) {
+ pixelData[pixelDataIndex++] = byteStream.byteArray[fragmentOffset++];
+ }
+ }
+
+ return pixelData;
+ }
+
+ function readFragmentsUntil(byteStream, endOfFrame) {
+ // Read fragments until we reach endOfFrame
+ var fragments = [];
+ var bufferSize = 0;
+ while(byteStream.position < endOfFrame && byteStream.position < byteStream.byteArray.length) {
+ var fragment = dicomParser.readSequenceItem(byteStream);
+ // NOTE: we only encounter this for the sequence delimiter tag when extracting the last frame
+ if(fragment.tag === 'xfffee0dd') {
+ break;
+ }
+ fragments.push(fragment);
+ byteStream.seek(fragment.length);
+ bufferSize += fragment.length;
+ }
+
+ // Convert the fragments into a single pixelData buffer
+ var pixelData = getPixelDataFromFragments(byteStream, fragments, bufferSize);
+ return pixelData;
+ }
+
+ function readEncapsulatedPixelDataWithBasicOffsetTable(pixelDataElement, byteStream, frame) {
+ // validate that we have an offset for this frame
+ var numFrames = pixelDataElement.basicOffsetTable.length;
+ if(frame > numFrames) {
+ throw "dicomParser.readEncapsulatedPixelData: parameter frame exceeds number of frames in basic offset table";
+ }
+
+ // move to the start of this frame
+ var frameOffset = pixelDataElement.basicOffsetTable[frame];
+ byteStream.seek(frameOffset);
+
+ // Find the end of this frame
+ var endOfFrameOffset = pixelDataElement.basicOffsetTable[frame + 1];
+ if(endOfFrameOffset === undefined) { // special case for last frame
+ endOfFrameOffset = byteStream.position + pixelDataElement.length;
+ }
+
+ // read this frame
+ var pixelData = readFragmentsUntil(byteStream, endOfFrameOffset);
+ return pixelData;
+ }
+
+ function readEncapsulatedDataNoBasicOffsetTable(pixelDataElement, byteStream, frame) {
+ // if the basic offset table is empty, this is a single frame so make sure the requested
+ // frame is 0
+ if(frame !== 0) {
+ throw 'dicomParser.readEncapsulatedPixelData: non zero frame specified for single frame encapsulated pixel data';
+ }
+
+ // read this frame
+ var endOfFrame = byteStream.position + pixelDataElement.length;
+ var pixelData = readFragmentsUntil(byteStream, endOfFrame);
+ return pixelData;
+ }
+
+ /**
+ * Returns the pixel data for the specified frame in an encapsulated pixel data element
+ *
+ * @param dataSet - the dataSet containing the encapsulated pixel data
+ * @param pixelDataElement - the pixel data element (x7fe00010) to extract the frame from
+ * @param frame - the zero based frame index
+ * @returns Uint8Array with the encapsulated pixel data
+ */
+ dicomParser.readEncapsulatedPixelData = function(dataSet, pixelDataElement, frame)
+ {
+ if(dataSet === undefined) {
+ throw "dicomParser.readEncapsulatedPixelData: missing required parameter 'dataSet'";
+ }
+ if(pixelDataElement === undefined) {
+ throw "dicomParser.readEncapsulatedPixelData: missing required parameter 'element'";
+ }
+ if(frame === undefined) {
+ throw "dicomParser.readEncapsulatedPixelData: missing required parameter 'frame'";
+ }
+ if(pixelDataElement.tag !== 'x7fe00010') {
+ throw "dicomParser.readEncapsulatedPixelData: parameter 'element' refers to non pixel data tag (expected tag = x7fe00010'";
+ }
+ if(pixelDataElement.encapsulatedPixelData !== true) {
+ throw "dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data";
+ }
+ if(pixelDataElement.hadUndefinedLength !== true) {
+ throw "dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data";
+ }
+ if(pixelDataElement.basicOffsetTable === undefined) {
+ throw "dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data";
+ }
+ if(pixelDataElement.fragments === undefined) {
+ throw "dicomParser.readEncapsulatedPixelData: parameter 'element' refers to pixel data element that does not have encapsulated pixel data";
+ }
+ if(frame < 0) {
+ throw "dicomParser.readEncapsulatedPixelData: parameter 'frame' must be >= 0";
+ }
+
+ // seek past the basic offset table (no need to parse it again since we already have)
+ var byteStream = new dicomParser.ByteStream(dataSet.byteArrayParser, dataSet.byteArray, pixelDataElement.dataOffset);
+ var basicOffsetTable = dicomParser.readSequenceItem(byteStream);
+ if(basicOffsetTable.tag !== 'xfffee000')
+ {
+ throw "dicomParser.readEncapsulatedPixelData: missing basic offset table xfffee000";
+ }
+ byteStream.seek(basicOffsetTable.length);
+
+ // If the basic offset table is empty (no entries), it is a single frame. If it is not empty,
+ // it has at least one frame so use the basic offset table to find the bytes
+ if(pixelDataElement.basicOffsetTable.length !== 0)
+ {
+ return readEncapsulatedPixelDataWithBasicOffsetTable(pixelDataElement, byteStream, frame);
+ }
+ else
+ {
+ return readEncapsulatedDataNoBasicOffsetTable(pixelDataElement, byteStream, frame);
+ }
+ };
+
+ return dicomParser;
+}(dicomParser));
+
+/**
+ * Internal helper functions for parsing different types from a big-endian byte array
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ dicomParser.bigEndianByteArrayParser = {
+ /**
+ *
+ * Parses an unsigned int 16 from a big-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed unsigned int 16
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readUint16: function (byteArray, position) {
+ if (position < 0) {
+ throw 'bigEndianByteArrayParser.readUint16: position cannot be less than 0';
+ }
+ if (position + 2 > byteArray.length) {
+ throw 'bigEndianByteArrayParser.readUint16: attempt to read past end of buffer';
+ }
+ return (byteArray[position] << 8) + byteArray[position + 1];
+ },
+
+ /**
+ *
+ * Parses a signed int 16 from a big-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed signed int 16
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readInt16: function (byteArray, position) {
+ if (position < 0) {
+ throw 'bigEndianByteArrayParser.readInt16: position cannot be less than 0';
+ }
+ if (position + 2 > byteArray.length) {
+ throw 'bigEndianByteArrayParser.readInt16: attempt to read past end of buffer';
+ }
+ var int16 = (byteArray[position] << 8) + byteArray[position + 1];
+ // fix sign
+ if (int16 & 0x8000) {
+ int16 = int16 - 0xFFFF - 1;
+ }
+ return int16;
+ },
+
+ /**
+ * Parses an unsigned int 32 from a big-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed unsigned int 32
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readUint32: function (byteArray, position) {
+ if (position < 0) {
+ throw 'bigEndianByteArrayParser.readUint32: position cannot be less than 0';
+ }
+
+ if (position + 4 > byteArray.length) {
+ throw 'bigEndianByteArrayParser.readUint32: attempt to read past end of buffer';
+ }
+
+ var uint32 = (256 * (256 * (256 * byteArray[position] +
+ byteArray[position + 1]) +
+ byteArray[position + 2]) +
+ byteArray[position + 3]);
+
+ return uint32;
+ },
+
+ /**
+ * Parses a signed int 32 from a big-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed signed int 32
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readInt32: function (byteArray, position) {
+ if (position < 0) {
+ throw 'bigEndianByteArrayParser.readInt32: position cannot be less than 0';
+ }
+
+ if (position + 4 > byteArray.length) {
+ throw 'bigEndianByteArrayParser.readInt32: attempt to read past end of buffer';
+ }
+
+ var int32 = ((byteArray[position] << 24) +
+ (byteArray[position + 1] << 16) +
+ (byteArray[position + 2] << 8) +
+ byteArray[position + 3]);
+
+ return int32;
+ },
+
+ /**
+ * Parses 32-bit float from a big-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed 32-bit float
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readFloat: function (byteArray, position) {
+ if (position < 0) {
+ throw 'bigEndianByteArrayParser.readFloat: position cannot be less than 0';
+ }
+
+ if (position + 4 > byteArray.length) {
+ throw 'bigEndianByteArrayParser.readFloat: attempt to read past end of buffer';
+ }
+
+ // I am sure there is a better way than this but this should be safe
+ var byteArrayForParsingFloat = new Uint8Array(4);
+ byteArrayForParsingFloat[3] = byteArray[position];
+ byteArrayForParsingFloat[2] = byteArray[position + 1];
+ byteArrayForParsingFloat[1] = byteArray[position + 2];
+ byteArrayForParsingFloat[0] = byteArray[position + 3];
+ var floatArray = new Float32Array(byteArrayForParsingFloat.buffer);
+ return floatArray[0];
+ },
+
+ /**
+ * Parses 64-bit float from a big-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed 64-bit float
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readDouble: function (byteArray, position) {
+ if (position < 0) {
+ throw 'bigEndianByteArrayParser.readDouble: position cannot be less than 0';
+ }
+
+ if (position + 8 > byteArray.length) {
+ throw 'bigEndianByteArrayParser.readDouble: attempt to read past end of buffer';
+ }
+
+ // I am sure there is a better way than this but this should be safe
+ var byteArrayForParsingFloat = new Uint8Array(8);
+ byteArrayForParsingFloat[7] = byteArray[position];
+ byteArrayForParsingFloat[6] = byteArray[position + 1];
+ byteArrayForParsingFloat[5] = byteArray[position + 2];
+ byteArrayForParsingFloat[4] = byteArray[position + 3];
+ byteArrayForParsingFloat[3] = byteArray[position + 4];
+ byteArrayForParsingFloat[2] = byteArray[position + 5];
+ byteArrayForParsingFloat[1] = byteArray[position + 6];
+ byteArrayForParsingFloat[0] = byteArray[position + 7];
+ var floatArray = new Float64Array(byteArrayForParsingFloat.buffer);
+ return floatArray[0];
+ }
+ };
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions common to parsing byte arrays of any type
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ /**
+ * Reads a string of 8-bit characters from an array of bytes and advances
+ * the position by length bytes. A null terminator will end the string
+ * but will not effect advancement of the position. Trailing and leading
+ * spaces are preserved (not trimmed)
+ * @param byteArray the byteArray to read from
+ * @param position the position in the byte array to read from
+ * @param length the maximum number of bytes to parse
+ * @returns {string} the parsed string
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ dicomParser.readFixedString = function(byteArray, position, length)
+ {
+ if(length < 0)
+ {
+ throw 'readFixedString - length cannot be less than 0';
+ }
+
+ if(position + length > byteArray.length) {
+ throw 'dicomParser.readFixedString: attempt to read past end of buffer';
+ }
+
+ var result = "";
+ for(var i=0; i < length; i++)
+ {
+ var byte = byteArray[position + i];
+ if(byte === 0) {
+ position += length;
+ return result;
+ }
+ result += String.fromCharCode(byte);
+ }
+
+ return result;
+ };
+
+
+ return dicomParser;
+}(dicomParser));
+/**
+ *
+ * Internal helper class to assist with parsing. Supports reading from a byte
+ * stream contained in a Uint8Array. Example usage:
+ *
+ * var byteArray = new Uint8Array(32);
+ * var byteStream = new dicomParser.ByteStream(dicomParser.littleEndianByteArrayParser, byteArray);
+ *
+ * */
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ /**
+ * Constructor for ByteStream objects.
+ * @param byteArrayParser a parser for parsing the byte array
+ * @param byteArray a Uint8Array containing the byte stream
+ * @param position (optional) the position to start reading from. 0 if not specified
+ * @constructor
+ * @throws will throw an error if the byteArrayParser parameter is not present
+ * @throws will throw an error if the byteArray parameter is not present or invalid
+ * @throws will throw an error if the position parameter is not inside the byte array
+ */
+ dicomParser.ByteStream = function(byteArrayParser, byteArray, position) {
+ if(byteArrayParser === undefined)
+ {
+ throw "dicomParser.ByteStream: missing required parameter 'byteArrayParser'";
+ }
+ if(byteArray === undefined)
+ {
+ throw "dicomParser.ByteStream: missing required parameter 'byteArray'";
+ }
+ if((byteArray instanceof Uint8Array) === false) {
+ throw 'dicomParser.ByteStream: parameter byteArray is not of type Uint8Array';
+ }
+ if(position < 0)
+ {
+ throw "dicomParser.ByteStream: parameter 'position' cannot be less than 0";
+ }
+ if(position >= byteArray.length)
+ {
+ throw "dicomParser.ByteStream: parameter 'position' cannot be greater than or equal to 'byteArray' length";
+
+ }
+ this.byteArrayParser = byteArrayParser;
+ this.byteArray = byteArray;
+ this.position = position ? position : 0;
+ this.warnings = []; // array of string warnings encountered while parsing
+ };
+
+ /**
+ * Safely seeks through the byte stream. Will throw an exception if an attempt
+ * is made to seek outside of the byte array.
+ * @param offset the number of bytes to add to the position
+ * @throws error if seek would cause position to be outside of the byteArray
+ */
+ dicomParser.ByteStream.prototype.seek = function(offset)
+ {
+ if(this.position + offset < 0)
+ {
+ throw "cannot seek to position < 0";
+ }
+ this.position += offset;
+ };
+
+ /**
+ * Returns a new ByteStream object from the current position and of the requested number of bytes
+ * @param numBytes the length of the byte array for the ByteStream to contain
+ * @returns {dicomParser.ByteStream}
+ * @throws error if buffer overread would occur
+ */
+ dicomParser.ByteStream.prototype.readByteStream = function(numBytes)
+ {
+ if(this.position + numBytes > this.byteArray.length) {
+ throw 'readByteStream - buffer overread';
+ }
+ var byteArrayView = new Uint8Array(this.byteArray.buffer, this.position, numBytes);
+ this.position += numBytes;
+ return new dicomParser.ByteStream(this.byteArrayParser, byteArrayView);
+ };
+
+ /**
+ *
+ * Parses an unsigned int 16 from a byte array and advances
+ * the position by 2 bytes
+ *
+ * @returns {*} the parsed unsigned int 16
+ * @throws error if buffer overread would occur
+ */
+ dicomParser.ByteStream.prototype.readUint16 = function()
+ {
+ var result = this.byteArrayParser.readUint16(this.byteArray, this.position);
+ this.position += 2;
+ return result;
+ };
+
+ /**
+ * Parses an unsigned int 32 from a byte array and advances
+ * the position by 2 bytes
+ *
+ * @returns {*} the parse unsigned int 32
+ * @throws error if buffer overread would occur
+ */
+ dicomParser.ByteStream.prototype.readUint32 = function()
+ {
+ var result = this.byteArrayParser.readUint32(this.byteArray, this.position);
+ this.position += 4;
+ return result;
+ };
+
+ /**
+ * Reads a string of 8-bit characters from an array of bytes and advances
+ * the position by length bytes. A null terminator will end the string
+ * but will not effect advancement of the position.
+ * @param length the maximum number of bytes to parse
+ * @returns {string} the parsed string
+ * @throws error if buffer overread would occur
+ */
+ dicomParser.ByteStream.prototype.readFixedString = function(length)
+ {
+ var result = dicomParser.readFixedString(this.byteArray, this.position, length);
+ this.position += length;
+ return result;
+ };
+
+ return dicomParser;
+}(dicomParser));
+/**
+ *
+ * The DataSet class encapsulates a collection of DICOM Elements and provides various functions
+ * to access the data in those elements
+ *
+ * Rules for handling padded spaces:
+ * DS = Strip leading and trailing spaces
+ * DT = Strip trailing spaces
+ * IS = Strip leading and trailing spaces
+ * PN = Strip trailing spaces
+ * TM = Strip trailing spaces
+ * AE = Strip leading and trailing spaces
+ * CS = Strip leading and trailing spaces
+ * SH = Strip leading and trailing spaces
+ * LO = Strip leading and trailing spaces
+ * LT = Strip trailing spaces
+ * ST = Strip trailing spaces
+ * UT = Strip trailing spaces
+ *
+ */
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ function getByteArrayParser(element, defaultParser)
+ {
+ return (element.parser !== undefined ? element.parser : defaultParser);
+ }
+
+ /**
+ * Constructs a new DataSet given byteArray and collection of elements
+ * @param byteArrayParser
+ * @param byteArray
+ * @param elements
+ * @constructor
+ */
+ dicomParser.DataSet = function(byteArrayParser, byteArray, elements)
+ {
+ this.byteArrayParser = byteArrayParser;
+ this.byteArray = byteArray;
+ this.elements = elements;
+ };
+
+ /**
+ * Finds the element for tag and returns an unsigned int 16 if it exists and has data
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the value in a multivalued element. Default is index 0 if not supplied
+ * @returns {*} unsigned int 16 or undefined if the attribute is not present or has data of length 0
+ */
+ dicomParser.DataSet.prototype.uint16 = function(tag, index)
+ {
+ var element = this.elements[tag];
+ index = (index !== undefined) ? index : 0;
+ if(element && element.length !== 0)
+ {
+ return getByteArrayParser(element, this.byteArrayParser).readUint16(this.byteArray, element.dataOffset + (index *2));
+ }
+ return undefined;
+ };
+
+ /**
+ * Finds the element for tag and returns an signed int 16 if it exists and has data
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the value in a multivalued element. Default is index 0 if not supplied
+ * @returns {*} signed int 16 or undefined if the attribute is not present or has data of length 0
+ */
+ dicomParser.DataSet.prototype.int16 = function(tag, index)
+ {
+ var element = this.elements[tag];
+ index = (index !== undefined) ? index : 0;
+ if(element && element.length !== 0)
+ {
+ return getByteArrayParser(element, this.byteArrayParser).readInt16(this.byteArray, element.dataOffset + (index * 2));
+ }
+ return undefined;
+ };
+
+ /**
+ * Finds the element for tag and returns an unsigned int 32 if it exists and has data
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the value in a multivalued element. Default is index 0 if not supplied
+ * @returns {*} unsigned int 32 or undefined if the attribute is not present or has data of length 0
+ */
+ dicomParser.DataSet.prototype.uint32 = function(tag, index)
+ {
+ var element = this.elements[tag];
+ index = (index !== undefined) ? index : 0;
+ if(element && element.length !== 0)
+ {
+ return getByteArrayParser(element, this.byteArrayParser).readUint32(this.byteArray, element.dataOffset + (index * 4));
+ }
+ return undefined;
+ };
+
+ /**
+ * Finds the element for tag and returns an signed int 32 if it exists and has data
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the value in a multivalued element. Default is index 0 if not supplied
+ * @returns {*} signed int 32 or undefined if the attribute is not present or has data of length 0
+ */
+ dicomParser.DataSet.prototype.int32 = function(tag, index)
+ {
+ var element = this.elements[tag];
+ index = (index !== undefined) ? index : 0;
+ if(element && element.length !== 0)
+ {
+ return getByteArrayParser(element, this.byteArrayParser).readInt32(this.byteArray, element.dataOffset + (index * 4));
+ }
+ return undefined;
+ };
+
+ /**
+ * Finds the element for tag and returns a 32 bit floating point number (VR=FL) if it exists and has data
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the value in a multivalued element. Default is index 0 if not supplied
+ * @returns {*} float or undefined if the attribute is not present or has data of length 0
+ */
+ dicomParser.DataSet.prototype.float = function(tag, index)
+ {
+ var element = this.elements[tag];
+ index = (index !== undefined) ? index : 0;
+ if(element && element.length !== 0)
+ {
+ return getByteArrayParser(element, this.byteArrayParser).readFloat(this.byteArray, element.dataOffset + (index * 4));
+ }
+ return undefined;
+ };
+
+ /**
+ * Finds the element for tag and returns a 64 bit floating point number (VR=FD) if it exists and has data
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the value in a multivalued element. Default is index 0 if not supplied
+ * @returns {*} float or undefined if the attribute is not present or doesn't has data of length 0
+ */
+ dicomParser.DataSet.prototype.double = function(tag, index)
+ {
+ var element = this.elements[tag];
+ index = (index !== undefined) ? index : 0;
+ if(element && element.length !== 0)
+ {
+ return getByteArrayParser(element, this.byteArrayParser).readDouble(this.byteArray, element.dataOffset + (index * 8));
+ }
+ return undefined;
+ };
+
+ /**
+ * Returns the number of string values for the element
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @returns {*} the number of string values or undefined if the attribute is not present or has zero length data
+ */
+ dicomParser.DataSet.prototype.numStringValues = function(tag)
+ {
+ var element = this.elements[tag];
+ if(element && element.length > 0)
+ {
+ var fixedString = dicomParser.readFixedString(this.byteArray, element.dataOffset, element.length);
+ var numMatching = fixedString.match(/\\/g);
+ if(numMatching === null)
+ {
+ return 1;
+ }
+ return numMatching.length + 1;
+ }
+ return undefined;
+ };
+
+ /**
+ * Returns a string for the element. If index is provided, the element is assumed to be
+ * multi-valued and will return the component specified by index. Undefined is returned
+ * if there is no component with the specified index, the element does not exist or is zero length.
+ *
+ * Use this function for VR types of AE, CS, SH and LO
+ *
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the desired value in a multi valued string or undefined for the entire string
+ * @returns {*}
+ */
+ dicomParser.DataSet.prototype.string = function(tag, index)
+ {
+ var element = this.elements[tag];
+ if(element && element.length > 0)
+ {
+ var fixedString = dicomParser.readFixedString(this.byteArray, element.dataOffset, element.length);
+ if(index >= 0)
+ {
+ var values = fixedString.split('\\');
+ // trim trailing spaces
+ return values[index].trim();
+ }
+ else
+ {
+ // trim trailing spaces
+ return fixedString.trim();
+ }
+ }
+ return undefined;
+ };
+
+ /**
+ * Returns a string with the leading spaces preserved and trailing spaces removed.
+ *
+ * Use this function to access data for VRs of type UT, ST and LT
+ *
+ * @param tag
+ * @param index
+ * @returns {*}
+ */
+ dicomParser.DataSet.prototype.text = function(tag, index)
+ {
+ var element = this.elements[tag];
+ if(element && element.length > 0)
+ {
+ var fixedString = dicomParser.readFixedString(this.byteArray, element.dataOffset, element.length);
+ if(index >= 0)
+ {
+ var values = fixedString.split('\\');
+ return values[index].replace(/ +$/, '');
+ }
+ else
+ {
+ return fixedString.replace(/ +$/, '');
+ }
+ }
+ return undefined;
+ };
+
+ /**
+ * Parses a string to a float for the specified index in a multi-valued element. If index is not specified,
+ * the first value in a multi-valued VR will be parsed if present.
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the desired value in a multi valued string or undefined for the first value
+ * @returns {*} a floating point number or undefined if not present or data not long enough
+ */
+ dicomParser.DataSet.prototype.floatString = function(tag, index)
+ {
+ var element = this.elements[tag];
+ if(element && element.length > 0)
+ {
+ index = (index !== undefined) ? index : 0;
+ var value = this.string(tag, index);
+ if(value !== undefined) {
+ return parseFloat(value);
+ }
+ }
+ return undefined;
+ };
+
+ /**
+ * Parses a string to an integer for the specified index in a multi-valued element. If index is not specified,
+ * the first value in a multi-valued VR will be parsed if present.
+ * @param tag The DICOM tag in the format xGGGGEEEE
+ * @param index the index of the desired value in a multi valued string or undefined for the first value
+ * @returns {*} an integer or undefined if not present or data not long enough
+ */
+ dicomParser.DataSet.prototype.intString = function(tag, index)
+ {
+ var element = this.elements[tag];
+ if(element && element.length > 0) {
+ index = (index !== undefined) ? index : 0;
+ var value = this.string(tag, index);
+ if(value !== undefined) {
+ return parseInt(value);
+ }
+ }
+ return undefined;
+ };
+
+ //dicomParser.DataSet = DataSet;
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for parsing DICOM elements
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ /**
+ * Reads an encapsulated pixel data element and adds an array of fragments to the element
+ * containing the offset and length of each fragment and any offsets from the basic offset
+ * table
+ * @param byteStream
+ * @param element
+ */
+ dicomParser.findEndOfEncapsulatedElement = function(byteStream, element, warnings)
+ {
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.findEndOfEncapsulatedElement: missing required parameter 'byteStream'";
+ }
+ if(element === undefined)
+ {
+ throw "dicomParser.findEndOfEncapsulatedElement: missing required parameter 'element'";
+ }
+
+ element.encapsulatedPixelData = true;
+ element.basicOffsetTable = [];
+ element.fragments = [];
+ var basicOffsetTableItemTag = dicomParser.readTag(byteStream);
+ if(basicOffsetTableItemTag !== 'xfffee000') {
+ throw "dicomParser.findEndOfEncapsulatedElement: basic offset table not found";
+ }
+ var basicOffsetTableItemlength = byteStream.readUint32();
+ var numFragments = basicOffsetTableItemlength / 4;
+ for(var i =0; i < numFragments; i++) {
+ var offset = byteStream.readUint32();
+ element.basicOffsetTable.push(offset);
+ }
+ var baseOffset = byteStream.position;
+
+ while(byteStream.position < byteStream.byteArray.length)
+ {
+ var tag = dicomParser.readTag(byteStream);
+ var length = byteStream.readUint32();
+ if(tag === 'xfffee0dd')
+ {
+ byteStream.seek(length);
+ element.length = byteStream.position - element.dataOffset;
+ return;
+ }
+ else if(tag === 'xfffee000')
+ {
+ element.fragments.push({
+ offset: byteStream.position - baseOffset - 8,
+ position : byteStream.position,
+ length : length
+ });
+ }
+ else {
+ if(warnings) {
+ warnings.push('unexpected tag ' + tag + ' while searching for end of pixel data element with undefined length');
+ }
+ if(length > byteStream.byteArray.length - byteStream.position)
+ {
+ // fix length
+ length = byteStream.byteArray.length - byteStream.position;
+ }
+ element.fragments.push({
+ offset: byteStream.position - baseOffset - 8,
+ position : byteStream.position,
+ length : length
+ });
+ byteStream.seek(length);
+ element.length = byteStream.position - element.dataOffset;
+ return;
+ }
+
+ byteStream.seek(length);
+ }
+
+ if(warnings) {
+ warnings.push("pixel data element " + element.tag + " missing sequence delimiter tag xfffee0dd");
+ }
+ };
+
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for parsing DICOM elements
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ /**
+ * reads from the byte stream until it finds the magic numbers for the item delimitation item
+ * and then sets the length of the element
+ * @param byteStream
+ * @param element
+ */
+ dicomParser.findItemDelimitationItemAndSetElementLength = function(byteStream, element)
+ {
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.readDicomElementImplicit: missing required parameter 'byteStream'";
+ }
+
+ var itemDelimitationItemLength = 8; // group, element, length
+ var maxPosition = byteStream.byteArray.length - itemDelimitationItemLength;
+ while(byteStream.position <= maxPosition)
+ {
+ var groupNumber = byteStream.readUint16();
+ if(groupNumber === 0xfffe)
+ {
+ var elementNumber = byteStream.readUint16();
+ if(elementNumber === 0xe00d)
+ {
+ // NOTE: It would be better to also check for the length to be 0 as part of the check above
+ // but we will just log a warning for now
+ var itemDelimiterLength = byteStream.readUint32(); // the length
+ if(itemDelimiterLength !== 0) {
+ byteStream.warnings('encountered non zero length following item delimiter at position' + byteStream.position - 4 + " while reading element of undefined length with tag ' + element.tag");
+ }
+ element.length = byteStream.position - element.dataOffset;
+ return;
+
+ }
+ }
+ }
+
+ // No item delimitation item - silently set the length to the end of the buffer and set the position past the end of the buffer
+ element.length = byteStream.byteArray.length - element.dataOffset;
+ byteStream.seek(byteStream.byteArray.length - byteStream.position);
+ };
+
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for parsing different types from a little-endian byte array
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ dicomParser.littleEndianByteArrayParser = {
+ /**
+ *
+ * Parses an unsigned int 16 from a little-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed unsigned int 16
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readUint16: function (byteArray, position) {
+ if (position < 0) {
+ throw 'littleEndianByteArrayParser.readUint16: position cannot be less than 0';
+ }
+ if (position + 2 > byteArray.length) {
+ throw 'littleEndianByteArrayParser.readUint16: attempt to read past end of buffer';
+ }
+ return byteArray[position] + (byteArray[position + 1] * 256);
+ },
+
+ /**
+ *
+ * Parses a signed int 16 from a little-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed signed int 16
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readInt16: function (byteArray, position) {
+ if (position < 0) {
+ throw 'littleEndianByteArrayParser.readInt16: position cannot be less than 0';
+ }
+ if (position + 2 > byteArray.length) {
+ throw 'littleEndianByteArrayParser.readInt16: attempt to read past end of buffer';
+ }
+ var int16 = byteArray[position] + (byteArray[position + 1] << 8);
+ // fix sign
+ if (int16 & 0x8000) {
+ int16 = int16 - 0xFFFF - 1;
+ }
+ return int16;
+ },
+
+
+ /**
+ * Parses an unsigned int 32 from a little-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed unsigned int 32
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readUint32: function (byteArray, position) {
+ if (position < 0) {
+ throw 'littleEndianByteArrayParser.readUint32: position cannot be less than 0';
+ }
+
+ if (position + 4 > byteArray.length) {
+ throw 'littleEndianByteArrayParser.readUint32: attempt to read past end of buffer';
+ }
+
+ var uint32 = (byteArray[position] +
+ (byteArray[position + 1] * 256) +
+ (byteArray[position + 2] * 256 * 256) +
+ (byteArray[position + 3] * 256 * 256 * 256 ));
+
+ return uint32;
+ },
+
+ /**
+ * Parses a signed int 32 from a little-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed unsigned int 32
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readInt32: function (byteArray, position) {
+ if (position < 0) {
+ throw 'littleEndianByteArrayParser.readInt32: position cannot be less than 0';
+ }
+
+ if (position + 4 > byteArray.length) {
+ throw 'littleEndianByteArrayParser.readInt32: attempt to read past end of buffer';
+ }
+
+ var int32 = (byteArray[position] +
+ (byteArray[position + 1] << 8) +
+ (byteArray[position + 2] << 16) +
+ (byteArray[position + 3] << 24));
+
+ return int32;
+
+ },
+
+ /**
+ * Parses 32-bit float from a little-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed 32-bit float
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readFloat: function (byteArray, position) {
+ if (position < 0) {
+ throw 'littleEndianByteArrayParser.readFloat: position cannot be less than 0';
+ }
+
+ if (position + 4 > byteArray.length) {
+ throw 'littleEndianByteArrayParser.readFloat: attempt to read past end of buffer';
+ }
+
+ // I am sure there is a better way than this but this should be safe
+ var byteArrayForParsingFloat = new Uint8Array(4);
+ byteArrayForParsingFloat[0] = byteArray[position];
+ byteArrayForParsingFloat[1] = byteArray[position + 1];
+ byteArrayForParsingFloat[2] = byteArray[position + 2];
+ byteArrayForParsingFloat[3] = byteArray[position + 3];
+ var floatArray = new Float32Array(byteArrayForParsingFloat.buffer);
+ return floatArray[0];
+ },
+
+ /**
+ * Parses 64-bit float from a little-endian byte array
+ *
+ * @param byteArray the byte array to read from
+ * @param position the position in the byte array to read from
+ * @returns {*} the parsed 64-bit float
+ * @throws error if buffer overread would occur
+ * @access private
+ */
+ readDouble: function (byteArray, position) {
+ if (position < 0) {
+ throw 'littleEndianByteArrayParser.readDouble: position cannot be less than 0';
+ }
+
+ if (position + 8 > byteArray.length) {
+ throw 'littleEndianByteArrayParser.readDouble: attempt to read past end of buffer';
+ }
+
+ // I am sure there is a better way than this but this should be safe
+ var byteArrayForParsingFloat = new Uint8Array(8);
+ byteArrayForParsingFloat[0] = byteArray[position];
+ byteArrayForParsingFloat[1] = byteArray[position + 1];
+ byteArrayForParsingFloat[2] = byteArray[position + 2];
+ byteArrayForParsingFloat[3] = byteArray[position + 3];
+ byteArrayForParsingFloat[4] = byteArray[position + 4];
+ byteArrayForParsingFloat[5] = byteArray[position + 5];
+ byteArrayForParsingFloat[6] = byteArray[position + 6];
+ byteArrayForParsingFloat[7] = byteArray[position + 7];
+ var floatArray = new Float64Array(byteArrayForParsingFloat.buffer);
+ return floatArray[0];
+ }
+ };
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for parsing implicit and explicit DICOM data sets
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ /**
+ * reads an explicit data set
+ * @param byteStream the byte stream to read from
+ * @param maxPosition the maximum position to read up to (optional - only needed when reading sequence items)
+ */
+ dicomParser.parseDicomDataSetExplicit = function (dataSet, byteStream, maxPosition, options) {
+
+ maxPosition = (maxPosition === undefined) ? byteStream.byteArray.length : maxPosition ;
+ options = options || {};
+
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.parseDicomDataSetExplicit: missing required parameter 'byteStream'";
+ }
+ if(maxPosition < byteStream.position || maxPosition > byteStream.byteArray.length)
+ {
+ throw "dicomParser.parseDicomDataSetExplicit: invalid value for parameter 'maxPosition'";
+ }
+ var elements = dataSet.elements;
+
+ while(byteStream.position < maxPosition)
+ {
+ var element = dicomParser.readDicomElementExplicit(byteStream, dataSet.warnings, options.untilTag);
+ elements[element.tag] = element;
+ if(element.tag === options.untilTag) {
+ return;
+ }
+ }
+ if(byteStream.position > maxPosition) {
+ throw "dicomParser:parseDicomDataSetExplicit: buffer overrun";
+ }
+ };
+
+ /**
+ * reads an implicit data set
+ * @param byteStream the byte stream to read from
+ * @param maxPosition the maximum position to read up to (optional - only needed when reading sequence items)
+ */
+ dicomParser.parseDicomDataSetImplicit = function(dataSet, byteStream, maxPosition, options)
+ {
+ maxPosition = (maxPosition === undefined) ? dataSet.byteArray.length : maxPosition ;
+ options = options || {};
+
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.parseDicomDataSetImplicit: missing required parameter 'byteStream'";
+ }
+ if(maxPosition < byteStream.position || maxPosition > byteStream.byteArray.length)
+ {
+ throw "dicomParser.parseDicomDataSetImplicit: invalid value for parameter 'maxPosition'";
+ }
+
+ var elements = dataSet.elements;
+
+ while(byteStream.position < maxPosition)
+ {
+ var element = dicomParser.readDicomElementImplicit(byteStream, options.untilTag);
+ elements[element.tag] = element;
+ if(element.tag === options.untilTag) {
+ return;
+ }
+ }
+ };
+
+ return dicomParser;
+}(dicomParser));
+
+/**
+ * Internal helper functions for for parsing DICOM elements
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ function getDataLengthSizeInBytesForVR(vr)
+ {
+ if( vr === 'OB' ||
+ vr === 'OW' ||
+ vr === 'SQ' ||
+ vr === 'OF' ||
+ vr === 'UT' ||
+ vr === 'UN')
+ {
+ return 4;
+ }
+ else
+ {
+ return 2;
+ }
+ }
+
+ dicomParser.readDicomElementExplicit = function(byteStream, warnings, untilTag)
+ {
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.readDicomElementExplicit: missing required parameter 'byteStream'";
+ }
+
+ var element = {
+ tag : dicomParser.readTag(byteStream),
+ vr : byteStream.readFixedString(2)
+ // length set below based on VR
+ // dataOffset set below based on VR and size of length
+ };
+
+ var dataLengthSizeBytes = getDataLengthSizeInBytesForVR(element.vr);
+ if(dataLengthSizeBytes === 2)
+ {
+ element.length = byteStream.readUint16();
+ element.dataOffset = byteStream.position;
+ }
+ else
+ {
+ byteStream.seek(2);
+ element.length = byteStream.readUint32();
+ element.dataOffset = byteStream.position;
+ }
+
+ if(element.length === 4294967295)
+ {
+ element.hadUndefinedLength = true;
+ }
+
+ if(element.tag === untilTag) {
+ return element;
+ }
+
+ // if VR is SQ, parse the sequence items
+ if(element.vr === 'SQ')
+ {
+ dicomParser.readSequenceItemsExplicit(byteStream, element, warnings);
+ return element;
+ }
+ if(element.length === 4294967295)
+ {
+ if(element.tag === 'x7fe00010') {
+ dicomParser.findEndOfEncapsulatedElement(byteStream, element, warnings);
+ return element;
+ } else {
+ dicomParser.findItemDelimitationItemAndSetElementLength(byteStream, element);
+ return element;
+ }
+ }
+
+ byteStream.seek(element.length);
+ return element;
+ };
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for for parsing DICOM elements
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ dicomParser.readDicomElementImplicit = function(byteStream, untilTag)
+ {
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.readDicomElementImplicit: missing required parameter 'byteStream'";
+ }
+
+ var element = {
+ tag : dicomParser.readTag(byteStream),
+ length: byteStream.readUint32(),
+ dataOffset : byteStream.position
+ };
+
+ if(element.length === 4294967295)
+ {
+ element.hadUndefinedLength = true;
+ }
+
+ if(element.tag === untilTag) {
+ return element;
+ }
+
+ // peek ahead at the next tag to see if it looks like a sequence. This is not 100%
+ // safe because a non sequence item could have data that has these bytes, but this
+ // is how to do it without a data dictionary.
+ if ((byteStream.position + 4) <= byteStream.byteArray.length) {
+ var nextTag = dicomParser.readTag(byteStream);
+ byteStream.seek(-4);
+
+ if (nextTag === 'xfffee000') {
+ // parse the sequence
+ dicomParser.readSequenceItemsImplicit(byteStream, element);
+ //element.length = byteStream.byteArray.length - element.dataOffset;
+ return element;
+ }
+ }
+
+ // if element is not a sequence and has undefined length, we have to
+ // scan the data for a magic number to figure out when it ends.
+ if(element.length === 4294967295)
+ {
+ dicomParser.findItemDelimitationItemAndSetElementLength(byteStream, element);
+ return element;
+ }
+
+ // non sequence element with known length, skip over the data part
+ byteStream.seek(element.length);
+ return element;
+ };
+
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for parsing DICOM elements
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ function readDicomDataSetExplicitUndefinedLength(byteStream, warnings)
+ {
+ var elements = {};
+
+ while(byteStream.position < byteStream.byteArray.length)
+ {
+ var element = dicomParser.readDicomElementExplicit(byteStream, warnings);
+ elements[element.tag] = element;
+
+ // we hit an item delimiter tag, return the current offset to mark
+ // the end of this sequence item
+ if(element.tag === 'xfffee00d')
+ {
+ return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
+ }
+
+ }
+
+ // eof encountered - log a warning and return what we have for the element
+ byteStream.warnings.push('eof encountered before finding sequence delimitation item while reading sequence item of undefined length');
+ return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
+ }
+
+ function readSequenceItemExplicit(byteStream, warnings)
+ {
+ var item = dicomParser.readSequenceItem(byteStream);
+
+ if(item.length === 4294967295)
+ {
+ item.hadUndefinedLength = true;
+ item.dataSet = readDicomDataSetExplicitUndefinedLength(byteStream, warnings);
+ item.length = byteStream.position - item.dataOffset;
+ }
+ else
+ {
+ item.dataSet = new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, {});
+ dicomParser.parseDicomDataSetExplicit(item.dataSet, byteStream, byteStream.position + item.length);
+ }
+ return item;
+ }
+
+ function readSQElementUndefinedLengthExplicit(byteStream, element, warnings)
+ {
+ while(byteStream.position < byteStream.byteArray.length)
+ {
+ var item = readSequenceItemExplicit(byteStream, warnings);
+ element.items.push(item);
+
+ // If this is the sequence delimitation item, return the offset of the next element
+ if(item.tag === 'xfffee0dd')
+ {
+ // sequence delimitation item, update attr data length and return
+ element.length = byteStream.position - element.dataOffset;
+ return;
+ }
+ }
+
+ // eof encountered - log a warning and set the length of the element based on the buffer size
+ byteStream.warnings.push('eof encountered before finding sequence delimitation item in sequence element of undefined length with tag ' + element.tag);
+ element.length = byteStream.byteArray.length - element.dataOffset;
+ }
+
+ function readSQElementKnownLengthExplicit(byteStream, element, warnings)
+ {
+ var maxPosition = element.dataOffset + element.length;
+ while(byteStream.position < maxPosition)
+ {
+ var item = readSequenceItemExplicit(byteStream, warnings);
+ element.items.push(item);
+ }
+ }
+
+ dicomParser.readSequenceItemsExplicit = function(byteStream, element, warnings)
+ {
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.readSequenceItemsExplicit: missing required parameter 'byteStream'";
+ }
+ if(element === undefined)
+ {
+ throw "dicomParser.readSequenceItemsExplicit: missing required parameter 'element'";
+ }
+
+ element.items = [];
+
+ if(element.length === 4294967295)
+ {
+ readSQElementUndefinedLengthExplicit(byteStream, element);
+ }
+ else
+ {
+ readSQElementKnownLengthExplicit(byteStream, element, warnings);
+ }
+ };
+
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for parsing DICOM elements
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ function readDicomDataSetImplicitUndefinedLength(byteStream)
+ {
+ var elements = {};
+
+ while(byteStream.position < byteStream.byteArray.length)
+ {
+ var element = dicomParser.readDicomElementImplicit(byteStream);
+ elements[element.tag] = element;
+
+ // we hit an item delimiter tag, return the current offset to mark
+ // the end of this sequence item
+ if(element.tag === 'xfffee00d')
+ {
+ return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
+ }
+ }
+ // eof encountered - log a warning and return what we have for the element
+ byteStream.warnings.push('eof encountered before finding sequence item delimiter in sequence item of undefined length');
+ return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
+ }
+
+ function readSequenceItemImplicit(byteStream)
+ {
+ var item = dicomParser.readSequenceItem(byteStream);
+
+ if(item.length === 4294967295)
+ {
+ item.hadUndefinedLength = true;
+ item.dataSet = readDicomDataSetImplicitUndefinedLength(byteStream);
+ item.length = byteStream.position - item.dataOffset;
+ }
+ else
+ {
+ item.dataSet = new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, {});
+ dicomParser.parseDicomDataSetImplicit(item.dataSet, byteStream, byteStream.position + item.length);
+ }
+ return item;
+ }
+
+ function readSQElementUndefinedLengthImplicit(byteStream, element)
+ {
+ while(byteStream.position < byteStream.byteArray.length)
+ {
+ var item = readSequenceItemImplicit(byteStream);
+ element.items.push(item);
+
+ // If this is the sequence delimitation item, return the offset of the next element
+ if(item.tag === 'xfffee0dd')
+ {
+ // sequence delimitation item, update attr data length and return
+ element.length = byteStream.position - element.dataOffset;
+ return;
+ }
+ }
+
+ // eof encountered - log a warning and set the length of the element based on the buffer size
+ byteStream.warnings.push('eof encountered before finding sequence delimitation item in sequence of undefined length');
+ element.length = byteStream.byteArray.length - element.dataOffset;
+ }
+
+ function readSQElementKnownLengthImplicit(byteStream, element)
+ {
+ var maxPosition = element.dataOffset + element.length;
+ while(byteStream.position < maxPosition)
+ {
+ var item = readSequenceItemImplicit(byteStream);
+ element.items.push(item);
+ }
+ }
+
+ /**
+ * Reads sequence items for an element in an implicit little endian byte stream
+ * @param byteStream the implicit little endian byte stream
+ * @param element the element to read the sequence items for
+ */
+ dicomParser.readSequenceItemsImplicit = function(byteStream, element)
+ {
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.readSequenceItemsImplicit: missing required parameter 'byteStream'";
+ }
+ if(element === undefined)
+ {
+ throw "dicomParser.readSequenceItemsImplicit: missing required parameter 'element'";
+ }
+
+ element.items = [];
+
+ if(element.length === 4294967295)
+ {
+ readSQElementUndefinedLengthImplicit(byteStream, element);
+ }
+ else
+ {
+ readSQElementKnownLengthImplicit(byteStream, element);
+ }
+ };
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for parsing DICOM elements
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ /**
+ * Reads the tag and length of a sequence item and returns them as an object with the following properties
+ * tag : string for the tag of this element in the format xggggeeee
+ * length: the number of bytes in this item or 4294967295 if undefined
+ * dataOffset: the offset into the byteStream of the data for this item
+ * @param byteStream the byte
+ * @returns {{tag: string, length: integer, dataOffset: integer}}
+ */
+ dicomParser.readSequenceItem = function(byteStream)
+ {
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.readSequenceItem: missing required parameter 'byteStream'";
+ }
+
+ var element = {
+ tag : dicomParser.readTag(byteStream),
+ length : byteStream.readUint32(),
+ dataOffset : byteStream.position
+ };
+
+ return element;
+ };
+
+
+ return dicomParser;
+}(dicomParser));
+/**
+ * Internal helper functions for parsing DICOM elements
+ */
+
+var dicomParser = (function (dicomParser)
+{
+ "use strict";
+
+ if(dicomParser === undefined)
+ {
+ dicomParser = {};
+ }
+
+ /**
+ * Reads a tag (group number and element number) from a byteStream
+ * @param byteStream the byte stream to read from
+ * @returns {string} the tag in format xggggeeee where gggg is the lowercase hex value of the group number
+ * and eeee is the lower case hex value of the element number
+ */
+ dicomParser.readTag = function(byteStream)
+ {
+ if(byteStream === undefined)
+ {
+ throw "dicomParser.readTag: missing required parameter 'byteStream'";
+ }
+
+ var groupNumber = byteStream.readUint16() * 256 * 256;
+ var elementNumber = byteStream.readUint16();
+ var tag = "x" + ('00000000' + (groupNumber + elementNumber).toString(16)).substr(-8);
+ return tag;
+ };
+
+ return dicomParser;
+}(dicomParser));
+ return dicomParser;
+}));
+
+},{}],7:[function(require,module,exports){
+if (typeof Object.create === 'function') {
+ // implementation from standard node.js 'util' module
+ module.exports = function inherits(ctor, superCtor) {
+ ctor.super_ = superCtor
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ });
+ };
+} else {
+ // old school shim for old browsers
+ module.exports = function inherits(ctor, superCtor) {
+ ctor.super_ = superCtor
+ var TempCtor = function () {}
+ TempCtor.prototype = superCtor.prototype
+ ctor.prototype = new TempCtor()
+ ctor.prototype.constructor = ctor
+ }
+}
+
+},{}],8:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+
+
+/*** Constructor ***/
+jpeg.lossless.ComponentSpec = jpeg.lossless.ComponentSpec || function () {
+ this.hSamp = 0; // Horizontal sampling factor
+ this.quantTableSel = 0; // Quantization table destination selector
+ this.vSamp = 0; // Vertical
+};
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.ComponentSpec;
+}
+
+},{}],9:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+
+
+/*** Constructor ***/
+jpeg.lossless.DataStream = jpeg.lossless.DataStream || function (data, offset, length) {
+ this.buffer = new DataView(data, offset, length);
+ this.index = 0;
+};
+
+
+
+jpeg.lossless.DataStream.prototype.get16 = function () {
+ var value = this.buffer.getUint16(this.index, false);
+ this.index += 2;
+ return value;
+};
+
+
+
+jpeg.lossless.DataStream.prototype.get8 = function () {
+ var value = this.buffer.getUint8(this.index);
+ this.index += 1;
+ return value;
+};
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.DataStream;
+}
+
+},{}],10:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+jpeg.lossless.DataStream = jpeg.lossless.DataStream || ((typeof require !== 'undefined') ? require('./data-stream.js') : null);
+jpeg.lossless.HuffmanTable = jpeg.lossless.HuffmanTable || ((typeof require !== 'undefined') ? require('./huffman-table.js') : null);
+jpeg.lossless.QuantizationTable = jpeg.lossless.QuantizationTable || ((typeof require !== 'undefined') ? require('./quantization-table.js') : null);
+jpeg.lossless.ScanHeader = jpeg.lossless.ScanHeader || ((typeof require !== 'undefined') ? require('./scan-header.js') : null);
+jpeg.lossless.FrameHeader = jpeg.lossless.FrameHeader || ((typeof require !== 'undefined') ? require('./frame-header.js') : null);
+jpeg.lossless.Utils = jpeg.lossless.Utils || ((typeof require !== 'undefined') ? require('./utils.js') : null);
+
+
+/*** Constructor ***/
+jpeg.lossless.Decoder = jpeg.lossless.Decoder || function (buffer, numBytes) {
+ this.buffer = buffer;
+ this.frame = new jpeg.lossless.FrameHeader();
+ this.huffTable = new jpeg.lossless.HuffmanTable();
+ this.quantTable = new jpeg.lossless.QuantizationTable();
+ this.scan = new jpeg.lossless.ScanHeader();
+ this.DU = jpeg.lossless.Utils.createArray(10, 4, 64); // at most 10 data units in a MCU, at most 4 data units in one component
+ this.HuffTab = jpeg.lossless.Utils.createArray(4, 2, 50 * 256);
+ this.IDCT_Source = [];
+ this.nBlock = []; // number of blocks in the i-th Comp in a scan
+ this.acTab = jpeg.lossless.Utils.createArray(10, 1); // ac HuffTab for the i-th Comp in a scan
+ this.dcTab = jpeg.lossless.Utils.createArray(10, 1); // dc HuffTab for the i-th Comp in a scan
+ this.qTab = jpeg.lossless.Utils.createArray(10, 1); // quantization table for the i-th Comp in a scan
+ this.marker = 0;
+ this.markerIndex = 0;
+ this.numComp = 0;
+ this.restartInterval = 0;
+ this.selection = 0;
+ this.xDim = 0;
+ this.yDim = 0;
+ this.xLoc = 0;
+ this.yLoc = 0;
+ this.numBytes = 0;
+ this.outputData = null;
+ this.restarting = false;
+ this.mask = 0;
+
+ if (typeof numBytes !== "undefined") {
+ this.numBytes = numBytes;
+ }
+};
+
+
+/*** Static Pseudo-constants ***/
+
+jpeg.lossless.Decoder.IDCT_P = [0, 5, 40, 16, 45, 2, 7, 42, 21, 56, 8, 61, 18, 47, 1, 4, 41, 23, 58, 13, 32, 24, 37, 10, 63, 17, 44, 3, 6, 43, 20,
+ 57, 15, 34, 29, 48, 53, 26, 39, 9, 60, 19, 46, 22, 59, 12, 33, 31, 50, 55, 25, 36, 11, 62, 14, 35, 28, 49, 52, 27, 38, 30, 51, 54];
+jpeg.lossless.Decoder.TABLE = [0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53,
+ 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63];
+jpeg.lossless.Decoder.MAX_HUFFMAN_SUBTREE = 50;
+jpeg.lossless.Decoder.MSB = 0x80000000;
+jpeg.lossless.Decoder.RESTART_MARKER_BEGIN = 0xFFD0;
+jpeg.lossless.Decoder.RESTART_MARKER_END = 0xFFD7;
+
+/*** Prototype Methods ***/
+
+jpeg.lossless.Decoder.prototype.decompress = function (buffer, offset, length) {
+ return this.decode(buffer, offset, length).buffer;
+};
+
+
+
+jpeg.lossless.Decoder.prototype.decode = function (buffer, offset, length, numBytes) {
+ /*jslint bitwise: true */
+
+ var current, scanNum = 0, pred = [], i, compN, temp = [], index = [], mcuNum;
+
+ if (typeof buffer !== "undefined") {
+ this.buffer = buffer;
+ }
+
+ if (typeof numBytes !== "undefined") {
+ this.numBytes = numBytes;
+ }
+
+ this.stream = new jpeg.lossless.DataStream(this.buffer, offset, length);
+ this.buffer = null;
+
+ this.xLoc = 0;
+ this.yLoc = 0;
+ current = this.stream.get16();
+
+ if (current !== 0xFFD8) { // SOI
+ throw new Error("Not a JPEG file");
+ }
+
+ current = this.stream.get16();
+
+ while ((((current >> 4) !== 0x0FFC) || (current === 0xFFC4))) { // SOF 0~15
+ switch (current) {
+ case 0xFFC4: // DHT
+ this.huffTable.read(this.stream, this.HuffTab);
+ break;
+ case 0xFFCC: // DAC
+ throw new Error("Program doesn't support arithmetic coding. (format throw new IOException)");
+ case 0xFFDB:
+ this.quantTable.read(this.stream, jpeg.lossless.Decoder.TABLE);
+ break;
+ case 0xFFDD:
+ this.restartInterval = this.readNumber();
+ break;
+ case 0xFFE0:
+ case 0xFFE1:
+ case 0xFFE2:
+ case 0xFFE3:
+ case 0xFFE4:
+ case 0xFFE5:
+ case 0xFFE6:
+ case 0xFFE7:
+ case 0xFFE8:
+ case 0xFFE9:
+ case 0xFFEA:
+ case 0xFFEB:
+ case 0xFFEC:
+ case 0xFFED:
+ case 0xFFEE:
+ case 0xFFEF:
+ this.readApp();
+ break;
+ case 0xFFFE:
+ this.readComment();
+ break;
+ default:
+ if ((current >> 8) !== 0xFF) {
+ throw new Error("ERROR: format throw new IOException! (decode)");
+ }
+ }
+
+ current = this.stream.get16();
+ }
+
+ if ((current < 0xFFC0) || (current > 0xFFC7)) {
+ throw new Error("ERROR: could not handle arithmetic code!");
+ }
+
+ this.frame.read(this.stream);
+ current = this.stream.get16();
+
+ do {
+ while (current !== 0x0FFDA) { // SOS
+ switch (current) {
+ case 0xFFC4: // DHT
+ this.huffTable.read(this.stream, this.HuffTab);
+ break;
+ case 0xFFCC: // DAC
+ throw new Error("Program doesn't support arithmetic coding. (format throw new IOException)");
+ case 0xFFDB:
+ this.quantTable.read(this.stream, jpeg.lossless.Decoder.TABLE);
+ break;
+ case 0xFFDD:
+ this.restartInterval = this.readNumber();
+ break;
+ case 0xFFE0:
+ case 0xFFE1:
+ case 0xFFE2:
+ case 0xFFE3:
+ case 0xFFE4:
+ case 0xFFE5:
+ case 0xFFE6:
+ case 0xFFE7:
+ case 0xFFE8:
+ case 0xFFE9:
+ case 0xFFEA:
+ case 0xFFEB:
+ case 0xFFEC:
+ case 0xFFED:
+ case 0xFFEE:
+ case 0xFFEF:
+ this.readApp();
+ break;
+ case 0xFFFE:
+ this.readComment();
+ break;
+ default:
+ if ((current >> 8) !== 0xFF) {
+ throw new Error("ERROR: format throw new IOException! (Parser.decode)");
+ }
+ }
+
+ current = this.stream.get16();
+ }
+
+ this.precision = this.frame.precision;
+ this.components = this.frame.components;
+
+ if (!this.numBytes) {
+ this.numBytes = parseInt(Math.ceil(this.precision / 8));
+ }
+
+ if (this.numBytes == 1) {
+ this.mask = 0xFF;
+ } else {
+ this.mask = 0xFFFF;
+ }
+
+ this.scan.read(this.stream);
+ this.numComp = this.scan.numComp;
+ this.selection = this.scan.selection;
+
+ if (this.numBytes === 1) {
+ if (this.numComp === 3) {
+ this.getter = this.getValueRGB;
+ this.setter = this.setValueRGB;
+ this.output = this.outputRGB;
+ } else {
+ this.getter = this.getValue8;
+ this.setter = this.setValue8;
+ this.output = this.outputSingle;
+ }
+ } else {
+ this.getter = this.getValue16;
+ this.setter = this.setValue16;
+ this.output = this.outputSingle;
+ }
+
+ switch (this.selection) {
+ case 2:
+ this.selector = this.select2;
+ break;
+ case 3:
+ this.selector = this.select3;
+ break;
+ case 4:
+ this.selector = this.select4;
+ break;
+ case 5:
+ this.selector = this.select5;
+ break;
+ case 6:
+ this.selector = this.select6;
+ break;
+ case 7:
+ this.selector = this.select7;
+ break;
+ default:
+ this.selector = this.select1;
+ break;
+ }
+
+ this.scanComps = this.scan.components;
+ this.quantTables = this.quantTable.quantTables;
+
+ for (i = 0; i < this.numComp; i+=1) {
+ compN = this.scanComps[i].scanCompSel;
+ this.qTab[i] = this.quantTables[this.components[compN].quantTableSel];
+ this.nBlock[i] = this.components[compN].vSamp * this.components[compN].hSamp;
+ this.dcTab[i] = this.HuffTab[this.scanComps[i].dcTabSel][0];
+ this.acTab[i] = this.HuffTab[this.scanComps[i].acTabSel][1];
+ }
+
+ this.xDim = this.frame.dimX;
+ this.yDim = this.frame.dimY;
+ this.outputData = new DataView(new ArrayBuffer(this.xDim * this.yDim * this.numBytes * this.numComp));
+
+ scanNum+=1;
+
+ while (true) { // Decode one scan
+ temp[0] = 0;
+ index[0] = 0;
+
+ for (i = 0; i < 10; i+=1) {
+ pred[i] = (1 << (this.precision - 1));
+ }
+
+ if (this.restartInterval === 0) {
+ current = this.decodeUnit(pred, temp, index);
+
+ while ((current === 0) && ((this.xLoc < this.xDim) && (this.yLoc < this.yDim))) {
+ this.output(pred);
+ current = this.decodeUnit(pred, temp, index);
+ }
+
+ break; //current=MARKER
+ }
+
+ for (mcuNum = 0; mcuNum < this.restartInterval; mcuNum+=1) {
+ this.restarting = (mcuNum == 0);
+ current = this.decodeUnit(pred, temp, index);
+ this.output(pred);
+
+ if (current !== 0) {
+ break;
+ }
+ }
+
+ if (current === 0) {
+ if (this.markerIndex !== 0) {
+ current = (0xFF00 | this.marker);
+ this.markerIndex = 0;
+ } else {
+ current = this.stream.get16();
+ }
+ }
+
+ if (!((current >= jpeg.lossless.Decoder.RESTART_MARKER_BEGIN) &&
+ (current <= jpeg.lossless.Decoder.RESTART_MARKER_END))) {
+ break; //current=MARKER
+ }
+ }
+
+ if ((current === 0xFFDC) && (scanNum === 1)) { //DNL
+ this.readNumber();
+ current = this.stream.get16();
+ }
+ } while ((current !== 0xFFD9) && ((this.xLoc < this.xDim) && (this.yLoc < this.yDim)) && (scanNum === 0));
+
+ return this.outputData;
+};
+
+
+
+jpeg.lossless.Decoder.prototype.decodeUnit = function (prev, temp, index) {
+ if (this.numComp == 1) {
+ return this.decodeSingle(prev, temp, index);
+ } else if (this.numComp == 3) {
+ return this.decodeRGB(prev, temp, index);
+ } else {
+ return -1;
+ }
+};
+
+
+
+jpeg.lossless.Decoder.prototype.select1 = function (compOffset) {
+ return this.getPreviousX(compOffset);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.select2 = function (compOffset) {
+ return this.getPreviousY(compOffset);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.select3 = function (compOffset) {
+ return this.getPreviousXY(compOffset);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.select4 = function (compOffset) {
+ return (this.getPreviousX(compOffset) + this.getPreviousY(compOffset)) - this.getPreviousXY(compOffset);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.select5 = function (compOffset) {
+ return this.getPreviousX(compOffset) + ((this.getPreviousY(compOffset) - this.getPreviousXY(compOffset)) >> 1);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.select6 = function (compOffset) {
+ return this.getPreviousY(compOffset) + ((this.getPreviousX(compOffset) - this.getPreviousXY(compOffset)) >> 1);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.select7 = function (compOffset) {
+ return ((this.getPreviousX(compOffset) + this.getPreviousY(compOffset)) / 2);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.decodeRGB = function (prev, temp, index) {
+ /*jslint bitwise: true */
+
+ var value, actab, dctab, qtab, ctrC, i, k, j;
+
+ prev[0] = this.selector(0);
+ prev[1] = this.selector(1);
+ prev[2] = this.selector(2);
+
+ for (ctrC = 0; ctrC < this.numComp; ctrC+=1) {
+ qtab = this.qTab[ctrC];
+ actab = this.acTab[ctrC];
+ dctab = this.dcTab[ctrC];
+ for (i = 0; i < this.nBlock[ctrC]; i+=1) {
+ for (k = 0; k < this.IDCT_Source.length; k+=1) {
+ this.IDCT_Source[k] = 0;
+ }
+
+ value = this.getHuffmanValue(dctab, temp, index);
+
+ if (value >= 0xFF00) {
+ return value;
+ }
+
+ prev[ctrC] = this.IDCT_Source[0] = prev[ctrC] + this.getn(index, value, temp, index);
+ this.IDCT_Source[0] *= qtab[0];
+
+ for (j = 1; j < 64; j+=1) {
+ value = this.getHuffmanValue(actab, temp, index);
+
+ if (value >= 0xFF00) {
+ return value;
+ }
+
+ j += (value >> 4);
+
+ if ((value & 0x0F) === 0) {
+ if ((value >> 4) === 0) {
+ break;
+ }
+ } else {
+ this.IDCT_Source[jpeg.lossless.Decoder.IDCT_P[j]] = this.getn(index, value & 0x0F, temp, index) * qtab[j];
+ }
+ }
+ }
+ }
+
+ return 0;
+};
+
+
+
+jpeg.lossless.Decoder.prototype.decodeSingle = function (prev, temp, index) {
+ /*jslint bitwise: true */
+
+ var value, i, n, nRestart;
+
+ if (this.restarting) {
+ this.restarting = false;
+ prev[0] = (1 << (this.frame.precision - 1));
+ } else {
+ prev[0] = this.selector();
+ }
+
+ for (i = 0; i < this.nBlock[0]; i+=1) {
+ value = this.getHuffmanValue(this.dcTab[0], temp, index);
+ if (value >= 0xFF00) {
+ return value;
+ }
+
+ n = this.getn(prev, value, temp, index);
+ nRestart = (n >> 8);
+
+ if ((nRestart >= jpeg.lossless.Decoder.RESTART_MARKER_BEGIN) && (nRestart <= jpeg.lossless.Decoder.RESTART_MARKER_END)) {
+ return nRestart;
+ }
+
+ prev[0] += n;
+ }
+
+ return 0;
+};
+
+
+
+// Huffman table for fast search: (HuffTab) 8-bit Look up table 2-layer search architecture, 1st-layer represent 256 node (8 bits) if codeword-length > 8
+// bits, then the entry of 1st-layer = (# of 2nd-layer table) | MSB and it is stored in the 2nd-layer Size of tables in each layer are 256.
+// HuffTab[*][*][0-256] is always the only 1st-layer table.
+//
+// An entry can be: (1) (# of 2nd-layer table) | MSB , for code length > 8 in 1st-layer (2) (Code length) << 8 | HuffVal
+//
+// HuffmanValue(table HuffTab[x][y] (ex) HuffmanValue(HuffTab[1][0],...)
+// ):
+// return: Huffman Value of table
+// 0xFF?? if it receives a MARKER
+// Parameter: table HuffTab[x][y] (ex) HuffmanValue(HuffTab[1][0],...)
+// temp temp storage for remainded bits
+// index index to bit of temp
+// in FILE pointer
+// Effect:
+// temp store new remainded bits
+// index change to new index
+// in change to new position
+// NOTE:
+// Initial by temp=0; index=0;
+// NOTE: (explain temp and index)
+// temp: is always in the form at calling time or returning time
+// | byte 4 | byte 3 | byte 2 | byte 1 |
+// | 0 | 0 | 00000000 | 00000??? | if not a MARKER
+// ^index=3 (from 0 to 15)
+// 321
+// NOTE (marker and marker_index):
+// If get a MARKER from 'in', marker=the low-byte of the MARKER
+// and marker_index=9
+// If marker_index=9 then index is always > 8, or HuffmanValue()
+// will not be called
+jpeg.lossless.Decoder.prototype.getHuffmanValue = function (table, temp, index) {
+ /*jslint bitwise: true */
+
+ var code, input, mask;
+ mask = 0xFFFF;
+
+ if (index[0] < 8) {
+ temp[0] <<= 8;
+ input = this.stream.get8();
+ if (input === 0xFF) {
+ this.marker = this.stream.get8();
+ if (this.marker !== 0) {
+ this.markerIndex = 9;
+ }
+ }
+ temp[0] |= input;
+ } else {
+ index[0] -= 8;
+ }
+
+ code = table[temp[0] >> index[0]];
+
+ if ((code & jpeg.lossless.Decoder.MSB) !== 0) {
+ if (this.markerIndex !== 0) {
+ this.markerIndex = 0;
+ return 0xFF00 | this.marker;
+ }
+
+ temp[0] &= (mask >> (16 - index[0]));
+ temp[0] <<= 8;
+ input = this.stream.get8();
+
+ if (input === 0xFF) {
+ this.marker = this.stream.get8();
+ if (this.marker !== 0) {
+ this.markerIndex = 9;
+ }
+ }
+
+ temp[0] |= input;
+ code = table[((code & 0xFF) * 256) + (temp[0] >> index[0])];
+ index[0] += 8;
+ }
+
+ index[0] += 8 - (code >> 8);
+
+ if (index[0] < 0) {
+ throw new Error("index=" + index[0] + " temp=" + temp[0] + " code=" + code + " in HuffmanValue()");
+ }
+
+ if (index[0] < this.markerIndex) {
+ this.markerIndex = 0;
+ return 0xFF00 | this.marker;
+ }
+
+ temp[0] &= (mask >> (16 - index[0]));
+ return code & 0xFF;
+};
+
+
+
+jpeg.lossless.Decoder.prototype.getn = function (PRED, n, temp, index) {
+ /*jslint bitwise: true */
+
+ var result, one, n_one, mask, input;
+ one = 1;
+ n_one = -1;
+ mask = 0xFFFF;
+
+ if (n === 0) {
+ return 0;
+ }
+
+ if (n === 16) {
+ if (PRED[0] >= 0) {
+ return -32768;
+ } else {
+ return 32768;
+ }
+ }
+
+ index[0] -= n;
+
+ if (index[0] >= 0) {
+ if ((index[0] < this.markerIndex) && !this.isLastPixel()) { // this was corrupting the last pixel in some cases
+ this.markerIndex = 0;
+ return (0xFF00 | this.marker) << 8;
+ }
+
+ result = temp[0] >> index[0];
+ temp[0] &= (mask >> (16 - index[0]));
+ } else {
+ temp[0] <<= 8;
+ input = this.stream.get8();
+
+ if (input === 0xFF) {
+ this.marker = this.stream.get8();
+ if (this.marker !== 0) {
+ this.markerIndex = 9;
+ }
+ }
+
+ temp[0] |= input;
+ index[0] += 8;
+
+ if (index[0] < 0) {
+ if (this.markerIndex !== 0) {
+ this.markerIndex = 0;
+ return (0xFF00 | this.marker) << 8;
+ }
+
+ temp[0] <<= 8;
+ input = this.stream.get8();
+
+ if (input === 0xFF) {
+ this.marker = this.stream.get8();
+ if (this.marker !== 0) {
+ this.markerIndex = 9;
+ }
+ }
+
+ temp[0] |= input;
+ index[0] += 8;
+ }
+
+ if (index[0] < 0) {
+ throw new Error("index=" + index[0] + " in getn()");
+ }
+
+ if (index[0] < this.markerIndex) {
+ this.markerIndex = 0;
+ return (0xFF00 | this.marker) << 8;
+ }
+
+ result = temp[0] >> index[0];
+ temp[0] &= (mask >> (16 - index[0]));
+ }
+
+ if (result < (one << (n - 1))) {
+ result += (n_one << n) + 1;
+ }
+
+ return result;
+};
+
+
+
+jpeg.lossless.Decoder.prototype.getPreviousX = function (compOffset) {
+ /*jslint bitwise: true */
+
+ if (this.xLoc > 0) {
+ return this.getter((((this.yLoc * this.xDim) + this.xLoc) - 1), compOffset);
+ } else if (this.yLoc > 0) {
+ return this.getPreviousY(compOffset);
+ } else {
+ return (1 << (this.frame.precision - 1));
+ }
+};
+
+
+
+jpeg.lossless.Decoder.prototype.getPreviousXY = function (compOffset) {
+ /*jslint bitwise: true */
+
+ if ((this.xLoc > 0) && (this.yLoc > 0)) {
+ return this.getter(((((this.yLoc - 1) * this.xDim) + this.xLoc) - 1), compOffset);
+ } else {
+ return this.getPreviousY(compOffset);
+ }
+};
+
+
+
+jpeg.lossless.Decoder.prototype.getPreviousY = function (compOffset) {
+ /*jslint bitwise: true */
+
+ if (this.yLoc > 0) {
+ return this.getter((((this.yLoc - 1) * this.xDim) + this.xLoc), compOffset);
+ } else {
+ return this.getPreviousX(compOffset);
+ }
+};
+
+
+
+jpeg.lossless.Decoder.prototype.isLastPixel = function () {
+ return (this.xLoc === (this.xDim - 1)) && (this.yLoc === (this.yDim - 1));
+};
+
+
+
+jpeg.lossless.Decoder.prototype.outputSingle = function (PRED) {
+ if ((this.xLoc < this.xDim) && (this.yLoc < this.yDim)) {
+ this.setter((((this.yLoc * this.xDim) + this.xLoc)), this.mask & PRED[0]);
+
+ this.xLoc+=1;
+
+ if (this.xLoc >= this.xDim) {
+ this.yLoc+=1;
+ this.xLoc = 0;
+ }
+ }
+};
+
+
+
+jpeg.lossless.Decoder.prototype.outputRGB = function (PRED) {
+ var offset = ((this.yLoc * this.xDim) + this.xLoc);
+
+ if ((this.xLoc < this.xDim) && (this.yLoc < this.yDim)) {
+ this.setter(offset, PRED[0], 0);
+ this.setter(offset, PRED[1], 1);
+ this.setter(offset, PRED[2], 2);
+
+ this.xLoc+=1;
+
+ if (this.xLoc >= this.xDim) {
+ this.yLoc+=1;
+ this.xLoc = 0;
+ }
+ }
+};
+
+
+
+jpeg.lossless.Decoder.prototype.setValue16 = function (index, val) {
+ this.outputData.setInt16(index * 2, val, true);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.getValue16 = function (index) {
+ return this.outputData.getInt16(index * 2, true);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.setValue8 = function (index, val) {
+ this.outputData.setInt8(index, val);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.getValue8 = function (index) {
+ return this.outputData.getInt8(index);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.setValueRGB = function (index, val, compOffset) {
+ this.outputData.setUint8(index * 3 + compOffset, val);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.getValueRGB = function (index, compOffset) {
+ return this.outputData.getUint8(index * 3 + compOffset);
+};
+
+
+
+jpeg.lossless.Decoder.prototype.readApp = function() {
+ var count = 0, length = this.stream.get16();
+ count += 2;
+
+ while (count < length) {
+ this.stream.get8();
+ count+=1;
+ }
+
+ return length;
+};
+
+
+
+jpeg.lossless.Decoder.prototype.readComment = function () {
+ var sb = "", count = 0, length;
+
+ length = this.stream.get16();
+ count += 2;
+
+ while (count < length) {
+ sb += this.stream.get8();
+ count+=1;
+ }
+
+ return sb;
+};
+
+
+
+jpeg.lossless.Decoder.prototype.readNumber = function() {
+ var Ld = this.stream.get16();
+
+ if (Ld !== 4) {
+ throw new Error("ERROR: Define number format throw new IOException [Ld!=4]");
+ }
+
+ return this.stream.get16();
+};
+
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.Decoder;
+}
+
+},{"./data-stream.js":9,"./frame-header.js":11,"./huffman-table.js":12,"./quantization-table.js":14,"./scan-header.js":16,"./utils.js":17}],11:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+jpeg.lossless.ComponentSpec = jpeg.lossless.ComponentSpec || ((typeof require !== 'undefined') ? require('./component-spec.js') : null);
+jpeg.lossless.DataStream = jpeg.lossless.DataStream || ((typeof require !== 'undefined') ? require('./data-stream.js') : null);
+
+
+/*** Constructor ***/
+jpeg.lossless.FrameHeader = jpeg.lossless.FrameHeader || function () {
+ this.components = []; // Components
+ this.dimX = 0; // Number of samples per line
+ this.dimY = 0; // Number of lines
+ this.numComp = 0; // Number of component in the frame
+ this.precision = 0; // Sample Precision (from the original image)
+};
+
+
+
+/*** Prototype Methods ***/
+
+jpeg.lossless.FrameHeader.prototype.read = function (data) {
+ /*jslint bitwise: true */
+
+ var count = 0, length, i, c, temp;
+
+ length = data.get16();
+ count += 2;
+
+ this.precision = data.get8();
+ count+=1;
+
+ this.dimY = data.get16();
+ count += 2;
+
+ this.dimX = data.get16();
+ count += 2;
+
+ this.numComp = data.get8();
+ count+=1;
+ for (i = 1; i <= this.numComp; i+=1) {
+ if (count > length) {
+ throw new Error("ERROR: frame format error");
+ }
+
+ c = data.get8();
+ count+=1;
+
+ if (count >= length) {
+ throw new Error("ERROR: frame format error [c>=Lf]");
+ }
+
+ temp = data.get8();
+ count+=1;
+
+ if (!this.components[c]) {
+ this.components[c] = new jpeg.lossless.ComponentSpec();
+ }
+
+ this.components[c].hSamp = temp >> 4;
+ this.components[c].vSamp = temp & 0x0F;
+ this.components[c].quantTableSel = data.get8();
+ count+=1;
+ }
+
+ if (count !== length) {
+ throw new Error("ERROR: frame format error [Lf!=count]");
+ }
+
+ return 1;
+};
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.FrameHeader;
+}
+
+},{"./component-spec.js":8,"./data-stream.js":9}],12:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+jpeg.lossless.DataStream = jpeg.lossless.DataStream || ((typeof require !== 'undefined') ? require('./data-stream.js') : null);
+jpeg.lossless.Utils = jpeg.lossless.Utils || ((typeof require !== 'undefined') ? require('./utils.js') : null);
+
+
+/*** Constructor ***/
+jpeg.lossless.HuffmanTable = jpeg.lossless.HuffmanTable || function () {
+ this.l = jpeg.lossless.Utils.createArray(4, 2, 16);
+ this.th = [];
+ this.v = jpeg.lossless.Utils.createArray(4, 2, 16, 200);
+ this.tc = jpeg.lossless.Utils.createArray(4, 2);
+
+ this.tc[0][0] = 0;
+ this.tc[1][0] = 0;
+ this.tc[2][0] = 0;
+ this.tc[3][0] = 0;
+ this.tc[0][1] = 0;
+ this.tc[1][1] = 0;
+ this.tc[2][1] = 0;
+ this.tc[3][1] = 0;
+ this.th[0] = 0;
+ this.th[1] = 0;
+ this.th[2] = 0;
+ this.th[3] = 0;
+};
+
+
+
+/*** Static Pseudo-constants ***/
+
+jpeg.lossless.HuffmanTable.MSB = 0x80000000;
+
+
+/*** Prototype Methods ***/
+
+jpeg.lossless.HuffmanTable.prototype.read = function(data, HuffTab) {
+ /*jslint bitwise: true */
+
+ var count = 0, length, temp, t, c, i, j;
+
+ length = data.get16();
+ count += 2;
+
+ while (count < length) {
+ temp = data.get8();
+ count+=1;
+ t = temp & 0x0F;
+ if (t > 3) {
+ throw new Error("ERROR: Huffman table ID > 3");
+ }
+
+ c = temp >> 4;
+ if (c > 2) {
+ throw new Error("ERROR: Huffman table [Table class > 2 ]");
+ }
+
+ this.th[t] = 1;
+ this.tc[t][c] = 1;
+
+ for (i = 0; i < 16; i+=1) {
+ this.l[t][c][i] = data.get8();
+ count+=1;
+ }
+
+ for (i = 0; i < 16; i+=1) {
+ for (j = 0; j < this.l[t][c][i]; j+=1) {
+ if (count > length) {
+ throw new Error("ERROR: Huffman table format error [count>Lh]");
+ }
+
+ this.v[t][c][i][j] = data.get8();
+ count+=1;
+ }
+ }
+ }
+
+ if (count !== length) {
+ throw new Error("ERROR: Huffman table format error [count!=Lf]");
+ }
+
+ for (i = 0; i < 4; i+=1) {
+ for (j = 0; j < 2; j+=1) {
+ if (this.tc[i][j] !== 0) {
+ this.buildHuffTable(HuffTab[i][j], this.l[i][j], this.v[i][j]);
+ }
+ }
+ }
+
+ return 1;
+};
+
+
+
+// Build_HuffTab()
+// Parameter: t table ID
+// c table class ( 0 for DC, 1 for AC )
+// L[i] # of codewords which length is i
+// V[i][j] Huffman Value (length=i)
+// Effect:
+// build up HuffTab[t][c] using L and V.
+jpeg.lossless.HuffmanTable.prototype.buildHuffTable = function(tab, L, V) {
+ /*jslint bitwise: true */
+
+ var currentTable, temp, k, i, j, n;
+ temp = 256;
+ k = 0;
+
+ for (i = 0; i < 8; i+=1) { // i+1 is Code length
+ for (j = 0; j < L[i]; j+=1) {
+ for (n = 0; n < (temp >> (i + 1)); n+=1) {
+ tab[k] = V[i][j] | ((i + 1) << 8);
+ k+=1;
+ }
+ }
+ }
+
+ for (i = 1; k < 256; i+=1, k+=1) {
+ tab[k] = i | jpeg.lossless.HuffmanTable.MSB;
+ }
+
+ currentTable = 1;
+ k = 0;
+
+ for (i = 8; i < 16; i+=1) { // i+1 is Code length
+ for (j = 0; j < L[i]; j+=1) {
+ for (n = 0; n < (temp >> (i - 7)); n+=1) {
+ tab[(currentTable * 256) + k] = V[i][j] | ((i + 1) << 8);
+ k+=1;
+ }
+
+ if (k >= 256) {
+ if (k > 256) {
+ throw new Error("ERROR: Huffman table error(1)!");
+ }
+
+ k = 0;
+ currentTable+=1;
+ }
+ }
+ }
+};
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.HuffmanTable;
+}
+
+},{"./data-stream.js":9,"./utils.js":17}],13:[function(require,module,exports){
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+jpeg.lossless.ComponentSpec = jpeg.lossless.ComponentSpec || ((typeof require !== 'undefined') ? require('./component-spec.js') : null);
+jpeg.lossless.DataStream = jpeg.lossless.DataStream || ((typeof require !== 'undefined') ? require('./data-stream.js') : null);
+jpeg.lossless.Decoder = jpeg.lossless.Decoder || ((typeof require !== 'undefined') ? require('./decoder.js') : null);
+jpeg.lossless.FrameHeader = jpeg.lossless.FrameHeader || ((typeof require !== 'undefined') ? require('./frame-header.js') : null);
+jpeg.lossless.HuffmanTable = jpeg.lossless.HuffmanTable || ((typeof require !== 'undefined') ? require('./huffman-table.js') : null);
+jpeg.lossless.QuantizationTable = jpeg.lossless.QuantizationTable || ((typeof require !== 'undefined') ? require('./quantization-table.js') : null);
+jpeg.lossless.ScanComponent = jpeg.lossless.ScanComponent || ((typeof require !== 'undefined') ? require('./scan-component.js') : null);
+jpeg.lossless.ScanHeader = jpeg.lossless.ScanHeader || ((typeof require !== 'undefined') ? require('./scan-header.js') : null);
+jpeg.lossless.Utils = jpeg.lossless.Utils || ((typeof require !== 'undefined') ? require('./utils.js') : null);
+
+
+/*** Exports ***/
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg;
+}
+
+},{"./component-spec.js":8,"./data-stream.js":9,"./decoder.js":10,"./frame-header.js":11,"./huffman-table.js":12,"./quantization-table.js":14,"./scan-component.js":15,"./scan-header.js":16,"./utils.js":17}],14:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+jpeg.lossless.DataStream = jpeg.lossless.DataStream || ((typeof require !== 'undefined') ? require('./data-stream.js') : null);
+jpeg.lossless.Utils = jpeg.lossless.Utils || ((typeof require !== 'undefined') ? require('./utils.js') : null);
+
+
+/*** Constructor ***/
+jpeg.lossless.QuantizationTable = jpeg.lossless.QuantizationTable || function () {
+ this.precision = []; // Quantization precision 8 or 16
+ this.tq = []; // 1: this table is presented
+ this.quantTables = jpeg.lossless.Utils.createArray(4, 64); // Tables
+
+ this.tq[0] = 0;
+ this.tq[1] = 0;
+ this.tq[2] = 0;
+ this.tq[3] = 0;
+};
+
+
+
+/*** Static Methods ***/
+
+jpeg.lossless.QuantizationTable.enhanceQuantizationTable = function(qtab, table) {
+ /*jslint bitwise: true */
+
+ var i;
+
+ for (i = 0; i < 8; i+=1) {
+ qtab[table[(0 * 8) + i]] *= 90;
+ qtab[table[(4 * 8) + i]] *= 90;
+ qtab[table[(2 * 8) + i]] *= 118;
+ qtab[table[(6 * 8) + i]] *= 49;
+ qtab[table[(5 * 8) + i]] *= 71;
+ qtab[table[(1 * 8) + i]] *= 126;
+ qtab[table[(7 * 8) + i]] *= 25;
+ qtab[table[(3 * 8) + i]] *= 106;
+ }
+
+ for (i = 0; i < 8; i+=1) {
+ qtab[table[0 + (8 * i)]] *= 90;
+ qtab[table[4 + (8 * i)]] *= 90;
+ qtab[table[2 + (8 * i)]] *= 118;
+ qtab[table[6 + (8 * i)]] *= 49;
+ qtab[table[5 + (8 * i)]] *= 71;
+ qtab[table[1 + (8 * i)]] *= 126;
+ qtab[table[7 + (8 * i)]] *= 25;
+ qtab[table[3 + (8 * i)]] *= 106;
+ }
+
+ for (i = 0; i < 64; i+=1) {
+ qtab[i] >>= 6;
+ }
+};
+
+
+/*** Prototype Methods ***/
+
+jpeg.lossless.QuantizationTable.prototype.read = function (data, table) {
+ /*jslint bitwise: true */
+
+ var count = 0, length, temp, t, i;
+
+ length = data.get16();
+ count += 2;
+
+ while (count < length) {
+ temp = data.get8();
+ count+=1;
+ t = temp & 0x0F;
+
+ if (t > 3) {
+ throw new Error("ERROR: Quantization table ID > 3");
+ }
+
+ this.precision[t] = temp >> 4;
+
+ if (this.precision[t] === 0) {
+ this.precision[t] = 8;
+ } else if (this.precision[t] === 1) {
+ this.precision[t] = 16;
+ } else {
+ throw new Error("ERROR: Quantization table precision error");
+ }
+
+ this.tq[t] = 1;
+
+ if (this.precision[t] === 8) {
+ for (i = 0; i < 64; i+=1) {
+ if (count > length) {
+ throw new Error("ERROR: Quantization table format error");
+ }
+
+ this.quantTables[t][i] = data.get8();
+ count+=1;
+ }
+
+ jpeg.lossless.QuantizationTable.enhanceQuantizationTable(this.quantTables[t], table);
+ } else {
+ for (i = 0; i < 64; i+=1) {
+ if (count > length) {
+ throw new Error("ERROR: Quantization table format error");
+ }
+
+ this.quantTables[t][i] = data.get16();
+ count += 2;
+ }
+
+ jpeg.lossless.QuantizationTable.enhanceQuantizationTable(this.quantTables[t], table);
+ }
+ }
+
+ if (count !== length) {
+ throw new Error("ERROR: Quantization table error [count!=Lq]");
+ }
+
+ return 1;
+};
+
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.QuantizationTable;
+}
+
+},{"./data-stream.js":9,"./utils.js":17}],15:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+
+
+/*** Constructor ***/
+jpeg.lossless.ScanComponent = jpeg.lossless.ScanComponent || function () {
+ this.acTabSel = 0; // AC table selector
+ this.dcTabSel = 0; // DC table selector
+ this.scanCompSel = 0; // Scan component selector
+};
+
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.ScanComponent;
+}
+
+},{}],16:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+jpeg.lossless.DataStream = jpeg.lossless.DataStream || ((typeof require !== 'undefined') ? require('./data-stream.js') : null);
+jpeg.lossless.ScanComponent = jpeg.lossless.ScanComponent || ((typeof require !== 'undefined') ? require('./scan-component.js') : null);
+
+
+/*** Constructor ***/
+jpeg.lossless.ScanHeader = jpeg.lossless.ScanHeader || function () {
+ this.ah = 0;
+ this.al = 0;
+ this.numComp = 0; // Number of components in the scan
+ this.selection = 0; // Start of spectral or predictor selection
+ this.spectralEnd = 0; // End of spectral selection
+ this.components = [];
+};
+
+
+/*** Prototype Methods ***/
+
+jpeg.lossless.ScanHeader.prototype.read = function(data) {
+ /*jslint bitwise: true */
+
+ var count = 0, length, i, temp;
+
+ length = data.get16();
+ count += 2;
+
+ this.numComp = data.get8();
+ count+=1;
+
+ for (i = 0; i < this.numComp; i+=1) {
+ this.components[i] = new jpeg.lossless.ScanComponent();
+
+ if (count > length) {
+ throw new Error("ERROR: scan header format error");
+ }
+
+ this.components[i].scanCompSel = data.get8();
+ count+=1;
+
+ temp = data.get8();
+ count+=1;
+
+ this.components[i].dcTabSel = (temp >> 4);
+ this.components[i].acTabSel = (temp & 0x0F);
+ }
+
+ this.selection = data.get8();
+ count+=1;
+
+ this.spectralEnd = data.get8();
+ count+=1;
+
+ temp = data.get8();
+ this.ah = (temp >> 4);
+ this.al = (temp & 0x0F);
+ count+=1;
+
+ if (count !== length) {
+ throw new Error("ERROR: scan header format error [count!=Ns]");
+ }
+
+ return 1;
+};
+
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.ScanHeader;
+}
+
+},{"./data-stream.js":9,"./scan-component.js":15}],17:[function(require,module,exports){
+/*
+ * Copyright (C) 2015 Michael Martinez
+ * Changes: Added support for selection values 2-7, fixed minor bugs &
+ * warnings, split into multiple class files, and general clean up.
+ *
+ * 08-25-2015: Helmut Dersch agreed to a license change from LGPL to MIT.
+ */
+
+/*
+ * Copyright (C) Helmut Dersch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+var jpeg = jpeg || {};
+jpeg.lossless = jpeg.lossless || {};
+
+
+/*** Constructor ***/
+jpeg.lossless.Utils = jpeg.lossless.Utils || {};
+
+
+/*** Static methods ***/
+
+// http://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript
+jpeg.lossless.Utils.createArray = function (length) {
+ var arr = new Array(length || 0),
+ i = length;
+
+ if (arguments.length > 1) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ while(i--) arr[length-1 - i] = jpeg.lossless.Utils.createArray.apply(this, args);
+ }
+
+ return arr;
+};
+
+
+// http://stackoverflow.com/questions/18638900/javascript-crc32
+jpeg.lossless.Utils.makeCRCTable = function(){
+ var c;
+ var crcTable = [];
+ for(var n =0; n < 256; n++){
+ c = n;
+ for(var k =0; k < 8; k++){
+ c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
+ }
+ crcTable[n] = c;
+ }
+ return crcTable;
+};
+
+jpeg.lossless.Utils.crc32 = function(dataView) {
+ var crcTable = jpeg.lossless.Utils.crcTable || (jpeg.lossless.Utils.crcTable = jpeg.lossless.Utils.makeCRCTable());
+ var crc = 0 ^ (-1);
+
+ for (var i = 0; i < dataView.byteLength; i++ ) {
+ crc = (crc >>> 8) ^ crcTable[(crc ^ dataView.getUint8(i)) & 0xFF];
+ }
+
+ return (crc ^ (-1)) >>> 0;
+};
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = jpeg.lossless.Utils;
+}
+
+},{}],18:[function(require,module,exports){
+'use strict';
+
+/**
+* FUNCTION: abs( x )
+* Computes the absolute value of `x`.
+*
+* @param {Number} x - input value
+* @returns {Number} absolute value
+*/
+function abs( x ) {
+ if ( x < 0 ) {
+ return -x;
+ }
+ if ( x === 0 ) {
+ return 0; // handle negative zero
+ }
+ return x;
+} // end FUNCTION abs()
+
+
+// EXPORTS //
+
+module.exports = abs;
+
+},{}],19:[function(require,module,exports){
+'use strict';
+
+// EXPORTS //
+
+module.exports = Math.ceil;
+
+},{}],20:[function(require,module,exports){
+'use strict';
+
+// MODULES //
+
+var floor = require( 'math-floor' );
+
+
+// DIV2 //
+
+/**
+* FUNCTION: div2( x )
+* Converts a nonnegative integer to a literal bit representation using the divide-by-2 algorithm.
+*
+* @param {Number} x - nonnegative integer
+* @returns {String} bit representation
+*/
+function div2( x ) {
+ var str = '';
+ var y;
+
+ // We repeatedly divide by 2 and check for a remainder. If a remainder exists, the number is odd and we add a '1' bit...
+ while ( x > 0 ) {
+ y = x / 2;
+ x = floor( y );
+ if ( y === x ) {
+ str = '0' + str;
+ } else {
+ str = '1' + str;
+ }
+ }
+ return str;
+} // end FUNCTION div2()
+
+
+// EXPORTS //
+
+module.exports = div2;
+
+},{"math-floor":23}],21:[function(require,module,exports){
+'use strict';
+
+// MODULES //
+
+var pinf = require( 'const-pinf-float32' );
+var ninf = require( 'const-ninf-float32' );
+var abs = require( 'math-abs' );
+var floor = require( 'math-floor' );
+var rpad = require( 'utils-right-pad-string' );
+var lpad = require( 'utils-left-pad-string' );
+var repeat = require( 'utils-repeat-string' );
+var div2 = require( './div2.js' );
+var mult2 = require( './mult2.js' );
+
+
+// CONSTANTS //
+
+var BIAS = 127; // exponent bias => (2**8)/2 - 1
+
+
+// BINARY STRING //
+
+/**
+* FUNCTION: binaryString( x )
+* Returns a string giving the literal bit representation of a single-precision floating-point number.
+*
+* @param {Number} x - input value
+* @returns {String} bit representation
+*/
+function binaryString( x ) {
+ var nbits;
+ var sign;
+ var str;
+ var exp;
+ var n;
+ var f;
+ var i;
+
+ // Check for a negative value or negative zero...
+ if ( x < 0 || 1/x === ninf ) {
+ sign = '1';
+ } else {
+ sign = '0';
+ }
+ // Special case: +-infinity
+ if ( x === pinf || x === ninf ) {
+ // Based on IEEE 754-2008...
+ exp = repeat( '1', 8 ); // all 1s
+ str = repeat( '0', 23 ); // all 0s
+ return sign + exp + str;
+ }
+ // Special case: NaN
+ if ( x !== x ) {
+ // Based on IEEE 754-2008...
+ exp = repeat( '1', 8 ); // all 1s
+ str = '1' + repeat( '0', 22 ); // can't be all 0s
+ return sign + exp + str;
+ }
+ // Special case: +-0
+ if ( x === 0 ) {
+ // Based on IEEE 754-2008...
+ exp = repeat( '0', 8 ); // all 0s
+ str = repeat( '0', 23 ); // all 0s
+ return sign + exp + str;
+ }
+ x = abs( x );
+
+ // Isolate the integer part (digits before the decimal):
+ n = floor( x );
+
+ // Isolate the fractional part (digits after the decimal):
+ f = x - n;
+
+ // Convert the integer and fractional parts to bit strings:
+ n = div2( n );
+ f = mult2( f );
+
+ // Determine the exponent needed to normalize the integer+fractional parts...
+ if ( n ) {
+ // Move the decimal `d` digits to the left:
+ exp = n.length - 1;
+ } else {
+ // Find the first '1' bit...
+ for ( i = 0; i < f.length; i++ ) {
+ if ( f[ i ] === '1' ) {
+ nbits = i + 1;
+ break;
+ }
+ }
+ // Move the decimal `d` digits to the right:
+ exp = -nbits;
+ }
+ // Normalize the combined integer+fractional string...
+ str = n + f;
+ if ( exp < 0 ) {
+ // Handle subnormals...
+ if ( exp <= -BIAS ) {
+ // Cap the number of bits removed:
+ nbits = BIAS - 1;
+ }
+ // Remove all leading zeros and the first '1' for normal values, and, for subnormals, remove at most BIAS-1 leading bits:
+ str = str.substring( nbits );
+ } else {
+ // Remove the leading '1' (implicit/hidden bit):
+ str = str.substring( 1 );
+ }
+ // Convert the exponent to a bit string:
+ exp = div2( exp + BIAS );
+ exp = lpad( exp, 8, '0' );
+
+ // Fill in any trailing zeros and ensure we have only 23 fraction bits:
+ str = rpad( str, 23, '0' ).substring( 0, 23 );
+
+ // Return a bit representation:
+ return sign + exp + str;
+} // end FUNCTION binaryString()
+
+
+// EXPORTS //
+
+module.exports = binaryString;
+
+},{"./div2.js":20,"./mult2.js":22,"const-ninf-float32":4,"const-pinf-float32":5,"math-abs":18,"math-floor":23,"utils-left-pad-string":48,"utils-repeat-string":49,"utils-right-pad-string":50}],22:[function(require,module,exports){
+'use strict';
+
+// VARIABLES //
+
+var MAX_ITER = 149; // 127+22 (subnormals)
+var MAX_BITS = 24; // only 23 bits for fraction
+
+
+// MULT2 //
+
+/**
+* FUNCTION: mult2( x )
+* Converts a fraction to a literal bit representation using the multiply-by-2 algorithm.
+*
+* @param {Number} x - number less than 1
+* @returns {String} bit representation
+*/
+function mult2( x ) {
+ var str;
+ var y;
+ var i;
+ var j;
+
+ str = '';
+ if ( x === 0 ) {
+ return str;
+ }
+ j = MAX_ITER;
+
+ // Each time we multiply by 2 and find a ones digit, add a '1'; otherwise, add a '0'..
+ for ( i = 0; i < MAX_ITER; i++ ) {
+ y = x * 2;
+ if ( y >= 1 ) {
+ x = y - 1;
+ str += '1';
+ if ( j === MAX_ITER ) {
+ j = i; // first '1'
+ }
+ } else {
+ x = y;
+ str += '0';
+ }
+ // Stop when we have no more decimals to process or in the event we found a fraction which cannot be represented in a finite number of bits...
+ if ( y === 1 || i-j > MAX_BITS ) {
+ break;
+ }
+ }
+ return str;
+} // end FUNCTION mult2()
+
+
+// EXPORTS //
+
+module.exports = mult2;
+
+},{}],23:[function(require,module,exports){
+'use strict';
+
+// EXPORTS //
+
+module.exports = Math.floor;
+
+},{}],24:[function(require,module,exports){
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+
+/**
+ * nifti
+ * @type {*|{}}
+ */
+var nifti = nifti || {};
+nifti.NIFTI1 = nifti.NIFTI1 || ((typeof require !== 'undefined') ? require('./nifti1.js') : null);
+nifti.NIFTI2 = nifti.NIFTI2 || ((typeof require !== 'undefined') ? require('./nifti2.js') : null);
+nifti.Utils = nifti.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null);
+
+var pako = pako || ((typeof require !== 'undefined') ? require('pako') : null);
+
+
+
+/*** Static Methods ***/
+
+/**
+ * Returns true if this data represents a NIFTI-1 header.
+ * @param {ArrayBuffer} data
+ * @returns {boolean}
+ */
+nifti.isNIFTI1 = function (data) {
+ var buf, mag1, mag2, mag3;
+
+ buf = new DataView(data);
+ mag1 = buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION);
+ mag2 = buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION + 1);
+ mag3 = buf.getUint8(nifti.NIFTI1.MAGIC_NUMBER_LOCATION + 2);
+
+ return !!((mag1 === nifti.NIFTI1.MAGIC_NUMBER[0]) && (mag2 === nifti.NIFTI1.MAGIC_NUMBER[1]) &&
+ (mag3 === nifti.NIFTI1.MAGIC_NUMBER[2]));
+};
+
+
+/**
+ * Returns true if this data represents a NIFTI-2 header.
+ * @param {ArrayBuffer} data
+ * @returns {boolean}
+ */
+nifti.isNIFTI2 = function (data) {
+ var buf, mag1, mag2, mag3;
+
+ buf = new DataView(data);
+ mag1 = buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION);
+ mag2 = buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION + 1);
+ mag3 = buf.getUint8(nifti.NIFTI2.MAGIC_NUMBER_LOCATION + 2);
+
+ return !!((mag1 === nifti.NIFTI2.MAGIC_NUMBER[0]) && (mag2 === nifti.NIFTI2.MAGIC_NUMBER[1]) &&
+ (mag3 === nifti.NIFTI2.MAGIC_NUMBER[2]));
+};
+
+
+
+/**
+ * Returns true if this data represents a NIFTI header.
+ * @param {ArrayBuffer} data
+ * @returns {boolean}
+ */
+nifti.isNIFTI = function (data) {
+ return (nifti.isNIFTI1(data) || nifti.isNIFTI2(data));
+};
+
+
+
+/**
+ * Returns true if this data is GZIP compressed.
+ * @param {ArrayBuffer} data
+ * @returns {boolean}
+ */
+nifti.isCompressed = function (data) {
+ var buf, magicCookie1, magicCookie2;
+
+ if (data) {
+ buf = new DataView(data);
+
+ magicCookie1 = buf.getUint8(0);
+ magicCookie2 = buf.getUint8(1);
+
+ if (magicCookie1 === nifti.Utils.GUNZIP_MAGIC_COOKIE1) {
+ return true;
+ }
+
+ if (magicCookie2 === nifti.Utils.GUNZIP_MAGIC_COOKIE2) {
+ return true;
+ }
+ }
+
+ return false;
+};
+
+
+
+/**
+ * Returns decompressed data.
+ * @param {ArrayBuffer} data
+ * @returns {ArrayBuffer}
+ */
+nifti.decompress = function (data) {
+ return pako.inflate(data).buffer;
+};
+
+
+
+/**
+ * Reads and returns the header object.
+ * @param {ArrayBuffer} data
+ * @returns {nifti.NIFTI1|nifti.NIFTI2|null}
+ */
+nifti.readHeader = function (data) {
+ var header = null;
+
+ if (nifti.isCompressed(data)) {
+ data = nifti.decompress(data);
+ }
+
+ if (nifti.isNIFTI1(data)) {
+ header = new nifti.NIFTI1();
+ } else if (nifti.isNIFTI2(data)) {
+ header = new nifti.NIFTI2();
+ }
+
+ if (header) {
+ header.readHeader(data);
+ } else {
+ console.error("That file does not appear to be NIFTI!");
+ }
+
+ return header;
+};
+
+
+
+/**
+ * Returns true if this header contains an extension.
+ * @param {nifti.NIFTI1|nifti.NIFTI2} header
+ * @returns {boolean}
+ */
+nifti.hasExtension = function (header) {
+ return (header.extensionFlag[0] != 0);
+};
+
+
+
+/**
+ * Returns the image data.
+ * @param {nifti.NIFTI1|nifti.NIFTI2} header
+ * @param {ArrayBuffer} data
+ * @returns {ArrayBuffer}
+ */
+nifti.readImage = function (header, data) {
+ var imageOffset = header.vox_offset,
+ timeDim = 1,
+ statDim = 1;
+
+ if (header.dims[4]) {
+ timeDim = header.dims[4];
+ }
+
+ if (header.dims[5]) {
+ statDim = header.dims[5];
+ }
+
+ var imageSize = header.dims[1] * header.dims[2] * header.dims[3] * timeDim * statDim * (header.numBitsPerVoxel / 8);
+ return data.slice(imageOffset, imageOffset + imageSize);
+};
+
+
+
+/**
+ * Returns the extension data (including extension header).
+ * @param {nifti.NIFTI1|nifti.NIFTI2} header
+ * @param {ArrayBuffer} data
+ * @returns {ArrayBuffer}
+ */
+nifti.readExtension = function (header, data) {
+ var loc = header.getExtensionLocation(),
+ size = header.extensionSize;
+
+ return data.slice(loc, loc + size);
+};
+
+
+
+/**
+ * Returns the extension data.
+ * @param {nifti.NIFTI1|nifti.NIFTI2} header
+ * @param {ArrayBuffer} data
+ * @returns {ArrayBuffer}
+ */
+nifti.readExtensionData = function (header, data) {
+ var loc = header.getExtensionLocation(),
+ size = header.extensionSize;
+
+ return data.slice(loc + 8, loc + size - 8);
+};
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = nifti;
+}
+
+},{"./nifti1.js":25,"./nifti2.js":26,"./utilities.js":27,"pako":29}],25:[function(require,module,exports){
+
+/*jslint browser: true, node: true */
+/*global */
+
+"use strict";
+
+/*** Imports ***/
+
+var nifti = nifti || {};
+nifti.Utils = nifti.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null);
+
+
+
+/*** Constructor ***/
+
+/**
+ * The NIFTI1 constructor.
+ * @constructor
+ * @property {boolean} littleEndian
+ * @property {number} dim_info
+ * @property {number[]} dims - image dimensions
+ * @property {number} intent_p1
+ * @property {number} intent_p2
+ * @property {number} intent_p3
+ * @property {number} intent_code
+ * @property {number} datatypeCode
+ * @property {number} numBitsPerVoxel
+ * @property {number} slice_start
+ * @property {number} slice_end
+ * @property {number} slice_code
+ * @property {number[]} pixDims - voxel dimensions
+ * @property {number} vox_offset
+ * @property {number} scl_slope
+ * @property {number} scl_inter
+ * @property {number} xyzt_units
+ * @property {number} cal_max
+ * @property {number} cal_min
+ * @property {number} slice_duration
+ * @property {number} toffset
+ * @property {string} description
+ * @property {string} aux_file
+ * @property {string} intent_name
+ * @property {number} qform_code
+ * @property {number} sform_code
+ * @property {number} quatern_b
+ * @property {number} quatern_c
+ * @property {number} quatern_d
+ * @property {number} quatern_x
+ * @property {number} quatern_y
+ * @property {number} quatern_z
+ * @property {Array.>} affine
+ * @property {string} magic
+ * @property {boolean} isHDR - if hdr/img format
+ * @property {number[]} extensionFlag
+ * @property {number} extensionSize
+ * @property {number} extensionCode
+ * @type {Function}
+ */
+nifti.NIFTI1 = nifti.NIFTI1 || function () {
+ this.littleEndian = false;
+ this.dim_info = 0;
+ this.dims = [];
+ this.intent_p1 = 0;
+ this.intent_p2 = 0;
+ this.intent_p3 = 0;
+ this.intent_code = 0;
+ this.datatypeCode = 0;
+ this.numBitsPerVoxel = 0;
+ this.slice_start = 0;
+ this.slice_end = 0;
+ this.slice_code = 0;
+ this.pixDims = [];
+ this.vox_offset = 0;
+ this.scl_slope = 1;
+ this.scl_inter = 0;
+ this.xyzt_units = 0;
+ this.cal_max = 0;
+ this.cal_min = 0;
+ this.slice_duration = 0;
+ this.toffset = 0;
+ this.description = "";
+ this.aux_file = "";
+ this.intent_name = "";
+ this.qform_code = 0;
+ this.sform_code = 0;
+ this.quatern_b = 0;
+ this.quatern_c = 0;
+ this.quatern_d = 0;
+ this.qoffset_x = 0;
+ this.qoffset_y = 0;
+ this.qoffset_z = 0;
+ this.affine = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
+ this.magic = 0;
+ this.isHDR = false;
+ this.extensionFlag = [0, 0, 0, 0];
+ this.extensionSize = 0;
+ this.extensionCode = 0;
+};
+
+
+
+/*** Static Pseudo-constants ***/
+
+// datatype codes
+nifti.NIFTI1.TYPE_NONE = 0;
+nifti.NIFTI1.TYPE_BINARY = 1;
+nifti.NIFTI1.TYPE_UINT8 = 2;
+nifti.NIFTI1.TYPE_INT16 = 4;
+nifti.NIFTI1.TYPE_INT32 = 8;
+nifti.NIFTI1.TYPE_FLOAT32 = 16;
+nifti.NIFTI1.TYPE_COMPLEX64 = 32;
+nifti.NIFTI1.TYPE_FLOAT64 = 64;
+nifti.NIFTI1.TYPE_RGB24 = 128;
+nifti.NIFTI1.TYPE_INT8 = 256;
+nifti.NIFTI1.TYPE_UINT16 = 512;
+nifti.NIFTI1.TYPE_UINT32 = 768;
+nifti.NIFTI1.TYPE_INT64 = 1024;
+nifti.NIFTI1.TYPE_UINT64 = 1280;
+nifti.NIFTI1.TYPE_FLOAT128 = 1536;
+nifti.NIFTI1.TYPE_COMPLEX128 = 1792;
+nifti.NIFTI1.TYPE_COMPLEX256 = 2048;
+
+// transform codes
+nifti.NIFTI1.XFORM_UNKNOWN = 0;
+nifti.NIFTI1.XFORM_SCANNER_ANAT = 1;
+nifti.NIFTI1.XFORM_ALIGNED_ANAT = 2;
+nifti.NIFTI1.XFORM_TALAIRACH = 3;
+nifti.NIFTI1.XFORM_MNI_152 = 4;
+
+// unit codes
+nifti.NIFTI1.SPATIAL_UNITS_MASK = 0x07;
+nifti.NIFTI1.TEMPORAL_UNITS_MASK = 0x38;
+nifti.NIFTI1.UNITS_UNKNOWN = 0;
+nifti.NIFTI1.UNITS_METER = 1;
+nifti.NIFTI1.UNITS_MM = 2;
+nifti.NIFTI1.UNITS_MICRON = 3;
+nifti.NIFTI1.UNITS_SEC = 8;
+nifti.NIFTI1.UNITS_MSEC = 16;
+nifti.NIFTI1.UNITS_USEC = 24;
+nifti.NIFTI1.UNITS_HZ = 32;
+nifti.NIFTI1.UNITS_PPM = 40;
+nifti.NIFTI1.UNITS_RADS = 48;
+
+// nifti1 codes
+nifti.NIFTI1.MAGIC_COOKIE = 348;
+nifti.NIFTI1.MAGIC_NUMBER_LOCATION = 344;
+nifti.NIFTI1.MAGIC_NUMBER = [0x6E, 0x2B, 0x31]; // n+1 (.nii)
+nifti.NIFTI1.MAGIC_NUMBER2 = [0x6E, 0x69, 0x31]; // ni1 (.hdr/.img)
+nifti.NIFTI1.EXTENSION_HEADER_SIZE = 8;
+
+
+/*** Prototype Methods ***/
+
+/**
+ * Reads the header data.
+ * @param {ArrayBuffer} data
+ */
+nifti.NIFTI1.prototype.readHeader = function (data) {
+ var rawData = new DataView(data),
+ magicCookieVal = nifti.Utils.getIntAt(rawData, 0, this.littleEndian),
+ ctr,
+ ctrOut,
+ ctrIn,
+ index;
+
+ if (magicCookieVal !== nifti.NIFTI1.MAGIC_COOKIE) { // try as little endian
+ this.littleEndian = true;
+ magicCookieVal = nifti.Utils.getIntAt(rawData, 0, this.littleEndian);
+ }
+
+ if (magicCookieVal !== nifti.NIFTI1.MAGIC_COOKIE) {
+ throw new Error("This does not appear to be a NIFTI file!");
+ }
+
+ this.dim_info = nifti.Utils.getByteAt(rawData, 39);
+
+ for (ctr = 0; ctr < 8; ctr += 1) {
+ index = 40 + (ctr * 2);
+ this.dims[ctr] = nifti.Utils.getShortAt(rawData, index, this.littleEndian);
+ }
+
+ this.intent_p1 = nifti.Utils.getFloatAt(rawData, 56, this.littleEndian);
+ this.intent_p2 = nifti.Utils.getFloatAt(rawData, 60, this.littleEndian);
+ this.intent_p3 = nifti.Utils.getFloatAt(rawData, 64, this.littleEndian);
+ this.intent_code = nifti.Utils.getShortAt(rawData, 68, this.littleEndian);
+
+ this.datatypeCode = nifti.Utils.getShortAt(rawData, 70, this.littleEndian);
+ this.numBitsPerVoxel = nifti.Utils.getShortAt(rawData, 72, this.littleEndian);
+
+ this.slice_start = nifti.Utils.getShortAt(rawData, 74, this.littleEndian);
+
+ for (ctr = 0; ctr < 8; ctr += 1) {
+ index = 76 + (ctr * 4);
+ this.pixDims[ctr] = nifti.Utils.getFloatAt(rawData, index, this.littleEndian);
+ }
+
+ this.vox_offset = nifti.Utils.getFloatAt(rawData, 108, this.littleEndian);
+
+ this.scl_slope = nifti.Utils.getFloatAt(rawData, 112, this.littleEndian);
+ this.scl_inter = nifti.Utils.getFloatAt(rawData, 116, this.littleEndian);
+
+ this.slice_end = nifti.Utils.getShortAt(rawData, 120, this.littleEndian);
+ this.slice_code = nifti.Utils.getByteAt(rawData, 122);
+
+ this.xyzt_units = nifti.Utils.getByteAt(rawData, 123);
+
+ this.cal_max = nifti.Utils.getFloatAt(rawData, 124, this.littleEndian);
+ this.cal_min = nifti.Utils.getFloatAt(rawData, 128, this.littleEndian);
+
+ this.slice_duration = nifti.Utils.getFloatAt(rawData, 132, this.littleEndian);
+ this.toffset = nifti.Utils.getFloatAt(rawData, 136, this.littleEndian);
+
+ this.description = nifti.Utils.getStringAt(rawData, 148, 228);
+ this.aux_file = nifti.Utils.getStringAt(rawData, 228, 252);
+
+ this.qform_code = nifti.Utils.getShortAt(rawData, 252, this.littleEndian);
+ this.sform_code = nifti.Utils.getShortAt(rawData, 254, this.littleEndian);
+
+ this.quatern_b = nifti.Utils.getFloatAt(rawData, 256, this.littleEndian);
+ this.quatern_c = nifti.Utils.getFloatAt(rawData, 260, this.littleEndian);
+ this.quatern_d = nifti.Utils.getFloatAt(rawData, 264, this.littleEndian);
+ this.qoffset_x = nifti.Utils.getFloatAt(rawData, 268, this.littleEndian);
+ this.qoffset_y = nifti.Utils.getFloatAt(rawData, 272, this.littleEndian);
+ this.qoffset_z = nifti.Utils.getFloatAt(rawData, 276, this.littleEndian);
+
+ for (ctrOut = 0; ctrOut < 3; ctrOut += 1) {
+ for (ctrIn = 0; ctrIn < 4; ctrIn += 1) {
+ index = 280 + (((ctrOut * 4) + ctrIn) * 4);
+ this.affine[ctrOut][ctrIn] = nifti.Utils.getFloatAt(rawData, index, this.littleEndian);
+ }
+ }
+
+ this.affine[3][0] = 0;
+ this.affine[3][1] = 0;
+ this.affine[3][2] = 0;
+ this.affine[3][3] = 1;
+
+ this.intent_name = nifti.Utils.getStringAt(rawData, 328, 344);
+ this.magic = nifti.Utils.getStringAt(rawData, 344, 348);
+
+ this.isHDR = (this.magic === nifti.NIFTI1.MAGIC_NUMBER2);
+
+ if (rawData.byteLength > nifti.NIFTI1.MAGIC_COOKIE) {
+ this.extensionFlag[0] = nifti.Utils.getByteAt(rawData, 348);
+ this.extensionFlag[1] = nifti.Utils.getByteAt(rawData, 348 + 1);
+ this.extensionFlag[2] = nifti.Utils.getByteAt(rawData, 348 + 2);
+ this.extensionFlag[3] = nifti.Utils.getByteAt(rawData, 348 + 3);
+
+ if (this.extensionFlag[0]) {
+ this.extensionSize = this.getExtensionSize(rawData);
+ this.extensionCode = this.getExtensionCode(rawData);
+ }
+ }
+};
+
+
+/**
+ * Returns a formatted string of header fields.
+ * @returns {string}
+ */
+nifti.NIFTI1.prototype.toFormattedString = function () {
+ var fmt = nifti.Utils.formatNumber,
+ string = "";
+
+ string += ("Dim Info = " + this.dim_info + "\n");
+
+ string += ("Image Dimensions (1-8): " +
+ this.dims[0] + ", " +
+ this.dims[1] + ", " +
+ this.dims[2] + ", " +
+ this.dims[3] + ", " +
+ this.dims[4] + ", " +
+ this.dims[5] + ", " +
+ this.dims[6] + ", " +
+ this.dims[7] + "\n");
+
+ string += ("Intent Parameters (1-3): " +
+ this.intent_p1 + ", " +
+ this.intent_p2 + ", " +
+ this.intent_p3) + "\n";
+
+ string += ("Intent Code = " + this.intent_code + "\n");
+ string += ("Datatype = " + this.datatypeCode + " (" + this.getDatatypeCodeString(this.datatypeCode) + ")\n");
+ string += ("Bits Per Voxel = " + this.numBitsPerVoxel + "\n");
+ string += ("Slice Start = " + this.slice_start + "\n");
+ string += ("Voxel Dimensions (1-8): " +
+ fmt(this.pixDims[0]) + ", " +
+ fmt(this.pixDims[1]) + ", " +
+ fmt(this.pixDims[2]) + ", " +
+ fmt(this.pixDims[3]) + ", " +
+ fmt(this.pixDims[4]) + ", " +
+ fmt(this.pixDims[5]) + ", " +
+ fmt(this.pixDims[6]) + ", " +
+ fmt(this.pixDims[7]) + "\n");
+
+ string += ("Image Offset = " + this.vox_offset + "\n");
+ string += ("Data Scale: Slope = " + fmt(this.scl_slope) + " Intercept = " + fmt(this.scl_inter) + "\n");
+ string += ("Slice End = " + this.slice_end + "\n");
+ string += ("Slice Code = " + this.slice_code + "\n");
+ string += ("Units Code = " + this.xyzt_units + " (" + this.getUnitsCodeString(nifti.NIFTI1.SPATIAL_UNITS_MASK & this.xyzt_units) + ", " + this.getUnitsCodeString(nifti.NIFTI1.TEMPORAL_UNITS_MASK & this.xyzt_units) + ")\n");
+ string += ("Display Range: Max = " + fmt(this.cal_max) + " Min = " + fmt(this.cal_min) + "\n");
+ string += ("Slice Duration = " + this.slice_duration + "\n");
+ string += ("Time Axis Shift = " + this.toffset + "\n");
+ string += ("Description: \"" + this.description + "\"\n");
+ string += ("Auxiliary File: \"" + this.aux_file + "\"\n");
+ string += ("Q-Form Code = " + this.qform_code + " (" + this.getTransformCodeString(this.qform_code) + ")\n");
+ string += ("S-Form Code = " + this.sform_code + " (" + this.getTransformCodeString(this.sform_code) + ")\n");
+ string += ("Quaternion Parameters: " +
+ "b = " + fmt(this.quatern_b) + " " +
+ "c = " + fmt(this.quatern_c) + " " +
+ "d = " + fmt(this.quatern_d) + "\n");
+
+ string += ("Quaternion Offsets: " +
+ "x = " + this.qoffset_x + " " +
+ "y = " + this.qoffset_y + " " +
+ "z = " + this.qoffset_z + "\n");
+
+ string += ("S-Form Parameters X: " +
+ fmt(this.affine[0][0]) + ", " +
+ fmt(this.affine[0][1]) + ", " +
+ fmt(this.affine[0][2]) + ", " +
+ fmt(this.affine[0][3]) + "\n");
+
+ string += ("S-Form Parameters Y: " +
+ fmt(this.affine[1][0]) + ", " +
+ fmt(this.affine[1][1]) + ", " +
+ fmt(this.affine[1][2]) + ", " +
+ fmt(this.affine[1][3]) + "\n");
+
+ string += ("S-Form Parameters Z: " +
+ fmt(this.affine[2][0]) + ", " +
+ fmt(this.affine[2][1]) + ", " +
+ fmt(this.affine[2][2]) + ", " +
+ fmt(this.affine[2][3]) + "\n");
+
+ string += ("Intent Name: \"" + this.intent_name + "\"\n");
+
+ if (this.extensionFlag[0]) {
+ string += ("Extension: Size = " + this.extensionSize + " Code = " + this.extensionCode + "\n");
+
+ }
+
+ return string;
+};
+
+
+/**
+ * Returns a human-readable string of datatype.
+ * @param {number} code
+ * @returns {string}
+ */
+nifti.NIFTI1.prototype.getDatatypeCodeString = function (code) {
+ if (code === nifti.NIFTI1.TYPE_UINT8) {
+ return "1-Byte Unsigned Integer";
+ } else if (code === nifti.NIFTI1.TYPE_INT16) {
+ return "2-Byte Signed Integer";
+ } else if (code === nifti.NIFTI1.TYPE_INT32) {
+ return "4-Byte Signed Integer";
+ } else if (code === nifti.NIFTI1.TYPE_FLOAT32) {
+ return "4-Byte Float";
+ } else if (code === nifti.NIFTI1.TYPE_FLOAT64) {
+ return "8-Byte Float";
+ } else if (code === nifti.NIFTI1.TYPE_RGB24) {
+ return "RGB";
+ } else if (code === nifti.NIFTI1.TYPE_INT8) {
+ return "1-Byte Signed Integer";
+ } else if (code === nifti.NIFTI1.TYPE_UINT16) {
+ return "2-Byte Unsigned Integer";
+ } else if (code === nifti.NIFTI1.TYPE_UINT32) {
+ return "4-Byte Unsigned Integer";
+ } else if (code === nifti.NIFTI1.TYPE_INT64) {
+ return "8-Byte Signed Integer";
+ } else if (code === nifti.NIFTI1.TYPE_UINT64) {
+ return "8-Byte Unsigned Integer";
+ } else {
+ return "Unknown";
+ }
+};
+
+
+/**
+ * Returns a human-readable string of transform type.
+ * @param {number} code
+ * @returns {string}
+ */
+nifti.NIFTI1.prototype.getTransformCodeString = function (code) {
+ if (code === nifti.NIFTI1.XFORM_SCANNER_ANAT) {
+ return "Scanner";
+ } else if (code === nifti.NIFTI1.XFORM_ALIGNED_ANAT) {
+ return "Aligned";
+ } else if (code === nifti.NIFTI1.XFORM_TALAIRACH) {
+ return "Talairach";
+ } else if (code === nifti.NIFTI1.XFORM_MNI_152) {
+ return "MNI";
+ } else {
+ return "Unknown";
+ }
+};
+
+
+/**
+ * Returns a human-readable string of spatial and temporal units.
+ * @param {number} code
+ * @returns {string}
+ */
+nifti.NIFTI1.prototype.getUnitsCodeString = function (code) {
+ if (code === nifti.NIFTI1.UNITS_METER) {
+ return "Meters";
+ } else if (code === nifti.NIFTI1.UNITS_MM) {
+ return "Millimeters";
+ } else if (code === nifti.NIFTI1.UNITS_MICRON) {
+ return "Microns";
+ } else if (code === nifti.NIFTI1.UNITS_SEC) {
+ return "Seconds";
+ } else if (code === nifti.NIFTI1.UNITS_MSEC) {
+ return "Milliseconds";
+ } else if (code === nifti.NIFTI1.UNITS_USEC) {
+ return "Microseconds";
+ } else if (code === nifti.NIFTI1.UNITS_HZ) {
+ return "Hz";
+ } else if (code === nifti.NIFTI1.UNITS_PPM) {
+ return "PPM";
+ } else if (code === nifti.NIFTI1.UNITS_RADS) {
+ return "Rads";
+ } else {
+ return "Unknown";
+ }
+};
+
+
+/**
+ * Returns the qform matrix.
+ * @returns {Array.>}
+ */
+nifti.NIFTI1.prototype.getQformMat = function () {
+ return this.convertNiftiQFormToNiftiSForm(this.quatern_b, this.quatern_c, this.quatern_d, this.qoffset_x,
+ this.qoffset_y, this.qoffset_z, this.pixDims[1], this.pixDims[2], this.pixDims[3], this.pixDims[0]);
+};
+
+
+
+/**
+ * Converts qform to an affine. (See http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c)
+ * @param {number} qb
+ * @param {number} qc
+ * @param {number} qd
+ * @param {number} qx
+ * @param {number} qy
+ * @param {number} qz
+ * @param {number} dx
+ * @param {number} dy
+ * @param {number} dz
+ * @param {number} qfac
+ * @returns {Array.>}
+ */
+nifti.NIFTI1.prototype.convertNiftiQFormToNiftiSForm = function (qb, qc, qd, qx, qy, qz, dx, dy, dz,
+ qfac) {
+ var R = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
+ a,
+ b = qb,
+ c = qc,
+ d = qd,
+ xd,
+ yd,
+ zd;
+
+ // last row is always [ 0 0 0 1 ]
+ R[3][0] = R[3][1] = R[3][2] = 0.0;
+ R[3][3] = 1.0;
+
+ // compute a parameter from b,c,d
+ a = 1.0 - (b * b + c * c + d * d);
+ if (a < 0.0000001) { /* special case */
+
+ a = 1.0 / Math.sqrt(b * b + c * c + d * d);
+ b *= a;
+ c *= a;
+ d *= a; /* normalize (b,c,d) vector */
+ a = 0.0; /* a = 0 ==> 180 degree rotation */
+ } else {
+
+ a = Math.sqrt(a); /* angle = 2*arccos(a) */
+ }
+
+ // load rotation matrix, including scaling factors for voxel sizes
+ xd = (dx > 0.0) ? dx : 1.0; /* make sure are positive */
+ yd = (dy > 0.0) ? dy : 1.0;
+ zd = (dz > 0.0) ? dz : 1.0;
+
+ if (qfac < 0.0) {
+ zd = -zd; /* left handedness? */
+ }
+
+ R[0][0] = (a * a + b * b - c * c - d * d) * xd;
+ R[0][1] = 2.0 * (b * c - a * d) * yd;
+ R[0][2] = 2.0 * (b * d + a * c) * zd;
+ R[1][0] = 2.0 * (b * c + a * d) * xd;
+ R[1][1] = (a * a + c * c - b * b - d * d) * yd;
+ R[1][2] = 2.0 * (c * d - a * b) * zd;
+ R[2][0] = 2.0 * (b * d - a * c) * xd;
+ R[2][1] = 2.0 * (c * d + a * b) * yd;
+ R[2][2] = (a * a + d * d - c * c - b * b) * zd;
+
+ // load offsets
+ R[0][3] = qx;
+ R[1][3] = qy;
+ R[2][3] = qz;
+
+ return R;
+};
+
+
+
+/**
+ * Converts sform to an orientation string (e.g., XYZ+--). (See http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c)
+ * @param {Array.>} R
+ * @returns {string}
+ */
+nifti.NIFTI1.prototype.convertNiftiSFormToNEMA = function (R) {
+ var xi, xj, xk, yi, yj, yk, zi, zj, zk, val, detQ, detP, i, j, k, p, q, r, ibest, jbest, kbest, pbest, qbest, rbest,
+ M, vbest, Q, P, iChar, jChar, kChar, iSense, jSense, kSense;
+ k = 0;
+
+ Q = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
+ P = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
+
+ //if( icod == NULL || jcod == NULL || kcod == NULL ) return ; /* bad */
+
+ //*icod = *jcod = *kcod = 0 ; /* this.errorMessage returns, if sh*t happens */
+
+ /* load column vectors for each (i,j,k) direction from matrix */
+
+ /*-- i axis --*/ /*-- j axis --*/ /*-- k axis --*/
+
+ xi = R[0][0];
+ xj = R[0][1];
+ xk = R[0][2];
+
+ yi = R[1][0];
+ yj = R[1][1];
+ yk = R[1][2];
+
+ zi = R[2][0];
+ zj = R[2][1];
+ zk = R[2][2];
+
+ /* normalize column vectors to get unit vectors along each ijk-axis */
+
+ /* normalize i axis */
+ val = Math.sqrt(xi * xi + yi * yi + zi * zi);
+ if (val === 0.0) { /* stupid input */
+ return null;
+ }
+
+ xi /= val;
+ yi /= val;
+ zi /= val;
+
+ /* normalize j axis */
+ val = Math.sqrt(xj * xj + yj * yj + zj * zj);
+ if (val === 0.0) { /* stupid input */
+ return null;
+ }
+
+ xj /= val;
+ yj /= val;
+ zj /= val;
+
+ /* orthogonalize j axis to i axis, if needed */
+ val = xi * xj + yi * yj + zi * zj; /* dot product between i and j */
+ if (Math.abs(val) > 1.E-4) {
+ xj -= val * xi;
+ yj -= val * yi;
+ zj -= val * zi;
+ val = Math.sqrt(xj * xj + yj * yj + zj * zj); /* must renormalize */
+ if (val === 0.0) { /* j was parallel to i? */
+ return null;
+ }
+ xj /= val;
+ yj /= val;
+ zj /= val;
+ }
+
+ /* normalize k axis; if it is zero, make it the cross product i x j */
+ val = Math.sqrt(xk * xk + yk * yk + zk * zk);
+ if (val === 0.0) {
+ xk = yi * zj - zi * yj;
+ yk = zi * xj - zj * xi;
+ zk = xi * yj - yi * xj;
+ } else {
+ xk /= val;
+ yk /= val;
+ zk /= val;
+ }
+
+ /* orthogonalize k to i */
+ val = xi * xk + yi * yk + zi * zk; /* dot product between i and k */
+ if (Math.abs(val) > 1.E-4) {
+ xk -= val * xi;
+ yk -= val * yi;
+ zk -= val * zi;
+ val = Math.sqrt(xk * xk + yk * yk + zk * zk);
+ if (val === 0.0) { /* bad */
+ return null;
+ }
+ xk /= val;
+ yk /= val;
+ zk /= val;
+ }
+
+ /* orthogonalize k to j */
+ val = xj * xk + yj * yk + zj * zk; /* dot product between j and k */
+ if (Math.abs(val) > 1.e-4) {
+ xk -= val * xj;
+ yk -= val * yj;
+ zk -= val * zj;
+ val = Math.sqrt(xk * xk + yk * yk + zk * zk);
+ if (val === 0.0) { /* bad */
+ return null;
+ }
+ xk /= val;
+ yk /= val;
+ zk /= val;
+ }
+
+ Q[0][0] = xi;
+ Q[0][1] = xj;
+ Q[0][2] = xk;
+ Q[1][0] = yi;
+ Q[1][1] = yj;
+ Q[1][2] = yk;
+ Q[2][0] = zi;
+ Q[2][1] = zj;
+ Q[2][2] = zk;
+
+ /* at this point, Q is the rotation matrix from the (i,j,k) to (x,y,z) axes */
+
+ detQ = this.nifti_mat33_determ(Q);
+ if (detQ === 0.0) { /* shouldn't happen unless user is a DUFIS */
+ return null;
+ }
+
+ /* Build and test all possible +1/-1 coordinate permutation matrices P;
+ then find the P such that the rotation matrix M=PQ is closest to the
+ identity, in the sense of M having the smallest total rotation angle. */
+
+ /* Despite the formidable looking 6 nested loops, there are
+ only 3*3*3*2*2*2 = 216 passes, which will run very quickly. */
+
+ vbest = -666.0;
+ ibest = pbest = qbest = rbest = 1;
+ jbest = 2;
+ kbest = 3;
+
+ for (i = 1; i <= 3; i += 1) { /* i = column number to use for row #1 */
+ for (j = 1; j <= 3; j += 1) { /* j = column number to use for row #2 */
+ if (i !== j) {
+ for (k = 1; k <= 3; k += 1) { /* k = column number to use for row #3 */
+ if (!(i === k || j === k)) {
+ P[0][0] = P[0][1] = P[0][2] = P[1][0] = P[1][1] = P[1][2] = P[2][0] = P[2][1] = P[2][2] = 0.0;
+ for (p = -1; p <= 1; p += 2) { /* p,q,r are -1 or +1 */
+ for (q = -1; q <= 1; q += 2) { /* and go into rows #1,2,3 */
+ for (r = -1; r <= 1; r += 2) {
+ P[0][i - 1] = p;
+ P[1][j - 1] = q;
+ P[2][k - 1] = r;
+ detP = this.nifti_mat33_determ(P); /* sign of permutation */
+ if ((detP * detQ) > 0.0) {
+ M = this.nifti_mat33_mul(P, Q);
+
+ /* angle of M rotation = 2.0*acos(0.5*sqrt(1.0+trace(M))) */
+ /* we want largest trace(M) == smallest angle == M nearest to I */
+
+ val = M[0][0] + M[1][1] + M[2][2]; /* trace */
+ if (val > vbest) {
+ vbest = val;
+ ibest = i;
+ jbest = j;
+ kbest = k;
+ pbest = p;
+ qbest = q;
+ rbest = r;
+ }
+ } /* doesn't match sign of Q */
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /* At this point ibest is 1 or 2 or 3; pbest is -1 or +1; etc.
+
+ The matrix P that corresponds is the best permutation approximation
+ to Q-inverse; that is, P (approximately) takes (x,y,z) coordinates
+ to the (i,j,k) axes.
+
+ For example, the first row of P (which contains pbest in column ibest)
+ determines the way the i axis points relative to the anatomical
+ (x,y,z) axes. If ibest is 2, then the i axis is along the y axis,
+ which is direction P2A (if pbest > 0) or A2P (if pbest < 0).
+
+ So, using ibest and pbest, we can assign the output code for
+ the i axis. Mutatis mutandis for the j and k axes, of course. */
+
+ iChar = jChar = kChar = iSense = jSense = kSense = 0;
+
+ switch (ibest * pbest) {
+ case 1: /*i = NIFTI_L2R*/
+ iChar = 'X';
+ iSense = '+';
+ break;
+ case -1: /*i = NIFTI_R2L*/
+ iChar = 'X';
+ iSense = '-';
+ break;
+ case 2: /*i = NIFTI_P2A*/
+ iChar = 'Y';
+ iSense = '+';
+ break;
+ case -2: /*i = NIFTI_A2P*/
+ iChar = 'Y';
+ iSense = '-';
+ break;
+ case 3: /*i = NIFTI_I2S*/
+ iChar = 'Z';
+ iSense = '+';
+ break;
+ case -3: /*i = NIFTI_S2I*/
+ iChar = 'Z';
+ iSense = '-';
+ break;
+ }
+
+ switch (jbest * qbest) {
+ case 1: /*j = NIFTI_L2R*/
+ jChar = 'X';
+ jSense = '+';
+ break;
+ case -1: /*j = NIFTI_R2L*/
+ jChar = 'X';
+ jSense = '-';
+ break;
+ case 2: /*j = NIFTI_P2A*/
+ jChar = 'Y';
+ jSense = '+';
+ break;
+ case -2: /*j = NIFTI_A2P*/
+ jChar = 'Y';
+ jSense = '-';
+ break;
+ case 3: /*j = NIFTI_I2S*/
+ jChar = 'Z';
+ jSense = '+';
+ break;
+ case -3: /*j = NIFTI_S2I*/
+ jChar = 'Z';
+ jSense = '-';
+ break;
+ }
+
+ switch (kbest * rbest) {
+ case 1: /*k = NIFTI_L2R*/
+ kChar = 'X';
+ kSense = '+';
+ break;
+ case -1: /*k = NIFTI_R2L*/
+ kChar = 'X';
+ kSense = '-';
+ break;
+ case 2: /*k = NIFTI_P2A*/
+ kChar = 'Y';
+ kSense = '+';
+ break;
+ case -2: /*k = NIFTI_A2P*/
+ kChar = 'Y';
+ kSense = '-';
+ break;
+ case 3: /*k = NIFTI_I2S*/
+ kChar = 'Z';
+ kSense = '+';
+ break;
+ case -3: /*k = NIFTI_S2I*/
+ kChar = 'Z';
+ kSense = '-';
+ break;
+ }
+
+ return (iChar + jChar + kChar + iSense + jSense + kSense);
+};
+
+
+
+nifti.NIFTI1.prototype.nifti_mat33_mul = function (A, B) {
+ var C = [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
+ i,
+ j;
+
+ for (i = 0; i < 3; i += 1) {
+ for (j = 0; j < 3; j += 1) {
+ C[i][j] = A[i][0] * B[0][j] + A[i][1] * B[1][j] + A[i][2] * B[2][j];
+ }
+ }
+
+ return C;
+};
+
+
+
+nifti.NIFTI1.prototype.nifti_mat33_determ = function (R) {
+ var r11, r12, r13, r21, r22, r23, r31, r32, r33;
+ /* INPUT MATRIX: */
+ r11 = R[0][0];
+ r12 = R[0][1];
+ r13 = R[0][2];
+ r21 = R[1][0];
+ r22 = R[1][1];
+ r23 = R[1][2];
+ r31 = R[2][0];
+ r32 = R[2][1];
+ r33 = R[2][2];
+
+ return (r11 * r22 * r33 - r11 * r32 * r23 - r21 * r12 * r33 + r21 * r32 * r13 + r31 * r12 * r23 - r31 * r22 * r13);
+};
+
+
+/**
+ * Returns the byte index of the extension.
+ * @returns {number}
+ */
+nifti.NIFTI1.prototype.getExtensionLocation = function() {
+ return nifti.NIFTI1.MAGIC_COOKIE + 4;
+};
+
+
+/**
+ * Returns the extension size.
+ * @param {DataView} data
+ * @returns {number}
+ */
+nifti.NIFTI1.prototype.getExtensionSize = function(data) {
+ return nifti.Utils.getIntAt(data, this.getExtensionLocation(), this.littleEndian);
+};
+
+
+
+/**
+ * Returns the extension code.
+ * @param {DataView} data
+ * @returns {number}
+ */
+nifti.NIFTI1.prototype.getExtensionCode = function(data) {
+ return nifti.Utils.getIntAt(data, this.getExtensionLocation() + 4, this.littleEndian);
+};
+
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = nifti.NIFTI1;
+}
+
+},{"./utilities.js":27}],26:[function(require,module,exports){
+
+/*jslint browser: true, node: true */
+/*global */
+
+"use strict";
+
+/*** Imports ***/
+
+var nifti = nifti || {};
+nifti.Utils = nifti.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null);
+nifti.NIFTI1 = nifti.NIFTI1 || ((typeof require !== 'undefined') ? require('./nifti1.js') : null);
+
+
+/*** Constructor ***/
+
+/**
+ * The NIFTI2 constructor.
+ * @constructor
+ * @property {boolean} littleEndian
+ * @property {number} dim_info
+ * @property {number[]} dims - image dimensions
+ * @property {number} intent_p1
+ * @property {number} intent_p2
+ * @property {number} intent_p3
+ * @property {number} intent_code
+ * @property {number} datatypeCode
+ * @property {number} numBitsPerVoxel
+ * @property {number} slice_start
+ * @property {number} slice_end
+ * @property {number} slice_code
+ * @property {number[]} pixDims - voxel dimensions
+ * @property {number} vox_offset
+ * @property {number} scl_slope
+ * @property {number} scl_inter
+ * @property {number} xyzt_units
+ * @property {number} cal_max
+ * @property {number} cal_min
+ * @property {number} slice_duration
+ * @property {number} toffset
+ * @property {string} description
+ * @property {string} aux_file
+ * @property {string} intent_name
+ * @property {number} qform_code
+ * @property {number} sform_code
+ * @property {number} quatern_b
+ * @property {number} quatern_c
+ * @property {number} quatern_d
+ * @property {number} quatern_x
+ * @property {number} quatern_y
+ * @property {number} quatern_z
+ * @property {Array.>} affine
+ * @property {string} magic
+ * @property {number[]} extensionFlag
+ * @type {Function}
+ */
+nifti.NIFTI2 = nifti.NIFTI2 || function () {
+ this.littleEndian = false;
+ this.dim_info = 0;
+ this.dims = [];
+ this.intent_p1 = 0;
+ this.intent_p2 = 0;
+ this.intent_p3 = 0;
+ this.intent_code = 0;
+ this.datatypeCode = 0;
+ this.numBitsPerVoxel = 0;
+ this.slice_start = 0;
+ this.slice_end = 0;
+ this.slice_code = 0;
+ this.pixDims = [];
+ this.vox_offset = 0;
+ this.scl_slope = 1;
+ this.scl_inter = 0;
+ this.xyzt_units = 0;
+ this.cal_max = 0;
+ this.cal_min = 0;
+ this.slice_duration = 0;
+ this.toffset = 0;
+ this.description = "";
+ this.aux_file = "";
+ this.intent_name = "";
+ this.qform_code = 0;
+ this.sform_code = 0;
+ this.quatern_b = 0;
+ this.quatern_c = 0;
+ this.quatern_d = 0;
+ this.qoffset_x = 0;
+ this.qoffset_y = 0;
+ this.qoffset_z = 0;
+ this.affine = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
+ this.magic = 0;
+ this.extensionFlag = [0, 0, 0, 0];
+};
+
+
+
+/*** Static Pseudo-constants ***/
+
+nifti.NIFTI2.MAGIC_COOKIE = 540;
+nifti.NIFTI2.MAGIC_NUMBER_LOCATION = 4;
+nifti.NIFTI2.MAGIC_NUMBER = [0x6E, 0x2B, 0x32, 0, 0x0D, 0x0A, 0x1A, 0x0A]; // n+2\0
+
+
+
+/*** Prototype Methods ***/
+
+/**
+ * Reads the header data.
+ * @param {ArrayBuffer} data
+ */
+nifti.NIFTI2.prototype.readHeader = function (data) {
+ var rawData = new DataView(data),
+ magicCookieVal = nifti.Utils.getIntAt(rawData, 0, this.littleEndian),
+ ctr,
+ ctrOut,
+ ctrIn,
+ index,
+ array;
+
+ if (magicCookieVal !== nifti.NIFTI2.MAGIC_COOKIE) { // try as little endian
+ this.littleEndian = true;
+ magicCookieVal = nifti.Utils.getIntAt(rawData, 0, this.littleEndian);
+ }
+
+ if (magicCookieVal !== nifti.NIFTI2.MAGIC_COOKIE) {
+ throw new Error("This does not appear to be a NIFTI file!");
+ }
+
+ this.datatypeCode = nifti.Utils.getShortAt(rawData, 12, this.littleEndian);
+ this.numBitsPerVoxel = nifti.Utils.getShortAt(rawData, 14, this.littleEndian);
+
+ for (ctr = 0; ctr < 8; ctr += 1) {
+ index = 16 + (ctr * 8);
+ this.dims[ctr] = nifti.Utils.getLongAt(rawData, index, this.littleEndian);
+ }
+
+ this.intent_p1 = nifti.Utils.getDoubleAt(rawData, 80, this.littleEndian);
+ this.intent_p2 = nifti.Utils.getDoubleAt(rawData, 88, this.littleEndian);
+ this.intent_p3 = nifti.Utils.getDoubleAt(rawData, 96, this.littleEndian);
+
+ for (ctr = 0; ctr < 8; ctr += 1) {
+ index = 104 + (ctr * 8);
+ this.pixDims[ctr] = nifti.Utils.getDoubleAt(rawData, index, this.littleEndian);
+ }
+
+ this.vox_offset = nifti.Utils.getLongAt(rawData, 168, this.littleEndian);
+
+ this.scl_slope = nifti.Utils.getDoubleAt(rawData, 176, this.littleEndian);
+ this.scl_inter = nifti.Utils.getDoubleAt(rawData, 184, this.littleEndian);
+
+ this.cal_max = nifti.Utils.getDoubleAt(rawData, 192, this.littleEndian);
+ this.cal_min = nifti.Utils.getDoubleAt(rawData, 200, this.littleEndian);
+
+ this.slice_duration = nifti.Utils.getDoubleAt(rawData, 208, this.littleEndian);
+
+ this.toffset = nifti.Utils.getDoubleAt(rawData, 216, this.littleEndian);
+
+ this.slice_start = nifti.Utils.getLongAt(rawData, 224, this.littleEndian);
+ this.slice_end = nifti.Utils.getLongAt(rawData, 232, this.littleEndian);
+
+ this.description = nifti.Utils.getStringAt(rawData, 240, 240 + 80);
+ this.aux_file = nifti.Utils.getStringAt(rawData, 320, 320 + 24);
+
+ this.qform_code = nifti.Utils.getIntAt(rawData, 344, this.littleEndian);
+ this.sform_code = nifti.Utils.getIntAt(rawData, 348, this.littleEndian);
+
+ this.quatern_b = nifti.Utils.getDoubleAt(rawData, 352, this.littleEndian);
+ this.quatern_c = nifti.Utils.getDoubleAt(rawData, 360, this.littleEndian);
+ this.quatern_d = nifti.Utils.getDoubleAt(rawData, 368, this.littleEndian);
+ this.qoffset_x = nifti.Utils.getDoubleAt(rawData, 376, this.littleEndian);
+ this.qoffset_y = nifti.Utils.getDoubleAt(rawData, 384, this.littleEndian);
+ this.qoffset_z = nifti.Utils.getDoubleAt(rawData, 392, this.littleEndian);
+
+ for (ctrOut = 0; ctrOut < 3; ctrOut += 1) {
+ for (ctrIn = 0; ctrIn < 4; ctrIn += 1) {
+ index = 400 + (((ctrOut * 4) + ctrIn) * 8);
+ this.affine[ctrOut][ctrIn] = nifti.Utils.getDoubleAt(rawData, index, this.littleEndian);
+ }
+ }
+
+ this.affine[3][0] = 0;
+ this.affine[3][1] = 0;
+ this.affine[3][2] = 0;
+ this.affine[3][3] = 1;
+
+ this.slice_code = nifti.Utils.getIntAt(rawData, 496, this.littleEndian);
+ this.xyzt_units = nifti.Utils.getIntAt(rawData, 500, this.littleEndian);
+ this.intent_code = nifti.Utils.getIntAt(rawData, 504, this.littleEndian);
+ this.intent_name = nifti.Utils.getStringAt(rawData, 508, 508 + 16);
+
+ this.dim_info = nifti.Utils.getByteAt(rawData, 524);
+
+ if (rawData.byteLength > nifti.NIFTI2.MAGIC_COOKIE) {
+ this.extensionFlag[0] = nifti.Utils.getByteAt(rawData, 540);
+ this.extensionFlag[1] = nifti.Utils.getByteAt(rawData, 540 + 1);
+ this.extensionFlag[2] = nifti.Utils.getByteAt(rawData, 540 + 2);
+ this.extensionFlag[3] = nifti.Utils.getByteAt(rawData, 540 + 3);
+
+ if (this.extensionFlag[0]) {
+ this.extensionSize = this.getExtensionSize(rawData);
+ this.extensionCode = this.getExtensionCode(rawData);
+ }
+ }
+};
+
+
+
+/**
+ * Returns a formatted string of header fields.
+ * @returns {string}
+ */
+nifti.NIFTI2.prototype.toFormattedString = function () {
+ var fmt = nifti.Utils.formatNumber,
+ string = "";
+
+ string += ("Datatype = " + + this.datatypeCode + " (" + this.getDatatypeCodeString(this.datatypeCode) + ")\n");
+ string += ("Bits Per Voxel = " + " = " + this.numBitsPerVoxel + "\n");
+ string += ("Image Dimensions" + " (1-8): " +
+ this.dims[0] + ", " +
+ this.dims[1] + ", " +
+ this.dims[2] + ", " +
+ this.dims[3] + ", " +
+ this.dims[4] + ", " +
+ this.dims[5] + ", " +
+ this.dims[6] + ", " +
+ this.dims[7] + "\n");
+
+ string += ("Intent Parameters (1-3): " +
+ this.intent_p1 + ", " +
+ this.intent_p2 + ", " +
+ this.intent_p3) + "\n";
+
+ string += ("Voxel Dimensions (1-8): " +
+ fmt(this.pixDims[0]) + ", " +
+ fmt(this.pixDims[1]) + ", " +
+ fmt(this.pixDims[2]) + ", " +
+ fmt(this.pixDims[3]) + ", " +
+ fmt(this.pixDims[4]) + ", " +
+ fmt(this.pixDims[5]) + ", " +
+ fmt(this.pixDims[6]) + ", " +
+ fmt(this.pixDims[7]) + "\n");
+
+ string += ("Image Offset = " + this.vox_offset + "\n");
+ string += ("Data Scale: Slope = " + fmt(this.scl_slope) + " Intercept = " + fmt(this.scl_inter) + "\n");
+ string += ("Display Range: Max = " + fmt(this.cal_max) + " Min = " + fmt(this.cal_min) + "\n");
+ string += ("Slice Duration = " + this.slice_duration + "\n");
+ string += ("Time Axis Shift = " + this.toffset + "\n");
+ string += ("Slice Start = " + this.slice_start + "\n");
+ string += ("Slice End = " + this.slice_end + "\n");
+ string += ("Description: \"" + this.description + "\"\n");
+ string += ("Auxiliary File: \"" + this.aux_file + "\"\n");
+ string += ("Q-Form Code = " + this.qform_code + " (" + this.getTransformCodeString(this.qform_code) + ")\n");
+ string += ("S-Form Code = " + this.sform_code + " (" + this.getTransformCodeString(this.sform_code) + ")\n");
+ string += ("Quaternion Parameters: " +
+ "b = " + fmt(this.quatern_b) + " " +
+ "c = " + fmt(this.quatern_c) + " " +
+ "d = " + fmt(this.quatern_d) + "\n");
+
+ string += ("Quaternion Offsets: " +
+ "x = " + this.qoffset_x + " " +
+ "y = " + this.qoffset_y + " " +
+ "z = " + this.qoffset_z + "\n");
+
+ string += ("S-Form Parameters X: " +
+ fmt(this.affine[0][0]) + ", " +
+ fmt(this.affine[0][1]) + ", " +
+ fmt(this.affine[0][2]) + ", " +
+ fmt(this.affine[0][3]) + "\n");
+
+ string += ("S-Form Parameters Y: " +
+ fmt(this.affine[1][0]) + ", " +
+ fmt(this.affine[1][1]) + ", " +
+ fmt(this.affine[1][2]) + ", " +
+ fmt(this.affine[1][3]) + "\n");
+
+ string += ("S-Form Parameters Z: " +
+ fmt(this.affine[2][0]) + ", " +
+ fmt(this.affine[2][1]) + ", " +
+ fmt(this.affine[2][2]) + ", " +
+ fmt(this.affine[2][3]) + "\n");
+
+ string += ("Slice Code = " + this.slice_code + "\n");
+ string += ("Units Code = " + this.xyzt_units + " (" + this.getUnitsCodeString(nifti.NIFTI1.SPATIAL_UNITS_MASK & this.xyzt_units) + ", " + this.getUnitsCodeString(nifti.NIFTI1.TEMPORAL_UNITS_MASK & this.xyzt_units) + ")\n");
+ string += ("Intent Code = " + this.intent_code + "\n");
+ string += ("Intent Name: \"" + this.intent_name + "\"\n");
+
+ string += ("Dim Info = " + this.dim_info + "\n");
+
+ return string;
+};
+
+
+
+/**
+ * Returns the byte index of the extension.
+ * @returns {number}
+ */
+nifti.NIFTI2.prototype.getExtensionLocation = function() {
+ return nifti.NIFTI2.MAGIC_COOKIE + 4;
+};
+
+
+
+/**
+ * Returns the extension size.
+ * @param {DataView} data
+ * @returns {number}
+ */
+nifti.NIFTI2.prototype.getExtensionSize = nifti.NIFTI1.prototype.getExtensionSize;
+
+
+
+/**
+ * Returns the extension code.
+ * @param {DataView} data
+ * @returns {number}
+ */
+nifti.NIFTI2.prototype.getExtensionCode = nifti.NIFTI1.prototype.getExtensionCode;
+
+
+
+/**
+ * Returns a human-readable string of datatype.
+ * @param {number} code
+ * @returns {string}
+ */
+nifti.NIFTI2.prototype.getDatatypeCodeString = nifti.NIFTI1.prototype.getDatatypeCodeString;
+
+
+
+/**
+ * Returns a human-readable string of transform type.
+ * @param {number} code
+ * @returns {string}
+ */
+nifti.NIFTI2.prototype.getTransformCodeString = nifti.NIFTI1.prototype.getTransformCodeString;
+
+
+
+/**
+ * Returns a human-readable string of spatial and temporal units.
+ * @param {number} code
+ * @returns {string}
+ */
+nifti.NIFTI2.prototype.getUnitsCodeString = nifti.NIFTI1.prototype.getUnitsCodeString;
+
+
+
+/**
+ * Returns the qform matrix.
+ * @returns {Array.>}
+ */
+nifti.NIFTI2.prototype.getQformMat = nifti.NIFTI1.prototype.getQformMat;
+
+
+
+/**
+ * Converts qform to an affine. (See http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c)
+ * @param {number} qb
+ * @param {number} qc
+ * @param {number} qd
+ * @param {number} qx
+ * @param {number} qy
+ * @param {number} qz
+ * @param {number} dx
+ * @param {number} dy
+ * @param {number} dz
+ * @param {number} qfac
+ * @returns {Array.>}
+ */
+nifti.NIFTI2.prototype.convertNiftiQFormToNiftiSForm = nifti.NIFTI1.prototype.convertNiftiQFormToNiftiSForm;
+
+
+
+/**
+ * Converts sform to an orientation string (e.g., XYZ+--). (See http://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1_io.c)
+ * @param {Array.>} R
+ * @returns {string}
+ */
+nifti.NIFTI2.prototype.convertNiftiSFormToNEMA = nifti.NIFTI1.prototype.convertNiftiSFormToNEMA;
+
+
+
+nifti.NIFTI2.prototype.nifti_mat33_mul = nifti.NIFTI1.prototype.nifti_mat33_mul;
+
+
+
+nifti.NIFTI2.prototype.nifti_mat33_determ = nifti.NIFTI1.prototype.nifti_mat33_determ;
+
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = nifti.NIFTI2;
+}
+
+},{"./nifti1.js":25,"./utilities.js":27}],27:[function(require,module,exports){
+
+/*jslint browser: true, node: true */
+/*global require, module */
+
+"use strict";
+
+/*** Imports ***/
+
+var nifti = nifti || {};
+nifti.Utils = nifti.Utils || {};
+
+
+
+/*** Static Pseudo-constants ***/
+
+nifti.Utils.crcTable = null;
+nifti.Utils.GUNZIP_MAGIC_COOKIE1 = 31;
+nifti.Utils.GUNZIP_MAGIC_COOKIE2 = 139;
+
+
+
+/*** Static methods ***/
+
+nifti.Utils.getStringAt = function (data, start, end) {
+ var str = "", ctr, ch;
+
+ for (ctr = start; ctr < end; ctr += 1) {
+ ch = data.getUint8(ctr);
+
+ if (ch !== 0) {
+ str += String.fromCharCode(ch);
+ }
+ }
+
+ return str;
+};
+
+
+
+nifti.Utils.getByteAt = function (data, start) {
+ return data.getInt8(start);
+};
+
+
+
+nifti.Utils.getShortAt = function (data, start, littleEndian) {
+ return data.getInt16(start, littleEndian);
+};
+
+
+
+nifti.Utils.getIntAt = function (data, start, littleEndian) {
+ return data.getInt32(start, littleEndian);
+};
+
+
+
+nifti.Utils.getFloatAt = function (data, start, littleEndian) {
+ return data.getFloat32(start, littleEndian);
+};
+
+
+
+nifti.Utils.getDoubleAt = function (data, start, littleEndian) {
+ return data.getFloat64(start, littleEndian);
+};
+
+
+
+nifti.Utils.getLongAt = function (data, start, littleEndian) {
+ var ctr, array = [], value = 0;
+
+ for (ctr = 0; ctr < 8; ctr += 1) {
+ array[ctr] = nifti.Utils.getByteAt(data, start + ctr, littleEndian);
+ }
+
+ for (ctr = array.length - 1; ctr >= 0; ctr--) {
+ value = (value * 256) + array[ctr];
+ }
+
+ return value;
+};
+
+
+
+nifti.Utils.toArrayBuffer = function (buffer) {
+ var ab, view, i;
+
+ ab = new ArrayBuffer(buffer.length);
+ view = new Uint8Array(ab);
+ for (i = 0; i < buffer.length; i += 1) {
+ view[i] = buffer[i];
+ }
+ return ab;
+};
+
+
+
+nifti.Utils.isString = function (obj) {
+ return (typeof obj === "string" || obj instanceof String);
+};
+
+
+nifti.Utils.formatNumber = function (num, shortFormat) {
+ var val = 0;
+
+ if (nifti.Utils.isString(num)) {
+ val = Number(num);
+ } else {
+ val = num;
+ }
+
+ if (shortFormat) {
+ val = val.toPrecision(5);
+ } else {
+ val = val.toPrecision(7);
+ }
+
+ return parseFloat(val);
+};
+
+
+
+// http://stackoverflow.com/questions/18638900/javascript-crc32
+nifti.Utils.makeCRCTable = function(){
+ var c;
+ var crcTable = [];
+ for(var n =0; n < 256; n++){
+ c = n;
+ for(var k =0; k < 8; k++){
+ c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
+ }
+ crcTable[n] = c;
+ }
+ return crcTable;
+};
+
+
+
+nifti.Utils.crc32 = function(dataView) {
+ var crcTable = nifti.Utils.crcTable || (nifti.Utils.crcTable = nifti.Utils.makeCRCTable());
+ var crc = 0 ^ (-1);
+
+ for (var i = 0; i < dataView.byteLength; i++ ) {
+ crc = (crc >>> 8) ^ crcTable[(crc ^ dataView.getUint8(i)) & 0xFF];
+ }
+
+ return (crc ^ (-1)) >>> 0;
+};
+
+
+
+/*** Exports ***/
+
+var moduleType = typeof module;
+if ((moduleType !== 'undefined') && module.exports) {
+ module.exports = nifti.Utils;
+}
+
+},{}],28:[function(require,module,exports){
+"use strict";
+var assert = require('assert');
+
+var lineSeparatorRE = /[ \f\t\v]*\r?\n/;
+var NRRDMagicRE = /^NRRD\d{4}$/;
+var lineRE = /^([^:]*)(:[ =])(.*)$/;
+var dataFileListRE = /^LIST(?: (\d+))?$/;
+
+// The minimal object this accepts is formed like this:
+// {data: SomeTypedArray, sizes: [...]}
+// On the other hand, if data is not given it must have a form like this:
+// {buffer: SomeArrayBuffer, type: ..., endian: ..., sizes: [...]}
+// Of course, if 'type' is an 8-bit type, endian is not needed, and if 'type' equals 'block', 'blockSize' should be set instead of 'endian'. In this case, no interpretation of buffer is done (at all, it is written serialized directly to the buffer).
+// TODO: For now this only supports serializing "inline" files, or files for which you have already prepared the data.
+module.exports.serialize = function (nrrdOrg) {
+ var i, buffer, arr, totalLen = 1, nrrd = {}, prop, nativeType, nativeSize, bufferData, arrData, line, lines = [], header;
+
+ // Copy nrrdOrg to nrrd to allow modifications without altering the original
+ for(prop in nrrdOrg) {
+ nrrd[prop] = nrrdOrg[prop];
+ }
+
+ // For saving files we allow inferring certain information if it is not explicitly given.
+ // Also we normalize some fields to make our own lives easier.
+ if (nrrd.sizes===undefined) { // 'sizes' should ALWAYS be given
+ throw new Error("Sizes missing from NRRD file!");
+ } else if (nrrd.dimension===undefined) {
+ nrrd.dimension = nrrd.sizes.length;
+ }
+ if (nrrd.data instanceof Int8Array) {
+ nativeType = "int8";
+ } else if (nrrd.data instanceof Uint8Array) {
+ nativeType = "uint8";
+ } else if (nrrd.data instanceof Int16Array) {
+ nativeType = "int16";
+ } else if (nrrd.data instanceof Uint16Array) {
+ nativeType = "uint16";
+ } else if (nrrd.data instanceof Int32Array) {
+ nativeType = "int32";
+ } else if (nrrd.data instanceof Uint32Array) {
+ nativeType = "uint32";
+ //} else if (nrrd.data instanceof Int64Array) {
+ // nativeType = "int64";
+ //} else if (nrrd.data instanceof Uint64Array) {
+ // nativeType = "uint64";
+ } else if (nrrd.data instanceof Float32Array) {
+ nativeType = "float";
+ } else if (nrrd.data instanceof Float64Array) {
+ nativeType = "double";
+ }
+ if (nrrd.type===undefined && nativeType!==undefined) {
+ nrrd.type = nativeType;
+ } else if (nrrd.type===undefined) {
+ throw new Error("Type of data is not given and cannot be inferred!");
+ } else if ((typeof nrrd.type) == "string" || nrrd.type instanceof String) {
+ nrrd.type = parseNRRDType(nrrd.type);
+ }
+ if (nrrd.encoding===undefined) {
+ nrrd.encoding = "raw";
+ } else if ((typeof nrrd.encoding) == "string" || nrrd.encoding instanceof String) {
+ nrrd.encoding = parseNRRDEncoding(nrrd.encoding);
+ }
+ if (nrrd.data && nrrd.type != 'block' && nrrd.type != 'int8' && nrrd.type != 'uint8' && nrrd.encoding != 'ascii') {
+ nrrd.endian = systemEndianness;
+ } else if (nrrd.type == 'block' || nrrd.type == 'int8' || nrrd.type == 'uint8' || nrrd.encoding == 'ascii') {
+ nrrd.endian = undefined;
+ } else if ((typeof nrrd.endian) == "string" || nrrd.endian instanceof String) {
+ nrrd.endian = parseNRRDEndian(nrrd.endian);
+ }
+
+ // Try to infer spatial dimension
+ var spaceDimension = undefined;
+ if (nrrd.spaceDimension!==undefined) {
+ spaceDimension = nrrd.spaceDimension;
+ } else if (nrrd.space!==undefined) {
+ switch(nrrd.space) {
+ case "right-anterior-superior":
+ case "RAS":
+ spaceDimension = 3;
+ break;
+ case "left-anterior-superior":
+ case "LAS":
+ spaceDimension = 3;
+ break;
+ case "left-posterior-superior":
+ case "LPS":
+ spaceDimension = 3;
+ break;
+ case "right-anterior-superior-time":
+ case "RAST":
+ spaceDimension = 4;
+ break;
+ case "left-anterior-superior-time":
+ case "LAST":
+ spaceDimension = 4;
+ break;
+ case "left-posterior-superior-time":
+ case "LPST":
+ spaceDimension = 4;
+ break;
+ case "scanner-xyz":
+ spaceDimension = 3;
+ break;
+ case "scanner-xyz-time":
+ spaceDimension = 4;
+ break;
+ case "3D-right-handed":
+ spaceDimension = 3;
+ break;
+ case "3D-left-handed":
+ spaceDimension = 3;
+ break;
+ case "3D-right-handed-time":
+ spaceDimension = 4;
+ break;
+ case "3D-left-handed-time":
+ spaceDimension = 4;
+ break;
+ default:
+ console.warn("Unrecognized space: " + nrrd.space);
+ }
+ }
+
+ // Now check that we have a valid nrrd structure.
+ checkNRRD(nrrd);
+
+ // Determine number of elements and check that we have enough data (if possible)
+ for(i=0; i0) integers!");
+ totalLen *= nrrd.sizes[i];
+ }
+ if (nrrd.data) {
+ if (nrrd.data.length < totalLen) {
+ throw new Error("Missing data to serialize!");
+ }
+ } else if (nrrd.buffer) {
+ if (nrrd.encoding == "raw") {
+ if (nrrd.type=="block" && nrrd.blockSize!==undefined) {
+ nativeSize = nrrd.blockSize;
+ } else {
+ nativeSize = getNRRDTypeSize(nrrd.type);
+ }
+ if (nrrd.buffer.byteLength < totalLen*nativeSize) {
+ throw new Error("Missing data to serialize!");
+ }
+ }
+ } else if (nrrd.dataFile) {
+ // Okay, if you have your data ready, we'll just write a header.
+ } else {
+ throw new Error("Will not serialize an empty NRRD file!");
+ }
+
+ // Make sure we have the correct buffer in bufferData.
+ if (nrrd.data) {
+ switch(nrrd.encoding) {
+ case 'raw':
+ if (nrrd.type == nativeType && nrrd.endian == systemEndianness) {
+ bufferData = nrrd.data.buffer.slice(nrrd.data.byteOffset, nrrd.data.byteOffset+nrrd.data.byteLength);
+ } else if (nrrd.endian == systemEndianness) {
+ bufferData = castTypedArray(nrrd.data, nrrd.type);
+ bufferData = bufferData.buffer.slice(bufferData.byteOffset, bufferData.byteOffset+bufferData.byteLength);
+ } else {
+ bufferData = serializeToBuffer(nrrd.data, nrrd.type, nrrd.endian);
+ }
+ break;
+ case 'ascii':
+ if (nrrd.type == nativeType) {
+ bufferData = serializeToTextBuffer(nrrd.data);
+ } else {
+ bufferData = serializeToTextBuffer(castTypedArray(nrrd.data, nrrd.type));
+ }
+ break;
+ default:
+ throw new Error("Unsupported NRRD encoding: " + nrrd.encoding);
+ }
+ } else if (nrrd.buffer) {
+ bufferData = nrrd.buffer;
+ }
+
+ // Start header
+ lines.push("NRRD0005"); // TODO: Adjust version based on features that are actually used and/or the version specified by the user (if any).
+ lines.push("# Generated by nrrd-js");
+
+ // Put in dimension and space dimension (the NRRD spec requires that these are present before any lists whose length depends on them)
+ var firstProps = ['dimension', 'spaceDimension', 'space'];
+ for(i=0; i=0) continue; // Skip the fields we already output.
+ line = serializeField(prop, nrrd[prop], nrrd.dimension, spaceDimension);
+ if (line!==undefined) lines.push(line);
+ }
+
+ // Put in keys (if any)
+ if (nrrd.keys) for(prop in nrrd.keys) {
+ if (prop.indexOf(":=")>=0) throw new Error("The combination ':=' is not allowed in an NRRD key!");
+ lines.push(prop + ":=" + escapeValue(nrrd[prop]));
+ }
+
+ // Put in data file list (if any)
+ if (nrrd.dataFile && nrrd.dataFile.length) {
+ lines.push("data file: LIST");
+ Array.prototype.push.apply(lines, nrrd.dataFile);
+ } else if (nrrd.dataFile && nrrd.dataFile.files && 'subdim' in nrrd.dataFile) {
+ lines.push("data file: LIST " + nrrd.dataFile.subdim);
+ Array.prototype.push.apply(lines, nrrd.dataFile.files);
+ }
+
+ // Put in empty line and inline data (if we have inline data) and convert lines to buffer
+ if (bufferData && !('dataFile' in nrrd)) {
+ lines.push("");
+ lines.push(""); // We actually need an extra blank line to make sure the previous is terminated.
+ header = lines.join("\n");
+ buffer = new ArrayBuffer(header.length + bufferData.byteLength);
+ arr = new Uint8Array(buffer);
+ for(i=0; i0 && l[0] != '#'; }); // Remove comment lines
+ if (!NRRDMagicRE.test(lines[0])) {
+ throw new Error("File is not an NRRD file!");
+ }
+ ret.version = parseInt(lines[0].substring(4, 8), 10);
+ if (ret.version>5) {
+ console.warn("Reading an unsupported version of the NRRD format; things may go haywire.");
+ }
+
+ // Parse lines
+ for(i=1; i=0) return NaN;
+ if (str.indexOf('-inf')>=0) return -Infinity;
+ if (str.indexOf('inf')>=0) return Infinity;
+ var val = parseFloat(str);
+ if (Number.isNaN(val)) throw new Error("Malformed NRRD float: " + str);
+ return val;
+}
+
+function parseNRRDVector(str) {
+ if (str == "none") return null;
+ if (str.length<2 || str[0]!=="(" || str[str.length-1]!==")") throw new Error("Malformed NRRD vector: " + str);
+ return str.slice(1, -1).split(",").map(parseNRRDFloat);
+}
+
+function parseNRRDQuotedString(str) {
+ if (length<2 || str[0]!='"' || str[str.length-1]!='"') {
+ throw new Error("Invalid NRRD quoted string: " + str);
+ }
+ return str.slice(1, -1).replace('\\"', '"');
+}
+
+function serializeNRRDQuotedString(str) {
+ return '"' + str.replace('"', '\\"') + '"';
+}
+
+var whitespaceListSeparator = /[ \t]+/; // Note that this excludes other types of whitespace on purpose!
+function parseNRRDWhitespaceSeparatedList(str, parseElement) {
+ return str.split(whitespaceListSeparator).map(parseElement);
+}
+
+function parseNRRDType(descriptor) {
+ switch(descriptor.toLowerCase()) {
+ case "signed char":
+ case "int8":
+ case "int8_t":
+ return 'int8';
+ case "uchar":
+ case "unsigned char":
+ case "uint8":
+ case "uint8_t":
+ return 'uint8';
+ case "short":
+ case "short int":
+ case "signed short":
+ case "signed short int":
+ case "int16":
+ case "int16_t":
+ return 'int16';
+ case "ushort":
+ case "unsigned short":
+ case "unsigned short int":
+ case "uint16":
+ case "uint16_t":
+ return 'uint16';
+ case "int":
+ case "signed int":
+ case "int32":
+ case "int32_t":
+ return 'int32';
+ case "uint":
+ case "unsigned int":
+ case "uint32":
+ case "uint32_t":
+ return 'uint32';
+ case "longlong":
+ case "long long":
+ case "long long int":
+ case "signed long long":
+ case "signed long long int":
+ case "int64":
+ case "int64_t":
+ return 'int64';
+ case "ulonglong":
+ case "unsigned long long":
+ case "unsigned long long int":
+ case "uint64":
+ case "uint64_t":
+ return 'uint64';
+ case "float":
+ return 'float';
+ case "double":
+ return 'double';
+ case "block":
+ return 'block';
+ default:
+ console.warn("Unrecognized NRRD type: " + descriptor);
+ return descriptor;
+ }
+}
+
+function parseNRRDEncoding(encoding) {
+ switch(encoding.toLowerCase()) {
+ case "raw":
+ return "raw";
+ case "txt":
+ case "text":
+ case "ascii":
+ return "ascii";
+ case "hex":
+ return "hex";
+ case "gz":
+ case "gzip":
+ return "gzip";
+ case "bz2":
+ case "bzip2":
+ return "bzip2";
+ default:
+ console.warn("Unrecognized NRRD encoding: " + encoding);
+ return encoding;
+ }
+}
+
+function parseNRRDSpace(space) {
+ switch(space.toLowerCase()) {
+ case "right-anterior-superior":
+ case "ras":
+ return "right-anterior-superior";
+ case "left-anterior-superior":
+ case "las":
+ return "left-anterior-superior";
+ case "left-posterior-superior":
+ case "lps":
+ return "left-posterior-superior";
+ case "right-anterior-superior-time":
+ case "rast":
+ return "right-anterior-superior-time";
+ case "left-anterior-superior-time":
+ case "last":
+ return "left-anterior-superior-time";
+ case "left-posterior-superior-time":
+ case "lpst":
+ return "left-posterior-superior-time";
+ case "scanner-xyz":
+ return "scanner-xyz";
+ case "scanner-xyz-time":
+ return "scanner-xyz-time";
+ case "3d-right-handed":
+ return "3D-right-handed";
+ case "3d-left-handed":
+ return "3D-left-handed";
+ case "3d-right-handed-time":
+ return "3D-right-handed-time";
+ case "3d-left-handed-time":
+ return "3D-left-handed-time";
+ default:
+ console.warn("Unrecognized space: " + space);
+ return space;
+ }
+}
+
+function parseNRRDEndian(endian) {
+ switch(endian.toLowerCase()) {
+ case 'little':
+ return 'little';
+ case 'big':
+ return 'big';
+ default:
+ console.warn("Unrecognized NRRD endianness: " + endian);
+ return endian;
+ }
+}
+
+// Note that this function will never encounter the LIST data file specification format, as this is handled elsewhere.
+var dataFileFormatRE = / (-?\d+) (-?\d+) (-?\d+)(?: (\d+))?$/;
+function parseNRRDDataFile(dataFile) {
+ var match = dataFileFormatRE.exec(dataFile);
+ if (match) { // We have a format specification
+ if (match.length == 5 && match[4]) { // subdim specification
+ return {
+ format: dataFile.substring(0, match.index),
+ min: parseNRRDInteger(match[1]),
+ max: parseNRRDInteger(match[2]),
+ step: parseNRRDInteger(match[3]),
+ subdim: parseNRRDInteger(match[4])
+ };
+ } else {
+ return {
+ format: dataFile.substring(0, match.index),
+ min: parseNRRDInteger(match[1]),
+ max: parseNRRDInteger(match[2]),
+ step: parseNRRDInteger(match[3])
+ };
+ }
+ } else { // Just a file
+ return dataFile;
+ }
+}
+
+function serializeNRRDDataFile(dataFile) {
+ if ((typeof dataFile) == "string" || dataFile instanceof String) {
+ return dataFile;
+ } else if ('format' in dataFile && 'min' in dataFile && 'max' in dataFile && 'step' in dataFile) {
+ if ('subdim' in dataFile) {
+ return dataFile.format + " " + dataFile.min + " " + dataFile.max + " " + dataFile.step + " " + dataFile.subdim;
+ } else {
+ return dataFile.format + " " + dataFile.min + " " + dataFile.max + " " + dataFile.step;
+ }
+ } else {
+ throw new Error("Unrecognized data file format!");
+ }
+}
+
+function parseNRRDCenter(center) {
+ switch(center.toLowerCase()) {
+ case "cell":
+ return "cell";
+ case "node":
+ return "node";
+ case "???":
+ case "none":
+ return null;
+ default:
+ console.warn("Unrecognized NRRD center: " + center);
+ return center;
+ }
+}
+
+var NRRDKinds = {
+ "domain": "domain",
+ "space": "space",
+ "time": "time",
+ "list": "list",
+ "point": "point",
+ "vector": "vector",
+ "covariant-vector": "covariant-vector",
+ "normal": "normal",
+ "stub": "stub",
+ "scalar": "scalar",
+ "complex": "complex",
+ "2-vector": "2-vector",
+ "3-color": "3-color",
+ "rgb-color": "RGB-color",
+ "hsv-color": "HSV-color",
+ "xyz-color": "XYZ-color",
+ "4-color": "4-color",
+ "rgba-color": "RGBA-color",
+ "3-vector": "3-vector",
+ "3-gradient": "3-gradient",
+ "3-normal": "3-normal",
+ "4-vector": "4-vector",
+ "quaternion": "quaternion",
+ "2d-symmetric-matrix": "2D-symmetric-matrix",
+ "2d-masked-symmetric-matrix": "2D-masked-symmetric-matrix",
+ "2d-matrix": "2D-matrix",
+ "2d-masked-matrix": "2D-masked-matrix",
+ "3d-symmetric-matrix": "3D-symmetric-matrix",
+ "3d-masked-symmetric-matrix": "3D-masked-symmetric-matrix",
+ "3d-matrix": "3D-matrix",
+ "3d-masked-matrix": "3D-masked-matrix",
+ "???": null,
+ "none": null
+};
+function parseNRRDKind(kind) {
+ var kindLC = kind.toLowerCase();
+ if (kindLC in NRRDKinds) return NRRDKinds[kindLC];
+ console.warn("Unrecognized NRRD kind: " + kind);
+ return kind;
+}
+
+function serializeNRRDOptional(a) {
+ return a===null ? "???" : a;
+}
+
+var systemEndianness = (function() {
+ var buf = new ArrayBuffer(4),
+ intArr = new Uint32Array(buf),
+ byteArr = new Uint8Array(buf);
+ intArr[0] = 0x01020304;
+ if (byteArr[0]==1 && byteArr[1]==2 && byteArr[2]==3 && byteArr[3]==4) {
+ return 'big';
+ } else if (byteArr[0]==4 && byteArr[1]==3 && byteArr[2]==2 && byteArr[3]==1) {
+ return 'little';
+ }
+ console.warn("Unrecognized system endianness!");
+ return undefined;
+})();
+
+function parseNRRDRawData(buffer, type, sizes, options) {
+ var i, arr, view, totalLen = 1, endianFlag;
+ for(i=0; i0) integers!");
+ totalLen *= sizes[i];
+ }
+ if (type == 'block') {
+ // Don't do anything special, just return the slice containing all blocks.
+ return buffer.slice(0,totalLen*options.blockSize);
+ } else if (type == 'int8' || type == 'uint8' || options.endian == systemEndianness) {
+ switch(type) {
+ case "int8":
+ checkSize(1);
+ return new Int8Array(buffer.slice(0,totalLen));
+ case "uint8":
+ checkSize(1);
+ return new Uint8Array(buffer.slice(0,totalLen));
+ case "int16":
+ checkSize(2);
+ return new Int16Array(buffer.slice(0,totalLen*2));
+ case "uint16":
+ checkSize(2);
+ return new Uint16Array(buffer.slice(0,totalLen*2));
+ case "int32":
+ checkSize(4);
+ return new Int32Array(buffer.slice(0,totalLen*4));
+ case "uint32":
+ checkSize(4);
+ return new Uint32Array(buffer.slice(0,totalLen*4));
+ //case "int64":
+ // checkSize(8);
+ // return new Int64Array(buffer.slice(0,totalLen*8));
+ //case "uint64":
+ // checkSize(8);
+ // return new Uint64Array(buffer.slice(0,totalLen*8));
+ case "float":
+ checkSize(4);
+ return new Float32Array(buffer.slice(0,totalLen*4));
+ case "double":
+ checkSize(8);
+ return new Float64Array(buffer.slice(0,totalLen*8));
+ default:
+ console.warn("Unsupported NRRD type: " + type + ", returning raw buffer.");
+ return undefined;
+ }
+ } else {
+ switch(options.endian) {
+ case 'big':
+ endianFlag = false;
+ break;
+ case 'little':
+ endianFlag = true;
+ break;
+ default:
+ console.warn("Unsupported endianness in NRRD file: " + options.endian);
+ return undefined;
+ }
+ view = new DataView(buffer);
+ switch(type) {
+ case "int8": // Note that here we do not need to check the size of the buffer, as the DataView.get methods should throw an exception if we read beyond the buffer.
+ arr = new Int8Array(totalLen);
+ for(i=0; i0) integers!");
+ totalLen *= sizes[i];
+ }
+ buf8 = new Uint8Array(buffer);
+ str = String.fromCharCode.apply(null, buf8);
+ strList = str.split(whitespaceDataValueListSeparatorRE);
+ if (strList.lengthtotalLen) {
+ if (strList[0] === '') strList = strList.slice(1); // Strictly speaking the spec doesn't (explicitly) allow whitespace in front of the first number, but let's be lenient.
+ strList = strList.slice(0, totalLen);
+ }
+ switch(type) {
+ case "int8":
+ return new Int8Array(strList.map(parseNRRDInteger));
+ case "uint8":
+ return new Uint8Array(strList.map(parseNRRDInteger));
+ case "int16":
+ return new Int16Array(strList.map(parseNRRDInteger));
+ case "uint16":
+ return new Uint16Array(strList.map(parseNRRDInteger));
+ case "int32":
+ return new Int32Array(strList.map(parseNRRDInteger));
+ case "uint32":
+ return new Uint32Array(strList.map(parseNRRDInteger));
+ //case "int64":
+ // return new Int64Array(strList.map(parseNRRDInteger));
+ //case "uint64":
+ // return new Uint64Array(strList.map(parseNRRDInteger));
+ case "float":
+ return new Float32Array(strList.map(parseNRRDFloat));
+ case "double":
+ return new Float64Array(strList.map(parseNRRDFloat));
+ default:
+ console.warn("Unsupported NRRD type: " + type + ".");
+ return undefined;
+ }
+}
+
+// This ALWAYS returns an integer, or throws an exception.
+function getNRRDTypeSize(type) {
+ switch(type) {
+ case "int8":
+ return 1;
+ case "uint8":
+ return 1;
+ case "int16":
+ return 2;
+ case "uint16":
+ return 2;
+ case "int32":
+ return 4;
+ case "uint32":
+ return 4;
+ case "int64":
+ return 8;
+ case "uint64":
+ return 8;
+ case "float":
+ return 4;
+ case "double":
+ return 8;
+ default:
+ throw new Error("Do not know the size of NRRD type: " + type);
+ }
+}
+
+function checkNRRD(ret) {
+ // Always necessary fields
+ if (ret.dimension===undefined) {
+ throw new Error("Dimension missing from NRRD file!");
+ } else if (ret.type===undefined) {
+ throw new Error("Type missing from NRRD file!");
+ } else if (ret.encoding===undefined) {
+ throw new Error("Encoding missing from NRRD file!");
+ } else if (ret.sizes===undefined) {
+ throw new Error("Sizes missing from NRRD file!");
+ }
+
+ // Sometimes necessary fields
+ if (ret.type != 'block' && ret.type != 'int8' && ret.type != 'uint8' &&
+ ret.encoding != 'ascii' && ret.endian === undefined) {
+ throw new Error("Endianness missing from NRRD file!");
+ } else if (ret.type == 'block' && ret.blockSize === undefined) {
+ throw new Error("Missing block size in NRRD file!");
+ }
+
+ // Check dimension and per-axis field lengths
+ if (ret.dimension === 0) {
+ throw new Error("Zero-dimensional NRRD file?");
+ } else if (ret.dimension != ret.sizes.length) {
+ throw new Error("Length of 'sizes' is different from 'dimension' in an NRRD file!");
+ } else if (ret.spacings && ret.dimension != ret.spacings.length) {
+ throw new Error("Length of 'spacings' is different from 'dimension' in an NRRD file!");
+ } else if (ret.thicknesses && ret.dimension != ret.thicknesses.length) {
+ throw new Error("Length of 'thicknesses' is different from 'dimension' in an NRRD file!");
+ } else if (ret.axisMins && ret.dimension != ret.axisMins.length) {
+ throw new Error("Length of 'axis mins' is different from 'dimension' in an NRRD file!");
+ } else if (ret.axisMaxs && ret.dimension != ret.axisMaxs.length) {
+ throw new Error("Length of 'axis maxs' is different from 'dimension' in an NRRD file!");
+ } else if (ret.centers && ret.dimension != ret.centers.length) {
+ throw new Error("Length of 'centers' is different from 'dimension' in an NRRD file!");
+ } else if (ret.labels && ret.dimension != ret.labels.length) {
+ throw new Error("Length of 'labels' is different from 'dimension' in an NRRD file!");
+ } else if (ret.units && ret.dimension != ret.units.length) {
+ throw new Error("Length of 'units' is different from 'dimension' in an NRRD file!");
+ } else if (ret.kinds && ret.dimension != ret.kinds.length) {
+ throw new Error("Length of 'kinds' is different from 'dimension' in an NRRD file!");
+ }
+
+ // TODO: Check space/orientation fields.
+
+ // We should either have inline data or external data
+ if ((ret.data === undefined || ret.data.length === 0) && (ret.buffer === undefined || ret.buffer.byteLength === 0) && ret.dataFile === undefined) {
+ throw new Error("NRRD file has neither inline or external data!");
+ }
+}
+
+function castTypedArray(data, type) {
+ switch(type) {
+ case "int8":
+ return new Int8Array(data);
+ case "uint8":
+ return new Uint8Array(data);
+ case "int16":
+ return new Int16Array(data);
+ case "uint16":
+ return new Uint16Array(data);
+ case "int32":
+ return new Int32Array(data);
+ case "uint32":
+ return new Uint32Array(data);
+ //case "int64":
+ // return new Int64Array(data);
+ //case "uint64":
+ // return new Uint64Array(data);
+ case "float":
+ return new Float32Array(data);
+ case "double":
+ return new Float64Array(data);
+ default:
+ throw new Error("Cannot cast to NRRD type: " + type);
+ }
+}
+
+function serializeToBuffer(data, type, endian) {
+ var i, endianFlag, view, nativeSize = getNRRDTypeSize(type), buffer = new ArrayBuffer(data.length*nativeSize);
+ switch(endian) {
+ case 'big':
+ endianFlag = false;
+ break;
+ case 'little':
+ endianFlag = true;
+ break;
+ default:
+ console.warn("Unsupported endianness in NRRD file: " + endian);
+ return undefined;
+ }
+ view = new DataView(buffer);
+ switch(type) {
+ case "int8": // Note that here we do not need to check the size of the buffer, as the DataView.get methods should throw an exception if we read beyond the buffer.
+ for(i=0; i Array
+ *
+ * Chunks of output data, if [[Deflate#onData]] not overriden.
+ **/
+
+/**
+ * Deflate.result -> Uint8Array|Array
+ *
+ * Compressed result, generated by default [[Deflate#onData]]
+ * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
+ * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
+ * push a chunk with explicit flush (call [[Deflate#push]] with
+ * `Z_SYNC_FLUSH` param).
+ **/
+
+/**
+ * Deflate.err -> Number
+ *
+ * Error code after deflate finished. 0 (Z_OK) on success.
+ * You will not need it in real life, because deflate errors
+ * are possible only on wrong options or bad `onData` / `onEnd`
+ * custom handlers.
+ **/
+
+/**
+ * Deflate.msg -> String
+ *
+ * Error message, if [[Deflate.err]] != 0
+ **/
+
+
+/**
+ * new Deflate(options)
+ * - options (Object): zlib deflate options.
+ *
+ * Creates new deflator instance with specified params. Throws exception
+ * on bad params. Supported options:
+ *
+ * - `level`
+ * - `windowBits`
+ * - `memLevel`
+ * - `strategy`
+ *
+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
+ * for more information on these.
+ *
+ * Additional options, for internal needs:
+ *
+ * - `chunkSize` - size of generated data chunks (16K by default)
+ * - `raw` (Boolean) - do raw deflate
+ * - `gzip` (Boolean) - create gzip wrapper
+ * - `to` (String) - if equal to 'string', then result will be "binary string"
+ * (each char code [0..255])
+ * - `header` (Object) - custom header for gzip
+ * - `text` (Boolean) - true if compressed data believed to be text
+ * - `time` (Number) - modification time, unix timestamp
+ * - `os` (Number) - operation system code
+ * - `extra` (Array) - array of bytes with extra data (max 65536)
+ * - `name` (String) - file name (binary string)
+ * - `comment` (String) - comment (binary string)
+ * - `hcrc` (Boolean) - true if header crc should be added
+ *
+ * ##### Example:
+ *
+ * ```javascript
+ * var pako = require('pako')
+ * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
+ * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
+ *
+ * var deflate = new pako.Deflate({ level: 3});
+ *
+ * deflate.push(chunk1, false);
+ * deflate.push(chunk2, true); // true -> last chunk
+ *
+ * if (deflate.err) { throw new Error(deflate.err); }
+ *
+ * console.log(deflate.result);
+ * ```
+ **/
+var Deflate = function(options) {
+
+ this.options = utils.assign({
+ level: Z_DEFAULT_COMPRESSION,
+ method: Z_DEFLATED,
+ chunkSize: 16384,
+ windowBits: 15,
+ memLevel: 8,
+ strategy: Z_DEFAULT_STRATEGY,
+ to: ''
+ }, options || {});
+
+ var opt = this.options;
+
+ if (opt.raw && (opt.windowBits > 0)) {
+ opt.windowBits = -opt.windowBits;
+ }
+
+ else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
+ opt.windowBits += 16;
+ }
+
+ this.err = 0; // error code, if happens (0 = Z_OK)
+ this.msg = ''; // error message
+ this.ended = false; // used to avoid multiple onEnd() calls
+ this.chunks = []; // chunks of compressed data
+
+ this.strm = new zstream();
+ this.strm.avail_out = 0;
+
+ var status = zlib_deflate.deflateInit2(
+ this.strm,
+ opt.level,
+ opt.method,
+ opt.windowBits,
+ opt.memLevel,
+ opt.strategy
+ );
+
+ if (status !== Z_OK) {
+ throw new Error(msg[status]);
+ }
+
+ if (opt.header) {
+ zlib_deflate.deflateSetHeader(this.strm, opt.header);
+ }
+};
+
+/**
+ * Deflate#push(data[, mode]) -> Boolean
+ * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
+ * converted to utf8 byte sequence.
+ * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
+ * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
+ *
+ * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
+ * new compressed chunks. Returns `true` on success. The last data block must have
+ * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
+ * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
+ * can use mode Z_SYNC_FLUSH, keeping the compression context.
+ *
+ * On fail call [[Deflate#onEnd]] with error code and return false.
+ *
+ * We strongly recommend to use `Uint8Array` on input for best speed (output
+ * array format is detected automatically). Also, don't skip last param and always
+ * use the same type in your code (boolean or number). That will improve JS speed.
+ *
+ * For regular `Array`-s make sure all elements are [0..255].
+ *
+ * ##### Example
+ *
+ * ```javascript
+ * push(chunk, false); // push one of data chunks
+ * ...
+ * push(chunk, true); // push last chunk
+ * ```
+ **/
+Deflate.prototype.push = function(data, mode) {
+ var strm = this.strm;
+ var chunkSize = this.options.chunkSize;
+ var status, _mode;
+
+ if (this.ended) { return false; }
+
+ _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
+
+ // Convert data if needed
+ if (typeof data === 'string') {
+ // If we need to compress text, change encoding to utf8.
+ strm.input = strings.string2buf(data);
+ } else if (toString.call(data) === '[object ArrayBuffer]') {
+ strm.input = new Uint8Array(data);
+ } else {
+ strm.input = data;
+ }
+
+ strm.next_in = 0;
+ strm.avail_in = strm.input.length;
+
+ do {
+ if (strm.avail_out === 0) {
+ strm.output = new utils.Buf8(chunkSize);
+ strm.next_out = 0;
+ strm.avail_out = chunkSize;
+ }
+ status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
+
+ if (status !== Z_STREAM_END && status !== Z_OK) {
+ this.onEnd(status);
+ this.ended = true;
+ return false;
+ }
+ if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
+ if (this.options.to === 'string') {
+ this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
+ } else {
+ this.onData(utils.shrinkBuf(strm.output, strm.next_out));
+ }
+ }
+ } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
+
+ // Finalize on the last chunk.
+ if (_mode === Z_FINISH) {
+ status = zlib_deflate.deflateEnd(this.strm);
+ this.onEnd(status);
+ this.ended = true;
+ return status === Z_OK;
+ }
+
+ // callback interim results if Z_SYNC_FLUSH.
+ if (_mode === Z_SYNC_FLUSH) {
+ this.onEnd(Z_OK);
+ strm.avail_out = 0;
+ return true;
+ }
+
+ return true;
+};
+
+
+/**
+ * Deflate#onData(chunk) -> Void
+ * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
+ * on js engine support. When string output requested, each chunk
+ * will be string.
+ *
+ * By default, stores data blocks in `chunks[]` property and glue
+ * those in `onEnd`. Override this handler, if you need another behaviour.
+ **/
+Deflate.prototype.onData = function(chunk) {
+ this.chunks.push(chunk);
+};
+
+
+/**
+ * Deflate#onEnd(status) -> Void
+ * - status (Number): deflate status. 0 (Z_OK) on success,
+ * other if not.
+ *
+ * Called once after you tell deflate that the input stream is
+ * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
+ * or if an error happened. By default - join collected chunks,
+ * free memory and fill `results` / `err` properties.
+ **/
+Deflate.prototype.onEnd = function(status) {
+ // On success - join
+ if (status === Z_OK) {
+ if (this.options.to === 'string') {
+ this.result = this.chunks.join('');
+ } else {
+ this.result = utils.flattenChunks(this.chunks);
+ }
+ }
+ this.chunks = [];
+ this.err = status;
+ this.msg = this.strm.msg;
+};
+
+
+/**
+ * deflate(data[, options]) -> Uint8Array|Array|String
+ * - data (Uint8Array|Array|String): input data to compress.
+ * - options (Object): zlib deflate options.
+ *
+ * Compress `data` with deflate alrorythm and `options`.
+ *
+ * Supported options are:
+ *
+ * - level
+ * - windowBits
+ * - memLevel
+ * - strategy
+ *
+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
+ * for more information on these.
+ *
+ * Sugar (options):
+ *
+ * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
+ * negative windowBits implicitly.
+ * - `to` (String) - if equal to 'string', then result will be "binary string"
+ * (each char code [0..255])
+ *
+ * ##### Example:
+ *
+ * ```javascript
+ * var pako = require('pako')
+ * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
+ *
+ * console.log(pako.deflate(data));
+ * ```
+ **/
+function deflate(input, options) {
+ var deflator = new Deflate(options);
+
+ deflator.push(input, true);
+
+ // That will never happens, if you don't cheat with options :)
+ if (deflator.err) { throw deflator.msg; }
+
+ return deflator.result;
+}
+
+
+/**
+ * deflateRaw(data[, options]) -> Uint8Array|Array|String
+ * - data (Uint8Array|Array|String): input data to compress.
+ * - options (Object): zlib deflate options.
+ *
+ * The same as [[deflate]], but creates raw data, without wrapper
+ * (header and adler32 crc).
+ **/
+function deflateRaw(input, options) {
+ options = options || {};
+ options.raw = true;
+ return deflate(input, options);
+}
+
+
+/**
+ * gzip(data[, options]) -> Uint8Array|Array|String
+ * - data (Uint8Array|Array|String): input data to compress.
+ * - options (Object): zlib deflate options.
+ *
+ * The same as [[deflate]], but create gzip wrapper instead of
+ * deflate one.
+ **/
+function gzip(input, options) {
+ options = options || {};
+ options.gzip = true;
+ return deflate(input, options);
+}
+
+
+exports.Deflate = Deflate;
+exports.deflate = deflate;
+exports.deflateRaw = deflateRaw;
+exports.gzip = gzip;
+
+},{"./utils/common":32,"./utils/strings":33,"./zlib/deflate.js":37,"./zlib/messages":42,"./zlib/zstream":44}],31:[function(require,module,exports){
+'use strict';
+
+
+var zlib_inflate = require('./zlib/inflate.js');
+var utils = require('./utils/common');
+var strings = require('./utils/strings');
+var c = require('./zlib/constants');
+var msg = require('./zlib/messages');
+var zstream = require('./zlib/zstream');
+var gzheader = require('./zlib/gzheader');
+
+var toString = Object.prototype.toString;
+
+/**
+ * class Inflate
+ *
+ * Generic JS-style wrapper for zlib calls. If you don't need
+ * streaming behaviour - use more simple functions: [[inflate]]
+ * and [[inflateRaw]].
+ **/
+
+/* internal
+ * inflate.chunks -> Array
+ *
+ * Chunks of output data, if [[Inflate#onData]] not overriden.
+ **/
+
+/**
+ * Inflate.result -> Uint8Array|Array|String
+ *
+ * Uncompressed result, generated by default [[Inflate#onData]]
+ * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
+ * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
+ * push a chunk with explicit flush (call [[Inflate#push]] with
+ * `Z_SYNC_FLUSH` param).
+ **/
+
+/**
+ * Inflate.err -> Number
+ *
+ * Error code after inflate finished. 0 (Z_OK) on success.
+ * Should be checked if broken data possible.
+ **/
+
+/**
+ * Inflate.msg -> String
+ *
+ * Error message, if [[Inflate.err]] != 0
+ **/
+
+
+/**
+ * new Inflate(options)
+ * - options (Object): zlib inflate options.
+ *
+ * Creates new inflator instance with specified params. Throws exception
+ * on bad params. Supported options:
+ *
+ * - `windowBits`
+ *
+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
+ * for more information on these.
+ *
+ * Additional options, for internal needs:
+ *
+ * - `chunkSize` - size of generated data chunks (16K by default)
+ * - `raw` (Boolean) - do raw inflate
+ * - `to` (String) - if equal to 'string', then result will be converted
+ * from utf8 to utf16 (javascript) string. When string output requested,
+ * chunk length can differ from `chunkSize`, depending on content.
+ *
+ * By default, when no options set, autodetect deflate/gzip data format via
+ * wrapper header.
+ *
+ * ##### Example:
+ *
+ * ```javascript
+ * var pako = require('pako')
+ * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
+ * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
+ *
+ * var inflate = new pako.Inflate({ level: 3});
+ *
+ * inflate.push(chunk1, false);
+ * inflate.push(chunk2, true); // true -> last chunk
+ *
+ * if (inflate.err) { throw new Error(inflate.err); }
+ *
+ * console.log(inflate.result);
+ * ```
+ **/
+var Inflate = function(options) {
+
+ this.options = utils.assign({
+ chunkSize: 16384,
+ windowBits: 0,
+ to: ''
+ }, options || {});
+
+ var opt = this.options;
+
+ // Force window size for `raw` data, if not set directly,
+ // because we have no header for autodetect.
+ if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
+ opt.windowBits = -opt.windowBits;
+ if (opt.windowBits === 0) { opt.windowBits = -15; }
+ }
+
+ // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
+ if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
+ !(options && options.windowBits)) {
+ opt.windowBits += 32;
+ }
+
+ // Gzip header has no info about windows size, we can do autodetect only
+ // for deflate. So, if window size not set, force it to max when gzip possible
+ if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
+ // bit 3 (16) -> gzipped data
+ // bit 4 (32) -> autodetect gzip/deflate
+ if ((opt.windowBits & 15) === 0) {
+ opt.windowBits |= 15;
+ }
+ }
+
+ this.err = 0; // error code, if happens (0 = Z_OK)
+ this.msg = ''; // error message
+ this.ended = false; // used to avoid multiple onEnd() calls
+ this.chunks = []; // chunks of compressed data
+
+ this.strm = new zstream();
+ this.strm.avail_out = 0;
+
+ var status = zlib_inflate.inflateInit2(
+ this.strm,
+ opt.windowBits
+ );
+
+ if (status !== c.Z_OK) {
+ throw new Error(msg[status]);
+ }
+
+ this.header = new gzheader();
+
+ zlib_inflate.inflateGetHeader(this.strm, this.header);
+};
+
+/**
+ * Inflate#push(data[, mode]) -> Boolean
+ * - data (Uint8Array|Array|ArrayBuffer|String): input data
+ * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
+ * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
+ *
+ * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
+ * new output chunks. Returns `true` on success. The last data block must have
+ * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
+ * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
+ * can use mode Z_SYNC_FLUSH, keeping the decompression context.
+ *
+ * On fail call [[Inflate#onEnd]] with error code and return false.
+ *
+ * We strongly recommend to use `Uint8Array` on input for best speed (output
+ * format is detected automatically). Also, don't skip last param and always
+ * use the same type in your code (boolean or number). That will improve JS speed.
+ *
+ * For regular `Array`-s make sure all elements are [0..255].
+ *
+ * ##### Example
+ *
+ * ```javascript
+ * push(chunk, false); // push one of data chunks
+ * ...
+ * push(chunk, true); // push last chunk
+ * ```
+ **/
+Inflate.prototype.push = function(data, mode) {
+ var strm = this.strm;
+ var chunkSize = this.options.chunkSize;
+ var status, _mode;
+ var next_out_utf8, tail, utf8str;
+
+ // Flag to properly process Z_BUF_ERROR on testing inflate call
+ // when we check that all output data was flushed.
+ var allowBufError = false;
+
+ if (this.ended) { return false; }
+ _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
+
+ // Convert data if needed
+ if (typeof data === 'string') {
+ // Only binary strings can be decompressed on practice
+ strm.input = strings.binstring2buf(data);
+ } else if (toString.call(data) === '[object ArrayBuffer]') {
+ strm.input = new Uint8Array(data);
+ } else {
+ strm.input = data;
+ }
+
+ strm.next_in = 0;
+ strm.avail_in = strm.input.length;
+
+ do {
+ if (strm.avail_out === 0) {
+ strm.output = new utils.Buf8(chunkSize);
+ strm.next_out = 0;
+ strm.avail_out = chunkSize;
+ }
+
+ status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
+
+ if (status === c.Z_BUF_ERROR && allowBufError === true) {
+ status = c.Z_OK;
+ allowBufError = false;
+ }
+
+ if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
+ this.onEnd(status);
+ this.ended = true;
+ return false;
+ }
+
+ if (strm.next_out) {
+ if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
+
+ if (this.options.to === 'string') {
+
+ next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
+
+ tail = strm.next_out - next_out_utf8;
+ utf8str = strings.buf2string(strm.output, next_out_utf8);
+
+ // move tail
+ strm.next_out = tail;
+ strm.avail_out = chunkSize - tail;
+ if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
+
+ this.onData(utf8str);
+
+ } else {
+ this.onData(utils.shrinkBuf(strm.output, strm.next_out));
+ }
+ }
+ }
+
+ // When no more input data, we should check that internal inflate buffers
+ // are flushed. The only way to do it when avail_out = 0 - run one more
+ // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
+ // Here we set flag to process this error properly.
+ //
+ // NOTE. Deflate does not return error in this case and does not needs such
+ // logic.
+ if (strm.avail_in === 0 && strm.avail_out === 0) {
+ allowBufError = true;
+ }
+
+ } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
+
+ if (status === c.Z_STREAM_END) {
+ _mode = c.Z_FINISH;
+ }
+
+ // Finalize on the last chunk.
+ if (_mode === c.Z_FINISH) {
+ status = zlib_inflate.inflateEnd(this.strm);
+ this.onEnd(status);
+ this.ended = true;
+ return status === c.Z_OK;
+ }
+
+ // callback interim results if Z_SYNC_FLUSH.
+ if (_mode === c.Z_SYNC_FLUSH) {
+ this.onEnd(c.Z_OK);
+ strm.avail_out = 0;
+ return true;
+ }
+
+ return true;
+};
+
+
+/**
+ * Inflate#onData(chunk) -> Void
+ * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
+ * on js engine support. When string output requested, each chunk
+ * will be string.
+ *
+ * By default, stores data blocks in `chunks[]` property and glue
+ * those in `onEnd`. Override this handler, if you need another behaviour.
+ **/
+Inflate.prototype.onData = function(chunk) {
+ this.chunks.push(chunk);
+};
+
+
+/**
+ * Inflate#onEnd(status) -> Void
+ * - status (Number): inflate status. 0 (Z_OK) on success,
+ * other if not.
+ *
+ * Called either after you tell inflate that the input stream is
+ * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
+ * or if an error happened. By default - join collected chunks,
+ * free memory and fill `results` / `err` properties.
+ **/
+Inflate.prototype.onEnd = function(status) {
+ // On success - join
+ if (status === c.Z_OK) {
+ if (this.options.to === 'string') {
+ // Glue & convert here, until we teach pako to send
+ // utf8 alligned strings to onData
+ this.result = this.chunks.join('');
+ } else {
+ this.result = utils.flattenChunks(this.chunks);
+ }
+ }
+ this.chunks = [];
+ this.err = status;
+ this.msg = this.strm.msg;
+};
+
+
+/**
+ * inflate(data[, options]) -> Uint8Array|Array|String
+ * - data (Uint8Array|Array|String): input data to decompress.
+ * - options (Object): zlib inflate options.
+ *
+ * Decompress `data` with inflate/ungzip and `options`. Autodetect
+ * format via wrapper header by default. That's why we don't provide
+ * separate `ungzip` method.
+ *
+ * Supported options are:
+ *
+ * - windowBits
+ *
+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
+ * for more information.
+ *
+ * Sugar (options):
+ *
+ * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
+ * negative windowBits implicitly.
+ * - `to` (String) - if equal to 'string', then result will be converted
+ * from utf8 to utf16 (javascript) string. When string output requested,
+ * chunk length can differ from `chunkSize`, depending on content.
+ *
+ *
+ * ##### Example:
+ *
+ * ```javascript
+ * var pako = require('pako')
+ * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
+ * , output;
+ *
+ * try {
+ * output = pako.inflate(input);
+ * } catch (err)
+ * console.log(err);
+ * }
+ * ```
+ **/
+function inflate(input, options) {
+ var inflator = new Inflate(options);
+
+ inflator.push(input, true);
+
+ // That will never happens, if you don't cheat with options :)
+ if (inflator.err) { throw inflator.msg; }
+
+ return inflator.result;
+}
+
+
+/**
+ * inflateRaw(data[, options]) -> Uint8Array|Array|String
+ * - data (Uint8Array|Array|String): input data to decompress.
+ * - options (Object): zlib inflate options.
+ *
+ * The same as [[inflate]], but creates raw data, without wrapper
+ * (header and adler32 crc).
+ **/
+function inflateRaw(input, options) {
+ options = options || {};
+ options.raw = true;
+ return inflate(input, options);
+}
+
+
+/**
+ * ungzip(data[, options]) -> Uint8Array|Array|String
+ * - data (Uint8Array|Array|String): input data to decompress.
+ * - options (Object): zlib inflate options.
+ *
+ * Just shortcut to [[inflate]], because it autodetects format
+ * by header.content. Done for convenience.
+ **/
+
+
+exports.Inflate = Inflate;
+exports.inflate = inflate;
+exports.inflateRaw = inflateRaw;
+exports.ungzip = inflate;
+
+},{"./utils/common":32,"./utils/strings":33,"./zlib/constants":35,"./zlib/gzheader":38,"./zlib/inflate.js":40,"./zlib/messages":42,"./zlib/zstream":44}],32:[function(require,module,exports){
+'use strict';
+
+
+var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
+ (typeof Uint16Array !== 'undefined') &&
+ (typeof Int32Array !== 'undefined');
+
+
+exports.assign = function (obj /*from1, from2, from3, ...*/) {
+ var sources = Array.prototype.slice.call(arguments, 1);
+ while (sources.length) {
+ var source = sources.shift();
+ if (!source) { continue; }
+
+ if (typeof source !== 'object') {
+ throw new TypeError(source + 'must be non-object');
+ }
+
+ for (var p in source) {
+ if (source.hasOwnProperty(p)) {
+ obj[p] = source[p];
+ }
+ }
+ }
+
+ return obj;
+};
+
+
+// reduce buffer size, avoiding mem copy
+exports.shrinkBuf = function (buf, size) {
+ if (buf.length === size) { return buf; }
+ if (buf.subarray) { return buf.subarray(0, size); }
+ buf.length = size;
+ return buf;
+};
+
+
+var fnTyped = {
+ arraySet: function (dest, src, src_offs, len, dest_offs) {
+ if (src.subarray && dest.subarray) {
+ dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
+ return;
+ }
+ // Fallback to ordinary array
+ for (var i=0; i= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
+}
+_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
+
+
+// convert string to array (typed, when possible)
+exports.string2buf = function (str) {
+ var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
+
+ // count binary size
+ for (m_pos = 0; m_pos < str_len; m_pos++) {
+ c = str.charCodeAt(m_pos);
+ if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
+ c2 = str.charCodeAt(m_pos+1);
+ if ((c2 & 0xfc00) === 0xdc00) {
+ c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
+ m_pos++;
+ }
+ }
+ buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
+ }
+
+ // allocate buffer
+ buf = new utils.Buf8(buf_len);
+
+ // convert
+ for (i=0, m_pos = 0; i < buf_len; m_pos++) {
+ c = str.charCodeAt(m_pos);
+ if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
+ c2 = str.charCodeAt(m_pos+1);
+ if ((c2 & 0xfc00) === 0xdc00) {
+ c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
+ m_pos++;
+ }
+ }
+ if (c < 0x80) {
+ /* one byte */
+ buf[i++] = c;
+ } else if (c < 0x800) {
+ /* two bytes */
+ buf[i++] = 0xC0 | (c >>> 6);
+ buf[i++] = 0x80 | (c & 0x3f);
+ } else if (c < 0x10000) {
+ /* three bytes */
+ buf[i++] = 0xE0 | (c >>> 12);
+ buf[i++] = 0x80 | (c >>> 6 & 0x3f);
+ buf[i++] = 0x80 | (c & 0x3f);
+ } else {
+ /* four bytes */
+ buf[i++] = 0xf0 | (c >>> 18);
+ buf[i++] = 0x80 | (c >>> 12 & 0x3f);
+ buf[i++] = 0x80 | (c >>> 6 & 0x3f);
+ buf[i++] = 0x80 | (c & 0x3f);
+ }
+ }
+
+ return buf;
+};
+
+// Helper (used in 2 places)
+function buf2binstring(buf, len) {
+ // use fallback for big arrays to avoid stack overflow
+ if (len < 65537) {
+ if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
+ return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
+ }
+ }
+
+ var result = '';
+ for (var i=0; i < len; i++) {
+ result += String.fromCharCode(buf[i]);
+ }
+ return result;
+}
+
+
+// Convert byte array to binary string
+exports.buf2binstring = function(buf) {
+ return buf2binstring(buf, buf.length);
+};
+
+
+// Convert binary string (typed, when possible)
+exports.binstring2buf = function(str) {
+ var buf = new utils.Buf8(str.length);
+ for (var i=0, len=buf.length; i < len; i++) {
+ buf[i] = str.charCodeAt(i);
+ }
+ return buf;
+};
+
+
+// convert array to string
+exports.buf2string = function (buf, max) {
+ var i, out, c, c_len;
+ var len = max || buf.length;
+
+ // Reserve max possible length (2 words per char)
+ // NB: by unknown reasons, Array is significantly faster for
+ // String.fromCharCode.apply than Uint16Array.
+ var utf16buf = new Array(len*2);
+
+ for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
+
+ // apply mask on first byte
+ c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
+ // join the rest
+ while (c_len > 1 && i < len) {
+ c = (c << 6) | (buf[i++] & 0x3f);
+ c_len--;
+ }
+
+ // terminated by end of string?
+ if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
+
+ if (c < 0x10000) {
+ utf16buf[out++] = c;
+ } else {
+ c -= 0x10000;
+ utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
+ utf16buf[out++] = 0xdc00 | (c & 0x3ff);
+ }
+ }
+
+ return buf2binstring(utf16buf, out);
+};
+
+
+// Calculate max possible position in utf8 buffer,
+// that will not break sequence. If that's not possible
+// - (very small limits) return max size as is.
+//
+// buf[] - utf8 bytes array
+// max - length limit (mandatory);
+exports.utf8border = function(buf, max) {
+ var pos;
+
+ max = max || buf.length;
+ if (max > buf.length) { max = buf.length; }
+
+ // go back from last position, until start of sequence found
+ pos = max-1;
+ while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
+
+ // Fuckup - very small and broken sequence,
+ // return max, because we should return something anyway.
+ if (pos < 0) { return max; }
+
+ // If we came to start of buffer - that means vuffer is too small,
+ // return max too.
+ if (pos === 0) { return max; }
+
+ return (pos + _utf8len[buf[pos]] > max) ? pos : max;
+};
+
+},{"./common":32}],34:[function(require,module,exports){
+'use strict';
+
+// Note: adler32 takes 12% for level 0 and 2% for level 6.
+// It doesn't worth to make additional optimizationa as in original.
+// Small size is preferable.
+
+function adler32(adler, buf, len, pos) {
+ var s1 = (adler & 0xffff) |0,
+ s2 = ((adler >>> 16) & 0xffff) |0,
+ n = 0;
+
+ while (len !== 0) {
+ // Set limit ~ twice less than 5552, to keep
+ // s2 in 31-bits, because we force signed ints.
+ // in other case %= will fail.
+ n = len > 2000 ? 2000 : len;
+ len -= n;
+
+ do {
+ s1 = (s1 + buf[pos++]) |0;
+ s2 = (s2 + s1) |0;
+ } while (--n);
+
+ s1 %= 65521;
+ s2 %= 65521;
+ }
+
+ return (s1 | (s2 << 16)) |0;
+}
+
+
+module.exports = adler32;
+
+},{}],35:[function(require,module,exports){
+module.exports = {
+
+ /* Allowed flush values; see deflate() and inflate() below for details */
+ Z_NO_FLUSH: 0,
+ Z_PARTIAL_FLUSH: 1,
+ Z_SYNC_FLUSH: 2,
+ Z_FULL_FLUSH: 3,
+ Z_FINISH: 4,
+ Z_BLOCK: 5,
+ Z_TREES: 6,
+
+ /* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
+ */
+ Z_OK: 0,
+ Z_STREAM_END: 1,
+ Z_NEED_DICT: 2,
+ Z_ERRNO: -1,
+ Z_STREAM_ERROR: -2,
+ Z_DATA_ERROR: -3,
+ //Z_MEM_ERROR: -4,
+ Z_BUF_ERROR: -5,
+ //Z_VERSION_ERROR: -6,
+
+ /* compression levels */
+ Z_NO_COMPRESSION: 0,
+ Z_BEST_SPEED: 1,
+ Z_BEST_COMPRESSION: 9,
+ Z_DEFAULT_COMPRESSION: -1,
+
+
+ Z_FILTERED: 1,
+ Z_HUFFMAN_ONLY: 2,
+ Z_RLE: 3,
+ Z_FIXED: 4,
+ Z_DEFAULT_STRATEGY: 0,
+
+ /* Possible values of the data_type field (though see inflate()) */
+ Z_BINARY: 0,
+ Z_TEXT: 1,
+ //Z_ASCII: 1, // = Z_TEXT (deprecated)
+ Z_UNKNOWN: 2,
+
+ /* The deflate compression method */
+ Z_DEFLATED: 8
+ //Z_NULL: null // Use -1 or null inline, depending on var type
+};
+
+},{}],36:[function(require,module,exports){
+'use strict';
+
+// Note: we can't get significant speed boost here.
+// So write code to minimize size - no pregenerated tables
+// and array tools dependencies.
+
+
+// Use ordinary array, since untyped makes no boost here
+function makeTable() {
+ var c, table = [];
+
+ for (var n =0; n < 256; n++) {
+ c = n;
+ for (var k =0; k < 8; k++) {
+ c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
+ }
+ table[n] = c;
+ }
+
+ return table;
+}
+
+// Create table on load. Just 255 signed longs. Not a problem.
+var crcTable = makeTable();
+
+
+function crc32(crc, buf, len, pos) {
+ var t = crcTable,
+ end = pos + len;
+
+ crc = crc ^ (-1);
+
+ for (var i = pos; i < end; i++) {
+ crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
+ }
+
+ return (crc ^ (-1)); // >>> 0;
+}
+
+
+module.exports = crc32;
+
+},{}],37:[function(require,module,exports){
+'use strict';
+
+var utils = require('../utils/common');
+var trees = require('./trees');
+var adler32 = require('./adler32');
+var crc32 = require('./crc32');
+var msg = require('./messages');
+
+/* Public constants ==========================================================*/
+/* ===========================================================================*/
+
+
+/* Allowed flush values; see deflate() and inflate() below for details */
+var Z_NO_FLUSH = 0;
+var Z_PARTIAL_FLUSH = 1;
+//var Z_SYNC_FLUSH = 2;
+var Z_FULL_FLUSH = 3;
+var Z_FINISH = 4;
+var Z_BLOCK = 5;
+//var Z_TREES = 6;
+
+
+/* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
+ */
+var Z_OK = 0;
+var Z_STREAM_END = 1;
+//var Z_NEED_DICT = 2;
+//var Z_ERRNO = -1;
+var Z_STREAM_ERROR = -2;
+var Z_DATA_ERROR = -3;
+//var Z_MEM_ERROR = -4;
+var Z_BUF_ERROR = -5;
+//var Z_VERSION_ERROR = -6;
+
+
+/* compression levels */
+//var Z_NO_COMPRESSION = 0;
+//var Z_BEST_SPEED = 1;
+//var Z_BEST_COMPRESSION = 9;
+var Z_DEFAULT_COMPRESSION = -1;
+
+
+var Z_FILTERED = 1;
+var Z_HUFFMAN_ONLY = 2;
+var Z_RLE = 3;
+var Z_FIXED = 4;
+var Z_DEFAULT_STRATEGY = 0;
+
+/* Possible values of the data_type field (though see inflate()) */
+//var Z_BINARY = 0;
+//var Z_TEXT = 1;
+//var Z_ASCII = 1; // = Z_TEXT
+var Z_UNKNOWN = 2;
+
+
+/* The deflate compression method */
+var Z_DEFLATED = 8;
+
+/*============================================================================*/
+
+
+var MAX_MEM_LEVEL = 9;
+/* Maximum value for memLevel in deflateInit2 */
+var MAX_WBITS = 15;
+/* 32K LZ77 window */
+var DEF_MEM_LEVEL = 8;
+
+
+var LENGTH_CODES = 29;
+/* number of length codes, not counting the special END_BLOCK code */
+var LITERALS = 256;
+/* number of literal bytes 0..255 */
+var L_CODES = LITERALS + 1 + LENGTH_CODES;
+/* number of Literal or Length codes, including the END_BLOCK code */
+var D_CODES = 30;
+/* number of distance codes */
+var BL_CODES = 19;
+/* number of codes used to transfer the bit lengths */
+var HEAP_SIZE = 2*L_CODES + 1;
+/* maximum heap size */
+var MAX_BITS = 15;
+/* All codes must not exceed MAX_BITS bits */
+
+var MIN_MATCH = 3;
+var MAX_MATCH = 258;
+var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
+
+var PRESET_DICT = 0x20;
+
+var INIT_STATE = 42;
+var EXTRA_STATE = 69;
+var NAME_STATE = 73;
+var COMMENT_STATE = 91;
+var HCRC_STATE = 103;
+var BUSY_STATE = 113;
+var FINISH_STATE = 666;
+
+var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
+var BS_BLOCK_DONE = 2; /* block flush performed */
+var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
+var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
+
+var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
+
+function err(strm, errorCode) {
+ strm.msg = msg[errorCode];
+ return errorCode;
+}
+
+function rank(f) {
+ return ((f) << 1) - ((f) > 4 ? 9 : 0);
+}
+
+function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
+
+
+/* =========================================================================
+ * Flush as much pending output as possible. All deflate() output goes
+ * through this function so some applications may wish to modify it
+ * to avoid allocating a large strm->output buffer and copying into it.
+ * (See also read_buf()).
+ */
+function flush_pending(strm) {
+ var s = strm.state;
+
+ //_tr_flush_bits(s);
+ var len = s.pending;
+ if (len > strm.avail_out) {
+ len = strm.avail_out;
+ }
+ if (len === 0) { return; }
+
+ utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
+ strm.next_out += len;
+ s.pending_out += len;
+ strm.total_out += len;
+ strm.avail_out -= len;
+ s.pending -= len;
+ if (s.pending === 0) {
+ s.pending_out = 0;
+ }
+}
+
+
+function flush_block_only (s, last) {
+ trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
+ s.block_start = s.strstart;
+ flush_pending(s.strm);
+}
+
+
+function put_byte(s, b) {
+ s.pending_buf[s.pending++] = b;
+}
+
+
+/* =========================================================================
+ * Put a short in the pending buffer. The 16-bit value is put in MSB order.
+ * IN assertion: the stream state is correct and there is enough room in
+ * pending_buf.
+ */
+function putShortMSB(s, b) {
+// put_byte(s, (Byte)(b >> 8));
+// put_byte(s, (Byte)(b & 0xff));
+ s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
+ s.pending_buf[s.pending++] = b & 0xff;
+}
+
+
+/* ===========================================================================
+ * Read a new buffer from the current input stream, update the adler32
+ * and total number of bytes read. All deflate() input goes through
+ * this function so some applications may wish to modify it to avoid
+ * allocating a large strm->input buffer and copying from it.
+ * (See also flush_pending()).
+ */
+function read_buf(strm, buf, start, size) {
+ var len = strm.avail_in;
+
+ if (len > size) { len = size; }
+ if (len === 0) { return 0; }
+
+ strm.avail_in -= len;
+
+ utils.arraySet(buf, strm.input, strm.next_in, len, start);
+ if (strm.state.wrap === 1) {
+ strm.adler = adler32(strm.adler, buf, len, start);
+ }
+
+ else if (strm.state.wrap === 2) {
+ strm.adler = crc32(strm.adler, buf, len, start);
+ }
+
+ strm.next_in += len;
+ strm.total_in += len;
+
+ return len;
+}
+
+
+/* ===========================================================================
+ * Set match_start to the longest match starting at the given string and
+ * return its length. Matches shorter or equal to prev_length are discarded,
+ * in which case the result is equal to prev_length and match_start is
+ * garbage.
+ * IN assertions: cur_match is the head of the hash chain for the current
+ * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
+ * OUT assertion: the match length is not greater than s->lookahead.
+ */
+function longest_match(s, cur_match) {
+ var chain_length = s.max_chain_length; /* max hash chain length */
+ var scan = s.strstart; /* current string */
+ var match; /* matched string */
+ var len; /* length of current match */
+ var best_len = s.prev_length; /* best match length so far */
+ var nice_match = s.nice_match; /* stop if match long enough */
+ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
+ s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
+
+ var _win = s.window; // shortcut
+
+ var wmask = s.w_mask;
+ var prev = s.prev;
+
+ /* Stop when cur_match becomes <= limit. To simplify the code,
+ * we prevent matches with the string of window index 0.
+ */
+
+ var strend = s.strstart + MAX_MATCH;
+ var scan_end1 = _win[scan + best_len - 1];
+ var scan_end = _win[scan + best_len];
+
+ /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
+ * It is easy to get rid of this optimization if necessary.
+ */
+ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
+
+ /* Do not waste too much time if we already have a good match: */
+ if (s.prev_length >= s.good_match) {
+ chain_length >>= 2;
+ }
+ /* Do not look for matches beyond the end of the input. This is necessary
+ * to make deflate deterministic.
+ */
+ if (nice_match > s.lookahead) { nice_match = s.lookahead; }
+
+ // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
+
+ do {
+ // Assert(cur_match < s->strstart, "no future");
+ match = cur_match;
+
+ /* Skip to next match if the match length cannot increase
+ * or if the match length is less than 2. Note that the checks below
+ * for insufficient lookahead only occur occasionally for performance
+ * reasons. Therefore uninitialized memory will be accessed, and
+ * conditional jumps will be made that depend on those values.
+ * However the length of the match is limited to the lookahead, so
+ * the output of deflate is not affected by the uninitialized values.
+ */
+
+ if (_win[match + best_len] !== scan_end ||
+ _win[match + best_len - 1] !== scan_end1 ||
+ _win[match] !== _win[scan] ||
+ _win[++match] !== _win[scan + 1]) {
+ continue;
+ }
+
+ /* The check at best_len-1 can be removed because it will be made
+ * again later. (This heuristic is not always a win.)
+ * It is not necessary to compare scan[2] and match[2] since they
+ * are always equal when the other bytes match, given that
+ * the hash keys are equal and that HASH_BITS >= 8.
+ */
+ scan += 2;
+ match++;
+ // Assert(*scan == *match, "match[2]?");
+
+ /* We check for insufficient lookahead only every 8th comparison;
+ * the 256th check will be made at strstart+258.
+ */
+ do {
+ /*jshint noempty:false*/
+ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
+ scan < strend);
+
+ // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+
+ len = MAX_MATCH - (strend - scan);
+ scan = strend - MAX_MATCH;
+
+ if (len > best_len) {
+ s.match_start = cur_match;
+ best_len = len;
+ if (len >= nice_match) {
+ break;
+ }
+ scan_end1 = _win[scan + best_len - 1];
+ scan_end = _win[scan + best_len];
+ }
+ } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
+
+ if (best_len <= s.lookahead) {
+ return best_len;
+ }
+ return s.lookahead;
+}
+
+
+/* ===========================================================================
+ * Fill the window when the lookahead becomes insufficient.
+ * Updates strstart and lookahead.
+ *
+ * IN assertion: lookahead < MIN_LOOKAHEAD
+ * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
+ * At least one byte has been read, or avail_in == 0; reads are
+ * performed for at least two bytes (required for the zip translate_eol
+ * option -- not supported here).
+ */
+function fill_window(s) {
+ var _w_size = s.w_size;
+ var p, n, m, more, str;
+
+ //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
+
+ do {
+ more = s.window_size - s.lookahead - s.strstart;
+
+ // JS ints have 32 bit, block below not needed
+ /* Deal with !@#$% 64K limit: */
+ //if (sizeof(int) <= 2) {
+ // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
+ // more = wsize;
+ //
+ // } else if (more == (unsigned)(-1)) {
+ // /* Very unlikely, but possible on 16 bit machine if
+ // * strstart == 0 && lookahead == 1 (input done a byte at time)
+ // */
+ // more--;
+ // }
+ //}
+
+
+ /* If the window is almost full and there is insufficient lookahead,
+ * move the upper half to the lower one to make room in the upper half.
+ */
+ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
+
+ utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
+ s.match_start -= _w_size;
+ s.strstart -= _w_size;
+ /* we now have strstart >= MAX_DIST */
+ s.block_start -= _w_size;
+
+ /* Slide the hash table (could be avoided with 32 bit values
+ at the expense of memory usage). We slide even when level == 0
+ to keep the hash table consistent if we switch back to level > 0
+ later. (Using level 0 permanently is not an optimal usage of
+ zlib, so we don't care about this pathological case.)
+ */
+
+ n = s.hash_size;
+ p = n;
+ do {
+ m = s.head[--p];
+ s.head[p] = (m >= _w_size ? m - _w_size : 0);
+ } while (--n);
+
+ n = _w_size;
+ p = n;
+ do {
+ m = s.prev[--p];
+ s.prev[p] = (m >= _w_size ? m - _w_size : 0);
+ /* If n is not on any hash chain, prev[n] is garbage but
+ * its value will never be used.
+ */
+ } while (--n);
+
+ more += _w_size;
+ }
+ if (s.strm.avail_in === 0) {
+ break;
+ }
+
+ /* If there was no sliding:
+ * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
+ * more == window_size - lookahead - strstart
+ * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
+ * => more >= window_size - 2*WSIZE + 2
+ * In the BIG_MEM or MMAP case (not yet supported),
+ * window_size == input_size + MIN_LOOKAHEAD &&
+ * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
+ * Otherwise, window_size == 2*WSIZE so more >= 2.
+ * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
+ */
+ //Assert(more >= 2, "more < 2");
+ n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
+ s.lookahead += n;
+
+ /* Initialize the hash value now that we have some input: */
+ if (s.lookahead + s.insert >= MIN_MATCH) {
+ str = s.strstart - s.insert;
+ s.ins_h = s.window[str];
+
+ /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
+//#if MIN_MATCH != 3
+// Call update_hash() MIN_MATCH-3 more times
+//#endif
+ while (s.insert) {
+ /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
+
+ s.prev[str & s.w_mask] = s.head[s.ins_h];
+ s.head[s.ins_h] = str;
+ str++;
+ s.insert--;
+ if (s.lookahead + s.insert < MIN_MATCH) {
+ break;
+ }
+ }
+ }
+ /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
+ * but this is not important since only literal bytes will be emitted.
+ */
+
+ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
+
+ /* If the WIN_INIT bytes after the end of the current data have never been
+ * written, then zero those bytes in order to avoid memory check reports of
+ * the use of uninitialized (or uninitialised as Julian writes) bytes by
+ * the longest match routines. Update the high water mark for the next
+ * time through here. WIN_INIT is set to MAX_MATCH since the longest match
+ * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
+ */
+// if (s.high_water < s.window_size) {
+// var curr = s.strstart + s.lookahead;
+// var init = 0;
+//
+// if (s.high_water < curr) {
+// /* Previous high water mark below current data -- zero WIN_INIT
+// * bytes or up to end of window, whichever is less.
+// */
+// init = s.window_size - curr;
+// if (init > WIN_INIT)
+// init = WIN_INIT;
+// zmemzero(s->window + curr, (unsigned)init);
+// s->high_water = curr + init;
+// }
+// else if (s->high_water < (ulg)curr + WIN_INIT) {
+// /* High water mark at or above current data, but below current data
+// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
+// * to end of window, whichever is less.
+// */
+// init = (ulg)curr + WIN_INIT - s->high_water;
+// if (init > s->window_size - s->high_water)
+// init = s->window_size - s->high_water;
+// zmemzero(s->window + s->high_water, (unsigned)init);
+// s->high_water += init;
+// }
+// }
+//
+// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
+// "not enough room for search");
+}
+
+/* ===========================================================================
+ * Copy without compression as much as possible from the input stream, return
+ * the current block state.
+ * This function does not insert new strings in the dictionary since
+ * uncompressible data is probably not useful. This function is used
+ * only for the level=0 compression option.
+ * NOTE: this function should be optimized to avoid extra copying from
+ * window to pending_buf.
+ */
+function deflate_stored(s, flush) {
+ /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
+ * to pending_buf_size, and each stored block has a 5 byte header:
+ */
+ var max_block_size = 0xffff;
+
+ if (max_block_size > s.pending_buf_size - 5) {
+ max_block_size = s.pending_buf_size - 5;
+ }
+
+ /* Copy as much as possible from input to output: */
+ for (;;) {
+ /* Fill the window as much as possible: */
+ if (s.lookahead <= 1) {
+
+ //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
+ // s->block_start >= (long)s->w_size, "slide too late");
+// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
+// s.block_start >= s.w_size)) {
+// throw new Error("slide too late");
+// }
+
+ fill_window(s);
+ if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
+ return BS_NEED_MORE;
+ }
+
+ if (s.lookahead === 0) {
+ break;
+ }
+ /* flush the current block */
+ }
+ //Assert(s->block_start >= 0L, "block gone");
+// if (s.block_start < 0) throw new Error("block gone");
+
+ s.strstart += s.lookahead;
+ s.lookahead = 0;
+
+ /* Emit a stored block if pending_buf will be full: */
+ var max_start = s.block_start + max_block_size;
+
+ if (s.strstart === 0 || s.strstart >= max_start) {
+ /* strstart == 0 is possible when wraparound on 16-bit machine */
+ s.lookahead = s.strstart - max_start;
+ s.strstart = max_start;
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+
+
+ }
+ /* Flush if we may have to slide, otherwise block_start may become
+ * negative and the data will be gone:
+ */
+ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+ }
+
+ s.insert = 0;
+
+ if (flush === Z_FINISH) {
+ /*** FLUSH_BLOCK(s, 1); ***/
+ flush_block_only(s, true);
+ if (s.strm.avail_out === 0) {
+ return BS_FINISH_STARTED;
+ }
+ /***/
+ return BS_FINISH_DONE;
+ }
+
+ if (s.strstart > s.block_start) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+
+ return BS_NEED_MORE;
+}
+
+/* ===========================================================================
+ * Compress as much as possible from the input stream, return the current
+ * block state.
+ * This function does not perform lazy evaluation of matches and inserts
+ * new strings in the dictionary only for unmatched strings or for short
+ * matches. It is used only for the fast compression options.
+ */
+function deflate_fast(s, flush) {
+ var hash_head; /* head of the hash chain */
+ var bflush; /* set if current block must be flushed */
+
+ for (;;) {
+ /* Make sure that we always have enough lookahead, except
+ * at the end of the input file. We need MAX_MATCH bytes
+ * for the next match, plus MIN_MATCH bytes to insert the
+ * string following the next match.
+ */
+ if (s.lookahead < MIN_LOOKAHEAD) {
+ fill_window(s);
+ if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
+ return BS_NEED_MORE;
+ }
+ if (s.lookahead === 0) {
+ break; /* flush the current block */
+ }
+ }
+
+ /* Insert the string window[strstart .. strstart+2] in the
+ * dictionary, and set hash_head to the head of the hash chain:
+ */
+ hash_head = 0/*NIL*/;
+ if (s.lookahead >= MIN_MATCH) {
+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/
+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
+ s.head[s.ins_h] = s.strstart;
+ /***/
+ }
+
+ /* Find the longest match, discarding those <= prev_length.
+ * At this point we have always match_length < MIN_MATCH
+ */
+ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
+ /* To simplify the code, we prevent matches with the string
+ * of window index 0 (in particular we have to avoid a match
+ * of the string with itself at the start of the input file).
+ */
+ s.match_length = longest_match(s, hash_head);
+ /* longest_match() sets match_start */
+ }
+ if (s.match_length >= MIN_MATCH) {
+ // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
+
+ /*** _tr_tally_dist(s, s.strstart - s.match_start,
+ s.match_length - MIN_MATCH, bflush); ***/
+ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
+
+ s.lookahead -= s.match_length;
+
+ /* Insert new strings in the hash table only if the match length
+ * is not too large. This saves time but degrades compression.
+ */
+ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
+ s.match_length--; /* string at strstart already in table */
+ do {
+ s.strstart++;
+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/
+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
+ s.head[s.ins_h] = s.strstart;
+ /***/
+ /* strstart never exceeds WSIZE-MAX_MATCH, so there are
+ * always MIN_MATCH bytes ahead.
+ */
+ } while (--s.match_length !== 0);
+ s.strstart++;
+ } else
+ {
+ s.strstart += s.match_length;
+ s.match_length = 0;
+ s.ins_h = s.window[s.strstart];
+ /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
+
+//#if MIN_MATCH != 3
+// Call UPDATE_HASH() MIN_MATCH-3 more times
+//#endif
+ /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
+ * matter since it will be recomputed at next deflate call.
+ */
+ }
+ } else {
+ /* No match, output a literal byte */
+ //Tracevv((stderr,"%c", s.window[s.strstart]));
+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
+
+ s.lookahead--;
+ s.strstart++;
+ }
+ if (bflush) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+ }
+ s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
+ if (flush === Z_FINISH) {
+ /*** FLUSH_BLOCK(s, 1); ***/
+ flush_block_only(s, true);
+ if (s.strm.avail_out === 0) {
+ return BS_FINISH_STARTED;
+ }
+ /***/
+ return BS_FINISH_DONE;
+ }
+ if (s.last_lit) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+ return BS_BLOCK_DONE;
+}
+
+/* ===========================================================================
+ * Same as above, but achieves better compression. We use a lazy
+ * evaluation for matches: a match is finally adopted only if there is
+ * no better match at the next window position.
+ */
+function deflate_slow(s, flush) {
+ var hash_head; /* head of hash chain */
+ var bflush; /* set if current block must be flushed */
+
+ var max_insert;
+
+ /* Process the input block. */
+ for (;;) {
+ /* Make sure that we always have enough lookahead, except
+ * at the end of the input file. We need MAX_MATCH bytes
+ * for the next match, plus MIN_MATCH bytes to insert the
+ * string following the next match.
+ */
+ if (s.lookahead < MIN_LOOKAHEAD) {
+ fill_window(s);
+ if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
+ return BS_NEED_MORE;
+ }
+ if (s.lookahead === 0) { break; } /* flush the current block */
+ }
+
+ /* Insert the string window[strstart .. strstart+2] in the
+ * dictionary, and set hash_head to the head of the hash chain:
+ */
+ hash_head = 0/*NIL*/;
+ if (s.lookahead >= MIN_MATCH) {
+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/
+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
+ s.head[s.ins_h] = s.strstart;
+ /***/
+ }
+
+ /* Find the longest match, discarding those <= prev_length.
+ */
+ s.prev_length = s.match_length;
+ s.prev_match = s.match_start;
+ s.match_length = MIN_MATCH-1;
+
+ if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
+ s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
+ /* To simplify the code, we prevent matches with the string
+ * of window index 0 (in particular we have to avoid a match
+ * of the string with itself at the start of the input file).
+ */
+ s.match_length = longest_match(s, hash_head);
+ /* longest_match() sets match_start */
+
+ if (s.match_length <= 5 &&
+ (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
+
+ /* If prev_match is also MIN_MATCH, match_start is garbage
+ * but we will ignore the current match anyway.
+ */
+ s.match_length = MIN_MATCH-1;
+ }
+ }
+ /* If there was a match at the previous step and the current
+ * match is not better, output the previous match:
+ */
+ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
+ max_insert = s.strstart + s.lookahead - MIN_MATCH;
+ /* Do not insert strings in hash table beyond this. */
+
+ //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
+
+ /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
+ s.prev_length - MIN_MATCH, bflush);***/
+ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
+ /* Insert in hash table all strings up to the end of the match.
+ * strstart-1 and strstart are already inserted. If there is not
+ * enough lookahead, the last two strings are not inserted in
+ * the hash table.
+ */
+ s.lookahead -= s.prev_length-1;
+ s.prev_length -= 2;
+ do {
+ if (++s.strstart <= max_insert) {
+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/
+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
+ s.head[s.ins_h] = s.strstart;
+ /***/
+ }
+ } while (--s.prev_length !== 0);
+ s.match_available = 0;
+ s.match_length = MIN_MATCH-1;
+ s.strstart++;
+
+ if (bflush) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+
+ } else if (s.match_available) {
+ /* If there was no match at the previous position, output a
+ * single literal. If there was a match but the current match
+ * is longer, truncate the previous match to a single literal.
+ */
+ //Tracevv((stderr,"%c", s->window[s->strstart-1]));
+ /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
+ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
+
+ if (bflush) {
+ /*** FLUSH_BLOCK_ONLY(s, 0) ***/
+ flush_block_only(s, false);
+ /***/
+ }
+ s.strstart++;
+ s.lookahead--;
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ } else {
+ /* There is no previous match to compare with, wait for
+ * the next step to decide.
+ */
+ s.match_available = 1;
+ s.strstart++;
+ s.lookahead--;
+ }
+ }
+ //Assert (flush != Z_NO_FLUSH, "no flush?");
+ if (s.match_available) {
+ //Tracevv((stderr,"%c", s->window[s->strstart-1]));
+ /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
+ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
+
+ s.match_available = 0;
+ }
+ s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
+ if (flush === Z_FINISH) {
+ /*** FLUSH_BLOCK(s, 1); ***/
+ flush_block_only(s, true);
+ if (s.strm.avail_out === 0) {
+ return BS_FINISH_STARTED;
+ }
+ /***/
+ return BS_FINISH_DONE;
+ }
+ if (s.last_lit) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+
+ return BS_BLOCK_DONE;
+}
+
+
+/* ===========================================================================
+ * For Z_RLE, simply look for runs of bytes, generate matches only of distance
+ * one. Do not maintain a hash table. (It will be regenerated if this run of
+ * deflate switches away from Z_RLE.)
+ */
+function deflate_rle(s, flush) {
+ var bflush; /* set if current block must be flushed */
+ var prev; /* byte at distance one to match */
+ var scan, strend; /* scan goes up to strend for length of run */
+
+ var _win = s.window;
+
+ for (;;) {
+ /* Make sure that we always have enough lookahead, except
+ * at the end of the input file. We need MAX_MATCH bytes
+ * for the longest run, plus one for the unrolled loop.
+ */
+ if (s.lookahead <= MAX_MATCH) {
+ fill_window(s);
+ if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
+ return BS_NEED_MORE;
+ }
+ if (s.lookahead === 0) { break; } /* flush the current block */
+ }
+
+ /* See how many times the previous byte repeats */
+ s.match_length = 0;
+ if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
+ scan = s.strstart - 1;
+ prev = _win[scan];
+ if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
+ strend = s.strstart + MAX_MATCH;
+ do {
+ /*jshint noempty:false*/
+ } while (prev === _win[++scan] && prev === _win[++scan] &&
+ prev === _win[++scan] && prev === _win[++scan] &&
+ prev === _win[++scan] && prev === _win[++scan] &&
+ prev === _win[++scan] && prev === _win[++scan] &&
+ scan < strend);
+ s.match_length = MAX_MATCH - (strend - scan);
+ if (s.match_length > s.lookahead) {
+ s.match_length = s.lookahead;
+ }
+ }
+ //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
+ }
+
+ /* Emit match if have run of MIN_MATCH or longer, else emit literal */
+ if (s.match_length >= MIN_MATCH) {
+ //check_match(s, s.strstart, s.strstart - 1, s.match_length);
+
+ /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
+ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
+
+ s.lookahead -= s.match_length;
+ s.strstart += s.match_length;
+ s.match_length = 0;
+ } else {
+ /* No match, output a literal byte */
+ //Tracevv((stderr,"%c", s->window[s->strstart]));
+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
+
+ s.lookahead--;
+ s.strstart++;
+ }
+ if (bflush) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+ }
+ s.insert = 0;
+ if (flush === Z_FINISH) {
+ /*** FLUSH_BLOCK(s, 1); ***/
+ flush_block_only(s, true);
+ if (s.strm.avail_out === 0) {
+ return BS_FINISH_STARTED;
+ }
+ /***/
+ return BS_FINISH_DONE;
+ }
+ if (s.last_lit) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+ return BS_BLOCK_DONE;
+}
+
+/* ===========================================================================
+ * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
+ * (It will be regenerated if this run of deflate switches away from Huffman.)
+ */
+function deflate_huff(s, flush) {
+ var bflush; /* set if current block must be flushed */
+
+ for (;;) {
+ /* Make sure that we have a literal to write. */
+ if (s.lookahead === 0) {
+ fill_window(s);
+ if (s.lookahead === 0) {
+ if (flush === Z_NO_FLUSH) {
+ return BS_NEED_MORE;
+ }
+ break; /* flush the current block */
+ }
+ }
+
+ /* Output a literal byte */
+ s.match_length = 0;
+ //Tracevv((stderr,"%c", s->window[s->strstart]));
+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
+ s.lookahead--;
+ s.strstart++;
+ if (bflush) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+ }
+ s.insert = 0;
+ if (flush === Z_FINISH) {
+ /*** FLUSH_BLOCK(s, 1); ***/
+ flush_block_only(s, true);
+ if (s.strm.avail_out === 0) {
+ return BS_FINISH_STARTED;
+ }
+ /***/
+ return BS_FINISH_DONE;
+ }
+ if (s.last_lit) {
+ /*** FLUSH_BLOCK(s, 0); ***/
+ flush_block_only(s, false);
+ if (s.strm.avail_out === 0) {
+ return BS_NEED_MORE;
+ }
+ /***/
+ }
+ return BS_BLOCK_DONE;
+}
+
+/* Values for max_lazy_match, good_match and max_chain_length, depending on
+ * the desired pack level (0..9). The values given below have been tuned to
+ * exclude worst case performance for pathological files. Better values may be
+ * found for specific files.
+ */
+var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
+ this.good_length = good_length;
+ this.max_lazy = max_lazy;
+ this.nice_length = nice_length;
+ this.max_chain = max_chain;
+ this.func = func;
+};
+
+var configuration_table;
+
+configuration_table = [
+ /* good lazy nice chain */
+ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
+ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
+ new Config(4, 5, 16, 8, deflate_fast), /* 2 */
+ new Config(4, 6, 32, 32, deflate_fast), /* 3 */
+
+ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
+ new Config(8, 16, 32, 32, deflate_slow), /* 5 */
+ new Config(8, 16, 128, 128, deflate_slow), /* 6 */
+ new Config(8, 32, 128, 256, deflate_slow), /* 7 */
+ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
+ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
+];
+
+
+/* ===========================================================================
+ * Initialize the "longest match" routines for a new zlib stream
+ */
+function lm_init(s) {
+ s.window_size = 2 * s.w_size;
+
+ /*** CLEAR_HASH(s); ***/
+ zero(s.head); // Fill with NIL (= 0);
+
+ /* Set the default configuration parameters:
+ */
+ s.max_lazy_match = configuration_table[s.level].max_lazy;
+ s.good_match = configuration_table[s.level].good_length;
+ s.nice_match = configuration_table[s.level].nice_length;
+ s.max_chain_length = configuration_table[s.level].max_chain;
+
+ s.strstart = 0;
+ s.block_start = 0;
+ s.lookahead = 0;
+ s.insert = 0;
+ s.match_length = s.prev_length = MIN_MATCH - 1;
+ s.match_available = 0;
+ s.ins_h = 0;
+}
+
+
+function DeflateState() {
+ this.strm = null; /* pointer back to this zlib stream */
+ this.status = 0; /* as the name implies */
+ this.pending_buf = null; /* output still pending */
+ this.pending_buf_size = 0; /* size of pending_buf */
+ this.pending_out = 0; /* next pending byte to output to the stream */
+ this.pending = 0; /* nb of bytes in the pending buffer */
+ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
+ this.gzhead = null; /* gzip header information to write */
+ this.gzindex = 0; /* where in extra, name, or comment */
+ this.method = Z_DEFLATED; /* can only be DEFLATED */
+ this.last_flush = -1; /* value of flush param for previous deflate call */
+
+ this.w_size = 0; /* LZ77 window size (32K by default) */
+ this.w_bits = 0; /* log2(w_size) (8..16) */
+ this.w_mask = 0; /* w_size - 1 */
+
+ this.window = null;
+ /* Sliding window. Input bytes are read into the second half of the window,
+ * and move to the first half later to keep a dictionary of at least wSize
+ * bytes. With this organization, matches are limited to a distance of
+ * wSize-MAX_MATCH bytes, but this ensures that IO is always
+ * performed with a length multiple of the block size.
+ */
+
+ this.window_size = 0;
+ /* Actual size of window: 2*wSize, except when the user input buffer
+ * is directly used as sliding window.
+ */
+
+ this.prev = null;
+ /* Link to older string with same hash index. To limit the size of this
+ * array to 64K, this link is maintained only for the last 32K strings.
+ * An index in this array is thus a window index modulo 32K.
+ */
+
+ this.head = null; /* Heads of the hash chains or NIL. */
+
+ this.ins_h = 0; /* hash index of string to be inserted */
+ this.hash_size = 0; /* number of elements in hash table */
+ this.hash_bits = 0; /* log2(hash_size) */
+ this.hash_mask = 0; /* hash_size-1 */
+
+ this.hash_shift = 0;
+ /* Number of bits by which ins_h must be shifted at each input
+ * step. It must be such that after MIN_MATCH steps, the oldest
+ * byte no longer takes part in the hash key, that is:
+ * hash_shift * MIN_MATCH >= hash_bits
+ */
+
+ this.block_start = 0;
+ /* Window position at the beginning of the current output block. Gets
+ * negative when the window is moved backwards.
+ */
+
+ this.match_length = 0; /* length of best match */
+ this.prev_match = 0; /* previous match */
+ this.match_available = 0; /* set if previous match exists */
+ this.strstart = 0; /* start of string to insert */
+ this.match_start = 0; /* start of matching string */
+ this.lookahead = 0; /* number of valid bytes ahead in window */
+
+ this.prev_length = 0;
+ /* Length of the best match at previous step. Matches not greater than this
+ * are discarded. This is used in the lazy match evaluation.
+ */
+
+ this.max_chain_length = 0;
+ /* To speed up deflation, hash chains are never searched beyond this
+ * length. A higher limit improves compression ratio but degrades the
+ * speed.
+ */
+
+ this.max_lazy_match = 0;
+ /* Attempt to find a better match only when the current match is strictly
+ * smaller than this value. This mechanism is used only for compression
+ * levels >= 4.
+ */
+ // That's alias to max_lazy_match, don't use directly
+ //this.max_insert_length = 0;
+ /* Insert new strings in the hash table only if the match length is not
+ * greater than this length. This saves time but degrades compression.
+ * max_insert_length is used only for compression levels <= 3.
+ */
+
+ this.level = 0; /* compression level (1..9) */
+ this.strategy = 0; /* favor or force Huffman coding*/
+
+ this.good_match = 0;
+ /* Use a faster search when the previous match is longer than this */
+
+ this.nice_match = 0; /* Stop searching when current match exceeds this */
+
+ /* used by trees.c: */
+
+ /* Didn't use ct_data typedef below to suppress compiler warning */
+
+ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
+ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
+ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
+
+ // Use flat array of DOUBLE size, with interleaved fata,
+ // because JS does not support effective
+ this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
+ this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
+ this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
+ zero(this.dyn_ltree);
+ zero(this.dyn_dtree);
+ zero(this.bl_tree);
+
+ this.l_desc = null; /* desc. for literal tree */
+ this.d_desc = null; /* desc. for distance tree */
+ this.bl_desc = null; /* desc. for bit length tree */
+
+ //ush bl_count[MAX_BITS+1];
+ this.bl_count = new utils.Buf16(MAX_BITS+1);
+ /* number of codes at each bit length for an optimal tree */
+
+ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
+ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
+ zero(this.heap);
+
+ this.heap_len = 0; /* number of elements in the heap */
+ this.heap_max = 0; /* element of largest frequency */
+ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
+ * The same heap array is used to build all trees.
+ */
+
+ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
+ zero(this.depth);
+ /* Depth of each subtree used as tie breaker for trees of equal frequency
+ */
+
+ this.l_buf = 0; /* buffer index for literals or lengths */
+
+ this.lit_bufsize = 0;
+ /* Size of match buffer for literals/lengths. There are 4 reasons for
+ * limiting lit_bufsize to 64K:
+ * - frequencies can be kept in 16 bit counters
+ * - if compression is not successful for the first block, all input
+ * data is still in the window so we can still emit a stored block even
+ * when input comes from standard input. (This can also be done for
+ * all blocks if lit_bufsize is not greater than 32K.)
+ * - if compression is not successful for a file smaller than 64K, we can
+ * even emit a stored file instead of a stored block (saving 5 bytes).
+ * This is applicable only for zip (not gzip or zlib).
+ * - creating new Huffman trees less frequently may not provide fast
+ * adaptation to changes in the input data statistics. (Take for
+ * example a binary file with poorly compressible code followed by
+ * a highly compressible string table.) Smaller buffer sizes give
+ * fast adaptation but have of course the overhead of transmitting
+ * trees more frequently.
+ * - I can't count above 4
+ */
+
+ this.last_lit = 0; /* running index in l_buf */
+
+ this.d_buf = 0;
+ /* Buffer index for distances. To simplify the code, d_buf and l_buf have
+ * the same number of elements. To use different lengths, an extra flag
+ * array would be necessary.
+ */
+
+ this.opt_len = 0; /* bit length of current block with optimal trees */
+ this.static_len = 0; /* bit length of current block with static trees */
+ this.matches = 0; /* number of string matches in current block */
+ this.insert = 0; /* bytes at end of window left to insert */
+
+
+ this.bi_buf = 0;
+ /* Output buffer. bits are inserted starting at the bottom (least
+ * significant bits).
+ */
+ this.bi_valid = 0;
+ /* Number of valid bits in bi_buf. All bits above the last valid bit
+ * are always zero.
+ */
+
+ // Used for window memory init. We safely ignore it for JS. That makes
+ // sense only for pointers and memory check tools.
+ //this.high_water = 0;
+ /* High water mark offset in window for initialized bytes -- bytes above
+ * this are set to zero in order to avoid memory check warnings when
+ * longest match routines access bytes past the input. This is then
+ * updated to the new high water mark.
+ */
+}
+
+
+function deflateResetKeep(strm) {
+ var s;
+
+ if (!strm || !strm.state) {
+ return err(strm, Z_STREAM_ERROR);
+ }
+
+ strm.total_in = strm.total_out = 0;
+ strm.data_type = Z_UNKNOWN;
+
+ s = strm.state;
+ s.pending = 0;
+ s.pending_out = 0;
+
+ if (s.wrap < 0) {
+ s.wrap = -s.wrap;
+ /* was made negative by deflate(..., Z_FINISH); */
+ }
+ s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
+ strm.adler = (s.wrap === 2) ?
+ 0 // crc32(0, Z_NULL, 0)
+ :
+ 1; // adler32(0, Z_NULL, 0)
+ s.last_flush = Z_NO_FLUSH;
+ trees._tr_init(s);
+ return Z_OK;
+}
+
+
+function deflateReset(strm) {
+ var ret = deflateResetKeep(strm);
+ if (ret === Z_OK) {
+ lm_init(strm.state);
+ }
+ return ret;
+}
+
+
+function deflateSetHeader(strm, head) {
+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }
+ if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
+ strm.state.gzhead = head;
+ return Z_OK;
+}
+
+
+function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
+ if (!strm) { // === Z_NULL
+ return Z_STREAM_ERROR;
+ }
+ var wrap = 1;
+
+ if (level === Z_DEFAULT_COMPRESSION) {
+ level = 6;
+ }
+
+ if (windowBits < 0) { /* suppress zlib wrapper */
+ wrap = 0;
+ windowBits = -windowBits;
+ }
+
+ else if (windowBits > 15) {
+ wrap = 2; /* write gzip wrapper instead */
+ windowBits -= 16;
+ }
+
+
+ if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
+ windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
+ strategy < 0 || strategy > Z_FIXED) {
+ return err(strm, Z_STREAM_ERROR);
+ }
+
+
+ if (windowBits === 8) {
+ windowBits = 9;
+ }
+ /* until 256-byte window bug fixed */
+
+ var s = new DeflateState();
+
+ strm.state = s;
+ s.strm = strm;
+
+ s.wrap = wrap;
+ s.gzhead = null;
+ s.w_bits = windowBits;
+ s.w_size = 1 << s.w_bits;
+ s.w_mask = s.w_size - 1;
+
+ s.hash_bits = memLevel + 7;
+ s.hash_size = 1 << s.hash_bits;
+ s.hash_mask = s.hash_size - 1;
+ s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
+
+ s.window = new utils.Buf8(s.w_size * 2);
+ s.head = new utils.Buf16(s.hash_size);
+ s.prev = new utils.Buf16(s.w_size);
+
+ // Don't need mem init magic for JS.
+ //s.high_water = 0; /* nothing written to s->window yet */
+
+ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
+
+ s.pending_buf_size = s.lit_bufsize * 4;
+ s.pending_buf = new utils.Buf8(s.pending_buf_size);
+
+ s.d_buf = s.lit_bufsize >> 1;
+ s.l_buf = (1 + 2) * s.lit_bufsize;
+
+ s.level = level;
+ s.strategy = strategy;
+ s.method = method;
+
+ return deflateReset(strm);
+}
+
+function deflateInit(strm, level) {
+ return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
+}
+
+
+function deflate(strm, flush) {
+ var old_flush, s;
+ var beg, val; // for gzip header write only
+
+ if (!strm || !strm.state ||
+ flush > Z_BLOCK || flush < 0) {
+ return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
+ }
+
+ s = strm.state;
+
+ if (!strm.output ||
+ (!strm.input && strm.avail_in !== 0) ||
+ (s.status === FINISH_STATE && flush !== Z_FINISH)) {
+ return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
+ }
+
+ s.strm = strm; /* just in case */
+ old_flush = s.last_flush;
+ s.last_flush = flush;
+
+ /* Write the header */
+ if (s.status === INIT_STATE) {
+
+ if (s.wrap === 2) { // GZIP header
+ strm.adler = 0; //crc32(0L, Z_NULL, 0);
+ put_byte(s, 31);
+ put_byte(s, 139);
+ put_byte(s, 8);
+ if (!s.gzhead) { // s->gzhead == Z_NULL
+ put_byte(s, 0);
+ put_byte(s, 0);
+ put_byte(s, 0);
+ put_byte(s, 0);
+ put_byte(s, 0);
+ put_byte(s, s.level === 9 ? 2 :
+ (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
+ 4 : 0));
+ put_byte(s, OS_CODE);
+ s.status = BUSY_STATE;
+ }
+ else {
+ put_byte(s, (s.gzhead.text ? 1 : 0) +
+ (s.gzhead.hcrc ? 2 : 0) +
+ (!s.gzhead.extra ? 0 : 4) +
+ (!s.gzhead.name ? 0 : 8) +
+ (!s.gzhead.comment ? 0 : 16)
+ );
+ put_byte(s, s.gzhead.time & 0xff);
+ put_byte(s, (s.gzhead.time >> 8) & 0xff);
+ put_byte(s, (s.gzhead.time >> 16) & 0xff);
+ put_byte(s, (s.gzhead.time >> 24) & 0xff);
+ put_byte(s, s.level === 9 ? 2 :
+ (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
+ 4 : 0));
+ put_byte(s, s.gzhead.os & 0xff);
+ if (s.gzhead.extra && s.gzhead.extra.length) {
+ put_byte(s, s.gzhead.extra.length & 0xff);
+ put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
+ }
+ if (s.gzhead.hcrc) {
+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
+ }
+ s.gzindex = 0;
+ s.status = EXTRA_STATE;
+ }
+ }
+ else // DEFLATE header
+ {
+ var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
+ var level_flags = -1;
+
+ if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
+ level_flags = 0;
+ } else if (s.level < 6) {
+ level_flags = 1;
+ } else if (s.level === 6) {
+ level_flags = 2;
+ } else {
+ level_flags = 3;
+ }
+ header |= (level_flags << 6);
+ if (s.strstart !== 0) { header |= PRESET_DICT; }
+ header += 31 - (header % 31);
+
+ s.status = BUSY_STATE;
+ putShortMSB(s, header);
+
+ /* Save the adler32 of the preset dictionary: */
+ if (s.strstart !== 0) {
+ putShortMSB(s, strm.adler >>> 16);
+ putShortMSB(s, strm.adler & 0xffff);
+ }
+ strm.adler = 1; // adler32(0L, Z_NULL, 0);
+ }
+ }
+
+//#ifdef GZIP
+ if (s.status === EXTRA_STATE) {
+ if (s.gzhead.extra/* != Z_NULL*/) {
+ beg = s.pending; /* start of bytes to update crc */
+
+ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
+ if (s.pending === s.pending_buf_size) {
+ if (s.gzhead.hcrc && s.pending > beg) {
+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
+ }
+ flush_pending(strm);
+ beg = s.pending;
+ if (s.pending === s.pending_buf_size) {
+ break;
+ }
+ }
+ put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
+ s.gzindex++;
+ }
+ if (s.gzhead.hcrc && s.pending > beg) {
+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
+ }
+ if (s.gzindex === s.gzhead.extra.length) {
+ s.gzindex = 0;
+ s.status = NAME_STATE;
+ }
+ }
+ else {
+ s.status = NAME_STATE;
+ }
+ }
+ if (s.status === NAME_STATE) {
+ if (s.gzhead.name/* != Z_NULL*/) {
+ beg = s.pending; /* start of bytes to update crc */
+ //int val;
+
+ do {
+ if (s.pending === s.pending_buf_size) {
+ if (s.gzhead.hcrc && s.pending > beg) {
+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
+ }
+ flush_pending(strm);
+ beg = s.pending;
+ if (s.pending === s.pending_buf_size) {
+ val = 1;
+ break;
+ }
+ }
+ // JS specific: little magic to add zero terminator to end of string
+ if (s.gzindex < s.gzhead.name.length) {
+ val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
+ } else {
+ val = 0;
+ }
+ put_byte(s, val);
+ } while (val !== 0);
+
+ if (s.gzhead.hcrc && s.pending > beg) {
+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
+ }
+ if (val === 0) {
+ s.gzindex = 0;
+ s.status = COMMENT_STATE;
+ }
+ }
+ else {
+ s.status = COMMENT_STATE;
+ }
+ }
+ if (s.status === COMMENT_STATE) {
+ if (s.gzhead.comment/* != Z_NULL*/) {
+ beg = s.pending; /* start of bytes to update crc */
+ //int val;
+
+ do {
+ if (s.pending === s.pending_buf_size) {
+ if (s.gzhead.hcrc && s.pending > beg) {
+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
+ }
+ flush_pending(strm);
+ beg = s.pending;
+ if (s.pending === s.pending_buf_size) {
+ val = 1;
+ break;
+ }
+ }
+ // JS specific: little magic to add zero terminator to end of string
+ if (s.gzindex < s.gzhead.comment.length) {
+ val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
+ } else {
+ val = 0;
+ }
+ put_byte(s, val);
+ } while (val !== 0);
+
+ if (s.gzhead.hcrc && s.pending > beg) {
+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
+ }
+ if (val === 0) {
+ s.status = HCRC_STATE;
+ }
+ }
+ else {
+ s.status = HCRC_STATE;
+ }
+ }
+ if (s.status === HCRC_STATE) {
+ if (s.gzhead.hcrc) {
+ if (s.pending + 2 > s.pending_buf_size) {
+ flush_pending(strm);
+ }
+ if (s.pending + 2 <= s.pending_buf_size) {
+ put_byte(s, strm.adler & 0xff);
+ put_byte(s, (strm.adler >> 8) & 0xff);
+ strm.adler = 0; //crc32(0L, Z_NULL, 0);
+ s.status = BUSY_STATE;
+ }
+ }
+ else {
+ s.status = BUSY_STATE;
+ }
+ }
+//#endif
+
+ /* Flush as much pending output as possible */
+ if (s.pending !== 0) {
+ flush_pending(strm);
+ if (strm.avail_out === 0) {
+ /* Since avail_out is 0, deflate will be called again with
+ * more output space, but possibly with both pending and
+ * avail_in equal to zero. There won't be anything to do,
+ * but this is not an error situation so make sure we
+ * return OK instead of BUF_ERROR at next call of deflate:
+ */
+ s.last_flush = -1;
+ return Z_OK;
+ }
+
+ /* Make sure there is something to do and avoid duplicate consecutive
+ * flushes. For repeated and useless calls with Z_FINISH, we keep
+ * returning Z_STREAM_END instead of Z_BUF_ERROR.
+ */
+ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
+ flush !== Z_FINISH) {
+ return err(strm, Z_BUF_ERROR);
+ }
+
+ /* User must not provide more input after the first FINISH: */
+ if (s.status === FINISH_STATE && strm.avail_in !== 0) {
+ return err(strm, Z_BUF_ERROR);
+ }
+
+ /* Start a new block or continue the current one.
+ */
+ if (strm.avail_in !== 0 || s.lookahead !== 0 ||
+ (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
+ var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
+ (s.strategy === Z_RLE ? deflate_rle(s, flush) :
+ configuration_table[s.level].func(s, flush));
+
+ if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
+ s.status = FINISH_STATE;
+ }
+ if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
+ if (strm.avail_out === 0) {
+ s.last_flush = -1;
+ /* avoid BUF_ERROR next call, see above */
+ }
+ return Z_OK;
+ /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
+ * of deflate should use the same flush parameter to make sure
+ * that the flush is complete. So we don't have to output an
+ * empty block here, this will be done at next call. This also
+ * ensures that for a very small output buffer, we emit at most
+ * one empty block.
+ */
+ }
+ if (bstate === BS_BLOCK_DONE) {
+ if (flush === Z_PARTIAL_FLUSH) {
+ trees._tr_align(s);
+ }
+ else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
+
+ trees._tr_stored_block(s, 0, 0, false);
+ /* For a full flush, this empty block will be recognized
+ * as a special marker by inflate_sync().
+ */
+ if (flush === Z_FULL_FLUSH) {
+ /*** CLEAR_HASH(s); ***/ /* forget history */
+ zero(s.head); // Fill with NIL (= 0);
+
+ if (s.lookahead === 0) {
+ s.strstart = 0;
+ s.block_start = 0;
+ s.insert = 0;
+ }
+ }
+ }
+ flush_pending(strm);
+ if (strm.avail_out === 0) {
+ s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
+ return Z_OK;
+ }
+ }
+ }
+ //Assert(strm->avail_out > 0, "bug2");
+ //if (strm.avail_out <= 0) { throw new Error("bug2");}
+
+ if (flush !== Z_FINISH) { return Z_OK; }
+ if (s.wrap <= 0) { return Z_STREAM_END; }
+
+ /* Write the trailer */
+ if (s.wrap === 2) {
+ put_byte(s, strm.adler & 0xff);
+ put_byte(s, (strm.adler >> 8) & 0xff);
+ put_byte(s, (strm.adler >> 16) & 0xff);
+ put_byte(s, (strm.adler >> 24) & 0xff);
+ put_byte(s, strm.total_in & 0xff);
+ put_byte(s, (strm.total_in >> 8) & 0xff);
+ put_byte(s, (strm.total_in >> 16) & 0xff);
+ put_byte(s, (strm.total_in >> 24) & 0xff);
+ }
+ else
+ {
+ putShortMSB(s, strm.adler >>> 16);
+ putShortMSB(s, strm.adler & 0xffff);
+ }
+
+ flush_pending(strm);
+ /* If avail_out is zero, the application will call deflate again
+ * to flush the rest.
+ */
+ if (s.wrap > 0) { s.wrap = -s.wrap; }
+ /* write the trailer only once! */
+ return s.pending !== 0 ? Z_OK : Z_STREAM_END;
+}
+
+function deflateEnd(strm) {
+ var status;
+
+ if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
+ return Z_STREAM_ERROR;
+ }
+
+ status = strm.state.status;
+ if (status !== INIT_STATE &&
+ status !== EXTRA_STATE &&
+ status !== NAME_STATE &&
+ status !== COMMENT_STATE &&
+ status !== HCRC_STATE &&
+ status !== BUSY_STATE &&
+ status !== FINISH_STATE
+ ) {
+ return err(strm, Z_STREAM_ERROR);
+ }
+
+ strm.state = null;
+
+ return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
+}
+
+/* =========================================================================
+ * Copy the source state to the destination state
+ */
+//function deflateCopy(dest, source) {
+//
+//}
+
+exports.deflateInit = deflateInit;
+exports.deflateInit2 = deflateInit2;
+exports.deflateReset = deflateReset;
+exports.deflateResetKeep = deflateResetKeep;
+exports.deflateSetHeader = deflateSetHeader;
+exports.deflate = deflate;
+exports.deflateEnd = deflateEnd;
+exports.deflateInfo = 'pako deflate (from Nodeca project)';
+
+/* Not implemented
+exports.deflateBound = deflateBound;
+exports.deflateCopy = deflateCopy;
+exports.deflateSetDictionary = deflateSetDictionary;
+exports.deflateParams = deflateParams;
+exports.deflatePending = deflatePending;
+exports.deflatePrime = deflatePrime;
+exports.deflateTune = deflateTune;
+*/
+
+},{"../utils/common":32,"./adler32":34,"./crc32":36,"./messages":42,"./trees":43}],38:[function(require,module,exports){
+'use strict';
+
+
+function GZheader() {
+ /* true if compressed data believed to be text */
+ this.text = 0;
+ /* modification time */
+ this.time = 0;
+ /* extra flags (not used when writing a gzip file) */
+ this.xflags = 0;
+ /* operating system */
+ this.os = 0;
+ /* pointer to extra field or Z_NULL if none */
+ this.extra = null;
+ /* extra field length (valid if extra != Z_NULL) */
+ this.extra_len = 0; // Actually, we don't need it in JS,
+ // but leave for few code modifications
+
+ //
+ // Setup limits is not necessary because in js we should not preallocate memory
+ // for inflate use constant limit in 65536 bytes
+ //
+
+ /* space at extra (only when reading header) */
+ // this.extra_max = 0;
+ /* pointer to zero-terminated file name or Z_NULL */
+ this.name = '';
+ /* space at name (only when reading header) */
+ // this.name_max = 0;
+ /* pointer to zero-terminated comment or Z_NULL */
+ this.comment = '';
+ /* space at comment (only when reading header) */
+ // this.comm_max = 0;
+ /* true if there was or will be a header crc */
+ this.hcrc = 0;
+ /* true when done reading gzip header (not used when writing a gzip file) */
+ this.done = false;
+}
+
+module.exports = GZheader;
+
+},{}],39:[function(require,module,exports){
+'use strict';
+
+// See state defs from inflate.js
+var BAD = 30; /* got a data error -- remain here until reset */
+var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
+
+/*
+ Decode literal, length, and distance codes and write out the resulting
+ literal and match bytes until either not enough input or output is
+ available, an end-of-block is encountered, or a data error is encountered.
+ When large enough input and output buffers are supplied to inflate(), for
+ example, a 16K input buffer and a 64K output buffer, more than 95% of the
+ inflate execution time is spent in this routine.
+
+ Entry assumptions:
+
+ state.mode === LEN
+ strm.avail_in >= 6
+ strm.avail_out >= 258
+ start >= strm.avail_out
+ state.bits < 8
+
+ On return, state.mode is one of:
+
+ LEN -- ran out of enough output space or enough available input
+ TYPE -- reached end of block code, inflate() to interpret next block
+ BAD -- error in block data
+
+ Notes:
+
+ - The maximum input bits used by a length/distance pair is 15 bits for the
+ length code, 5 bits for the length extra, 15 bits for the distance code,
+ and 13 bits for the distance extra. This totals 48 bits, or six bytes.
+ Therefore if strm.avail_in >= 6, then there is enough input to avoid
+ checking for available input while decoding.
+
+ - The maximum bytes that a single length/distance pair can output is 258
+ bytes, which is the maximum length that can be coded. inflate_fast()
+ requires strm.avail_out >= 258 for each loop to avoid checking for
+ output space.
+ */
+module.exports = function inflate_fast(strm, start) {
+ var state;
+ var _in; /* local strm.input */
+ var last; /* have enough input while in < last */
+ var _out; /* local strm.output */
+ var beg; /* inflate()'s initial strm.output */
+ var end; /* while out < end, enough space available */
+//#ifdef INFLATE_STRICT
+ var dmax; /* maximum distance from zlib header */
+//#endif
+ var wsize; /* window size or zero if not using window */
+ var whave; /* valid bytes in the window */
+ var wnext; /* window write index */
+ // Use `s_window` instead `window`, avoid conflict with instrumentation tools
+ var s_window; /* allocated sliding window, if wsize != 0 */
+ var hold; /* local strm.hold */
+ var bits; /* local strm.bits */
+ var lcode; /* local strm.lencode */
+ var dcode; /* local strm.distcode */
+ var lmask; /* mask for first level of length codes */
+ var dmask; /* mask for first level of distance codes */
+ var here; /* retrieved table entry */
+ var op; /* code bits, operation, extra bits, or */
+ /* window position, window bytes to copy */
+ var len; /* match length, unused bytes */
+ var dist; /* match distance */
+ var from; /* where to copy match from */
+ var from_source;
+
+
+ var input, output; // JS specific, because we have no pointers
+
+ /* copy state to local variables */
+ state = strm.state;
+ //here = state.here;
+ _in = strm.next_in;
+ input = strm.input;
+ last = _in + (strm.avail_in - 5);
+ _out = strm.next_out;
+ output = strm.output;
+ beg = _out - (start - strm.avail_out);
+ end = _out + (strm.avail_out - 257);
+//#ifdef INFLATE_STRICT
+ dmax = state.dmax;
+//#endif
+ wsize = state.wsize;
+ whave = state.whave;
+ wnext = state.wnext;
+ s_window = state.window;
+ hold = state.hold;
+ bits = state.bits;
+ lcode = state.lencode;
+ dcode = state.distcode;
+ lmask = (1 << state.lenbits) - 1;
+ dmask = (1 << state.distbits) - 1;
+
+
+ /* decode literals and length/distances until end-of-block or not enough
+ input data or output space */
+
+ top:
+ do {
+ if (bits < 15) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ hold += input[_in++] << bits;
+ bits += 8;
+ }
+
+ here = lcode[hold & lmask];
+
+ dolen:
+ for (;;) { // Goto emulation
+ op = here >>> 24/*here.bits*/;
+ hold >>>= op;
+ bits -= op;
+ op = (here >>> 16) & 0xff/*here.op*/;
+ if (op === 0) { /* literal */
+ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+ // "inflate: literal '%c'\n" :
+ // "inflate: literal 0x%02x\n", here.val));
+ output[_out++] = here & 0xffff/*here.val*/;
+ }
+ else if (op & 16) { /* length base */
+ len = here & 0xffff/*here.val*/;
+ op &= 15; /* number of extra bits */
+ if (op) {
+ if (bits < op) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ }
+ len += hold & ((1 << op) - 1);
+ hold >>>= op;
+ bits -= op;
+ }
+ //Tracevv((stderr, "inflate: length %u\n", len));
+ if (bits < 15) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ hold += input[_in++] << bits;
+ bits += 8;
+ }
+ here = dcode[hold & dmask];
+
+ dodist:
+ for (;;) { // goto emulation
+ op = here >>> 24/*here.bits*/;
+ hold >>>= op;
+ bits -= op;
+ op = (here >>> 16) & 0xff/*here.op*/;
+
+ if (op & 16) { /* distance base */
+ dist = here & 0xffff/*here.val*/;
+ op &= 15; /* number of extra bits */
+ if (bits < op) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ if (bits < op) {
+ hold += input[_in++] << bits;
+ bits += 8;
+ }
+ }
+ dist += hold & ((1 << op) - 1);
+//#ifdef INFLATE_STRICT
+ if (dist > dmax) {
+ strm.msg = 'invalid distance too far back';
+ state.mode = BAD;
+ break top;
+ }
+//#endif
+ hold >>>= op;
+ bits -= op;
+ //Tracevv((stderr, "inflate: distance %u\n", dist));
+ op = _out - beg; /* max distance in output */
+ if (dist > op) { /* see if copy from window */
+ op = dist - op; /* distance back in window */
+ if (op > whave) {
+ if (state.sane) {
+ strm.msg = 'invalid distance too far back';
+ state.mode = BAD;
+ break top;
+ }
+
+// (!) This block is disabled in zlib defailts,
+// don't enable it for binary compatibility
+//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+// if (len <= op - whave) {
+// do {
+// output[_out++] = 0;
+// } while (--len);
+// continue top;
+// }
+// len -= op - whave;
+// do {
+// output[_out++] = 0;
+// } while (--op > whave);
+// if (op === 0) {
+// from = _out - dist;
+// do {
+// output[_out++] = output[from++];
+// } while (--len);
+// continue top;
+// }
+//#endif
+ }
+ from = 0; // window index
+ from_source = s_window;
+ if (wnext === 0) { /* very common case */
+ from += wsize - op;
+ if (op < len) { /* some from window */
+ len -= op;
+ do {
+ output[_out++] = s_window[from++];
+ } while (--op);
+ from = _out - dist; /* rest from output */
+ from_source = output;
+ }
+ }
+ else if (wnext < op) { /* wrap around window */
+ from += wsize + wnext - op;
+ op -= wnext;
+ if (op < len) { /* some from end of window */
+ len -= op;
+ do {
+ output[_out++] = s_window[from++];
+ } while (--op);
+ from = 0;
+ if (wnext < len) { /* some from start of window */
+ op = wnext;
+ len -= op;
+ do {
+ output[_out++] = s_window[from++];
+ } while (--op);
+ from = _out - dist; /* rest from output */
+ from_source = output;
+ }
+ }
+ }
+ else { /* contiguous in window */
+ from += wnext - op;
+ if (op < len) { /* some from window */
+ len -= op;
+ do {
+ output[_out++] = s_window[from++];
+ } while (--op);
+ from = _out - dist; /* rest from output */
+ from_source = output;
+ }
+ }
+ while (len > 2) {
+ output[_out++] = from_source[from++];
+ output[_out++] = from_source[from++];
+ output[_out++] = from_source[from++];
+ len -= 3;
+ }
+ if (len) {
+ output[_out++] = from_source[from++];
+ if (len > 1) {
+ output[_out++] = from_source[from++];
+ }
+ }
+ }
+ else {
+ from = _out - dist; /* copy direct from output */
+ do { /* minimum length is three */
+ output[_out++] = output[from++];
+ output[_out++] = output[from++];
+ output[_out++] = output[from++];
+ len -= 3;
+ } while (len > 2);
+ if (len) {
+ output[_out++] = output[from++];
+ if (len > 1) {
+ output[_out++] = output[from++];
+ }
+ }
+ }
+ }
+ else if ((op & 64) === 0) { /* 2nd level distance code */
+ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
+ continue dodist;
+ }
+ else {
+ strm.msg = 'invalid distance code';
+ state.mode = BAD;
+ break top;
+ }
+
+ break; // need to emulate goto via "continue"
+ }
+ }
+ else if ((op & 64) === 0) { /* 2nd level length code */
+ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
+ continue dolen;
+ }
+ else if (op & 32) { /* end-of-block */
+ //Tracevv((stderr, "inflate: end of block\n"));
+ state.mode = TYPE;
+ break top;
+ }
+ else {
+ strm.msg = 'invalid literal/length code';
+ state.mode = BAD;
+ break top;
+ }
+
+ break; // need to emulate goto via "continue"
+ }
+ } while (_in < last && _out < end);
+
+ /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
+ len = bits >> 3;
+ _in -= len;
+ bits -= len << 3;
+ hold &= (1 << bits) - 1;
+
+ /* update state and return */
+ strm.next_in = _in;
+ strm.next_out = _out;
+ strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
+ strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
+ state.hold = hold;
+ state.bits = bits;
+ return;
+};
+
+},{}],40:[function(require,module,exports){
+'use strict';
+
+
+var utils = require('../utils/common');
+var adler32 = require('./adler32');
+var crc32 = require('./crc32');
+var inflate_fast = require('./inffast');
+var inflate_table = require('./inftrees');
+
+var CODES = 0;
+var LENS = 1;
+var DISTS = 2;
+
+/* Public constants ==========================================================*/
+/* ===========================================================================*/
+
+
+/* Allowed flush values; see deflate() and inflate() below for details */
+//var Z_NO_FLUSH = 0;
+//var Z_PARTIAL_FLUSH = 1;
+//var Z_SYNC_FLUSH = 2;
+//var Z_FULL_FLUSH = 3;
+var Z_FINISH = 4;
+var Z_BLOCK = 5;
+var Z_TREES = 6;
+
+
+/* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
+ */
+var Z_OK = 0;
+var Z_STREAM_END = 1;
+var Z_NEED_DICT = 2;
+//var Z_ERRNO = -1;
+var Z_STREAM_ERROR = -2;
+var Z_DATA_ERROR = -3;
+var Z_MEM_ERROR = -4;
+var Z_BUF_ERROR = -5;
+//var Z_VERSION_ERROR = -6;
+
+/* The deflate compression method */
+var Z_DEFLATED = 8;
+
+
+/* STATES ====================================================================*/
+/* ===========================================================================*/
+
+
+var HEAD = 1; /* i: waiting for magic header */
+var FLAGS = 2; /* i: waiting for method and flags (gzip) */
+var TIME = 3; /* i: waiting for modification time (gzip) */
+var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
+var EXLEN = 5; /* i: waiting for extra length (gzip) */
+var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
+var NAME = 7; /* i: waiting for end of file name (gzip) */
+var COMMENT = 8; /* i: waiting for end of comment (gzip) */
+var HCRC = 9; /* i: waiting for header crc (gzip) */
+var DICTID = 10; /* i: waiting for dictionary check value */
+var DICT = 11; /* waiting for inflateSetDictionary() call */
+var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
+var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
+var STORED = 14; /* i: waiting for stored size (length and complement) */
+var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
+var COPY = 16; /* i/o: waiting for input or output to copy stored block */
+var TABLE = 17; /* i: waiting for dynamic block table lengths */
+var LENLENS = 18; /* i: waiting for code length code lengths */
+var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
+var LEN_ = 20; /* i: same as LEN below, but only first time in */
+var LEN = 21; /* i: waiting for length/lit/eob code */
+var LENEXT = 22; /* i: waiting for length extra bits */
+var DIST = 23; /* i: waiting for distance code */
+var DISTEXT = 24; /* i: waiting for distance extra bits */
+var MATCH = 25; /* o: waiting for output space to copy string */
+var LIT = 26; /* o: waiting for output space to write literal */
+var CHECK = 27; /* i: waiting for 32-bit check value */
+var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
+var DONE = 29; /* finished check, done -- remain here until reset */
+var BAD = 30; /* got a data error -- remain here until reset */
+var MEM = 31; /* got an inflate() memory error -- remain here until reset */
+var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
+
+/* ===========================================================================*/
+
+
+
+var ENOUGH_LENS = 852;
+var ENOUGH_DISTS = 592;
+//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
+
+var MAX_WBITS = 15;
+/* 32K LZ77 window */
+var DEF_WBITS = MAX_WBITS;
+
+
+function ZSWAP32(q) {
+ return (((q >>> 24) & 0xff) +
+ ((q >>> 8) & 0xff00) +
+ ((q & 0xff00) << 8) +
+ ((q & 0xff) << 24));
+}
+
+
+function InflateState() {
+ this.mode = 0; /* current inflate mode */
+ this.last = false; /* true if processing last block */
+ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
+ this.havedict = false; /* true if dictionary provided */
+ this.flags = 0; /* gzip header method and flags (0 if zlib) */
+ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
+ this.check = 0; /* protected copy of check value */
+ this.total = 0; /* protected copy of output count */
+ // TODO: may be {}
+ this.head = null; /* where to save gzip header information */
+
+ /* sliding window */
+ this.wbits = 0; /* log base 2 of requested window size */
+ this.wsize = 0; /* window size or zero if not using window */
+ this.whave = 0; /* valid bytes in the window */
+ this.wnext = 0; /* window write index */
+ this.window = null; /* allocated sliding window, if needed */
+
+ /* bit accumulator */
+ this.hold = 0; /* input bit accumulator */
+ this.bits = 0; /* number of bits in "in" */
+
+ /* for string and stored block copying */
+ this.length = 0; /* literal or length of data to copy */
+ this.offset = 0; /* distance back to copy string from */
+
+ /* for table and code decoding */
+ this.extra = 0; /* extra bits needed */
+
+ /* fixed and dynamic code tables */
+ this.lencode = null; /* starting table for length/literal codes */
+ this.distcode = null; /* starting table for distance codes */
+ this.lenbits = 0; /* index bits for lencode */
+ this.distbits = 0; /* index bits for distcode */
+
+ /* dynamic table building */
+ this.ncode = 0; /* number of code length code lengths */
+ this.nlen = 0; /* number of length code lengths */
+ this.ndist = 0; /* number of distance code lengths */
+ this.have = 0; /* number of code lengths in lens[] */
+ this.next = null; /* next available space in codes[] */
+
+ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
+ this.work = new utils.Buf16(288); /* work area for code table building */
+
+ /*
+ because we don't have pointers in js, we use lencode and distcode directly
+ as buffers so we don't need codes
+ */
+ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
+ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
+ this.distdyn = null; /* dynamic table for distance codes (JS specific) */
+ this.sane = 0; /* if false, allow invalid distance too far */
+ this.back = 0; /* bits back of last unprocessed length/lit */
+ this.was = 0; /* initial length of match */
+}
+
+function inflateResetKeep(strm) {
+ var state;
+
+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }
+ state = strm.state;
+ strm.total_in = strm.total_out = state.total = 0;
+ strm.msg = ''; /*Z_NULL*/
+ if (state.wrap) { /* to support ill-conceived Java test suite */
+ strm.adler = state.wrap & 1;
+ }
+ state.mode = HEAD;
+ state.last = 0;
+ state.havedict = 0;
+ state.dmax = 32768;
+ state.head = null/*Z_NULL*/;
+ state.hold = 0;
+ state.bits = 0;
+ //state.lencode = state.distcode = state.next = state.codes;
+ state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
+ state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
+
+ state.sane = 1;
+ state.back = -1;
+ //Tracev((stderr, "inflate: reset\n"));
+ return Z_OK;
+}
+
+function inflateReset(strm) {
+ var state;
+
+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }
+ state = strm.state;
+ state.wsize = 0;
+ state.whave = 0;
+ state.wnext = 0;
+ return inflateResetKeep(strm);
+
+}
+
+function inflateReset2(strm, windowBits) {
+ var wrap;
+ var state;
+
+ /* get the state */
+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }
+ state = strm.state;
+
+ /* extract wrap request from windowBits parameter */
+ if (windowBits < 0) {
+ wrap = 0;
+ windowBits = -windowBits;
+ }
+ else {
+ wrap = (windowBits >> 4) + 1;
+ if (windowBits < 48) {
+ windowBits &= 15;
+ }
+ }
+
+ /* set number of window bits, free window if different */
+ if (windowBits && (windowBits < 8 || windowBits > 15)) {
+ return Z_STREAM_ERROR;
+ }
+ if (state.window !== null && state.wbits !== windowBits) {
+ state.window = null;
+ }
+
+ /* update state and reset the rest of it */
+ state.wrap = wrap;
+ state.wbits = windowBits;
+ return inflateReset(strm);
+}
+
+function inflateInit2(strm, windowBits) {
+ var ret;
+ var state;
+
+ if (!strm) { return Z_STREAM_ERROR; }
+ //strm.msg = Z_NULL; /* in case we return an error */
+
+ state = new InflateState();
+
+ //if (state === Z_NULL) return Z_MEM_ERROR;
+ //Tracev((stderr, "inflate: allocated\n"));
+ strm.state = state;
+ state.window = null/*Z_NULL*/;
+ ret = inflateReset2(strm, windowBits);
+ if (ret !== Z_OK) {
+ strm.state = null/*Z_NULL*/;
+ }
+ return ret;
+}
+
+function inflateInit(strm) {
+ return inflateInit2(strm, DEF_WBITS);
+}
+
+
+/*
+ Return state with length and distance decoding tables and index sizes set to
+ fixed code decoding. Normally this returns fixed tables from inffixed.h.
+ If BUILDFIXED is defined, then instead this routine builds the tables the
+ first time it's called, and returns those tables the first time and
+ thereafter. This reduces the size of the code by about 2K bytes, in
+ exchange for a little execution time. However, BUILDFIXED should not be
+ used for threaded applications, since the rewriting of the tables and virgin
+ may not be thread-safe.
+ */
+var virgin = true;
+
+var lenfix, distfix; // We have no pointers in JS, so keep tables separate
+
+function fixedtables(state) {
+ /* build fixed huffman tables if first call (may not be thread safe) */
+ if (virgin) {
+ var sym;
+
+ lenfix = new utils.Buf32(512);
+ distfix = new utils.Buf32(32);
+
+ /* literal/length table */
+ sym = 0;
+ while (sym < 144) { state.lens[sym++] = 8; }
+ while (sym < 256) { state.lens[sym++] = 9; }
+ while (sym < 280) { state.lens[sym++] = 7; }
+ while (sym < 288) { state.lens[sym++] = 8; }
+
+ inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
+
+ /* distance table */
+ sym = 0;
+ while (sym < 32) { state.lens[sym++] = 5; }
+
+ inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
+
+ /* do this just once */
+ virgin = false;
+ }
+
+ state.lencode = lenfix;
+ state.lenbits = 9;
+ state.distcode = distfix;
+ state.distbits = 5;
+}
+
+
+/*
+ Update the window with the last wsize (normally 32K) bytes written before
+ returning. If window does not exist yet, create it. This is only called
+ when a window is already in use, or when output has been written during this
+ inflate call, but the end of the deflate stream has not been reached yet.
+ It is also called to create a window for dictionary data when a dictionary
+ is loaded.
+
+ Providing output buffers larger than 32K to inflate() should provide a speed
+ advantage, since only the last 32K of output is copied to the sliding window
+ upon return from inflate(), and since all distances after the first 32K of
+ output will fall in the output data, making match copies simpler and faster.
+ The advantage may be dependent on the size of the processor's data caches.
+ */
+function updatewindow(strm, src, end, copy) {
+ var dist;
+ var state = strm.state;
+
+ /* if it hasn't been done already, allocate space for the window */
+ if (state.window === null) {
+ state.wsize = 1 << state.wbits;
+ state.wnext = 0;
+ state.whave = 0;
+
+ state.window = new utils.Buf8(state.wsize);
+ }
+
+ /* copy state->wsize or less output bytes into the circular window */
+ if (copy >= state.wsize) {
+ utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
+ state.wnext = 0;
+ state.whave = state.wsize;
+ }
+ else {
+ dist = state.wsize - state.wnext;
+ if (dist > copy) {
+ dist = copy;
+ }
+ //zmemcpy(state->window + state->wnext, end - copy, dist);
+ utils.arraySet(state.window,src, end - copy, dist, state.wnext);
+ copy -= dist;
+ if (copy) {
+ //zmemcpy(state->window, end - copy, copy);
+ utils.arraySet(state.window,src, end - copy, copy, 0);
+ state.wnext = copy;
+ state.whave = state.wsize;
+ }
+ else {
+ state.wnext += dist;
+ if (state.wnext === state.wsize) { state.wnext = 0; }
+ if (state.whave < state.wsize) { state.whave += dist; }
+ }
+ }
+ return 0;
+}
+
+function inflate(strm, flush) {
+ var state;
+ var input, output; // input/output buffers
+ var next; /* next input INDEX */
+ var put; /* next output INDEX */
+ var have, left; /* available input and output */
+ var hold; /* bit buffer */
+ var bits; /* bits in bit buffer */
+ var _in, _out; /* save starting available input and output */
+ var copy; /* number of stored or match bytes to copy */
+ var from; /* where to copy match bytes from */
+ var from_source;
+ var here = 0; /* current decoding table entry */
+ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
+ //var last; /* parent table entry */
+ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
+ var len; /* length to copy for repeats, bits to drop */
+ var ret; /* return code */
+ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
+ var opts;
+
+ var n; // temporary var for NEED_BITS
+
+ var order = /* permutation of code lengths */
+ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
+
+
+ if (!strm || !strm.state || !strm.output ||
+ (!strm.input && strm.avail_in !== 0)) {
+ return Z_STREAM_ERROR;
+ }
+
+ state = strm.state;
+ if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
+
+
+ //--- LOAD() ---
+ put = strm.next_out;
+ output = strm.output;
+ left = strm.avail_out;
+ next = strm.next_in;
+ input = strm.input;
+ have = strm.avail_in;
+ hold = state.hold;
+ bits = state.bits;
+ //---
+
+ _in = have;
+ _out = left;
+ ret = Z_OK;
+
+ inf_leave: // goto emulation
+ for (;;) {
+ switch (state.mode) {
+ case HEAD:
+ if (state.wrap === 0) {
+ state.mode = TYPEDO;
+ break;
+ }
+ //=== NEEDBITS(16);
+ while (bits < 16) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
+ state.check = 0/*crc32(0L, Z_NULL, 0)*/;
+ //=== CRC2(state.check, hold);
+ hbuf[0] = hold & 0xff;
+ hbuf[1] = (hold >>> 8) & 0xff;
+ state.check = crc32(state.check, hbuf, 2, 0);
+ //===//
+
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ state.mode = FLAGS;
+ break;
+ }
+ state.flags = 0; /* expect zlib header */
+ if (state.head) {
+ state.head.done = false;
+ }
+ if (!(state.wrap & 1) || /* check if zlib header allowed */
+ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
+ strm.msg = 'incorrect header check';
+ state.mode = BAD;
+ break;
+ }
+ if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
+ strm.msg = 'unknown compression method';
+ state.mode = BAD;
+ break;
+ }
+ //--- DROPBITS(4) ---//
+ hold >>>= 4;
+ bits -= 4;
+ //---//
+ len = (hold & 0x0f)/*BITS(4)*/ + 8;
+ if (state.wbits === 0) {
+ state.wbits = len;
+ }
+ else if (len > state.wbits) {
+ strm.msg = 'invalid window size';
+ state.mode = BAD;
+ break;
+ }
+ state.dmax = 1 << len;
+ //Tracev((stderr, "inflate: zlib header ok\n"));
+ strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
+ state.mode = hold & 0x200 ? DICTID : TYPE;
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ break;
+ case FLAGS:
+ //=== NEEDBITS(16); */
+ while (bits < 16) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ state.flags = hold;
+ if ((state.flags & 0xff) !== Z_DEFLATED) {
+ strm.msg = 'unknown compression method';
+ state.mode = BAD;
+ break;
+ }
+ if (state.flags & 0xe000) {
+ strm.msg = 'unknown header flags set';
+ state.mode = BAD;
+ break;
+ }
+ if (state.head) {
+ state.head.text = ((hold >> 8) & 1);
+ }
+ if (state.flags & 0x0200) {
+ //=== CRC2(state.check, hold);
+ hbuf[0] = hold & 0xff;
+ hbuf[1] = (hold >>> 8) & 0xff;
+ state.check = crc32(state.check, hbuf, 2, 0);
+ //===//
+ }
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ state.mode = TIME;
+ /* falls through */
+ case TIME:
+ //=== NEEDBITS(32); */
+ while (bits < 32) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ if (state.head) {
+ state.head.time = hold;
+ }
+ if (state.flags & 0x0200) {
+ //=== CRC4(state.check, hold)
+ hbuf[0] = hold & 0xff;
+ hbuf[1] = (hold >>> 8) & 0xff;
+ hbuf[2] = (hold >>> 16) & 0xff;
+ hbuf[3] = (hold >>> 24) & 0xff;
+ state.check = crc32(state.check, hbuf, 4, 0);
+ //===
+ }
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ state.mode = OS;
+ /* falls through */
+ case OS:
+ //=== NEEDBITS(16); */
+ while (bits < 16) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ if (state.head) {
+ state.head.xflags = (hold & 0xff);
+ state.head.os = (hold >> 8);
+ }
+ if (state.flags & 0x0200) {
+ //=== CRC2(state.check, hold);
+ hbuf[0] = hold & 0xff;
+ hbuf[1] = (hold >>> 8) & 0xff;
+ state.check = crc32(state.check, hbuf, 2, 0);
+ //===//
+ }
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ state.mode = EXLEN;
+ /* falls through */
+ case EXLEN:
+ if (state.flags & 0x0400) {
+ //=== NEEDBITS(16); */
+ while (bits < 16) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ state.length = hold;
+ if (state.head) {
+ state.head.extra_len = hold;
+ }
+ if (state.flags & 0x0200) {
+ //=== CRC2(state.check, hold);
+ hbuf[0] = hold & 0xff;
+ hbuf[1] = (hold >>> 8) & 0xff;
+ state.check = crc32(state.check, hbuf, 2, 0);
+ //===//
+ }
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ }
+ else if (state.head) {
+ state.head.extra = null/*Z_NULL*/;
+ }
+ state.mode = EXTRA;
+ /* falls through */
+ case EXTRA:
+ if (state.flags & 0x0400) {
+ copy = state.length;
+ if (copy > have) { copy = have; }
+ if (copy) {
+ if (state.head) {
+ len = state.head.extra_len - state.length;
+ if (!state.head.extra) {
+ // Use untyped array for more conveniend processing later
+ state.head.extra = new Array(state.head.extra_len);
+ }
+ utils.arraySet(
+ state.head.extra,
+ input,
+ next,
+ // extra field is limited to 65536 bytes
+ // - no need for additional size check
+ copy,
+ /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
+ len
+ );
+ //zmemcpy(state.head.extra + len, next,
+ // len + copy > state.head.extra_max ?
+ // state.head.extra_max - len : copy);
+ }
+ if (state.flags & 0x0200) {
+ state.check = crc32(state.check, input, copy, next);
+ }
+ have -= copy;
+ next += copy;
+ state.length -= copy;
+ }
+ if (state.length) { break inf_leave; }
+ }
+ state.length = 0;
+ state.mode = NAME;
+ /* falls through */
+ case NAME:
+ if (state.flags & 0x0800) {
+ if (have === 0) { break inf_leave; }
+ copy = 0;
+ do {
+ // TODO: 2 or 1 bytes?
+ len = input[next + copy++];
+ /* use constant limit because in js we should not preallocate memory */
+ if (state.head && len &&
+ (state.length < 65536 /*state.head.name_max*/)) {
+ state.head.name += String.fromCharCode(len);
+ }
+ } while (len && copy < have);
+
+ if (state.flags & 0x0200) {
+ state.check = crc32(state.check, input, copy, next);
+ }
+ have -= copy;
+ next += copy;
+ if (len) { break inf_leave; }
+ }
+ else if (state.head) {
+ state.head.name = null;
+ }
+ state.length = 0;
+ state.mode = COMMENT;
+ /* falls through */
+ case COMMENT:
+ if (state.flags & 0x1000) {
+ if (have === 0) { break inf_leave; }
+ copy = 0;
+ do {
+ len = input[next + copy++];
+ /* use constant limit because in js we should not preallocate memory */
+ if (state.head && len &&
+ (state.length < 65536 /*state.head.comm_max*/)) {
+ state.head.comment += String.fromCharCode(len);
+ }
+ } while (len && copy < have);
+ if (state.flags & 0x0200) {
+ state.check = crc32(state.check, input, copy, next);
+ }
+ have -= copy;
+ next += copy;
+ if (len) { break inf_leave; }
+ }
+ else if (state.head) {
+ state.head.comment = null;
+ }
+ state.mode = HCRC;
+ /* falls through */
+ case HCRC:
+ if (state.flags & 0x0200) {
+ //=== NEEDBITS(16); */
+ while (bits < 16) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ if (hold !== (state.check & 0xffff)) {
+ strm.msg = 'header crc mismatch';
+ state.mode = BAD;
+ break;
+ }
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ }
+ if (state.head) {
+ state.head.hcrc = ((state.flags >> 9) & 1);
+ state.head.done = true;
+ }
+ strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
+ state.mode = TYPE;
+ break;
+ case DICTID:
+ //=== NEEDBITS(32); */
+ while (bits < 32) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ strm.adler = state.check = ZSWAP32(hold);
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ state.mode = DICT;
+ /* falls through */
+ case DICT:
+ if (state.havedict === 0) {
+ //--- RESTORE() ---
+ strm.next_out = put;
+ strm.avail_out = left;
+ strm.next_in = next;
+ strm.avail_in = have;
+ state.hold = hold;
+ state.bits = bits;
+ //---
+ return Z_NEED_DICT;
+ }
+ strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
+ state.mode = TYPE;
+ /* falls through */
+ case TYPE:
+ if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
+ /* falls through */
+ case TYPEDO:
+ if (state.last) {
+ //--- BYTEBITS() ---//
+ hold >>>= bits & 7;
+ bits -= bits & 7;
+ //---//
+ state.mode = CHECK;
+ break;
+ }
+ //=== NEEDBITS(3); */
+ while (bits < 3) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ state.last = (hold & 0x01)/*BITS(1)*/;
+ //--- DROPBITS(1) ---//
+ hold >>>= 1;
+ bits -= 1;
+ //---//
+
+ switch ((hold & 0x03)/*BITS(2)*/) {
+ case 0: /* stored block */
+ //Tracev((stderr, "inflate: stored block%s\n",
+ // state.last ? " (last)" : ""));
+ state.mode = STORED;
+ break;
+ case 1: /* fixed block */
+ fixedtables(state);
+ //Tracev((stderr, "inflate: fixed codes block%s\n",
+ // state.last ? " (last)" : ""));
+ state.mode = LEN_; /* decode codes */
+ if (flush === Z_TREES) {
+ //--- DROPBITS(2) ---//
+ hold >>>= 2;
+ bits -= 2;
+ //---//
+ break inf_leave;
+ }
+ break;
+ case 2: /* dynamic block */
+ //Tracev((stderr, "inflate: dynamic codes block%s\n",
+ // state.last ? " (last)" : ""));
+ state.mode = TABLE;
+ break;
+ case 3:
+ strm.msg = 'invalid block type';
+ state.mode = BAD;
+ }
+ //--- DROPBITS(2) ---//
+ hold >>>= 2;
+ bits -= 2;
+ //---//
+ break;
+ case STORED:
+ //--- BYTEBITS() ---// /* go to byte boundary */
+ hold >>>= bits & 7;
+ bits -= bits & 7;
+ //---//
+ //=== NEEDBITS(32); */
+ while (bits < 32) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
+ strm.msg = 'invalid stored block lengths';
+ state.mode = BAD;
+ break;
+ }
+ state.length = hold & 0xffff;
+ //Tracev((stderr, "inflate: stored length %u\n",
+ // state.length));
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ state.mode = COPY_;
+ if (flush === Z_TREES) { break inf_leave; }
+ /* falls through */
+ case COPY_:
+ state.mode = COPY;
+ /* falls through */
+ case COPY:
+ copy = state.length;
+ if (copy) {
+ if (copy > have) { copy = have; }
+ if (copy > left) { copy = left; }
+ if (copy === 0) { break inf_leave; }
+ //--- zmemcpy(put, next, copy); ---
+ utils.arraySet(output, input, next, copy, put);
+ //---//
+ have -= copy;
+ next += copy;
+ left -= copy;
+ put += copy;
+ state.length -= copy;
+ break;
+ }
+ //Tracev((stderr, "inflate: stored end\n"));
+ state.mode = TYPE;
+ break;
+ case TABLE:
+ //=== NEEDBITS(14); */
+ while (bits < 14) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
+ //--- DROPBITS(5) ---//
+ hold >>>= 5;
+ bits -= 5;
+ //---//
+ state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
+ //--- DROPBITS(5) ---//
+ hold >>>= 5;
+ bits -= 5;
+ //---//
+ state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
+ //--- DROPBITS(4) ---//
+ hold >>>= 4;
+ bits -= 4;
+ //---//
+//#ifndef PKZIP_BUG_WORKAROUND
+ if (state.nlen > 286 || state.ndist > 30) {
+ strm.msg = 'too many length or distance symbols';
+ state.mode = BAD;
+ break;
+ }
+//#endif
+ //Tracev((stderr, "inflate: table sizes ok\n"));
+ state.have = 0;
+ state.mode = LENLENS;
+ /* falls through */
+ case LENLENS:
+ while (state.have < state.ncode) {
+ //=== NEEDBITS(3);
+ while (bits < 3) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
+ //--- DROPBITS(3) ---//
+ hold >>>= 3;
+ bits -= 3;
+ //---//
+ }
+ while (state.have < 19) {
+ state.lens[order[state.have++]] = 0;
+ }
+ // We have separate tables & no pointers. 2 commented lines below not needed.
+ //state.next = state.codes;
+ //state.lencode = state.next;
+ // Switch to use dynamic table
+ state.lencode = state.lendyn;
+ state.lenbits = 7;
+
+ opts = {bits: state.lenbits};
+ ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
+ state.lenbits = opts.bits;
+
+ if (ret) {
+ strm.msg = 'invalid code lengths set';
+ state.mode = BAD;
+ break;
+ }
+ //Tracev((stderr, "inflate: code lengths ok\n"));
+ state.have = 0;
+ state.mode = CODELENS;
+ /* falls through */
+ case CODELENS:
+ while (state.have < state.nlen + state.ndist) {
+ for (;;) {
+ here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
+ here_bits = here >>> 24;
+ here_op = (here >>> 16) & 0xff;
+ here_val = here & 0xffff;
+
+ if ((here_bits) <= bits) { break; }
+ //--- PULLBYTE() ---//
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ //---//
+ }
+ if (here_val < 16) {
+ //--- DROPBITS(here.bits) ---//
+ hold >>>= here_bits;
+ bits -= here_bits;
+ //---//
+ state.lens[state.have++] = here_val;
+ }
+ else {
+ if (here_val === 16) {
+ //=== NEEDBITS(here.bits + 2);
+ n = here_bits + 2;
+ while (bits < n) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ //--- DROPBITS(here.bits) ---//
+ hold >>>= here_bits;
+ bits -= here_bits;
+ //---//
+ if (state.have === 0) {
+ strm.msg = 'invalid bit length repeat';
+ state.mode = BAD;
+ break;
+ }
+ len = state.lens[state.have - 1];
+ copy = 3 + (hold & 0x03);//BITS(2);
+ //--- DROPBITS(2) ---//
+ hold >>>= 2;
+ bits -= 2;
+ //---//
+ }
+ else if (here_val === 17) {
+ //=== NEEDBITS(here.bits + 3);
+ n = here_bits + 3;
+ while (bits < n) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ //--- DROPBITS(here.bits) ---//
+ hold >>>= here_bits;
+ bits -= here_bits;
+ //---//
+ len = 0;
+ copy = 3 + (hold & 0x07);//BITS(3);
+ //--- DROPBITS(3) ---//
+ hold >>>= 3;
+ bits -= 3;
+ //---//
+ }
+ else {
+ //=== NEEDBITS(here.bits + 7);
+ n = here_bits + 7;
+ while (bits < n) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ //--- DROPBITS(here.bits) ---//
+ hold >>>= here_bits;
+ bits -= here_bits;
+ //---//
+ len = 0;
+ copy = 11 + (hold & 0x7f);//BITS(7);
+ //--- DROPBITS(7) ---//
+ hold >>>= 7;
+ bits -= 7;
+ //---//
+ }
+ if (state.have + copy > state.nlen + state.ndist) {
+ strm.msg = 'invalid bit length repeat';
+ state.mode = BAD;
+ break;
+ }
+ while (copy--) {
+ state.lens[state.have++] = len;
+ }
+ }
+ }
+
+ /* handle error breaks in while */
+ if (state.mode === BAD) { break; }
+
+ /* check for end-of-block code (better have one) */
+ if (state.lens[256] === 0) {
+ strm.msg = 'invalid code -- missing end-of-block';
+ state.mode = BAD;
+ break;
+ }
+
+ /* build code tables -- note: do not change the lenbits or distbits
+ values here (9 and 6) without reading the comments in inftrees.h
+ concerning the ENOUGH constants, which depend on those values */
+ state.lenbits = 9;
+
+ opts = {bits: state.lenbits};
+ ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
+ // We have separate tables & no pointers. 2 commented lines below not needed.
+ // state.next_index = opts.table_index;
+ state.lenbits = opts.bits;
+ // state.lencode = state.next;
+
+ if (ret) {
+ strm.msg = 'invalid literal/lengths set';
+ state.mode = BAD;
+ break;
+ }
+
+ state.distbits = 6;
+ //state.distcode.copy(state.codes);
+ // Switch to use dynamic table
+ state.distcode = state.distdyn;
+ opts = {bits: state.distbits};
+ ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
+ // We have separate tables & no pointers. 2 commented lines below not needed.
+ // state.next_index = opts.table_index;
+ state.distbits = opts.bits;
+ // state.distcode = state.next;
+
+ if (ret) {
+ strm.msg = 'invalid distances set';
+ state.mode = BAD;
+ break;
+ }
+ //Tracev((stderr, 'inflate: codes ok\n'));
+ state.mode = LEN_;
+ if (flush === Z_TREES) { break inf_leave; }
+ /* falls through */
+ case LEN_:
+ state.mode = LEN;
+ /* falls through */
+ case LEN:
+ if (have >= 6 && left >= 258) {
+ //--- RESTORE() ---
+ strm.next_out = put;
+ strm.avail_out = left;
+ strm.next_in = next;
+ strm.avail_in = have;
+ state.hold = hold;
+ state.bits = bits;
+ //---
+ inflate_fast(strm, _out);
+ //--- LOAD() ---
+ put = strm.next_out;
+ output = strm.output;
+ left = strm.avail_out;
+ next = strm.next_in;
+ input = strm.input;
+ have = strm.avail_in;
+ hold = state.hold;
+ bits = state.bits;
+ //---
+
+ if (state.mode === TYPE) {
+ state.back = -1;
+ }
+ break;
+ }
+ state.back = 0;
+ for (;;) {
+ here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
+ here_bits = here >>> 24;
+ here_op = (here >>> 16) & 0xff;
+ here_val = here & 0xffff;
+
+ if (here_bits <= bits) { break; }
+ //--- PULLBYTE() ---//
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ //---//
+ }
+ if (here_op && (here_op & 0xf0) === 0) {
+ last_bits = here_bits;
+ last_op = here_op;
+ last_val = here_val;
+ for (;;) {
+ here = state.lencode[last_val +
+ ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
+ here_bits = here >>> 24;
+ here_op = (here >>> 16) & 0xff;
+ here_val = here & 0xffff;
+
+ if ((last_bits + here_bits) <= bits) { break; }
+ //--- PULLBYTE() ---//
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ //---//
+ }
+ //--- DROPBITS(last.bits) ---//
+ hold >>>= last_bits;
+ bits -= last_bits;
+ //---//
+ state.back += last_bits;
+ }
+ //--- DROPBITS(here.bits) ---//
+ hold >>>= here_bits;
+ bits -= here_bits;
+ //---//
+ state.back += here_bits;
+ state.length = here_val;
+ if (here_op === 0) {
+ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+ // "inflate: literal '%c'\n" :
+ // "inflate: literal 0x%02x\n", here.val));
+ state.mode = LIT;
+ break;
+ }
+ if (here_op & 32) {
+ //Tracevv((stderr, "inflate: end of block\n"));
+ state.back = -1;
+ state.mode = TYPE;
+ break;
+ }
+ if (here_op & 64) {
+ strm.msg = 'invalid literal/length code';
+ state.mode = BAD;
+ break;
+ }
+ state.extra = here_op & 15;
+ state.mode = LENEXT;
+ /* falls through */
+ case LENEXT:
+ if (state.extra) {
+ //=== NEEDBITS(state.extra);
+ n = state.extra;
+ while (bits < n) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
+ //--- DROPBITS(state.extra) ---//
+ hold >>>= state.extra;
+ bits -= state.extra;
+ //---//
+ state.back += state.extra;
+ }
+ //Tracevv((stderr, "inflate: length %u\n", state.length));
+ state.was = state.length;
+ state.mode = DIST;
+ /* falls through */
+ case DIST:
+ for (;;) {
+ here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
+ here_bits = here >>> 24;
+ here_op = (here >>> 16) & 0xff;
+ here_val = here & 0xffff;
+
+ if ((here_bits) <= bits) { break; }
+ //--- PULLBYTE() ---//
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ //---//
+ }
+ if ((here_op & 0xf0) === 0) {
+ last_bits = here_bits;
+ last_op = here_op;
+ last_val = here_val;
+ for (;;) {
+ here = state.distcode[last_val +
+ ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
+ here_bits = here >>> 24;
+ here_op = (here >>> 16) & 0xff;
+ here_val = here & 0xffff;
+
+ if ((last_bits + here_bits) <= bits) { break; }
+ //--- PULLBYTE() ---//
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ //---//
+ }
+ //--- DROPBITS(last.bits) ---//
+ hold >>>= last_bits;
+ bits -= last_bits;
+ //---//
+ state.back += last_bits;
+ }
+ //--- DROPBITS(here.bits) ---//
+ hold >>>= here_bits;
+ bits -= here_bits;
+ //---//
+ state.back += here_bits;
+ if (here_op & 64) {
+ strm.msg = 'invalid distance code';
+ state.mode = BAD;
+ break;
+ }
+ state.offset = here_val;
+ state.extra = (here_op) & 15;
+ state.mode = DISTEXT;
+ /* falls through */
+ case DISTEXT:
+ if (state.extra) {
+ //=== NEEDBITS(state.extra);
+ n = state.extra;
+ while (bits < n) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
+ //--- DROPBITS(state.extra) ---//
+ hold >>>= state.extra;
+ bits -= state.extra;
+ //---//
+ state.back += state.extra;
+ }
+//#ifdef INFLATE_STRICT
+ if (state.offset > state.dmax) {
+ strm.msg = 'invalid distance too far back';
+ state.mode = BAD;
+ break;
+ }
+//#endif
+ //Tracevv((stderr, "inflate: distance %u\n", state.offset));
+ state.mode = MATCH;
+ /* falls through */
+ case MATCH:
+ if (left === 0) { break inf_leave; }
+ copy = _out - left;
+ if (state.offset > copy) { /* copy from window */
+ copy = state.offset - copy;
+ if (copy > state.whave) {
+ if (state.sane) {
+ strm.msg = 'invalid distance too far back';
+ state.mode = BAD;
+ break;
+ }
+// (!) This block is disabled in zlib defailts,
+// don't enable it for binary compatibility
+//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+// Trace((stderr, "inflate.c too far\n"));
+// copy -= state.whave;
+// if (copy > state.length) { copy = state.length; }
+// if (copy > left) { copy = left; }
+// left -= copy;
+// state.length -= copy;
+// do {
+// output[put++] = 0;
+// } while (--copy);
+// if (state.length === 0) { state.mode = LEN; }
+// break;
+//#endif
+ }
+ if (copy > state.wnext) {
+ copy -= state.wnext;
+ from = state.wsize - copy;
+ }
+ else {
+ from = state.wnext - copy;
+ }
+ if (copy > state.length) { copy = state.length; }
+ from_source = state.window;
+ }
+ else { /* copy from output */
+ from_source = output;
+ from = put - state.offset;
+ copy = state.length;
+ }
+ if (copy > left) { copy = left; }
+ left -= copy;
+ state.length -= copy;
+ do {
+ output[put++] = from_source[from++];
+ } while (--copy);
+ if (state.length === 0) { state.mode = LEN; }
+ break;
+ case LIT:
+ if (left === 0) { break inf_leave; }
+ output[put++] = state.length;
+ left--;
+ state.mode = LEN;
+ break;
+ case CHECK:
+ if (state.wrap) {
+ //=== NEEDBITS(32);
+ while (bits < 32) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ // Use '|' insdead of '+' to make sure that result is signed
+ hold |= input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ _out -= left;
+ strm.total_out += _out;
+ state.total += _out;
+ if (_out) {
+ strm.adler = state.check =
+ /*UPDATE(state.check, put - _out, _out);*/
+ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
+
+ }
+ _out = left;
+ // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
+ if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
+ strm.msg = 'incorrect data check';
+ state.mode = BAD;
+ break;
+ }
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ //Tracev((stderr, "inflate: check matches trailer\n"));
+ }
+ state.mode = LENGTH;
+ /* falls through */
+ case LENGTH:
+ if (state.wrap && state.flags) {
+ //=== NEEDBITS(32);
+ while (bits < 32) {
+ if (have === 0) { break inf_leave; }
+ have--;
+ hold += input[next++] << bits;
+ bits += 8;
+ }
+ //===//
+ if (hold !== (state.total & 0xffffffff)) {
+ strm.msg = 'incorrect length check';
+ state.mode = BAD;
+ break;
+ }
+ //=== INITBITS();
+ hold = 0;
+ bits = 0;
+ //===//
+ //Tracev((stderr, "inflate: length matches trailer\n"));
+ }
+ state.mode = DONE;
+ /* falls through */
+ case DONE:
+ ret = Z_STREAM_END;
+ break inf_leave;
+ case BAD:
+ ret = Z_DATA_ERROR;
+ break inf_leave;
+ case MEM:
+ return Z_MEM_ERROR;
+ case SYNC:
+ /* falls through */
+ default:
+ return Z_STREAM_ERROR;
+ }
+ }
+
+ // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
+
+ /*
+ Return from inflate(), updating the total counts and the check value.
+ If there was no progress during the inflate() call, return a buffer
+ error. Call updatewindow() to create and/or update the window state.
+ Note: a memory error from inflate() is non-recoverable.
+ */
+
+ //--- RESTORE() ---
+ strm.next_out = put;
+ strm.avail_out = left;
+ strm.next_in = next;
+ strm.avail_in = have;
+ state.hold = hold;
+ state.bits = bits;
+ //---
+
+ if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
+ (state.mode < CHECK || flush !== Z_FINISH))) {
+ if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
+ state.mode = MEM;
+ return Z_MEM_ERROR;
+ }
+ }
+ _in -= strm.avail_in;
+ _out -= strm.avail_out;
+ strm.total_in += _in;
+ strm.total_out += _out;
+ state.total += _out;
+ if (state.wrap && _out) {
+ strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
+ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
+ }
+ strm.data_type = state.bits + (state.last ? 64 : 0) +
+ (state.mode === TYPE ? 128 : 0) +
+ (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
+ if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
+ ret = Z_BUF_ERROR;
+ }
+ return ret;
+}
+
+function inflateEnd(strm) {
+
+ if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
+ return Z_STREAM_ERROR;
+ }
+
+ var state = strm.state;
+ if (state.window) {
+ state.window = null;
+ }
+ strm.state = null;
+ return Z_OK;
+}
+
+function inflateGetHeader(strm, head) {
+ var state;
+
+ /* check state */
+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }
+ state = strm.state;
+ if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
+
+ /* save header structure */
+ state.head = head;
+ head.done = false;
+ return Z_OK;
+}
+
+
+exports.inflateReset = inflateReset;
+exports.inflateReset2 = inflateReset2;
+exports.inflateResetKeep = inflateResetKeep;
+exports.inflateInit = inflateInit;
+exports.inflateInit2 = inflateInit2;
+exports.inflate = inflate;
+exports.inflateEnd = inflateEnd;
+exports.inflateGetHeader = inflateGetHeader;
+exports.inflateInfo = 'pako inflate (from Nodeca project)';
+
+/* Not implemented
+exports.inflateCopy = inflateCopy;
+exports.inflateGetDictionary = inflateGetDictionary;
+exports.inflateMark = inflateMark;
+exports.inflatePrime = inflatePrime;
+exports.inflateSetDictionary = inflateSetDictionary;
+exports.inflateSync = inflateSync;
+exports.inflateSyncPoint = inflateSyncPoint;
+exports.inflateUndermine = inflateUndermine;
+*/
+
+},{"../utils/common":32,"./adler32":34,"./crc32":36,"./inffast":39,"./inftrees":41}],41:[function(require,module,exports){
+'use strict';
+
+
+var utils = require('../utils/common');
+
+var MAXBITS = 15;
+var ENOUGH_LENS = 852;
+var ENOUGH_DISTS = 592;
+//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
+
+var CODES = 0;
+var LENS = 1;
+var DISTS = 2;
+
+var lbase = [ /* Length codes 257..285 base */
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
+];
+
+var lext = [ /* Length codes 257..285 extra */
+ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
+ 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
+];
+
+var dbase = [ /* Distance codes 0..29 base */
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+ 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+ 8193, 12289, 16385, 24577, 0, 0
+];
+
+var dext = [ /* Distance codes 0..29 extra */
+ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
+ 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
+ 28, 28, 29, 29, 64, 64
+];
+
+module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
+{
+ var bits = opts.bits;
+ //here = opts.here; /* table entry for duplication */
+
+ var len = 0; /* a code's length in bits */
+ var sym = 0; /* index of code symbols */
+ var min = 0, max = 0; /* minimum and maximum code lengths */
+ var root = 0; /* number of index bits for root table */
+ var curr = 0; /* number of index bits for current table */
+ var drop = 0; /* code bits to drop for sub-table */
+ var left = 0; /* number of prefix codes available */
+ var used = 0; /* code entries in table used */
+ var huff = 0; /* Huffman code */
+ var incr; /* for incrementing code, index */
+ var fill; /* index for replicating entries */
+ var low; /* low bits for current root entry */
+ var mask; /* mask for low root bits */
+ var next; /* next available space in table */
+ var base = null; /* base value table to use */
+ var base_index = 0;
+// var shoextra; /* extra bits table to use */
+ var end; /* use base and extra for symbol > end */
+ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
+ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
+ var extra = null;
+ var extra_index = 0;
+
+ var here_bits, here_op, here_val;
+
+ /*
+ Process a set of code lengths to create a canonical Huffman code. The
+ code lengths are lens[0..codes-1]. Each length corresponds to the
+ symbols 0..codes-1. The Huffman code is generated by first sorting the
+ symbols by length from short to long, and retaining the symbol order
+ for codes with equal lengths. Then the code starts with all zero bits
+ for the first code of the shortest length, and the codes are integer
+ increments for the same length, and zeros are appended as the length
+ increases. For the deflate format, these bits are stored backwards
+ from their more natural integer increment ordering, and so when the
+ decoding tables are built in the large loop below, the integer codes
+ are incremented backwards.
+
+ This routine assumes, but does not check, that all of the entries in
+ lens[] are in the range 0..MAXBITS. The caller must assure this.
+ 1..MAXBITS is interpreted as that code length. zero means that that
+ symbol does not occur in this code.
+
+ The codes are sorted by computing a count of codes for each length,
+ creating from that a table of starting indices for each length in the
+ sorted table, and then entering the symbols in order in the sorted
+ table. The sorted table is work[], with that space being provided by
+ the caller.
+
+ The length counts are used for other purposes as well, i.e. finding
+ the minimum and maximum length codes, determining if there are any
+ codes at all, checking for a valid set of lengths, and looking ahead
+ at length counts to determine sub-table sizes when building the
+ decoding tables.
+ */
+
+ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
+ for (len = 0; len <= MAXBITS; len++) {
+ count[len] = 0;
+ }
+ for (sym = 0; sym < codes; sym++) {
+ count[lens[lens_index + sym]]++;
+ }
+
+ /* bound code lengths, force root to be within code lengths */
+ root = bits;
+ for (max = MAXBITS; max >= 1; max--) {
+ if (count[max] !== 0) { break; }
+ }
+ if (root > max) {
+ root = max;
+ }
+ if (max === 0) { /* no symbols to code at all */
+ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
+ //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
+ //table.val[opts.table_index++] = 0; //here.val = (var short)0;
+ table[table_index++] = (1 << 24) | (64 << 16) | 0;
+
+
+ //table.op[opts.table_index] = 64;
+ //table.bits[opts.table_index] = 1;
+ //table.val[opts.table_index++] = 0;
+ table[table_index++] = (1 << 24) | (64 << 16) | 0;
+
+ opts.bits = 1;
+ return 0; /* no symbols, but wait for decoding to report error */
+ }
+ for (min = 1; min < max; min++) {
+ if (count[min] !== 0) { break; }
+ }
+ if (root < min) {
+ root = min;
+ }
+
+ /* check for an over-subscribed or incomplete set of lengths */
+ left = 1;
+ for (len = 1; len <= MAXBITS; len++) {
+ left <<= 1;
+ left -= count[len];
+ if (left < 0) {
+ return -1;
+ } /* over-subscribed */
+ }
+ if (left > 0 && (type === CODES || max !== 1)) {
+ return -1; /* incomplete set */
+ }
+
+ /* generate offsets into symbol table for each length for sorting */
+ offs[1] = 0;
+ for (len = 1; len < MAXBITS; len++) {
+ offs[len + 1] = offs[len] + count[len];
+ }
+
+ /* sort symbols by length, by symbol order within each length */
+ for (sym = 0; sym < codes; sym++) {
+ if (lens[lens_index + sym] !== 0) {
+ work[offs[lens[lens_index + sym]]++] = sym;
+ }
+ }
+
+ /*
+ Create and fill in decoding tables. In this loop, the table being
+ filled is at next and has curr index bits. The code being used is huff
+ with length len. That code is converted to an index by dropping drop
+ bits off of the bottom. For codes where len is less than drop + curr,
+ those top drop + curr - len bits are incremented through all values to
+ fill the table with replicated entries.
+
+ root is the number of index bits for the root table. When len exceeds
+ root, sub-tables are created pointed to by the root entry with an index
+ of the low root bits of huff. This is saved in low to check for when a
+ new sub-table should be started. drop is zero when the root table is
+ being filled, and drop is root when sub-tables are being filled.
+
+ When a new sub-table is needed, it is necessary to look ahead in the
+ code lengths to determine what size sub-table is needed. The length
+ counts are used for this, and so count[] is decremented as codes are
+ entered in the tables.
+
+ used keeps track of how many table entries have been allocated from the
+ provided *table space. It is checked for LENS and DIST tables against
+ the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
+ the initial root table size constants. See the comments in inftrees.h
+ for more information.
+
+ sym increments through all symbols, and the loop terminates when
+ all codes of length max, i.e. all codes, have been processed. This
+ routine permits incomplete codes, so another loop after this one fills
+ in the rest of the decoding tables with invalid code markers.
+ */
+
+ /* set up for code type */
+ // poor man optimization - use if-else instead of switch,
+ // to avoid deopts in old v8
+ if (type === CODES) {
+ base = extra = work; /* dummy value--not used */
+ end = 19;
+
+ } else if (type === LENS) {
+ base = lbase;
+ base_index -= 257;
+ extra = lext;
+ extra_index -= 257;
+ end = 256;
+
+ } else { /* DISTS */
+ base = dbase;
+ extra = dext;
+ end = -1;
+ }
+
+ /* initialize opts for loop */
+ huff = 0; /* starting code */
+ sym = 0; /* starting code symbol */
+ len = min; /* starting code length */
+ next = table_index; /* current table to fill in */
+ curr = root; /* current table index bits */
+ drop = 0; /* current bits to drop from code for index */
+ low = -1; /* trigger new sub-table when len > root */
+ used = 1 << root; /* use root table entries */
+ mask = used - 1; /* mask for comparing low */
+
+ /* check available table space */
+ if ((type === LENS && used > ENOUGH_LENS) ||
+ (type === DISTS && used > ENOUGH_DISTS)) {
+ return 1;
+ }
+
+ var i=0;
+ /* process all codes and make table entries */
+ for (;;) {
+ i++;
+ /* create table entry */
+ here_bits = len - drop;
+ if (work[sym] < end) {
+ here_op = 0;
+ here_val = work[sym];
+ }
+ else if (work[sym] > end) {
+ here_op = extra[extra_index + work[sym]];
+ here_val = base[base_index + work[sym]];
+ }
+ else {
+ here_op = 32 + 64; /* end of block */
+ here_val = 0;
+ }
+
+ /* replicate for those indices with low len bits equal to huff */
+ incr = 1 << (len - drop);
+ fill = 1 << curr;
+ min = fill; /* save offset to next table */
+ do {
+ fill -= incr;
+ table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
+ } while (fill !== 0);
+
+ /* backwards increment the len-bit code huff */
+ incr = 1 << (len - 1);
+ while (huff & incr) {
+ incr >>= 1;
+ }
+ if (incr !== 0) {
+ huff &= incr - 1;
+ huff += incr;
+ } else {
+ huff = 0;
+ }
+
+ /* go to next symbol, update count, len */
+ sym++;
+ if (--count[len] === 0) {
+ if (len === max) { break; }
+ len = lens[lens_index + work[sym]];
+ }
+
+ /* create new sub-table if needed */
+ if (len > root && (huff & mask) !== low) {
+ /* if first time, transition to sub-tables */
+ if (drop === 0) {
+ drop = root;
+ }
+
+ /* increment past last table */
+ next += min; /* here min is 1 << curr */
+
+ /* determine length of next table */
+ curr = len - drop;
+ left = 1 << curr;
+ while (curr + drop < max) {
+ left -= count[curr + drop];
+ if (left <= 0) { break; }
+ curr++;
+ left <<= 1;
+ }
+
+ /* check for enough space */
+ used += 1 << curr;
+ if ((type === LENS && used > ENOUGH_LENS) ||
+ (type === DISTS && used > ENOUGH_DISTS)) {
+ return 1;
+ }
+
+ /* point entry in root table to sub-table */
+ low = huff & mask;
+ /*table.op[low] = curr;
+ table.bits[low] = root;
+ table.val[low] = next - opts.table_index;*/
+ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
+ }
+ }
+
+ /* fill in remaining table entry if code is incomplete (guaranteed to have
+ at most one remaining entry, since if the code is incomplete, the
+ maximum code length that was allowed to get this far is one bit) */
+ if (huff !== 0) {
+ //table.op[next + huff] = 64; /* invalid code marker */
+ //table.bits[next + huff] = len - drop;
+ //table.val[next + huff] = 0;
+ table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
+ }
+
+ /* set return parameters */
+ //opts.table_index += used;
+ opts.bits = root;
+ return 0;
+};
+
+},{"../utils/common":32}],42:[function(require,module,exports){
+'use strict';
+
+module.exports = {
+ '2': 'need dictionary', /* Z_NEED_DICT 2 */
+ '1': 'stream end', /* Z_STREAM_END 1 */
+ '0': '', /* Z_OK 0 */
+ '-1': 'file error', /* Z_ERRNO (-1) */
+ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
+ '-3': 'data error', /* Z_DATA_ERROR (-3) */
+ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
+ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
+ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
+};
+
+},{}],43:[function(require,module,exports){
+'use strict';
+
+
+var utils = require('../utils/common');
+
+/* Public constants ==========================================================*/
+/* ===========================================================================*/
+
+
+//var Z_FILTERED = 1;
+//var Z_HUFFMAN_ONLY = 2;
+//var Z_RLE = 3;
+var Z_FIXED = 4;
+//var Z_DEFAULT_STRATEGY = 0;
+
+/* Possible values of the data_type field (though see inflate()) */
+var Z_BINARY = 0;
+var Z_TEXT = 1;
+//var Z_ASCII = 1; // = Z_TEXT
+var Z_UNKNOWN = 2;
+
+/*============================================================================*/
+
+
+function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
+
+// From zutil.h
+
+var STORED_BLOCK = 0;
+var STATIC_TREES = 1;
+var DYN_TREES = 2;
+/* The three kinds of block type */
+
+var MIN_MATCH = 3;
+var MAX_MATCH = 258;
+/* The minimum and maximum match lengths */
+
+// From deflate.h
+/* ===========================================================================
+ * Internal compression state.
+ */
+
+var LENGTH_CODES = 29;
+/* number of length codes, not counting the special END_BLOCK code */
+
+var LITERALS = 256;
+/* number of literal bytes 0..255 */
+
+var L_CODES = LITERALS + 1 + LENGTH_CODES;
+/* number of Literal or Length codes, including the END_BLOCK code */
+
+var D_CODES = 30;
+/* number of distance codes */
+
+var BL_CODES = 19;
+/* number of codes used to transfer the bit lengths */
+
+var HEAP_SIZE = 2*L_CODES + 1;
+/* maximum heap size */
+
+var MAX_BITS = 15;
+/* All codes must not exceed MAX_BITS bits */
+
+var Buf_size = 16;
+/* size of bit buffer in bi_buf */
+
+
+/* ===========================================================================
+ * Constants
+ */
+
+var MAX_BL_BITS = 7;
+/* Bit length codes must not exceed MAX_BL_BITS bits */
+
+var END_BLOCK = 256;
+/* end of block literal code */
+
+var REP_3_6 = 16;
+/* repeat previous bit length 3-6 times (2 bits of repeat count) */
+
+var REPZ_3_10 = 17;
+/* repeat a zero length 3-10 times (3 bits of repeat count) */
+
+var REPZ_11_138 = 18;
+/* repeat a zero length 11-138 times (7 bits of repeat count) */
+
+var extra_lbits = /* extra bits for each length code */
+ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
+
+var extra_dbits = /* extra bits for each distance code */
+ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
+
+var extra_blbits = /* extra bits for each bit length code */
+ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
+
+var bl_order =
+ [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
+/* The lengths of the bit length codes are sent in order of decreasing
+ * probability, to avoid transmitting the lengths for unused bit length codes.
+ */
+
+/* ===========================================================================
+ * Local data. These are initialized only once.
+ */
+
+// We pre-fill arrays with 0 to avoid uninitialized gaps
+
+var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
+
+// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
+var static_ltree = new Array((L_CODES+2) * 2);
+zero(static_ltree);
+/* The static literal tree. Since the bit lengths are imposed, there is no
+ * need for the L_CODES extra codes used during heap construction. However
+ * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
+ * below).
+ */
+
+var static_dtree = new Array(D_CODES * 2);
+zero(static_dtree);
+/* The static distance tree. (Actually a trivial tree since all codes use
+ * 5 bits.)
+ */
+
+var _dist_code = new Array(DIST_CODE_LEN);
+zero(_dist_code);
+/* Distance codes. The first 256 values correspond to the distances
+ * 3 .. 258, the last 256 values correspond to the top 8 bits of
+ * the 15 bit distances.
+ */
+
+var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
+zero(_length_code);
+/* length code for each normalized match length (0 == MIN_MATCH) */
+
+var base_length = new Array(LENGTH_CODES);
+zero(base_length);
+/* First normalized length for each code (0 = MIN_MATCH) */
+
+var base_dist = new Array(D_CODES);
+zero(base_dist);
+/* First normalized distance for each code (0 = distance of 1) */
+
+
+var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
+
+ this.static_tree = static_tree; /* static tree or NULL */
+ this.extra_bits = extra_bits; /* extra bits for each code or NULL */
+ this.extra_base = extra_base; /* base index for extra_bits */
+ this.elems = elems; /* max number of elements in the tree */
+ this.max_length = max_length; /* max bit length for the codes */
+
+ // show if `static_tree` has data or dummy - needed for monomorphic objects
+ this.has_stree = static_tree && static_tree.length;
+};
+
+
+var static_l_desc;
+var static_d_desc;
+var static_bl_desc;
+
+
+var TreeDesc = function(dyn_tree, stat_desc) {
+ this.dyn_tree = dyn_tree; /* the dynamic tree */
+ this.max_code = 0; /* largest code with non zero frequency */
+ this.stat_desc = stat_desc; /* the corresponding static tree */
+};
+
+
+
+function d_code(dist) {
+ return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
+}
+
+
+/* ===========================================================================
+ * Output a short LSB first on the stream.
+ * IN assertion: there is enough room in pendingBuf.
+ */
+function put_short (s, w) {
+// put_byte(s, (uch)((w) & 0xff));
+// put_byte(s, (uch)((ush)(w) >> 8));
+ s.pending_buf[s.pending++] = (w) & 0xff;
+ s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
+}
+
+
+/* ===========================================================================
+ * Send a value on a given number of bits.
+ * IN assertion: length <= 16 and value fits in length bits.
+ */
+function send_bits(s, value, length) {
+ if (s.bi_valid > (Buf_size - length)) {
+ s.bi_buf |= (value << s.bi_valid) & 0xffff;
+ put_short(s, s.bi_buf);
+ s.bi_buf = value >> (Buf_size - s.bi_valid);
+ s.bi_valid += length - Buf_size;
+ } else {
+ s.bi_buf |= (value << s.bi_valid) & 0xffff;
+ s.bi_valid += length;
+ }
+}
+
+
+function send_code(s, c, tree) {
+ send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
+}
+
+
+/* ===========================================================================
+ * Reverse the first len bits of a code, using straightforward code (a faster
+ * method would use a table)
+ * IN assertion: 1 <= len <= 15
+ */
+function bi_reverse(code, len) {
+ var res = 0;
+ do {
+ res |= code & 1;
+ code >>>= 1;
+ res <<= 1;
+ } while (--len > 0);
+ return res >>> 1;
+}
+
+
+/* ===========================================================================
+ * Flush the bit buffer, keeping at most 7 bits in it.
+ */
+function bi_flush(s) {
+ if (s.bi_valid === 16) {
+ put_short(s, s.bi_buf);
+ s.bi_buf = 0;
+ s.bi_valid = 0;
+
+ } else if (s.bi_valid >= 8) {
+ s.pending_buf[s.pending++] = s.bi_buf & 0xff;
+ s.bi_buf >>= 8;
+ s.bi_valid -= 8;
+ }
+}
+
+
+/* ===========================================================================
+ * Compute the optimal bit lengths for a tree and update the total bit length
+ * for the current block.
+ * IN assertion: the fields freq and dad are set, heap[heap_max] and
+ * above are the tree nodes sorted by increasing frequency.
+ * OUT assertions: the field len is set to the optimal bit length, the
+ * array bl_count contains the frequencies for each bit length.
+ * The length opt_len is updated; static_len is also updated if stree is
+ * not null.
+ */
+function gen_bitlen(s, desc)
+// deflate_state *s;
+// tree_desc *desc; /* the tree descriptor */
+{
+ var tree = desc.dyn_tree;
+ var max_code = desc.max_code;
+ var stree = desc.stat_desc.static_tree;
+ var has_stree = desc.stat_desc.has_stree;
+ var extra = desc.stat_desc.extra_bits;
+ var base = desc.stat_desc.extra_base;
+ var max_length = desc.stat_desc.max_length;
+ var h; /* heap index */
+ var n, m; /* iterate over the tree elements */
+ var bits; /* bit length */
+ var xbits; /* extra bits */
+ var f; /* frequency */
+ var overflow = 0; /* number of elements with bit length too large */
+
+ for (bits = 0; bits <= MAX_BITS; bits++) {
+ s.bl_count[bits] = 0;
+ }
+
+ /* In a first pass, compute the optimal bit lengths (which may
+ * overflow in the case of the bit length tree).
+ */
+ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
+
+ for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
+ n = s.heap[h];
+ bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
+ if (bits > max_length) {
+ bits = max_length;
+ overflow++;
+ }
+ tree[n*2 + 1]/*.Len*/ = bits;
+ /* We overwrite tree[n].Dad which is no longer needed */
+
+ if (n > max_code) { continue; } /* not a leaf node */
+
+ s.bl_count[bits]++;
+ xbits = 0;
+ if (n >= base) {
+ xbits = extra[n-base];
+ }
+ f = tree[n * 2]/*.Freq*/;
+ s.opt_len += f * (bits + xbits);
+ if (has_stree) {
+ s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
+ }
+ }
+ if (overflow === 0) { return; }
+
+ // Trace((stderr,"\nbit length overflow\n"));
+ /* This happens for example on obj2 and pic of the Calgary corpus */
+
+ /* Find the first bit length which could increase: */
+ do {
+ bits = max_length-1;
+ while (s.bl_count[bits] === 0) { bits--; }
+ s.bl_count[bits]--; /* move one leaf down the tree */
+ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
+ s.bl_count[max_length]--;
+ /* The brother of the overflow item also moves one step up,
+ * but this does not affect bl_count[max_length]
+ */
+ overflow -= 2;
+ } while (overflow > 0);
+
+ /* Now recompute all bit lengths, scanning in increasing frequency.
+ * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
+ * lengths instead of fixing only the wrong ones. This idea is taken
+ * from 'ar' written by Haruhiko Okumura.)
+ */
+ for (bits = max_length; bits !== 0; bits--) {
+ n = s.bl_count[bits];
+ while (n !== 0) {
+ m = s.heap[--h];
+ if (m > max_code) { continue; }
+ if (tree[m*2 + 1]/*.Len*/ !== bits) {
+ // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
+ s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
+ tree[m*2 + 1]/*.Len*/ = bits;
+ }
+ n--;
+ }
+ }
+}
+
+
+/* ===========================================================================
+ * Generate the codes for a given tree and bit counts (which need not be
+ * optimal).
+ * IN assertion: the array bl_count contains the bit length statistics for
+ * the given tree and the field len is set for all tree elements.
+ * OUT assertion: the field code is set for all tree elements of non
+ * zero code length.
+ */
+function gen_codes(tree, max_code, bl_count)
+// ct_data *tree; /* the tree to decorate */
+// int max_code; /* largest code with non zero frequency */
+// ushf *bl_count; /* number of codes at each bit length */
+{
+ var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
+ var code = 0; /* running code value */
+ var bits; /* bit index */
+ var n; /* code index */
+
+ /* The distribution counts are first used to generate the code values
+ * without bit reversal.
+ */
+ for (bits = 1; bits <= MAX_BITS; bits++) {
+ next_code[bits] = code = (code + bl_count[bits-1]) << 1;
+ }
+ /* Check that the bit counts in bl_count are consistent. The last code
+ * must be all ones.
+ */
+ //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */
+ length = 0;
+ for (code = 0; code < LENGTH_CODES-1; code++) {
+ base_length[code] = length;
+ for (n = 0; n < (1< dist code (0..29) */
+ dist = 0;
+ for (code = 0 ; code < 16; code++) {
+ base_dist[code] = dist;
+ for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */
+ for (; code < D_CODES; code++) {
+ base_dist[code] = dist << 7;
+ for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
+ _dist_code[256 + dist++] = code;
+ }
+ }
+ //Assert (dist == 256, "tr_static_init: 256+dist != 512");
+
+ /* Construct the codes of the static literal tree */
+ for (bits = 0; bits <= MAX_BITS; bits++) {
+ bl_count[bits] = 0;
+ }
+
+ n = 0;
+ while (n <= 143) {
+ static_ltree[n*2 + 1]/*.Len*/ = 8;
+ n++;
+ bl_count[8]++;
+ }
+ while (n <= 255) {
+ static_ltree[n*2 + 1]/*.Len*/ = 9;
+ n++;
+ bl_count[9]++;
+ }
+ while (n <= 279) {
+ static_ltree[n*2 + 1]/*.Len*/ = 7;
+ n++;
+ bl_count[7]++;
+ }
+ while (n <= 287) {
+ static_ltree[n*2 + 1]/*.Len*/ = 8;
+ n++;
+ bl_count[8]++;
+ }
+ /* Codes 286 and 287 do not exist, but we must include them in the
+ * tree construction to get a canonical Huffman tree (longest code
+ * all ones)
+ */
+ gen_codes(static_ltree, L_CODES+1, bl_count);
+
+ /* The static distance tree is trivial: */
+ for (n = 0; n < D_CODES; n++) {
+ static_dtree[n*2 + 1]/*.Len*/ = 5;
+ static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
+ }
+
+ // Now data ready and we can init static trees
+ static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
+ static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
+ static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
+
+ //static_init_done = true;
+}
+
+
+/* ===========================================================================
+ * Initialize a new block.
+ */
+function init_block(s) {
+ var n; /* iterates over tree elements */
+
+ /* Initialize the trees. */
+ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
+ for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
+ for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
+
+ s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
+ s.opt_len = s.static_len = 0;
+ s.last_lit = s.matches = 0;
+}
+
+
+/* ===========================================================================
+ * Flush the bit buffer and align the output on a byte boundary
+ */
+function bi_windup(s)
+{
+ if (s.bi_valid > 8) {
+ put_short(s, s.bi_buf);
+ } else if (s.bi_valid > 0) {
+ //put_byte(s, (Byte)s->bi_buf);
+ s.pending_buf[s.pending++] = s.bi_buf;
+ }
+ s.bi_buf = 0;
+ s.bi_valid = 0;
+}
+
+/* ===========================================================================
+ * Copy a stored block, storing first the length and its
+ * one's complement if requested.
+ */
+function copy_block(s, buf, len, header)
+//DeflateState *s;
+//charf *buf; /* the input data */
+//unsigned len; /* its length */
+//int header; /* true if block header must be written */
+{
+ bi_windup(s); /* align on byte boundary */
+
+ if (header) {
+ put_short(s, len);
+ put_short(s, ~len);
+ }
+// while (len--) {
+// put_byte(s, *buf++);
+// }
+ utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
+ s.pending += len;
+}
+
+/* ===========================================================================
+ * Compares to subtrees, using the tree depth as tie breaker when
+ * the subtrees have equal frequency. This minimizes the worst case length.
+ */
+function smaller(tree, n, m, depth) {
+ var _n2 = n*2;
+ var _m2 = m*2;
+ return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
+ (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
+}
+
+/* ===========================================================================
+ * Restore the heap property by moving down the tree starting at node k,
+ * exchanging a node with the smallest of its two sons if necessary, stopping
+ * when the heap property is re-established (each father smaller than its
+ * two sons).
+ */
+function pqdownheap(s, tree, k)
+// deflate_state *s;
+// ct_data *tree; /* the tree to restore */
+// int k; /* node to move down */
+{
+ var v = s.heap[k];
+ var j = k << 1; /* left son of k */
+ while (j <= s.heap_len) {
+ /* Set j to the smallest of the two sons: */
+ if (j < s.heap_len &&
+ smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
+ j++;
+ }
+ /* Exit if v is smaller than both sons */
+ if (smaller(tree, v, s.heap[j], s.depth)) { break; }
+
+ /* Exchange v with the smallest son */
+ s.heap[k] = s.heap[j];
+ k = j;
+
+ /* And continue down the tree, setting j to the left son of k */
+ j <<= 1;
+ }
+ s.heap[k] = v;
+}
+
+
+// inlined manually
+// var SMALLEST = 1;
+
+/* ===========================================================================
+ * Send the block data compressed using the given Huffman trees
+ */
+function compress_block(s, ltree, dtree)
+// deflate_state *s;
+// const ct_data *ltree; /* literal tree */
+// const ct_data *dtree; /* distance tree */
+{
+ var dist; /* distance of matched string */
+ var lc; /* match length or unmatched char (if dist == 0) */
+ var lx = 0; /* running index in l_buf */
+ var code; /* the code to send */
+ var extra; /* number of extra bits to send */
+
+ if (s.last_lit !== 0) {
+ do {
+ dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
+ lc = s.pending_buf[s.l_buf + lx];
+ lx++;
+
+ if (dist === 0) {
+ send_code(s, lc, ltree); /* send a literal byte */
+ //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
+ } else {
+ /* Here, lc is the match length - MIN_MATCH */
+ code = _length_code[lc];
+ send_code(s, code+LITERALS+1, ltree); /* send the length code */
+ extra = extra_lbits[code];
+ if (extra !== 0) {
+ lc -= base_length[code];
+ send_bits(s, lc, extra); /* send the extra length bits */
+ }
+ dist--; /* dist is now the match distance - 1 */
+ code = d_code(dist);
+ //Assert (code < D_CODES, "bad d_code");
+
+ send_code(s, code, dtree); /* send the distance code */
+ extra = extra_dbits[code];
+ if (extra !== 0) {
+ dist -= base_dist[code];
+ send_bits(s, dist, extra); /* send the extra distance bits */
+ }
+ } /* literal or match pair ? */
+
+ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
+ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
+ // "pendingBuf overflow");
+
+ } while (lx < s.last_lit);
+ }
+
+ send_code(s, END_BLOCK, ltree);
+}
+
+
+/* ===========================================================================
+ * Construct one Huffman tree and assigns the code bit strings and lengths.
+ * Update the total bit length for the current block.
+ * IN assertion: the field freq is set for all tree elements.
+ * OUT assertions: the fields len and code are set to the optimal bit length
+ * and corresponding code. The length opt_len is updated; static_len is
+ * also updated if stree is not null. The field max_code is set.
+ */
+function build_tree(s, desc)
+// deflate_state *s;
+// tree_desc *desc; /* the tree descriptor */
+{
+ var tree = desc.dyn_tree;
+ var stree = desc.stat_desc.static_tree;
+ var has_stree = desc.stat_desc.has_stree;
+ var elems = desc.stat_desc.elems;
+ var n, m; /* iterate over heap elements */
+ var max_code = -1; /* largest code with non zero frequency */
+ var node; /* new node being created */
+
+ /* Construct the initial heap, with least frequent element in
+ * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
+ * heap[0] is not used.
+ */
+ s.heap_len = 0;
+ s.heap_max = HEAP_SIZE;
+
+ for (n = 0; n < elems; n++) {
+ if (tree[n * 2]/*.Freq*/ !== 0) {
+ s.heap[++s.heap_len] = max_code = n;
+ s.depth[n] = 0;
+
+ } else {
+ tree[n*2 + 1]/*.Len*/ = 0;
+ }
+ }
+
+ /* The pkzip format requires that at least one distance code exists,
+ * and that at least one bit should be sent even if there is only one
+ * possible code. So to avoid special checks later on we force at least
+ * two codes of non zero frequency.
+ */
+ while (s.heap_len < 2) {
+ node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
+ tree[node * 2]/*.Freq*/ = 1;
+ s.depth[node] = 0;
+ s.opt_len--;
+
+ if (has_stree) {
+ s.static_len -= stree[node*2 + 1]/*.Len*/;
+ }
+ /* node is 0 or 1 so it does not have extra bits */
+ }
+ desc.max_code = max_code;
+
+ /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
+ * establish sub-heaps of increasing lengths:
+ */
+ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
+
+ /* Construct the Huffman tree by repeatedly combining the least two
+ * frequent nodes.
+ */
+ node = elems; /* next internal node of the tree */
+ do {
+ //pqremove(s, tree, n); /* n = node of least frequency */
+ /*** pqremove ***/
+ n = s.heap[1/*SMALLEST*/];
+ s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
+ pqdownheap(s, tree, 1/*SMALLEST*/);
+ /***/
+
+ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
+
+ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
+ s.heap[--s.heap_max] = m;
+
+ /* Create a new node father of n and m */
+ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
+ s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
+ tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
+
+ /* and insert the new node in the heap */
+ s.heap[1/*SMALLEST*/] = node++;
+ pqdownheap(s, tree, 1/*SMALLEST*/);
+
+ } while (s.heap_len >= 2);
+
+ s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
+
+ /* At this point, the fields freq and dad are set. We can now
+ * generate the bit lengths.
+ */
+ gen_bitlen(s, desc);
+
+ /* The field len is now set, we can generate the bit codes */
+ gen_codes(tree, max_code, s.bl_count);
+}
+
+
+/* ===========================================================================
+ * Scan a literal or distance tree to determine the frequencies of the codes
+ * in the bit length tree.
+ */
+function scan_tree(s, tree, max_code)
+// deflate_state *s;
+// ct_data *tree; /* the tree to be scanned */
+// int max_code; /* and its largest code of non zero frequency */
+{
+ var n; /* iterates over all tree elements */
+ var prevlen = -1; /* last emitted length */
+ var curlen; /* length of current code */
+
+ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
+
+ var count = 0; /* repeat count of the current code */
+ var max_count = 7; /* max repeat count */
+ var min_count = 4; /* min repeat count */
+
+ if (nextlen === 0) {
+ max_count = 138;
+ min_count = 3;
+ }
+ tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
+
+ for (n = 0; n <= max_code; n++) {
+ curlen = nextlen;
+ nextlen = tree[(n+1)*2 + 1]/*.Len*/;
+
+ if (++count < max_count && curlen === nextlen) {
+ continue;
+
+ } else if (count < min_count) {
+ s.bl_tree[curlen * 2]/*.Freq*/ += count;
+
+ } else if (curlen !== 0) {
+
+ if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
+ s.bl_tree[REP_3_6*2]/*.Freq*/++;
+
+ } else if (count <= 10) {
+ s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
+
+ } else {
+ s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
+ }
+
+ count = 0;
+ prevlen = curlen;
+
+ if (nextlen === 0) {
+ max_count = 138;
+ min_count = 3;
+
+ } else if (curlen === nextlen) {
+ max_count = 6;
+ min_count = 3;
+
+ } else {
+ max_count = 7;
+ min_count = 4;
+ }
+ }
+}
+
+
+/* ===========================================================================
+ * Send a literal or distance tree in compressed form, using the codes in
+ * bl_tree.
+ */
+function send_tree(s, tree, max_code)
+// deflate_state *s;
+// ct_data *tree; /* the tree to be scanned */
+// int max_code; /* and its largest code of non zero frequency */
+{
+ var n; /* iterates over all tree elements */
+ var prevlen = -1; /* last emitted length */
+ var curlen; /* length of current code */
+
+ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
+
+ var count = 0; /* repeat count of the current code */
+ var max_count = 7; /* max repeat count */
+ var min_count = 4; /* min repeat count */
+
+ /* tree[max_code+1].Len = -1; */ /* guard already set */
+ if (nextlen === 0) {
+ max_count = 138;
+ min_count = 3;
+ }
+
+ for (n = 0; n <= max_code; n++) {
+ curlen = nextlen;
+ nextlen = tree[(n+1)*2 + 1]/*.Len*/;
+
+ if (++count < max_count && curlen === nextlen) {
+ continue;
+
+ } else if (count < min_count) {
+ do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
+
+ } else if (curlen !== 0) {
+ if (curlen !== prevlen) {
+ send_code(s, curlen, s.bl_tree);
+ count--;
+ }
+ //Assert(count >= 3 && count <= 6, " 3_6?");
+ send_code(s, REP_3_6, s.bl_tree);
+ send_bits(s, count-3, 2);
+
+ } else if (count <= 10) {
+ send_code(s, REPZ_3_10, s.bl_tree);
+ send_bits(s, count-3, 3);
+
+ } else {
+ send_code(s, REPZ_11_138, s.bl_tree);
+ send_bits(s, count-11, 7);
+ }
+
+ count = 0;
+ prevlen = curlen;
+ if (nextlen === 0) {
+ max_count = 138;
+ min_count = 3;
+
+ } else if (curlen === nextlen) {
+ max_count = 6;
+ min_count = 3;
+
+ } else {
+ max_count = 7;
+ min_count = 4;
+ }
+ }
+}
+
+
+/* ===========================================================================
+ * Construct the Huffman tree for the bit lengths and return the index in
+ * bl_order of the last bit length code to send.
+ */
+function build_bl_tree(s) {
+ var max_blindex; /* index of last bit length code of non zero freq */
+
+ /* Determine the bit length frequencies for literal and distance trees */
+ scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
+ scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
+
+ /* Build the bit length tree: */
+ build_tree(s, s.bl_desc);
+ /* opt_len now includes the length of the tree representations, except
+ * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
+ */
+
+ /* Determine the number of bit length codes to send. The pkzip format
+ * requires that at least 4 bit length codes be sent. (appnote.txt says
+ * 3 but the actual value used is 4.)
+ */
+ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
+ if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
+ break;
+ }
+ }
+ /* Update opt_len to include the bit length tree and counts */
+ s.opt_len += 3*(max_blindex+1) + 5+5+4;
+ //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
+ // s->opt_len, s->static_len));
+
+ return max_blindex;
+}
+
+
+/* ===========================================================================
+ * Send the header for a block using dynamic Huffman trees: the counts, the
+ * lengths of the bit length codes, the literal tree and the distance tree.
+ * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
+ */
+function send_all_trees(s, lcodes, dcodes, blcodes)
+// deflate_state *s;
+// int lcodes, dcodes, blcodes; /* number of codes for each tree */
+{
+ var rank; /* index in bl_order */
+
+ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
+ //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
+ // "too many codes");
+ //Tracev((stderr, "\nbl counts: "));
+ send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
+ send_bits(s, dcodes-1, 5);
+ send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
+ for (rank = 0; rank < blcodes; rank++) {
+ //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
+ send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
+ }
+ //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
+
+ send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
+ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
+
+ send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
+ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
+}
+
+
+/* ===========================================================================
+ * Check if the data type is TEXT or BINARY, using the following algorithm:
+ * - TEXT if the two conditions below are satisfied:
+ * a) There are no non-portable control characters belonging to the
+ * "black list" (0..6, 14..25, 28..31).
+ * b) There is at least one printable character belonging to the
+ * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
+ * - BINARY otherwise.
+ * - The following partially-portable control characters form a
+ * "gray list" that is ignored in this detection algorithm:
+ * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
+ * IN assertion: the fields Freq of dyn_ltree are set.
+ */
+function detect_data_type(s) {
+ /* black_mask is the bit mask of black-listed bytes
+ * set bits 0..6, 14..25, and 28..31
+ * 0xf3ffc07f = binary 11110011111111111100000001111111
+ */
+ var black_mask = 0xf3ffc07f;
+ var n;
+
+ /* Check for non-textual ("black-listed") bytes. */
+ for (n = 0; n <= 31; n++, black_mask >>>= 1) {
+ if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
+ return Z_BINARY;
+ }
+ }
+
+ /* Check for textual ("white-listed") bytes. */
+ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
+ s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
+ return Z_TEXT;
+ }
+ for (n = 32; n < LITERALS; n++) {
+ if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
+ return Z_TEXT;
+ }
+ }
+
+ /* There are no "black-listed" or "white-listed" bytes:
+ * this stream either is empty or has tolerated ("gray-listed") bytes only.
+ */
+ return Z_BINARY;
+}
+
+
+var static_init_done = false;
+
+/* ===========================================================================
+ * Initialize the tree data structures for a new zlib stream.
+ */
+function _tr_init(s)
+{
+
+ if (!static_init_done) {
+ tr_static_init();
+ static_init_done = true;
+ }
+
+ s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
+ s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
+ s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
+
+ s.bi_buf = 0;
+ s.bi_valid = 0;
+
+ /* Initialize the first block of the first file: */
+ init_block(s);
+}
+
+
+/* ===========================================================================
+ * Send a stored block
+ */
+function _tr_stored_block(s, buf, stored_len, last)
+//DeflateState *s;
+//charf *buf; /* input block */
+//ulg stored_len; /* length of input block */
+//int last; /* one if this is the last block for a file */
+{
+ send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
+ copy_block(s, buf, stored_len, true); /* with header */
+}
+
+
+/* ===========================================================================
+ * Send one empty static block to give enough lookahead for inflate.
+ * This takes 10 bits, of which 7 may remain in the bit buffer.
+ */
+function _tr_align(s) {
+ send_bits(s, STATIC_TREES<<1, 3);
+ send_code(s, END_BLOCK, static_ltree);
+ bi_flush(s);
+}
+
+
+/* ===========================================================================
+ * Determine the best encoding for the current block: dynamic trees, static
+ * trees or store, and output the encoded block to the zip file.
+ */
+function _tr_flush_block(s, buf, stored_len, last)
+//DeflateState *s;
+//charf *buf; /* input block, or NULL if too old */
+//ulg stored_len; /* length of input block */
+//int last; /* one if this is the last block for a file */
+{
+ var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
+ var max_blindex = 0; /* index of last bit length code of non zero freq */
+
+ /* Build the Huffman trees unless a stored block is forced */
+ if (s.level > 0) {
+
+ /* Check if the file is binary or text */
+ if (s.strm.data_type === Z_UNKNOWN) {
+ s.strm.data_type = detect_data_type(s);
+ }
+
+ /* Construct the literal and distance trees */
+ build_tree(s, s.l_desc);
+ // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
+ // s->static_len));
+
+ build_tree(s, s.d_desc);
+ // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
+ // s->static_len));
+ /* At this point, opt_len and static_len are the total bit lengths of
+ * the compressed block data, excluding the tree representations.
+ */
+
+ /* Build the bit length tree for the above two trees, and get the index
+ * in bl_order of the last bit length code to send.
+ */
+ max_blindex = build_bl_tree(s);
+
+ /* Determine the best encoding. Compute the block lengths in bytes. */
+ opt_lenb = (s.opt_len+3+7) >>> 3;
+ static_lenb = (s.static_len+3+7) >>> 3;
+
+ // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
+ // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
+ // s->last_lit));
+
+ if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
+
+ } else {
+ // Assert(buf != (char*)0, "lost buf");
+ opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
+ }
+
+ if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
+ /* 4: two words for the lengths */
+
+ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
+ * Otherwise we can't have processed more than WSIZE input bytes since
+ * the last block flush, because compression would have been
+ * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
+ * transform a block into a stored block.
+ */
+ _tr_stored_block(s, buf, stored_len, last);
+
+ } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
+
+ send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
+ compress_block(s, static_ltree, static_dtree);
+
+ } else {
+ send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
+ send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
+ compress_block(s, s.dyn_ltree, s.dyn_dtree);
+ }
+ // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
+ /* The above check is made mod 2^32, for files larger than 512 MB
+ * and uLong implemented on 32 bits.
+ */
+ init_block(s);
+
+ if (last) {
+ bi_windup(s);
+ }
+ // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
+ // s->compressed_len-7*last));
+}
+
+/* ===========================================================================
+ * Save the match info and tally the frequency counts. Return true if
+ * the current block must be flushed.
+ */
+function _tr_tally(s, dist, lc)
+// deflate_state *s;
+// unsigned dist; /* distance of matched string */
+// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
+{
+ //var out_length, in_length, dcode;
+
+ s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
+ s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
+
+ s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
+ s.last_lit++;
+
+ if (dist === 0) {
+ /* lc is the unmatched char */
+ s.dyn_ltree[lc*2]/*.Freq*/++;
+ } else {
+ s.matches++;
+ /* Here, lc is the match length - MIN_MATCH */
+ dist--; /* dist = match distance - 1 */
+ //Assert((ush)dist < (ush)MAX_DIST(s) &&
+ // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
+ // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
+
+ s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
+ s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
+ }
+
+// (!) This block is disabled in zlib defailts,
+// don't enable it for binary compatibility
+
+//#ifdef TRUNCATE_BLOCK
+// /* Try to guess if it is profitable to stop the current block here */
+// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
+// /* Compute an upper bound for the compressed length */
+// out_length = s.last_lit*8;
+// in_length = s.strstart - s.block_start;
+//
+// for (dcode = 0; dcode < D_CODES; dcode++) {
+// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
+// }
+// out_length >>>= 3;
+// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
+// // s->last_lit, in_length, out_length,
+// // 100L - out_length*100L/in_length));
+// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
+// return true;
+// }
+// }
+//#endif
+
+ return (s.last_lit === s.lit_bufsize-1);
+ /* We avoid equality with lit_bufsize because of wraparound at 64K
+ * on 16 bit machines and because stored blocks are restricted to
+ * 64K-1 bytes.
+ */
+}
+
+exports._tr_init = _tr_init;
+exports._tr_stored_block = _tr_stored_block;
+exports._tr_flush_block = _tr_flush_block;
+exports._tr_tally = _tr_tally;
+exports._tr_align = _tr_align;
+
+},{"../utils/common":32}],44:[function(require,module,exports){
+'use strict';
+
+
+function ZStream() {
+ /* next input byte */
+ this.input = null; // JS specific, because we have no pointers
+ this.next_in = 0;
+ /* number of bytes available at input */
+ this.avail_in = 0;
+ /* total number of input bytes read so far */
+ this.total_in = 0;
+ /* next output byte should be put there */
+ this.output = null; // JS specific, because we have no pointers
+ this.next_out = 0;
+ /* remaining free space at output */
+ this.avail_out = 0;
+ /* total number of bytes output so far */
+ this.total_out = 0;
+ /* last error message, NULL if no error */
+ this.msg = ''/*Z_NULL*/;
+ /* not visible by applications */
+ this.state = null;
+ /* best guess about the data type: binary or text */
+ this.data_type = 2/*Z_UNKNOWN*/;
+ /* adler32 value of the uncompressed data */
+ this.adler = 0;
+}
+
+module.exports = ZStream;
+
+},{}],45:[function(require,module,exports){
+// shim for using process in browser
+
+var process = module.exports = {};
+var queue = [];
+var draining = false;
+var currentQueue;
+var queueIndex = -1;
+
+function cleanUpNextTick() {
+ draining = false;
+ if (currentQueue.length) {
+ queue = currentQueue.concat(queue);
+ } else {
+ queueIndex = -1;
+ }
+ if (queue.length) {
+ drainQueue();
+ }
+}
+
+function drainQueue() {
+ if (draining) {
+ return;
+ }
+ var timeout = setTimeout(cleanUpNextTick);
+ draining = true;
+
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ while (++queueIndex < len) {
+ if (currentQueue) {
+ currentQueue[queueIndex].run();
+ }
+ }
+ queueIndex = -1;
+ len = queue.length;
+ }
+ currentQueue = null;
+ draining = false;
+ clearTimeout(timeout);
+}
+
+process.nextTick = function (fun) {
+ var args = new Array(arguments.length - 1);
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+ }
+ queue.push(new Item(fun, args));
+ if (queue.length === 1 && !draining) {
+ setTimeout(drainQueue, 0);
+ }
+};
+
+// v8 likes predictible objects
+function Item(fun, array) {
+ this.fun = fun;
+ this.array = array;
+}
+Item.prototype.run = function () {
+ this.fun.apply(null, this.array);
+};
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+process.versions = {};
+
+function noop() {}
+
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
+
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
+};
+
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
+};
+process.umask = function() { return 0; };
+
+},{}],46:[function(require,module,exports){
+module.exports = function isBuffer(arg) {
+ return arg && typeof arg === 'object'
+ && typeof arg.copy === 'function'
+ && typeof arg.fill === 'function'
+ && typeof arg.readUInt8 === 'function';
+}
+},{}],47:[function(require,module,exports){
+(function (process,global){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var formatRegExp = /%[sdj%]/g;
+exports.format = function(f) {
+ if (!isString(f)) {
+ var objects = [];
+ for (var i = 0; i < arguments.length; i++) {
+ objects.push(inspect(arguments[i]));
+ }
+ return objects.join(' ');
+ }
+
+ var i = 1;
+ var args = arguments;
+ var len = args.length;
+ var str = String(f).replace(formatRegExp, function(x) {
+ if (x === '%%') return '%';
+ if (i >= len) return x;
+ switch (x) {
+ case '%s': return String(args[i++]);
+ case '%d': return Number(args[i++]);
+ case '%j':
+ try {
+ return JSON.stringify(args[i++]);
+ } catch (_) {
+ return '[Circular]';
+ }
+ default:
+ return x;
+ }
+ });
+ for (var x = args[i]; i < len; x = args[++i]) {
+ if (isNull(x) || !isObject(x)) {
+ str += ' ' + x;
+ } else {
+ str += ' ' + inspect(x);
+ }
+ }
+ return str;
+};
+
+
+// Mark that a method should not be used.
+// Returns a modified function which warns once by default.
+// If --no-deprecation is set, then it is a no-op.
+exports.deprecate = function(fn, msg) {
+ // Allow for deprecating things in the process of starting up.
+ if (isUndefined(global.process)) {
+ return function() {
+ return exports.deprecate(fn, msg).apply(this, arguments);
+ };
+ }
+
+ if (process.noDeprecation === true) {
+ return fn;
+ }
+
+ var warned = false;
+ function deprecated() {
+ if (!warned) {
+ if (process.throwDeprecation) {
+ throw new Error(msg);
+ } else if (process.traceDeprecation) {
+ console.trace(msg);
+ } else {
+ console.error(msg);
+ }
+ warned = true;
+ }
+ return fn.apply(this, arguments);
+ }
+
+ return deprecated;
+};
+
+
+var debugs = {};
+var debugEnviron;
+exports.debuglog = function(set) {
+ if (isUndefined(debugEnviron))
+ debugEnviron = process.env.NODE_DEBUG || '';
+ set = set.toUpperCase();
+ if (!debugs[set]) {
+ if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
+ var pid = process.pid;
+ debugs[set] = function() {
+ var msg = exports.format.apply(exports, arguments);
+ console.error('%s %d: %s', set, pid, msg);
+ };
+ } else {
+ debugs[set] = function() {};
+ }
+ }
+ return debugs[set];
+};
+
+
+/**
+ * Echos the value of a value. Trys to print the value out
+ * in the best way possible given the different types.
+ *
+ * @param {Object} obj The object to print out.
+ * @param {Object} opts Optional options object that alters the output.
+ */
+/* legacy: obj, showHidden, depth, colors*/
+function inspect(obj, opts) {
+ // default options
+ var ctx = {
+ seen: [],
+ stylize: stylizeNoColor
+ };
+ // legacy...
+ if (arguments.length >= 3) ctx.depth = arguments[2];
+ if (arguments.length >= 4) ctx.colors = arguments[3];
+ if (isBoolean(opts)) {
+ // legacy...
+ ctx.showHidden = opts;
+ } else if (opts) {
+ // got an "options" object
+ exports._extend(ctx, opts);
+ }
+ // set default options
+ if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
+ if (isUndefined(ctx.depth)) ctx.depth = 2;
+ if (isUndefined(ctx.colors)) ctx.colors = false;
+ if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
+ if (ctx.colors) ctx.stylize = stylizeWithColor;
+ return formatValue(ctx, obj, ctx.depth);
+}
+exports.inspect = inspect;
+
+
+// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
+inspect.colors = {
+ 'bold' : [1, 22],
+ 'italic' : [3, 23],
+ 'underline' : [4, 24],
+ 'inverse' : [7, 27],
+ 'white' : [37, 39],
+ 'grey' : [90, 39],
+ 'black' : [30, 39],
+ 'blue' : [34, 39],
+ 'cyan' : [36, 39],
+ 'green' : [32, 39],
+ 'magenta' : [35, 39],
+ 'red' : [31, 39],
+ 'yellow' : [33, 39]
+};
+
+// Don't use 'blue' not visible on cmd.exe
+inspect.styles = {
+ 'special': 'cyan',
+ 'number': 'yellow',
+ 'boolean': 'yellow',
+ 'undefined': 'grey',
+ 'null': 'bold',
+ 'string': 'green',
+ 'date': 'magenta',
+ // "name": intentionally not styling
+ 'regexp': 'red'
+};
+
+
+function stylizeWithColor(str, styleType) {
+ var style = inspect.styles[styleType];
+
+ if (style) {
+ return '\u001b[' + inspect.colors[style][0] + 'm' + str +
+ '\u001b[' + inspect.colors[style][1] + 'm';
+ } else {
+ return str;
+ }
+}
+
+
+function stylizeNoColor(str, styleType) {
+ return str;
+}
+
+
+function arrayToHash(array) {
+ var hash = {};
+
+ array.forEach(function(val, idx) {
+ hash[val] = true;
+ });
+
+ return hash;
+}
+
+
+function formatValue(ctx, value, recurseTimes) {
+ // Provide a hook for user-specified inspect functions.
+ // Check that value is an object with an inspect function on it
+ if (ctx.customInspect &&
+ value &&
+ isFunction(value.inspect) &&
+ // Filter out the util module, it's inspect function is special
+ value.inspect !== exports.inspect &&
+ // Also filter out any prototype objects using the circular check.
+ !(value.constructor && value.constructor.prototype === value)) {
+ var ret = value.inspect(recurseTimes, ctx);
+ if (!isString(ret)) {
+ ret = formatValue(ctx, ret, recurseTimes);
+ }
+ return ret;
+ }
+
+ // Primitive types cannot have properties
+ var primitive = formatPrimitive(ctx, value);
+ if (primitive) {
+ return primitive;
+ }
+
+ // Look up the keys of the object.
+ var keys = Object.keys(value);
+ var visibleKeys = arrayToHash(keys);
+
+ if (ctx.showHidden) {
+ keys = Object.getOwnPropertyNames(value);
+ }
+
+ // IE doesn't make error fields non-enumerable
+ // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
+ if (isError(value)
+ && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
+ return formatError(value);
+ }
+
+ // Some type of object without properties can be shortcutted.
+ if (keys.length === 0) {
+ if (isFunction(value)) {
+ var name = value.name ? ': ' + value.name : '';
+ return ctx.stylize('[Function' + name + ']', 'special');
+ }
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ }
+ if (isDate(value)) {
+ return ctx.stylize(Date.prototype.toString.call(value), 'date');
+ }
+ if (isError(value)) {
+ return formatError(value);
+ }
+ }
+
+ var base = '', array = false, braces = ['{', '}'];
+
+ // Make Array say that they are Array
+ if (isArray(value)) {
+ array = true;
+ braces = ['[', ']'];
+ }
+
+ // Make functions say that they are functions
+ if (isFunction(value)) {
+ var n = value.name ? ': ' + value.name : '';
+ base = ' [Function' + n + ']';
+ }
+
+ // Make RegExps say that they are RegExps
+ if (isRegExp(value)) {
+ base = ' ' + RegExp.prototype.toString.call(value);
+ }
+
+ // Make dates with properties first say the date
+ if (isDate(value)) {
+ base = ' ' + Date.prototype.toUTCString.call(value);
+ }
+
+ // Make error with message first say the error
+ if (isError(value)) {
+ base = ' ' + formatError(value);
+ }
+
+ if (keys.length === 0 && (!array || value.length == 0)) {
+ return braces[0] + base + braces[1];
+ }
+
+ if (recurseTimes < 0) {
+ if (isRegExp(value)) {
+ return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
+ } else {
+ return ctx.stylize('[Object]', 'special');
+ }
+ }
+
+ ctx.seen.push(value);
+
+ var output;
+ if (array) {
+ output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
+ } else {
+ output = keys.map(function(key) {
+ return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
+ });
+ }
+
+ ctx.seen.pop();
+
+ return reduceToSingleString(output, base, braces);
+}
+
+
+function formatPrimitive(ctx, value) {
+ if (isUndefined(value))
+ return ctx.stylize('undefined', 'undefined');
+ if (isString(value)) {
+ var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
+ .replace(/'/g, "\\'")
+ .replace(/\\"/g, '"') + '\'';
+ return ctx.stylize(simple, 'string');
+ }
+ if (isNumber(value))
+ return ctx.stylize('' + value, 'number');
+ if (isBoolean(value))
+ return ctx.stylize('' + value, 'boolean');
+ // For some reason typeof null is "object", so special case here.
+ if (isNull(value))
+ return ctx.stylize('null', 'null');
+}
+
+
+function formatError(value) {
+ return '[' + Error.prototype.toString.call(value) + ']';
+}
+
+
+function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
+ var output = [];
+ for (var i = 0, l = value.length; i < l; ++i) {
+ if (hasOwnProperty(value, String(i))) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+ String(i), true));
+ } else {
+ output.push('');
+ }
+ }
+ keys.forEach(function(key) {
+ if (!key.match(/^\d+$/)) {
+ output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
+ key, true));
+ }
+ });
+ return output;
+}
+
+
+function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
+ var name, str, desc;
+ desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
+ if (desc.get) {
+ if (desc.set) {
+ str = ctx.stylize('[Getter/Setter]', 'special');
+ } else {
+ str = ctx.stylize('[Getter]', 'special');
+ }
+ } else {
+ if (desc.set) {
+ str = ctx.stylize('[Setter]', 'special');
+ }
+ }
+ if (!hasOwnProperty(visibleKeys, key)) {
+ name = '[' + key + ']';
+ }
+ if (!str) {
+ if (ctx.seen.indexOf(desc.value) < 0) {
+ if (isNull(recurseTimes)) {
+ str = formatValue(ctx, desc.value, null);
+ } else {
+ str = formatValue(ctx, desc.value, recurseTimes - 1);
+ }
+ if (str.indexOf('\n') > -1) {
+ if (array) {
+ str = str.split('\n').map(function(line) {
+ return ' ' + line;
+ }).join('\n').substr(2);
+ } else {
+ str = '\n' + str.split('\n').map(function(line) {
+ return ' ' + line;
+ }).join('\n');
+ }
+ }
+ } else {
+ str = ctx.stylize('[Circular]', 'special');
+ }
+ }
+ if (isUndefined(name)) {
+ if (array && key.match(/^\d+$/)) {
+ return str;
+ }
+ name = JSON.stringify('' + key);
+ if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
+ name = name.substr(1, name.length - 2);
+ name = ctx.stylize(name, 'name');
+ } else {
+ name = name.replace(/'/g, "\\'")
+ .replace(/\\"/g, '"')
+ .replace(/(^"|"$)/g, "'");
+ name = ctx.stylize(name, 'string');
+ }
+ }
+
+ return name + ': ' + str;
+}
+
+
+function reduceToSingleString(output, base, braces) {
+ var numLinesEst = 0;
+ var length = output.reduce(function(prev, cur) {
+ numLinesEst++;
+ if (cur.indexOf('\n') >= 0) numLinesEst++;
+ return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
+ }, 0);
+
+ if (length > 60) {
+ return braces[0] +
+ (base === '' ? '' : base + '\n ') +
+ ' ' +
+ output.join(',\n ') +
+ ' ' +
+ braces[1];
+ }
+
+ return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
+}
+
+
+// NOTE: These type checking functions intentionally don't use `instanceof`
+// because it is fragile and can be easily faked with `Object.create()`.
+function isArray(ar) {
+ return Array.isArray(ar);
+}
+exports.isArray = isArray;
+
+function isBoolean(arg) {
+ return typeof arg === 'boolean';
+}
+exports.isBoolean = isBoolean;
+
+function isNull(arg) {
+ return arg === null;
+}
+exports.isNull = isNull;
+
+function isNullOrUndefined(arg) {
+ return arg == null;
+}
+exports.isNullOrUndefined = isNullOrUndefined;
+
+function isNumber(arg) {
+ return typeof arg === 'number';
+}
+exports.isNumber = isNumber;
+
+function isString(arg) {
+ return typeof arg === 'string';
+}
+exports.isString = isString;
+
+function isSymbol(arg) {
+ return typeof arg === 'symbol';
+}
+exports.isSymbol = isSymbol;
+
+function isUndefined(arg) {
+ return arg === void 0;
+}
+exports.isUndefined = isUndefined;
+
+function isRegExp(re) {
+ return isObject(re) && objectToString(re) === '[object RegExp]';
+}
+exports.isRegExp = isRegExp;
+
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+}
+exports.isObject = isObject;
+
+function isDate(d) {
+ return isObject(d) && objectToString(d) === '[object Date]';
+}
+exports.isDate = isDate;
+
+function isError(e) {
+ return isObject(e) &&
+ (objectToString(e) === '[object Error]' || e instanceof Error);
+}
+exports.isError = isError;
+
+function isFunction(arg) {
+ return typeof arg === 'function';
+}
+exports.isFunction = isFunction;
+
+function isPrimitive(arg) {
+ return arg === null ||
+ typeof arg === 'boolean' ||
+ typeof arg === 'number' ||
+ typeof arg === 'string' ||
+ typeof arg === 'symbol' || // ES6 symbol
+ typeof arg === 'undefined';
+}
+exports.isPrimitive = isPrimitive;
+
+exports.isBuffer = require('./support/isBuffer');
+
+function objectToString(o) {
+ return Object.prototype.toString.call(o);
+}
+
+
+function pad(n) {
+ return n < 10 ? '0' + n.toString(10) : n.toString(10);
+}
+
+
+var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
+ 'Oct', 'Nov', 'Dec'];
+
+// 26 Feb 16:19:34
+function timestamp() {
+ var d = new Date();
+ var time = [pad(d.getHours()),
+ pad(d.getMinutes()),
+ pad(d.getSeconds())].join(':');
+ return [d.getDate(), months[d.getMonth()], time].join(' ');
+}
+
+
+// log is just a thin wrapper to console.log that prepends a timestamp
+exports.log = function() {
+ console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
+};
+
+
+/**
+ * Inherit the prototype methods from one constructor into another.
+ *
+ * The Function.prototype.inherits from lang.js rewritten as a standalone
+ * function (not on Function.prototype). NOTE: If this file is to be loaded
+ * during bootstrapping this function needs to be rewritten using some native
+ * functions as prototype setup using normal JavaScript does not work as
+ * expected during bootstrapping (see mirror.js in r114903).
+ *
+ * @param {function} ctor Constructor function which needs to inherit the
+ * prototype.
+ * @param {function} superCtor Constructor function to inherit prototype from.
+ */
+exports.inherits = require('inherits');
+
+exports._extend = function(origin, add) {
+ // Don't do anything if add isn't an object
+ if (!add || !isObject(add)) return origin;
+
+ var keys = Object.keys(add);
+ var i = keys.length;
+ while (i--) {
+ origin[keys[i]] = add[keys[i]];
+ }
+ return origin;
+};
+
+function hasOwnProperty(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+}
+
+}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+
+},{"./support/isBuffer":46,"_process":45,"inherits":7}],48:[function(require,module,exports){
+'use strict';
+
+// MODULES //
+
+var isString = require( 'validate.io-string-primitive' );
+var isNonNegativeInteger = require( 'validate.io-nonnegative-integer' );
+var ceil = require( 'math-ceil' );
+var repeat = require( 'utils-repeat-string' );
+
+
+// CONSTANTS //
+
+var MAX_SAFE_INTEGER = 9007199254740991; // 2**53 - 1
+
+
+// LEFT PAD //
+
+/**
+* FUNCTION: lpad( str, len[, pad] )
+* Left pads a string such that the padded string has a length of at least `len`.
+*
+* @param {String} str - string to pad
+* @param {Number} len - minimum string length
+* @param {String} [pad=' '] - string used to pad
+* @returns {String} padded string
+*/
+function lpad( str, len, pad ) {
+ var n;
+ var p;
+ if ( !isString( str ) ) {
+ throw new TypeError( 'invalid input argument. First argument must be a string. Value: `' + str + '`.' );
+ }
+ if ( !isNonNegativeInteger( len ) ) {
+ throw new TypeError( 'invalid input argument. Second argument must be a nonnegative integer. Value: `' + len + '`.' );
+ }
+ if ( arguments.length > 2 ) {
+ p = pad;
+ if ( !isString( p ) ) {
+ throw new TypeError( 'invalid input argument. Third argument must be a string. Value: `' + p + '`.' );
+ }
+ if ( p.length === 0 ) {
+ throw new RangeError( 'invalid input argument. Pad string must not be an empty string.' );
+ }
+ } else {
+ p = ' ';
+ }
+ if ( len > MAX_SAFE_INTEGER ) {
+ throw new RangeError( 'invalid input argument. Output string length exceeds maximum allowed string length.' );
+ }
+ n = ( len - str.length ) / p.length;
+ if ( n <= 0 ) {
+ return str;
+ }
+ n = ceil( n );
+ return repeat( p, n ) + str;
+} // end FUNCTION lpad()
+
+
+// EXPORTS //
+
+module.exports = lpad;
+
+},{"math-ceil":19,"utils-repeat-string":49,"validate.io-nonnegative-integer":52,"validate.io-string-primitive":54}],49:[function(require,module,exports){
+'use strict';
+
+// MODULES //
+
+var isString = require( 'validate.io-string-primitive' );
+var isNonNegativeInteger = require( 'validate.io-nonnegative-integer' );
+
+
+// NOTES //
+
+/**
+* The algorithmic trick used in the implementation is to treat string concatenation the same as binary addition (i.e., any natural number (nonnegative integer) can be expressed as a sum of powers of two).
+*
+* For example,
+*
+* n = 10 => 1010 => 2^3 + 2^0 + 2^1 + 2^0
+*
+* We can produce a 10-repeat string by "adding" the results of a 8-repeat string and a 2-repeat string.
+*
+* The implementation is then as follows:
+* : Let `s` be the string to be repeated and `o` be an output string.
+* 0) Initialize an output string `o`.
+* 1) Check the least significant bit to determine if the current `s` string should be "added" to the output "total".
+* - if the bit is a one, add
+* - otherwise, move on
+* 2) Double the string `s` by adding `s` to `s`.
+* 3) Right-shift the bits of `n`.
+* 4) Check if we have shifted off all bits.
+* - if yes, done.
+* - otherwise, move on
+* 5) Repeat 1-4.
+*
+* The result is that, as the string is repeated, we continually check to see if the doubled string is one which we want to add to our "total".
+*
+* The algorithm runs in O(log_2(n)) compared to O(n).
+*/
+
+
+// CONSTANTS //
+
+var MAX_SAFE_INTEGER = 9007199254740991; // 2**53 - 1
+
+
+// REPEAT //
+
+/**
+* FUNCTION: repeat( str, n )
+* Repeats a string a specified number of times and returns the concatenated result.
+*
+* @param {String} str - string to repeat
+* @param {Number} n - number of times to repeat the string
+* @returns {String}
+*/
+function repeat( str, n ) {
+ var rpt;
+ var cnt;
+ if ( !isString( str ) ) {
+ throw new TypeError( 'invalid input argument. First argument must be a string. Value: `' + str + '`.' );
+ }
+ if ( !isNonNegativeInteger( n ) ) {
+ throw new TypeError( 'invalid input argument. Second argument must be a nonnegative integer. Value: `' + n + '`.' );
+ }
+ if ( str.length === 0 || n === 0 ) {
+ return '';
+ }
+ // Check that output string will not exceed the maximum string length:
+ if ( str.length * n > MAX_SAFE_INTEGER ) {
+ throw new RangeError( 'invalid input argument. Output string length exceeds maximum allowed string length.' );
+ }
+ rpt = '';
+ cnt = n;
+ for( ; ; ) {
+ // If the count is odd, append the current concatenated string:
+ if ( (cnt&1) === 1 ) {
+ rpt += str;
+ }
+ // Right-shift the bits:
+ cnt >>>= 1;
+ if ( cnt === 0 ) {
+ break;
+ }
+ // Double the string:
+ str += str;
+ }
+ return rpt;
+} // end FUNCTION repeat()
+
+
+// EXPORTS //
+
+module.exports = repeat;
+
+},{"validate.io-nonnegative-integer":52,"validate.io-string-primitive":54}],50:[function(require,module,exports){
+'use strict';
+
+// MODULES //
+
+var isString = require( 'validate.io-string-primitive' );
+var isNonNegativeInteger = require( 'validate.io-nonnegative-integer' );
+var ceil = require( 'math-ceil' );
+var repeat = require( 'utils-repeat-string' );
+
+
+// CONSTANTS //
+
+var MAX_SAFE_INTEGER = 9007199254740991; // 2**53 - 1
+
+
+// RIGHT PAD //
+
+/**
+* FUNCTION: rpad( str, len[, pad] )
+* Right pads a string such that the padded string has a length of at least `len`.
+*
+* @param {String} str - string to pad
+* @param {Number} len - minimum string length
+* @param {String} [pad=' '] - string used to pad
+* @returns {String} padded string
+*/
+function rpad( str, len, pad ) {
+ var n;
+ var p;
+ if ( !isString( str ) ) {
+ throw new TypeError( 'invalid input argument. First argument must be a string. Value: `' + str + '`.' );
+ }
+ if ( !isNonNegativeInteger( len ) ) {
+ throw new TypeError( 'invalid input argument. Second argument must be a nonnegative integer. Value: `' + len + '`.' );
+ }
+ if ( arguments.length > 2 ) {
+ p = pad;
+ if ( !isString( p ) ) {
+ throw new TypeError( 'invalid input argument. Third argument must be a string. Value: `' + p + '`.' );
+ }
+ if ( p.length === 0 ) {
+ throw new RangeError( 'invalid input argument. Pad string must not be an empty string.' );
+ }
+ } else {
+ p = ' ';
+ }
+ if ( len > MAX_SAFE_INTEGER ) {
+ throw new RangeError( 'invalid input argument. Output string length exceeds maximum allowed string length.' );
+ }
+ n = ( len - str.length ) / p.length;
+ if ( n <= 0 ) {
+ return str;
+ }
+ n = ceil( n );
+ return str + repeat( p, n );
+} // end FUNCTION rpad()
+
+
+// EXPORTS //
+
+module.exports = rpad;
+
+},{"math-ceil":19,"utils-repeat-string":49,"validate.io-nonnegative-integer":52,"validate.io-string-primitive":54}],51:[function(require,module,exports){
+/**
+*
+* VALIDATE: integer
+*
+*
+* DESCRIPTION:
+* - Validates if a value is an integer.
+*
+*
+* NOTES:
+* [1]
+*
+*
+* TODO:
+* [1]
+*
+*
+* LICENSE:
+* MIT
+*
+* Copyright (c) 2014. Athan Reines.
+*
+*
+* AUTHOR:
+* Athan Reines. kgryte@gmail.com. 2014.
+*
+*/
+
+'use strict';
+
+// MODULES //
+
+var isNumber = require( 'validate.io-number' );
+
+
+// ISINTEGER //
+
+/**
+* FUNCTION: isInteger( value )
+* Validates if a value is an integer.
+*
+* @param {Number} value - value to be validated
+* @returns {Boolean} boolean indicating whether value is an integer
+*/
+function isInteger( value ) {
+ return isNumber( value ) && value%1 === 0;
+} // end FUNCTION isInteger()
+
+
+// EXPORTS //
+
+module.exports = isInteger;
+
+},{"validate.io-number":53}],52:[function(require,module,exports){
+/**
+*
+* VALIDATE: nonnegative-integer
+*
+*
+* DESCRIPTION:
+* - Validates if a value is a nonnegative integer.
+*
+*
+* NOTES:
+* [1]
+*
+*
+* TODO:
+* [1]
+*
+*
+* LICENSE:
+* MIT
+*
+* Copyright (c) 2015. Athan Reines.
+*
+*
+* AUTHOR:
+* Athan Reines. kgryte@gmail.com. 2015.
+*
+*/
+
+'use strict';
+
+// MODULES //
+
+var isInteger = require( 'validate.io-integer' );
+
+
+// IS NONNEGATIVE INTEGER //
+
+/**
+* FUNCTION: isNonNegativeInteger( value )
+* Validates if a value is a nonnegative integer.
+*
+* @param {*} value - value to be validated
+* @returns {Boolean} boolean indicating if a value is a nonnegative integer
+*/
+function isNonNegativeInteger( value ) {
+ return isInteger( value ) && value >= 0;
+} // end FUNCTION isNonNegativeInteger()
+
+
+// EXPORTS //
+
+module.exports = isNonNegativeInteger;
+
+},{"validate.io-integer":51}],53:[function(require,module,exports){
+/**
+*
+* VALIDATE: number
+*
+*
+* DESCRIPTION:
+* - Validates if a value is a number.
+*
+*
+* NOTES:
+* [1]
+*
+*
+* TODO:
+* [1]
+*
+*
+* LICENSE:
+* MIT
+*
+* Copyright (c) 2014. Athan Reines.
+*
+*
+* AUTHOR:
+* Athan Reines. kgryte@gmail.com. 2014.
+*
+*/
+
+'use strict';
+
+/**
+* FUNCTION: isNumber( value )
+* Validates if a value is a number.
+*
+* @param {*} value - value to be validated
+* @returns {Boolean} boolean indicating whether value is a number
+*/
+function isNumber( value ) {
+ return ( typeof value === 'number' || Object.prototype.toString.call( value ) === '[object Number]' ) && value.valueOf() === value.valueOf();
+} // end FUNCTION isNumber()
+
+
+// EXPORTS //
+
+module.exports = isNumber;
+
+},{}],54:[function(require,module,exports){
+/**
+*
+* VALIDATE: string-primitive
+*
+*
+* DESCRIPTION:
+* - Validates if a value is a string primitive.
+*
+*
+* NOTES:
+* [1]
+*
+*
+* TODO:
+* [1]
+*
+*
+* LICENSE:
+* MIT
+*
+* Copyright (c) 2015. Athan Reines.
+*
+*
+* AUTHOR:
+* Athan Reines. kgryte@gmail.com. 2015.
+*
+*/
+
+'use strict';
+
+/**
+* FUNCTION: isString( value )
+* Validates if a value is a string primitive.
+*
+* @param {*} value - value to be validated
+* @returns {Boolean} boolean indicating if a value is a string primitive
+*/
+function isString( value ) {
+ return typeof value === 'string';
+} // end FUNCTION isString()
+
+
+// EXPORTS //
+
+module.exports = isString;
+
+},{}],55:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _cameras = require('./cameras/cameras');
+
+var _cameras2 = _interopRequireDefault(_cameras);
+
+var _controls = require('./controls/controls');
+
+var _controls2 = _interopRequireDefault(_controls);
+
+var _core = require('./core/core');
+
+var _core2 = _interopRequireDefault(_core);
+
+var _geometries = require('./geometries/geometries');
+
+var _geometries2 = _interopRequireDefault(_geometries);
+
+var _helpers = require('./helpers/helpers');
+
+var _helpers2 = _interopRequireDefault(_helpers);
+
+var _loaders = require('./loaders/loaders');
+
+var _loaders2 = _interopRequireDefault(_loaders);
+
+var _models = require('./models/models');
+
+var _models2 = _interopRequireDefault(_models);
+
+var _parsers = require('./parsers/parsers');
+
+var _parsers2 = _interopRequireDefault(_parsers);
+
+var _shaders = require('./shaders/shaders');
+
+var _shaders2 = _interopRequireDefault(_shaders);
+
+var _widgets = require('./widgets/widgets');
+
+var _widgets2 = _interopRequireDefault(_widgets);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+exports.default = {
+ Cameras: _cameras2.default,
+ Controls: _controls2.default,
+ Core: _core2.default,
+ Geometries: _geometries2.default,
+ Helpers: _helpers2.default,
+ Loaders: _loaders2.default,
+ Models: _models2.default,
+ Parsers: _parsers2.default,
+ Shaders: _shaders2.default,
+ Widgets: _widgets2.default
+};
+
+},{"./cameras/cameras":56,"./controls/controls":58,"./core/core":62,"./geometries/geometries":66,"./helpers/helpers":71,"./loaders/loaders":79,"./models/models":83,"./parsers/parsers":88,"./shaders/shaders":93,"./widgets/widgets":95}],56:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _cameras = require('./cameras.orthographic');
+
+var _cameras2 = _interopRequireDefault(_cameras);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+/**
+ * @module cameras
+ */
+exports.default = {
+ Orthographic: _cameras2.default
+};
+
+},{"./cameras.orthographic":57}],57:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+var _core = require('../core/core.intersections');
+
+var _core2 = _interopRequireDefault(_core);
+
+var _core3 = require('../core/core.validators');
+
+var _core4 = _interopRequireDefault(_core3);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
+
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
+
+/**
+ * Orthographic camera from THREE.JS with some extra convenience
+ * functionalities.
+ *
+ * @example
+ * //
+ * //
+ *
+ * @module cameras/orthographic
+ */
+
+var CamerasOrthographic = function (_THREE$OrthographicCa) {
+ _inherits(CamerasOrthographic, _THREE$OrthographicCa);
+
+ function CamerasOrthographic(left, right, top, bottom, near, far) {
+ _classCallCheck(this, CamerasOrthographic);
+
+ var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(CamerasOrthographic).call(this, left, right, top, bottom, near, far));
+
+ _this._front = null;
+ _this._back = null;
+
+ _this._xCosine = null;
+ _this._yCosine = null;
+ _this._zCosine = null;
+
+ _this._controls = null;
+ _this._box = null;
+ _this._canvas = {
+ width: null,
+ height: null
+ };
+
+ _this._fromFront = true;
+ return _this;
+ }
+
+ /**
+ * Initialize orthographic camera variables
+ */
+
+
+ _createClass(CamerasOrthographic, [{
+ key: 'init',
+ value: function init(xCosine, yCosine, zCosine, controls, box, canvas) {
+ //
+ if (!(_core4.default.vector3(xCosine) && _core4.default.vector3(yCosine) && _core4.default.vector3(zCosine) && _core4.default.box(box) && controls)) {
+ window.console.log('Invalid input provided.');
+
+ return false;
+ }
+
+ this._xCosine = xCosine;
+ this._yCosine = yCosine;
+ this._zCosine = zCosine;
+ this._controls = controls;
+ this._box = box;
+ this._canvas = canvas;
+
+ var ray = {
+ position: this._box.center,
+ direction: this._zCosine
+ };
+
+ var intersections = _core2.default.rayBox(ray, this._box);
+ this._front = intersections[0];
+ this._back = intersections[1];
+
+ // set default values
+ this.up.set(this._yCosine.x, this._yCosine.y, this._yCosine.z);
+ this._updateCanvas();
+ this._updatePositionAndTarget(this._front, this._back);
+ this._updateMatrices();
+ }
+
+ /**
+ * Invert rows in the current slice.
+ * Inverting rows in 2 steps:
+ * * Flip the "up" vector
+ * * Look at the slice from the other side
+ */
+
+ }, {
+ key: 'invertRows',
+ value: function invertRows() {
+ // flip "up" vector
+ // we flip up first because invertColumns update projectio matrices
+ this.up.multiplyScalar(-1);
+
+ this.invertColumns();
+ }
+
+ /**
+ * Invert rows in the current slice.
+ * Inverting rows in 1 step:
+ * * Look at the slice from the other side
+ */
+
+ }, {
+ key: 'invertColumns',
+ value: function invertColumns() {
+ this.center();
+ // rotate 180 degrees around the up vector...
+ var oppositePosition = this._oppositePosition(this.position);
+
+ // update posistion and target
+ // clone is needed because this.position is overwritten in method
+ this._updatePositionAndTarget(oppositePosition, this.position.clone());
+ this._updateMatrices();
+ this._fromFront = !this._fromFront;
+ }
+
+ /**
+ * Center slice in the camera FOV.
+ * It also updates the controllers properly.
+ * We can center a camera from the front or from the back.
+ */
+
+ }, {
+ key: 'center',
+ value: function center() {
+ if (this._fromFront) {
+ this._updatePositionAndTarget(this._front, this._back);
+ } else {
+ this._updatePositionAndTarget(this._back, this._front);
+ }
+
+ this._updateMatrices();
+ }
+
+ /**
+ * Pi/2 rotation around the zCosine axis.
+ * Clock-wise rotation from the user point of view.
+ */
+
+ }, {
+ key: 'rotate',
+ value: function rotate() {
+ this.center();
+
+ // Pi/2 rotation if camera is positions at the front of the volume
+ // else -Pi/2 rotation
+ var clockwise = 1;
+ if (this.position.distanceTo(this._back) < this.position.distanceTo(this._front)) {
+ clockwise = -1;
+ }
+
+ // Rotate the up vector around the "zCosine"
+ var rotation = new THREE.Matrix4().makeRotationAxis(this._zCosine, clockwise * Math.PI / 2);
+ this.up.applyMatrix4(rotation);
+
+ this._updateMatrices();
+ }
+
+ // dimensions[0] // width
+ // dimensions[1] // height
+ // direction= 0 width, 1 height, 2 best
+ // factor
+
+ }, {
+ key: 'fitBox',
+ value: function fitBox() {
+ var direction = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
+ var factor = arguments.length <= 1 || arguments[1] === undefined ? 1.5 : arguments[1];
+
+ //
+ // if (!(dimensions && dimensions.length >= 2)) {
+ // window.console.log('Invalid dimensions container.');
+ // window.console.log(dimensions);
+
+ // return false;
+ // }
+
+ //
+ var zoom = 1;
+
+ // update zoom
+ switch (direction) {
+ case 0:
+ zoom = factor * this._computeZoom(this._canvas.width, this._xCosine);
+ break;
+ case 1:
+ zoom = factor * this._computeZoom(this._canvas.height, this._yCosine);
+ break;
+ case 2:
+ zoom = factor * Math.min(this._computeZoom(this._canvas.width, this._xCosine), this._computeZoom(this._canvas.height, this._yCosine));
+ break;
+ default:
+ break;
+ }
+
+ if (!zoom) {
+ return false;
+ }
+
+ this.zoom = zoom;
+
+ this.center();
+ }
+ }, {
+ key: '_updateCanvas',
+ value: function _updateCanvas() {
+ var camFactor = 2;
+ this.left = -this._canvas.width / camFactor;
+ this.right = this._canvas.width / camFactor;
+ this.top = this._canvas.height / camFactor;
+ this.bottom = -this._canvas.height / camFactor;
+
+ this._updateMatrices();
+ this.controls.handleResize();
+ }
+ }, {
+ key: '_oppositePosition',
+ value: function _oppositePosition(position) {
+ var oppositePosition = position.clone();
+ // center world postion around box center
+ oppositePosition.sub(this._box.center);
+ // rotate
+ var rotation = new THREE.Matrix4().makeRotationAxis(this.up, Math.PI);
+ oppositePosition.applyMatrix4(rotation);
+ // translate back to world position
+ oppositePosition.add(this._box.center);
+ return oppositePosition;
+ }
+ }, {
+ key: '_computeZoom',
+ value: function _computeZoom(dimension, direction) {
+
+ if (!(dimension && dimension > 0)) {
+ window.console.log('Invalid dimension provided.');
+ window.console.log(dimension);
+ return false;
+ }
+
+ // ray
+ var ray = {
+ position: this._box.center.clone(),
+ direction: direction
+ };
+
+ var intersections = _core2.default.rayBox(ray, this._box);
+ if (intersections.length < 2) {
+ window.console.log('Can not adjust the camera ( < 2 intersections).');
+ window.console.log(ray);
+ window.console.log(this._box);
+ return false;
+ }
+
+ return dimension / intersections[0].distanceTo(intersections[1]);
+ }
+ }, {
+ key: '_updatePositionAndTarget',
+ value: function _updatePositionAndTarget(position, target) {
+ // position
+ this.position.set(position.x, position.y, position.z);
+
+ // targets
+ this.lookAt(target.x, target.y, target.z);
+ this._controls.target.set(target.x, target.y, target.z);
+ }
+ }, {
+ key: '_updateMatrices',
+ value: function _updateMatrices() {
+ this._controls.update();
+ // THEN camera
+ this.updateProjectionMatrix();
+ this.updateMatrixWorld();
+ }
+ }, {
+ key: 'xCosine',
+ set: function set(xCosine) {
+ this._xCosine = xCosine;
+ },
+ get: function get() {
+ return this._xCosine;
+ }
+ }, {
+ key: 'yCosine',
+ set: function set(yCosine) {
+ this._yCosine = yCosine;
+ },
+ get: function get() {
+ return this._yCosine;
+ }
+ }, {
+ key: 'zCosine',
+ set: function set(zCosine) {
+ this._zCosine = zCosine;
+ },
+ get: function get() {
+ return this._zCosine;
+ }
+ }, {
+ key: 'controls',
+ set: function set(controls) {
+ this._controls = controls;
+ },
+ get: function get() {
+ return this._controls;
+ }
+ }, {
+ key: 'box',
+ set: function set(box) {
+ this._box = box;
+ },
+ get: function get() {
+ return this._box;
+ }
+ }, {
+ key: 'canvas',
+ set: function set(canvas) {
+ this._canvas = canvas;
+ this._updateCanvas();
+ },
+ get: function get() {
+ return this._canvas;
+ }
+ }]);
+
+ return CamerasOrthographic;
+}(THREE.OrthographicCamera);
+
+exports.default = CamerasOrthographic;
+
+},{"../core/core.intersections":61,"../core/core.validators":65}],58:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _controls = require('./controls.trackball');
+
+var _controls2 = _interopRequireDefault(_controls);
+
+var _controls3 = require('./controls.trackballortho');
+
+var _controls4 = _interopRequireDefault(_controls3);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+exports.default = {
+ Trackball: _controls2.default,
+ TrackballOrtho: _controls4.default
+};
+
+},{"./controls.trackball":59,"./controls.trackballortho":60}],59:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
+
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
+
+/**
+ * Original authors from THREEJS repo
+ * @author Eberhard Graether / http://egraether.com/
+ * @author Mark Lundin / http://mark-lundin.com
+ * @author Simone Manini / http://daron1337.github.io
+ * @author Luca Antiga / http://lantiga.github.io
+ */
+
+var Trackball = function (_THREE$EventDispatche) {
+ _inherits(Trackball, _THREE$EventDispatche);
+
+ function Trackball(object, domElement) {
+ _classCallCheck(this, Trackball);
+
+ var _this2 = _possibleConstructorReturn(this, Object.getPrototypeOf(Trackball).call(this));
+
+ var _this = _this2;
+ var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM: 4, TOUCH_PAN: 5, CUSTOM: 99 };
+
+ _this2.object = object;
+ _this2.domElement = domElement !== undefined ? domElement : document;
+
+ // API
+
+ _this2.enabled = true;
+
+ _this2.screen = { left: 0, top: 0, width: 0, height: 0 };
+
+ _this2.rotateSpeed = 1.0;
+ _this2.zoomSpeed = 1.2;
+ _this2.panSpeed = 0.3;
+
+ _this2.noRotate = false;
+ _this2.noZoom = false;
+ _this2.noPan = false;
+ _this2.noCustom = false;
+
+ _this2.forceState = -1;
+
+ _this2.staticMoving = false;
+ _this2.dynamicDampingFactor = 0.2;
+
+ _this2.minDistance = 0;
+ _this2.maxDistance = Infinity;
+
+ _this2.keys = [65 /*A*/, 83 /*S*/, 68 /*D*/];
+
+ // internals
+
+ _this2.target = new THREE.Vector3();
+
+ var EPS = 0.000001;
+
+ var lastPosition = new THREE.Vector3();
+
+ var _state = STATE.NONE,
+ _prevState = STATE.NONE,
+ _eye = new THREE.Vector3(),
+ _movePrev = new THREE.Vector2(),
+ _moveCurr = new THREE.Vector2(),
+ _lastAxis = new THREE.Vector3(),
+ _lastAngle = 0,
+ _zoomStart = new THREE.Vector2(),
+ _zoomEnd = new THREE.Vector2(),
+ _touchZoomDistanceStart = 0,
+ _touchZoomDistanceEnd = 0,
+ _panStart = new THREE.Vector2(),
+ _panEnd = new THREE.Vector2(),
+ _customStart = new THREE.Vector2(),
+ _customEnd = new THREE.Vector2();
+
+ // for reset
+
+ _this2.target0 = _this2.target.clone();
+ _this2.position0 = _this2.object.position.clone();
+ _this2.up0 = _this2.object.up.clone();
+
+ // events
+
+ var changeEvent = { type: 'change' };
+ var startEvent = { type: 'start' };
+ var endEvent = { type: 'end' };
+
+ // methods
+
+ _this2.handleResize = function () {
+
+ if (this.domElement === document) {
+
+ this.screen.left = 0;
+ this.screen.top = 0;
+ this.screen.width = window.innerWidth;
+ this.screen.height = window.innerHeight;
+ } else {
+
+ var box = this.domElement.getBoundingClientRect();
+ // adjustments come from similar code in the jquery offset() function
+ var d = this.domElement.ownerDocument.documentElement;
+ this.screen.left = box.left + window.pageXOffset - d.clientLeft;
+ this.screen.top = box.top + window.pageYOffset - d.clientTop;
+ this.screen.width = box.width;
+ this.screen.height = box.height;
+ }
+ };
+
+ _this2.handleEvent = function (event) {
+
+ if (typeof this[event.type] == 'function') {
+
+ this[event.type](event);
+ }
+ };
+
+ var getMouseOnScreen = function () {
+
+ var vector = new THREE.Vector2();
+
+ return function (pageX, pageY) {
+
+ vector.set((pageX - _this.screen.left) / _this.screen.width, (pageY - _this.screen.top) / _this.screen.height);
+
+ return vector;
+ };
+ }();
+
+ var getMouseOnCircle = function () {
+
+ var vector = new THREE.Vector2();
+
+ return function (pageX, pageY) {
+
+ vector.set((pageX - _this.screen.width * 0.5 - _this.screen.left) / (_this.screen.width * 0.5), (_this.screen.height + 2 * (_this.screen.top - pageY)) / _this.screen.width);
+
+ // screen.width intentional
+ return vector;
+ };
+ }();
+
+ _this2.rotateCamera = function () {
+
+ var axis = new THREE.Vector3(),
+ quaternion = new THREE.Quaternion(),
+ eyeDirection = new THREE.Vector3(),
+ objectUpDirection = new THREE.Vector3(),
+ objectSidewaysDirection = new THREE.Vector3(),
+ moveDirection = new THREE.Vector3(),
+ angle;
+
+ return function () {
+
+ moveDirection.set(_moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0);
+ angle = moveDirection.length();
+
+ if (angle) {
+
+ _eye.copy(_this.object.position).sub(_this.target);
+
+ eyeDirection.copy(_eye).normalize();
+ objectUpDirection.copy(_this.object.up).normalize();
+ objectSidewaysDirection.crossVectors(objectUpDirection, eyeDirection).normalize();
+
+ objectUpDirection.setLength(_moveCurr.y - _movePrev.y);
+ objectSidewaysDirection.setLength(_moveCurr.x - _movePrev.x);
+
+ moveDirection.copy(objectUpDirection.add(objectSidewaysDirection));
+
+ axis.crossVectors(moveDirection, _eye).normalize();
+
+ angle *= _this.rotateSpeed;
+ quaternion.setFromAxisAngle(axis, angle);
+
+ _eye.applyQuaternion(quaternion);
+ _this.object.up.applyQuaternion(quaternion);
+
+ _lastAxis.copy(axis);
+ _lastAngle = angle;
+ } else if (!_this.staticMoving && _lastAngle) {
+
+ _lastAngle *= Math.sqrt(1.0 - _this.dynamicDampingFactor);
+ _eye.copy(_this.object.position).sub(_this.target);
+ quaternion.setFromAxisAngle(_lastAxis, _lastAngle);
+ _eye.applyQuaternion(quaternion);
+ _this.object.up.applyQuaternion(quaternion);
+ }
+
+ _movePrev.copy(_moveCurr);
+ };
+ }();
+
+ _this2.zoomCamera = function () {
+
+ var factor;
+
+ if (_state === STATE.TOUCH_ZOOM) {
+
+ factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
+ _touchZoomDistanceStart = _touchZoomDistanceEnd;
+ _eye.multiplyScalar(factor);
+ } else {
+
+ factor = 1.0 + (_zoomEnd.y - _zoomStart.y) * _this.zoomSpeed;
+
+ if (factor !== 1.0 && factor > 0.0) {
+
+ _eye.multiplyScalar(factor);
+
+ if (_this.staticMoving) {
+
+ _zoomStart.copy(_zoomEnd);
+ } else {
+
+ _zoomStart.y += (_zoomEnd.y - _zoomStart.y) * this.dynamicDampingFactor;
+ }
+ }
+ }
+ };
+
+ _this2.panCamera = function () {
+
+ var mouseChange = new THREE.Vector2(),
+ objectUp = new THREE.Vector3(),
+ pan = new THREE.Vector3();
+
+ return function () {
+
+ mouseChange.copy(_panEnd).sub(_panStart);
+
+ if (mouseChange.lengthSq()) {
+
+ mouseChange.multiplyScalar(_eye.length() * _this.panSpeed);
+
+ pan.copy(_eye).cross(_this.object.up).setLength(mouseChange.x);
+ pan.add(objectUp.copy(_this.object.up).setLength(mouseChange.y));
+
+ _this.object.position.add(pan);
+ _this.target.add(pan);
+
+ if (_this.staticMoving) {
+
+ _panStart.copy(_panEnd);
+ } else {
+
+ _panStart.add(mouseChange.subVectors(_panEnd, _panStart).multiplyScalar(_this.dynamicDampingFactor));
+ }
+ }
+ };
+ }();
+
+ _this2.checkDistances = function () {
+
+ if (!_this.noZoom || !_this.noPan) {
+
+ if (_eye.lengthSq() > _this.maxDistance * _this.maxDistance) {
+
+ _this.object.position.addVectors(_this.target, _eye.setLength(_this.maxDistance));
+ }
+
+ if (_eye.lengthSq() < _this.minDistance * _this.minDistance) {
+
+ _this.object.position.addVectors(_this.target, _eye.setLength(_this.minDistance));
+ }
+ }
+ };
+
+ _this2.update = function () {
+
+ _eye.subVectors(_this.object.position, _this.target);
+
+ if (!_this.noRotate) {
+
+ _this.rotateCamera();
+ }
+
+ if (!_this.noZoom) {
+
+ _this.zoomCamera();
+ }
+
+ if (!_this.noPan) {
+
+ _this.panCamera();
+ }
+
+ if (!_this.noCustom) {
+
+ _this.custom(_customStart, _customEnd);
+ }
+
+ _this.object.position.addVectors(_this.target, _eye);
+
+ _this.checkDistances();
+
+ _this.object.lookAt(_this.target);
+
+ if (lastPosition.distanceToSquared(_this.object.position) > EPS) {
+
+ _this.dispatchEvent(changeEvent);
+
+ lastPosition.copy(_this.object.position);
+ }
+ };
+
+ _this2.reset = function () {
+
+ _state = STATE.NONE;
+ _prevState = STATE.NONE;
+
+ _this.target.copy(_this.target0);
+ _this.object.position.copy(_this.position0);
+ _this.object.up.copy(_this.up0);
+
+ _eye.subVectors(_this.object.position, _this.target);
+
+ _this.object.lookAt(_this.target);
+
+ _this.dispatchEvent(changeEvent);
+
+ lastPosition.copy(_this.object.position);
+ };
+
+ _this2.setState = function (targetState) {
+
+ _this.forceState = targetState;
+ _prevState = targetState;
+ _state = targetState;
+ };
+
+ _this2.custom = function (customStart, customEnd) {};
+
+ // listeners
+
+ function keydown(event) {
+
+ if (_this.enabled === false) return;
+
+ window.removeEventListener('keydown', keydown);
+
+ _prevState = _state;
+
+ if (_state !== STATE.NONE) {
+
+ return;
+ } else if (event.keyCode === _this.keys[STATE.ROTATE] && !_this.noRotate) {
+
+ _state = STATE.ROTATE;
+ } else if (event.keyCode === _this.keys[STATE.ZOOM] && !_this.noZoom) {
+
+ _state = STATE.ZOOM;
+ } else if (event.keyCode === _this.keys[STATE.PAN] && !_this.noPan) {
+
+ _state = STATE.PAN;
+ }
+ }
+
+ function keyup(event) {
+
+ if (_this.enabled === false) return;
+
+ _state = _prevState;
+
+ window.addEventListener('keydown', keydown, false);
+ }
+
+ function mousedown(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (_state === STATE.NONE) {
+
+ _state = event.button;
+ }
+
+ if (_state === STATE.ROTATE && !_this.noRotate) {
+
+ _moveCurr.copy(getMouseOnCircle(event.pageX, event.pageY));
+ _movePrev.copy(_moveCurr);
+ } else if (_state === STATE.ZOOM && !_this.noZoom) {
+
+ _zoomStart.copy(getMouseOnScreen(event.pageX, event.pageY));
+ _zoomEnd.copy(_zoomStart);
+ } else if (_state === STATE.PAN && !_this.noPan) {
+
+ _panStart.copy(getMouseOnScreen(event.pageX, event.pageY));
+ _panEnd.copy(_panStart);
+ } else if (_state === STATE.CUSTOM && !_this.noCustom) {
+
+ _customStart.copy(getMouseOnScreen(event.pageX, event.pageY));
+ _customEnd.copy(_panStart);
+ }
+
+ document.addEventListener('mousemove', mousemove, false);
+ document.addEventListener('mouseup', mouseup, false);
+
+ _this.dispatchEvent(startEvent);
+ }
+
+ function mousemove(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (_state === STATE.ROTATE && !_this.noRotate) {
+
+ _movePrev.copy(_moveCurr);
+ _moveCurr.copy(getMouseOnCircle(event.pageX, event.pageY));
+ } else if (_state === STATE.ZOOM && !_this.noZoom) {
+
+ _zoomEnd.copy(getMouseOnScreen(event.pageX, event.pageY));
+ } else if (_state === STATE.PAN && !_this.noPan) {
+
+ _panEnd.copy(getMouseOnScreen(event.pageX, event.pageY));
+ } else if (_state === STATE.CUSTOM && !_this.noCustom) {
+
+ _customEnd.copy(getMouseOnScreen(event.pageX, event.pageY));
+ }
+ }
+
+ function mouseup(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (_this.forceState === -1) {
+ _state = STATE.NONE;
+ }
+
+ document.removeEventListener('mousemove', mousemove);
+ document.removeEventListener('mouseup', mouseup);
+ _this.dispatchEvent(endEvent);
+ }
+
+ function mousewheel(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ var delta = 0;
+
+ if (event.wheelDelta) {
+ // WebKit / Opera / Explorer 9
+
+ delta = event.wheelDelta / 40;
+ } else if (event.detail) {
+ // Firefox
+
+ delta = -event.detail / 3;
+ }
+
+ if (_state !== STATE.CUSTOM) {
+ _zoomStart.y += delta * 0.01;
+ } else if (_state === STATE.CUSTOM) {
+ _customStart.y += delta * 0.01;
+ }
+
+ _this.dispatchEvent(startEvent);
+ _this.dispatchEvent(endEvent);
+ }
+
+ function touchstart(event) {
+
+ if (_this.enabled === false) return;
+
+ if (_this.forceState === -1) {
+
+ switch (event.touches.length) {
+
+ case 1:
+ _state = STATE.TOUCH_ROTATE;
+ _moveCurr.copy(getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY));
+ _movePrev.copy(_moveCurr);
+ break;
+
+ case 2:
+ _state = STATE.TOUCH_ZOOM;
+ var dx = event.touches[0].pageX - event.touches[1].pageX;
+ var dy = event.touches[0].pageY - event.touches[1].pageY;
+ _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy);
+
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panStart.copy(getMouseOnScreen(x, y));
+ _panEnd.copy(_panStart);
+ break;
+
+ default:
+ _state = STATE.NONE;
+
+ }
+ } else {
+
+ //{ NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4, CUSTOM: 99 };
+ switch (_state) {
+
+ case 0:
+ // 1 or 2 fingers, smae behavior
+ _state = STATE.TOUCH_ROTATE;
+ _moveCurr.copy(getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY));
+ _movePrev.copy(_moveCurr);
+ break;
+
+ case 1:
+ case 4:
+ if (event.touches.length >= 2) {
+ _state = STATE.TOUCH_ZOOM;
+ var dx = event.touches[0].pageX - event.touches[1].pageX;
+ var dy = event.touches[0].pageY - event.touches[1].pageY;
+ _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy);
+ } else {
+ _state = STATE.ZOOM;
+ _zoomStart.copy(getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY));
+ _zoomEnd.copy(_zoomStart);
+ }
+ break;
+
+ case 2:
+ case 5:
+ if (event.touches.length >= 2) {
+ _state = STATE.TOUCH_PAN;
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panStart.copy(getMouseOnScreen(x, y));
+ _panEnd.copy(_panStart);
+ } else {
+ _state = STATE.PAN;
+ _panStart.copy(getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY));
+ _panEnd.copy(_panStart);
+ }
+ break;
+
+ case 99:
+ _state = STATE.CUSTOM;
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _customStart.copy(getMouseOnScreen(x, y));
+ _customEnd.copy(_customStart);
+ break;
+
+ default:
+ _state = STATE.NONE;
+
+ }
+ }
+
+ _this.dispatchEvent(startEvent);
+ }
+
+ function touchmove(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (_this.forceState === -1) {
+
+ switch (event.touches.length) {
+
+ case 1:
+ _movePrev.copy(_moveCurr);
+ _moveCurr.copy(getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY));
+ break;
+
+ case 2:
+ var dx = event.touches[0].pageX - event.touches[1].pageX;
+ var dy = event.touches[0].pageY - event.touches[1].pageY;
+ _touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy);
+
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panEnd.copy(getMouseOnScreen(x, y));
+ break;
+
+ default:
+ _state = STATE.NONE;
+ }
+ } else {
+ //{ NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4, CUSTOM: 99 };
+ switch (_state) {
+
+ case 0:
+ _movePrev.copy(_moveCurr);
+ _moveCurr.copy(getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY));
+ break;
+
+ case 1:
+ _zoomEnd.copy(getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY));
+ break;
+
+ case 2:
+ _panEnd.copy(getMouseOnScreen(event.touches[0].pageX, event.touches[0].pageY));
+ break;
+
+ case 4:
+ // 2 fingers!
+ // TOUCH ZOOM
+ var dx = event.touches[0].pageX - event.touches[1].pageX;
+ var dy = event.touches[0].pageY - event.touches[1].pageY;
+ _touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy);
+ break;
+
+ case 5:
+ // 2 fingers
+ // TOUCH_PAN
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panEnd.copy(getMouseOnScreen(x, y));
+ break;
+
+ case 99:
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _customEnd.copy(getMouseOnScreen(x, y));
+ break;
+
+ default:
+ _state = STATE.NONE;
+
+ }
+ }
+ }
+
+ function touchend(event) {
+
+ if (_this.enabled === false) return;
+
+ if (_this.forceState === -1) {
+ switch (event.touches.length) {
+
+ case 1:
+ _movePrev.copy(_moveCurr);
+ _moveCurr.copy(getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY));
+ break;
+
+ case 2:
+ _touchZoomDistanceStart = _touchZoomDistanceEnd = 0;
+
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panEnd.copy(getMouseOnScreen(x, y));
+ _panStart.copy(_panEnd);
+ break;
+
+ }
+
+ _state = STATE.NONE;
+ } else {
+ switch (_state) {
+
+ case 0:
+ _movePrev.copy(_moveCurr);
+ _moveCurr.copy(getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY));
+ break;
+
+ case 1:
+ case 2:
+ break;
+
+ case 4:
+ // TOUCH ZOOM
+ _touchZoomDistanceStart = _touchZoomDistanceEnd = 0;
+ _state = STATE.ZOOM;
+ break;
+
+ case 5:
+ // TOUCH ZOOM
+ if (event.touches.length >= 2) {
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panEnd.copy(getMouseOnScreen(x, y));
+ _panStart.copy(_panEnd);
+ }
+ _state = STATE.PAN;
+ break;
+
+ case 99:
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _customEnd.copy(getMouseOnScreen(x, y));
+ _customStart.copy(_customEnd);
+ break;
+
+ default:
+ _state = STATE.NONE;
+
+ }
+ }
+
+ _this.dispatchEvent(endEvent);
+ }
+
+ _this2.domElement.addEventListener('contextmenu', function (event) {
+ event.preventDefault();
+ }, false);
+
+ _this2.domElement.addEventListener('mousedown', mousedown, false);
+
+ _this2.domElement.addEventListener('mousewheel', mousewheel, false);
+ _this2.domElement.addEventListener('DOMMouseScroll', mousewheel, false); // firefox
+
+ _this2.domElement.addEventListener('touchstart', touchstart, false);
+ _this2.domElement.addEventListener('touchend', touchend, false);
+ _this2.domElement.addEventListener('touchmove', touchmove, false);
+
+ window.addEventListener('keydown', keydown, false);
+ window.addEventListener('keyup', keyup, false);
+
+ _this2.handleResize();
+
+ // force an update at start
+ _this2.update();
+
+ return _this2;
+ }
+
+ return Trackball;
+}(THREE.EventDispatcher);
+
+exports.default = Trackball;
+
+},{}],60:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
+
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
+
+/**
+ * @author Eberhard Graether / http://egraether.com/
+ * @author Mark Lundin / http://mark-lundin.com
+ * @author Patrick Fuller / http://patrick-fuller.com
+ * @author Max Smolens / https://github.com/msmolens
+ */
+
+var Trackballortho = function (_THREE$EventDispatche) {
+ _inherits(Trackballortho, _THREE$EventDispatche);
+
+ function Trackballortho(object, domElement) {
+ _classCallCheck(this, Trackballortho);
+
+ var _this2 = _possibleConstructorReturn(this, Object.getPrototypeOf(Trackballortho).call(this));
+
+ var _this = _this2;
+ var STATE = { NONE: -1, ROTATE: 1, ZOOM: 2, PAN: 0, SCROLL: 4, TOUCH_ROTATE: 4, TOUCH_ZOOM_PAN: 5 };
+
+ _this2.object = object;
+ _this2.domElement = domElement !== undefined ? domElement : document;
+
+ // API
+
+ _this2.enabled = true;
+
+ _this2.screen = { left: 0, top: 0, width: 0, height: 0 };
+
+ _this2.radius = 0;
+
+ _this2.zoomSpeed = 1.2;
+
+ _this2.noZoom = false;
+ _this2.noPan = false;
+
+ _this2.staticMoving = false;
+ _this2.dynamicDampingFactor = 0.2;
+
+ _this2.keys = [65 /*A*/, 83 /*S*/, 68 /*D*/];
+
+ // internals
+
+ _this2.target = new THREE.Vector3();
+
+ var EPS = 0.000001;
+
+ var _changed = true;
+
+ var _state = STATE.NONE,
+ _prevState = STATE.NONE,
+ _eye = new THREE.Vector3(),
+ _zoomStart = new THREE.Vector2(),
+ _zoomEnd = new THREE.Vector2(),
+ _touchZoomDistanceStart = 0,
+ _touchZoomDistanceEnd = 0,
+ _panStart = new THREE.Vector2(),
+ _panEnd = new THREE.Vector2();
+
+ // window level fire after...
+
+ // for reset
+
+ _this2.target0 = _this2.target.clone();
+ _this2.position0 = _this2.object.position.clone();
+ _this2.up0 = _this2.object.up.clone();
+
+ _this2.left0 = _this2.object.left;
+ _this2.right0 = _this2.object.right;
+ _this2.top0 = _this2.object.top;
+ _this2.bottom0 = _this2.object.bottom;
+
+ // events
+
+ var changeEvent = { type: 'change' };
+ var startEvent = { type: 'start' };
+ var endEvent = { type: 'end' };
+
+ // methods
+
+ _this2.handleResize = function () {
+
+ if (this.domElement === document) {
+
+ this.screen.left = 0;
+ this.screen.top = 0;
+ this.screen.width = window.innerWidth;
+ this.screen.height = window.innerHeight;
+ } else {
+
+ var box = this.domElement.getBoundingClientRect();
+ // adjustments come from similar code in the jquery offset() function
+ var d = this.domElement.ownerDocument.documentElement;
+ this.screen.left = box.left + window.pageXOffset - d.clientLeft;
+ this.screen.top = box.top + window.pageYOffset - d.clientTop;
+ this.screen.width = box.width;
+ this.screen.height = box.height;
+ }
+
+ this.radius = 0.5 * Math.min(this.screen.width, this.screen.height);
+
+ this.left0 = this.object.left;
+ this.right0 = this.object.right;
+ this.top0 = this.object.top;
+ this.bottom0 = this.object.bottom;
+ };
+
+ _this2.handleEvent = function (event) {
+
+ if (typeof this[event.type] == 'function') {
+
+ this[event.type](event);
+ }
+ };
+
+ var getMouseOnScreen = function () {
+
+ var vector = new THREE.Vector2();
+
+ return function getMouseOnScreen(pageX, pageY) {
+
+ vector.set((pageX - _this.screen.left) / _this.screen.width, (pageY - _this.screen.top) / _this.screen.height);
+
+ return vector;
+ };
+ }();
+
+ _this2.zoomCamera = function () {
+
+ if (_state === STATE.TOUCH_ZOOM_PAN) {
+
+ var factor = _touchZoomDistanceEnd / _touchZoomDistanceStart;
+ _touchZoomDistanceStart = _touchZoomDistanceEnd;
+
+ _this.object.zoom *= factor;
+
+ _changed = true;
+ } else {
+
+ var factor = 1.0 + (_zoomEnd.y - _zoomStart.y) * _this.zoomSpeed;
+
+ if (Math.abs(factor - 1.0) > EPS && factor > 0.0) {
+
+ _this.object.zoom /= factor;
+
+ if (_this.staticMoving) {
+
+ _zoomStart.copy(_zoomEnd);
+ } else {
+
+ _zoomStart.y += (_zoomEnd.y - _zoomStart.y) * this.dynamicDampingFactor;
+ }
+
+ _changed = true;
+ }
+ }
+ };
+
+ _this2.panCamera = function () {
+
+ var mouseChange = new THREE.Vector2(),
+ objectUp = new THREE.Vector3(),
+ pan = new THREE.Vector3();
+
+ return function panCamera() {
+
+ mouseChange.copy(_panEnd).sub(_panStart);
+
+ if (mouseChange.lengthSq()) {
+
+ // Scale movement to keep clicked/dragged position under cursor
+ var scale_x = (_this.object.right - _this.object.left) / _this.object.zoom;
+ var scale_y = (_this.object.top - _this.object.bottom) / _this.object.zoom;
+ mouseChange.x *= scale_x;
+ mouseChange.y *= scale_y;
+
+ pan.copy(_eye).cross(_this.object.up).setLength(mouseChange.x);
+ pan.add(objectUp.copy(_this.object.up).setLength(mouseChange.y));
+
+ _this.object.position.add(pan);
+ _this.target.add(pan);
+
+ if (_this.staticMoving) {
+
+ _panStart.copy(_panEnd);
+ } else {
+
+ _panStart.add(mouseChange.subVectors(_panEnd, _panStart).multiplyScalar(_this.dynamicDampingFactor));
+ }
+
+ _changed = true;
+ }
+ };
+ }();
+
+ _this2.update = function () {
+
+ _eye.subVectors(_this.object.position, _this.target);
+
+ if (!_this.noZoom) {
+
+ _this.zoomCamera();
+
+ if (_changed) {
+
+ _this.object.updateProjectionMatrix();
+ }
+ }
+
+ if (!_this.noPan) {
+
+ _this.panCamera();
+ }
+
+ _this.object.position.addVectors(_this.target, _eye);
+
+ _this.object.lookAt(_this.target);
+
+ if (_changed) {
+
+ _this.dispatchEvent(changeEvent);
+
+ _changed = false;
+ }
+ };
+
+ _this2.reset = function () {
+
+ _state = STATE.NONE;
+ _prevState = STATE.NONE;
+
+ _this.target.copy(_this.target0);
+ _this.object.position.copy(_this.position0);
+ _this.object.up.copy(_this.up0);
+
+ _eye.subVectors(_this.object.position, _this.target);
+
+ _this.object.left = _this.left0;
+ _this.object.right = _this.right0;
+ _this.object.top = _this.top0;
+ _this.object.bottom = _this.bottom0;
+
+ _this.object.lookAt(_this.target);
+
+ _this.dispatchEvent(changeEvent);
+
+ _changed = false;
+ };
+
+ // listeners
+
+ function keydown(event) {
+
+ if (_this.enabled === false) return;
+
+ window.removeEventListener('keydown', keydown);
+
+ _prevState = _state;
+
+ if (_state !== STATE.NONE) {
+
+ return;
+ } else if (event.keyCode === _this.keys[STATE.ROTATE] && !_this.noRotate) {
+
+ _state = STATE.ROTATE;
+ } else if (event.keyCode === _this.keys[STATE.ZOOM] && !_this.noZoom) {
+
+ _state = STATE.ZOOM;
+ } else if (event.keyCode === _this.keys[STATE.PAN] && !_this.noPan) {
+
+ _state = STATE.PAN;
+ }
+ }
+
+ function keyup(event) {
+
+ if (_this.enabled === false) return;
+
+ _state = _prevState;
+
+ window.addEventListener('keydown', keydown, false);
+ }
+
+ function mousedown(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (_state === STATE.NONE) {
+
+ _state = event.button;
+ }
+
+ if (_state === STATE.ROTATE && !_this.noRotate) {} else if (_state === STATE.ZOOM && !_this.noZoom) {
+
+ _zoomStart.copy(getMouseOnScreen(event.pageX, event.pageY));
+ _zoomEnd.copy(_zoomStart);
+ } else if (_state === STATE.PAN && !_this.noPan) {
+
+ _panStart.copy(getMouseOnScreen(event.pageX, event.pageY));
+ _panEnd.copy(_panStart);
+ }
+
+ document.addEventListener('mousemove', mousemove, false);
+ document.addEventListener('mouseup', mouseup, false);
+
+ _this.dispatchEvent(startEvent);
+ }
+
+ function mousemove(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (_state === STATE.ROTATE && !_this.noRotate) {} else if (_state === STATE.ZOOM && !_this.noZoom) {
+
+ _zoomEnd.copy(getMouseOnScreen(event.pageX, event.pageY));
+ } else if (_state === STATE.PAN && !_this.noPan) {
+
+ _panEnd.copy(getMouseOnScreen(event.pageX, event.pageY));
+ }
+ }
+
+ function mouseup(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ _state = STATE.NONE;
+
+ document.removeEventListener('mousemove', mousemove);
+ document.removeEventListener('mouseup', mouseup);
+ _this.dispatchEvent(endEvent);
+ }
+
+ function mousewheel(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ var delta = 0;
+
+ if (event.wheelDelta) {
+
+ // WebKit / Opera / Explorer 9
+
+ delta = event.wheelDelta / 40;
+ } else if (event.detail) {
+
+ // Firefox
+
+ delta = -event.detail / 3;
+ }
+
+ // FIRE SCROLL EVENT
+
+ _this.dispatchEvent({
+ type: 'OnScroll',
+ delta: delta
+ });
+
+ //_zoomStart.y += delta * 0.01;
+ _this.dispatchEvent(startEvent);
+ _this.dispatchEvent(endEvent);
+ }
+
+ function touchstart(event) {
+
+ if (_this.enabled === false) return;
+
+ switch (event.touches.length) {
+
+ case 1:
+ _state = STATE.TOUCH_ROTATE;
+
+ break;
+
+ case 2:
+ _state = STATE.TOUCH_ZOOM_PAN;
+ var dx = event.touches[0].pageX - event.touches[1].pageX;
+ var dy = event.touches[0].pageY - event.touches[1].pageY;
+ _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy);
+
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panStart.copy(getMouseOnScreen(x, y));
+ _panEnd.copy(_panStart);
+ break;
+
+ default:
+ _state = STATE.NONE;
+
+ }
+ _this.dispatchEvent(startEvent);
+ }
+
+ function touchmove(event) {
+
+ if (_this.enabled === false) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ switch (event.touches.length) {
+
+ case 1:
+
+ break;
+
+ case 2:
+ var dx = event.touches[0].pageX - event.touches[1].pageX;
+ var dy = event.touches[0].pageY - event.touches[1].pageY;
+ _touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy);
+
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panEnd.copy(getMouseOnScreen(x, y));
+ break;
+
+ default:
+ _state = STATE.NONE;
+
+ }
+ }
+
+ function touchend(event) {
+
+ if (_this.enabled === false) return;
+
+ switch (event.touches.length) {
+
+ case 1:
+
+ break;
+
+ case 2:
+ _touchZoomDistanceStart = _touchZoomDistanceEnd = 0;
+
+ var x = (event.touches[0].pageX + event.touches[1].pageX) / 2;
+ var y = (event.touches[0].pageY + event.touches[1].pageY) / 2;
+ _panEnd.copy(getMouseOnScreen(x, y));
+ _panStart.copy(_panEnd);
+ break;
+
+ }
+
+ _state = STATE.NONE;
+ _this.dispatchEvent(endEvent);
+ }
+
+ function contextmenu(event) {
+
+ event.preventDefault();
+ }
+
+ _this2.dispose = function () {
+
+ this.domElement.removeEventListener('contextmenu', contextmenu, false);
+ this.domElement.removeEventListener('mousedown', mousedown, false);
+ this.domElement.removeEventListener('mousewheel', mousewheel, false);
+ this.domElement.removeEventListener('MozMousePixelScroll', mousewheel, false); // firefox
+
+ this.domElement.removeEventListener('touchstart', touchstart, false);
+ this.domElement.removeEventListener('touchend', touchend, false);
+ this.domElement.removeEventListener('touchmove', touchmove, false);
+
+ document.removeEventListener('mousemove', mousemove, false);
+ document.removeEventListener('mouseup', mouseup, false);
+
+ window.removeEventListener('keydown', keydown, false);
+ window.removeEventListener('keyup', keyup, false);
+ };
+
+ _this2.domElement.addEventListener('contextmenu', contextmenu, false);
+ _this2.domElement.addEventListener('mousedown', mousedown, false);
+ _this2.domElement.addEventListener('mousewheel', mousewheel, false);
+ _this2.domElement.addEventListener('MozMousePixelScroll', mousewheel, false); // firefox
+
+ _this2.domElement.addEventListener('touchstart', touchstart, false);
+ _this2.domElement.addEventListener('touchend', touchend, false);
+ _this2.domElement.addEventListener('touchmove', touchmove, false);
+
+ window.addEventListener('keydown', keydown, false);
+ window.addEventListener('keyup', keyup, false);
+
+ _this2.handleResize();
+
+ // force an update at start
+ _this2.update();
+
+ return _this2;
+ }
+
+ return Trackballortho;
+}(THREE.EventDispatcher);
+
+exports.default = Trackballortho;
+
+},{}],61:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+var _core = require('./core.utils');
+
+var _core2 = _interopRequireDefault(_core);
+
+var _core3 = require('./core.validators');
+
+var _core4 = _interopRequireDefault(_core3);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+/**
+ * Compute/test intersection between different objects.
+ *
+ * @module core/intersections
+ */
+
+var Intersections = function () {
+ function Intersections() {
+ _classCallCheck(this, Intersections);
+ }
+
+ _createClass(Intersections, null, [{
+ key: 'aabbPlane',
+
+
+ /**
+ * Compute intersection between oriented bounding box and a plane.
+ *
+ * Returns intersection in plane's space.
+ *
+ * Should return at least 3 intersections. If not, the plane and the box do not
+ * intersect.
+ *
+ * @param {Object} aabb - Axe Aligned Bounding Box representation.
+ * @param {THREE.Vector3} aabb.halfDimensions - Half dimensions of the box.
+ * @param {THREE.Vector3} aabb.center - Center of the box.
+ * @param {THREE.Matrix4} aabb.toAABB - Transform to go from plane space to box space.
+ * @param {Object} plane - Plane representation
+ * @param {THREE.Vector3} plane.position - position of normal which describes the plane.
+ * @param {THREE.Vector3} plane.direction - Direction of normal which describes the plane.
+ *
+ * @returns {Array} List of all intersections in plane's space.
+ * @returns {boolean} false is invalid input provided.
+ *
+ * @example
+ * //Returns array with intersection N intersections
+ * let aabb = {
+ * center: new THREE.Vector3(150, 150, 150),
+ * halfDimensions: new THREE.Vector3(50, 60, 70),
+ * toAABB: new THREE.Matrix4()
+ * }
+ * let plane = {
+ * position: new THREE.Vector3(110, 120, 130),
+ * direction: new THREE.Vector3(1, 0, 0)
+ * }
+ *
+ * let intersections = CoreIntersections.aabbPlane(aabb, plane);
+ * // intersections ==
+ * //[ { x : 110, y : 90, z : 80 },
+ * // { x : 110, y : 210, z : 220 },
+ * // { x : 110, y : 210, z : 80 },
+ * // { x : 110, y : 90, z : 220 } ]
+ *
+ * //Returns empty array with 0 intersections
+ * let aabb = {
+ *
+ * }
+ * let plane = {
+ *
+ * }
+ *
+ * let intersections = VJS.Core.Validators.matrix4(new THREE.Vector3());
+ *
+ * //Returns false if invalid input?
+ *
+ */
+ value: function aabbPlane(aabb, plane) {
+ //
+ // obb = { halfDimensions, orientation, center, toAABB }
+ // plane = { position, direction }
+ //
+ //
+ // LOGIC:
+ //
+ // Test intersection of each edge of the Oriented Bounding Box with the Plane
+ //
+ // ALL EDGES
+ //
+ // .+-------+
+ // .' | .'|
+ // +---+---+' |
+ // | | | |
+ // | ,+---+---+
+ // |.' | .'
+ // +-------+'
+ //
+ // SPACE ORIENTATION
+ //
+ // +
+ // j |
+ // |
+ // | i
+ // k ,+-------+
+ // .'
+ // +
+ //
+ //
+ // 1- Move Plane position and orientation in IJK space
+ // 2- Test Edges/ IJK Plane intersections
+ // 3- Return intersection Edge/ IJK Plane if it touches the Oriented BBox
+
+ var intersections = [];
+
+ if (!(this.validateAabb(aabb) && this.validatePlane(plane))) {
+ window.console.log('Invalid aabb or plane provided.');
+ return false;
+ }
+
+ // invert space matrix
+ var fromAABB = new THREE.Matrix4();
+ fromAABB.getInverse(aabb.toAABB);
+
+ var t1 = plane.direction.clone().applyMatrix4(aabb.toAABB);
+ var t0 = new THREE.Vector3(0, 0, 0).applyMatrix4(aabb.toAABB);
+
+ var planeAABB = this.posdir(plane.position.clone().applyMatrix4(aabb.toAABB), new THREE.Vector3(t1.x - t0.x, t1.y - t0.y, t1.z - t0.z).normalize());
+
+ var bbox = _core2.default.bbox(aabb.center, aabb.halfDimensions);
+
+ var orientation = new THREE.Vector3(new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1));
+
+ // 12 edges (i.e. ray)/plane intersection tests
+ // RAYS STARTING FROM THE FIRST CORNER (0, 0, 0)
+ //
+ // +
+ // |
+ // |
+ // |
+ // ,+---+---+
+ // .'
+ // +
+
+ var ray = this.posdir(new THREE.Vector3(aabb.center.x - aabb.halfDimensions.x, aabb.center.y - aabb.halfDimensions.y, aabb.center.z - aabb.halfDimensions.z), orientation.x);
+ this.rayPlaneInBBox(ray, planeAABB, bbox, intersections);
+
+ ray.direction = orientation.y;
+ this.rayPlaneInBBox(ray, planeAABB, bbox, intersections);
+
+ ray.direction = orientation.z;
+ this.rayPlaneInBBox(ray, planeAABB, bbox, intersections);
+
+ // RAYS STARTING FROM THE LAST CORNER
+ //
+ // +
+ // .'
+ // +-------+'
+ // |
+ // |
+ // |
+ // +
+ //
+
+ var ray2 = this.posdir(new THREE.Vector3(aabb.center.x + aabb.halfDimensions.x, aabb.center.y + aabb.halfDimensions.y, aabb.center.z + aabb.halfDimensions.z), orientation.x);
+ this.rayPlaneInBBox(ray2, planeAABB, bbox, intersections);
+
+ ray2.direction = orientation.y;
+ this.rayPlaneInBBox(ray2, planeAABB, bbox, intersections);
+
+ ray2.direction = orientation.z;
+ this.rayPlaneInBBox(ray2, planeAABB, bbox, intersections);
+
+ // RAYS STARTING FROM THE SECOND CORNER
+ //
+ // +
+ // |
+ // |
+ // |
+ // +
+ // .'
+ // +'
+
+ var ray3 = this.posdir(new THREE.Vector3(aabb.center.x + aabb.halfDimensions.x, aabb.center.y - aabb.halfDimensions.y, aabb.center.z - aabb.halfDimensions.z), orientation.y);
+ this.rayPlaneInBBox(ray3, planeAABB, bbox, intersections);
+
+ ray3.direction = orientation.z;
+ this.rayPlaneInBBox(ray3, planeAABB, bbox, intersections);
+
+ // RAYS STARTING FROM THE THIRD CORNER
+ //
+ // .+-------+
+ // .'
+ // +
+ //
+ //
+ //
+ //
+
+ var ray4 = this.posdir(new THREE.Vector3(aabb.center.x - aabb.halfDimensions.x, aabb.center.y + aabb.halfDimensions.y, aabb.center.z - aabb.halfDimensions.z), orientation.x);
+ this.rayPlaneInBBox(ray4, planeAABB, bbox, intersections);
+
+ ray4.direction = orientation.z;
+ this.rayPlaneInBBox(ray4, planeAABB, bbox, intersections);
+
+ // RAYS STARTING FROM THE FOURTH CORNER
+ //
+ //
+ //
+ // +
+ // |
+ // |
+ // |
+ // +-------+
+
+ var ray5 = this.posdir(new THREE.Vector3(aabb.center.x - aabb.halfDimensions.x, aabb.center.y - aabb.halfDimensions.y, aabb.center.z + aabb.halfDimensions.z), orientation.x);
+ this.rayPlaneInBBox(ray5, planeAABB, bbox, intersections);
+
+ ray5.direction = orientation.y;
+ this.rayPlaneInBBox(ray5, planeAABB, bbox, intersections);
+
+ // @todo make sure objects are unique...
+
+ // back to original space
+ intersections.map(function (element) {
+ return element.applyMatrix4(fromAABB);
+ });
+
+ return intersections;
+ }
+
+ /**
+ * Compute intersection between a ray and a plane.
+ *
+ * @memberOf this
+ * @public
+ *
+ * @param {Object} ray - Ray representation.
+ * @param {THREE.Vector3} ray.position - position of normal which describes the ray.
+ * @param {THREE.Vector3} ray.direction - Direction of normal which describes the ray.
+ * @param {Object} plane - Plane representation
+ * @param {THREE.Vector3} plane.position - position of normal which describes the plane.
+ * @param {THREE.Vector3} plane.direction - Direction of normal which describes the plane.
+ *
+ * @returns {THREE.Vector3|null} Intersection between ray and plane or null.
+ */
+
+ }, {
+ key: 'rayPlane',
+ value: function rayPlane(ray, plane) {
+ // ray: {position, direction}
+ // plane: {position, direction}
+
+ if (ray.direction.dot(plane.direction) !== 0) {
+ //
+ // not parallel, move forward
+ //
+ // LOGIC:
+ //
+ // Ray equation: P = P0 + tV
+ // P =
+ // P0 =
+ // V =
+ //
+ // Therefore:
+ // Px = ray.position.x + t*ray.direction.x
+ // Py = ray.position.y + t*ray.direction.y
+ // Pz = ray.position.z + t*ray.direction.z
+ //
+ //
+ //
+ // Plane equation: ax + by + cz + d = 0
+ // a = plane.direction.x
+ // b = plane.direction.y
+ // c = plane.direction.z
+ // d = -( plane.direction.x*plane.position.x +
+ // plane.direction.y*plane.position.y +
+ // plane.direction.z*plane.position.z )
+ //
+ //
+ // 1- in the plane equation, we replace x, y and z by Px, Py and Pz
+ // 2- find t
+ // 3- replace t in Px, Py and Pz to get the coordinate of the intersection
+ //
+ var t = (plane.direction.x * (plane.position.x - ray.position.x) + plane.direction.y * (plane.position.y - ray.position.y) + plane.direction.z * (plane.position.z - ray.position.z)) / (plane.direction.x * ray.direction.x + plane.direction.y * ray.direction.y + plane.direction.z * ray.direction.z);
+
+ var intersection = new THREE.Vector3(ray.position.x + t * ray.direction.x, ray.position.y + t * ray.direction.y, ray.position.z + t * ray.direction.z);
+
+ return intersection;
+ }
+
+ return null;
+ }
+ }, {
+ key: 'rayBox',
+ value: function rayBox(ray, box) {
+ // should also do the space transforms here
+ // ray: {position, direction}
+ // box: {halfDimensions, center}
+
+ var intersections = [];
+
+ var bbox = _core2.default.bbox(box.center, box.halfDimensions);
+
+ // window.console.log(bbox);
+
+ // X min
+ var plane = this.posdir(new THREE.Vector3(bbox.min.x, box.center.y, box.center.z), new THREE.Vector3(-1, 0, 0));
+ this.rayPlaneInBBox(ray, plane, bbox, intersections);
+
+ // X max
+ plane = this.posdir(new THREE.Vector3(bbox.max.x, box.center.y, box.center.z), new THREE.Vector3(1, 0, 0));
+ this.rayPlaneInBBox(ray, plane, bbox, intersections);
+
+ // Y min
+ plane = this.posdir(new THREE.Vector3(box.center.x, bbox.min.y, box.center.z), new THREE.Vector3(0, -1, 0));
+ this.rayPlaneInBBox(ray, plane, bbox, intersections);
+
+ // Y max
+ plane = this.posdir(new THREE.Vector3(box.center.x, bbox.max.y, box.center.z), new THREE.Vector3(0, 1, 0));
+ this.rayPlaneInBBox(ray, plane, bbox, intersections);
+
+ // Z min
+ plane = this.posdir(new THREE.Vector3(box.center.x, box.center.y, bbox.min.z), new THREE.Vector3(0, 0, -1));
+ this.rayPlaneInBBox(ray, plane, bbox, intersections);
+
+ // Z max
+ plane = this.posdir(new THREE.Vector3(box.center.x, box.center.y, bbox.max.z), new THREE.Vector3(0, 0, 1));
+ this.rayPlaneInBBox(ray, plane, bbox, intersections);
+
+ return intersections;
+ }
+ }, {
+ key: 'rayPlaneInBBox',
+ value: function rayPlaneInBBox(ray, planeAABB, bbox, intersections) {
+ var intersection = this.rayPlane(ray, planeAABB);
+ // window.console.log(intersection);
+ if (intersection && this.inBBox(intersection, bbox)) {
+ if (!intersections.find(this.findIntersection(intersection))) {
+ intersections.push(intersection);
+ }
+ }
+ }
+ }, {
+ key: 'findIntersection',
+ value: function findIntersection(myintersection) {
+ return function found(element, index, array) {
+ if (myintersection.x === element.x && myintersection.y === element.y && myintersection.z === element.z) {
+ return true;
+ }
+
+ return false;
+ };
+ }
+ }, {
+ key: 'inBBox',
+ value: function inBBox(point, bbox) {
+ //
+ var epsilon = 0.0001;
+ if (point && point.x >= bbox.min.x - epsilon && point.y >= bbox.min.y - epsilon && point.z >= bbox.min.z - epsilon && point.x <= bbox.max.x + epsilon && point.y <= bbox.max.y + epsilon && point.z <= bbox.max.z + epsilon) {
+ return true;
+ }
+ return false;
+ }
+ }, {
+ key: 'posdir',
+ value: function posdir(position, direction) {
+ return { position: position, direction: direction };
+ }
+ }, {
+ key: 'validatePlane',
+ value: function validatePlane(plane) {
+ //
+ if (plane === null) {
+
+ window.console.log('Invalid plane.');
+ window.console.log(plane);
+
+ return false;
+ }
+
+ if (!_core4.default.vector3(plane.position)) {
+
+ window.console.log('Invalid plane.position.');
+ window.console.log(plane.position);
+
+ return false;
+ }
+
+ if (!_core4.default.vector3(plane.direction)) {
+
+ window.console.log('Invalid plane.direction.');
+ window.console.log(plane.direction);
+
+ return false;
+ }
+
+ return true;
+ }
+ }, {
+ key: 'validateAabb',
+ value: function validateAabb(aabb) {
+ //
+ if (aabb === null) {
+ window.console.log('Invalid aabb.');
+ window.console.log(aabb);
+ return false;
+ }
+
+ if (!_core4.default.matrix4(aabb.toAABB)) {
+
+ window.console.log('Invalid aabb.toAABB: ');
+ window.console.log(aabb.toAABB);
+
+ return false;
+ }
+
+ if (!_core4.default.vector3(aabb.center)) {
+
+ window.console.log('Invalid aabb.center.');
+ window.console.log(aabb.center);
+
+ return false;
+ }
+
+ if (!(_core4.default.vector3(aabb.halfDimensions) && aabb.halfDimensions.x >= 0 && aabb.halfDimensions.y >= 0 && aabb.halfDimensions.z >= 0)) {
+
+ window.console.log('Invalid aabb.halfDimensions.');
+ window.console.log(aabb.halfDimensions);
+
+ return false;
+ }
+
+ return true;
+ }
+ }]);
+
+ return Intersections;
+}();
+
+exports.default = Intersections;
+
+},{"./core.utils":64,"./core.validators":65}],62:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _core = require('./core.intersections');
+
+var _core2 = _interopRequireDefault(_core);
+
+var _core3 = require('./core.pack');
+
+var _core4 = _interopRequireDefault(_core3);
+
+var _core5 = require('./core.validators');
+
+var _core6 = _interopRequireDefault(_core5);
+
+var _core7 = require('./core.utils');
+
+var _core8 = _interopRequireDefault(_core7);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+//import Pack from './core.pack';
+
+/**
+ * @module core
+ */
+exports.default = {
+ Intersections: _core2.default,
+ Utils: _core8.default,
+ Validators: _core6.default
+ //,
+ // Pack
+};
+
+},{"./core.intersections":61,"./core.pack":63,"./core.utils":64,"./core.validators":65}],63:[function(require,module,exports){
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+/**
+ * Packing functions.
+ *
+ * @module core/pack */
+
+var Pack = function Pack() {
+ _classCallCheck(this, Pack);
+};
+
+exports.default = Pack;
+
+},{}],64:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+var _core = require('./core.validators');
+
+var _core2 = _interopRequireDefault(_core);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+/**
+ * General purpose functions.
+ *
+ * @module core/utils
+ */
+
+var Utils = function () {
+ function Utils() {
+ _classCallCheck(this, Utils);
+ }
+
+ _createClass(Utils, null, [{
+ key: 'bbox',
+
+
+ /**
+ * Generate a bouding box object.
+ * @param {THREE.Vector3} center - Center of the box.
+ * @param {THREE.Vector3} halfDimensions - Half Dimensions of the box.
+ * @return {Object} The bounding box object. {Object.min} is a {THREE.Vector3}
+ * containing the min bounds. {Object.max} is a {THREE.Vector3} containing the
+ * max bounds.
+ * @return {boolean} False input NOT valid.
+ * @example
+ * // Returns
+ * //{ min: { x : 0, y : 0, z : 0 },
+ * // max: { x : 2, y : 4, z : 6 }
+ * //}
+ * VJS.Core.Utils.bbox( new THREE.Vector3(1, 2, 3), new THREE.Vector3(1, 2, 3));
+ *
+ * //Returns false
+ * VJS.Core.Utils.bbox(new THREE.Vector3(), new THREE.Matrix4());
+ *
+ */
+ value: function bbox(center, halfDimensions) {
+
+ // make sure we have valid inputs
+ if (!(_core2.default.vector3(center) && _core2.default.vector3(halfDimensions))) {
+ window.console.log('Invalid center or plane halfDimensions.');
+ return false;
+ }
+
+ // make sure half dimensions are >= 0
+ if (!(halfDimensions.x >= 0 && halfDimensions.y >= 0 && halfDimensions.z >= 0)) {
+ window.console.log('halfDimensions must be >= 0.');
+ window.console.log(halfDimensions);
+ return false;
+ }
+
+ // min/max bound
+ var min = center.clone().sub(halfDimensions);
+ var max = center.clone().add(halfDimensions);
+
+ return {
+ min: min,
+ max: max
+ };
+ }
+ }]);
+
+ return Utils;
+}();
+
+exports.default = Utils;
+
+},{"./core.validators":65}],65:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+/**
+ * Validate basic structures.
+ *
+ * @example
+ * //Returns true
+ * VJS.Core.Validators.matrix4(new THREE.Matrix4());
+ *
+ * //Returns false
+ * VJS.Core.Validators.matrix4(new THREE.Vector3());
+ *
+ * @module core/validators
+ */
+
+var Validators = function () {
+ function Validators() {
+ _classCallCheck(this, Validators);
+ }
+
+ _createClass(Validators, null, [{
+ key: 'matrix4',
+
+
+ /**
+ * Validates a matrix as a THREEJS.Matrix4
+ * link
+ * @param {Object} objectToTest - The object to be tested.
+ * @return {boolean} True if valid Matrix4, false if NOT.
+ */
+ value: function matrix4(objectToTest) {
+
+ if (!(objectToTest !== null && typeof objectToTest !== 'undefined' && objectToTest.hasOwnProperty('elements') && objectToTest.elements.length === 16 && typeof objectToTest.identity === 'function' && typeof objectToTest.copy === 'function' && typeof objectToTest.determinant === 'function')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Validates a vector as a THREEJS.Vector3
+ * @param {Object} objectToTest - The object to be tested.
+ * @return {boolean} True if valid Vector3, false if NOT.
+ */
+
+ }, {
+ key: 'vector3',
+ value: function vector3(objectToTest) {
+
+ if (!(objectToTest !== null && typeof objectToTest !== 'undefined' && objectToTest.hasOwnProperty('x') && objectToTest.hasOwnProperty('y') && objectToTest.hasOwnProperty('z') && !objectToTest.hasOwnProperty('w'))) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Validates a box.
+ *
+ * @example
+ * // a box is defined as
+ * let box = {
+ * center: THREE.Vector3,
+ * halfDimensions: THREE.Vector3
+ * }
+ *
+ * @param {Object} objectToTest - The object to be tested.
+ * @return {boolean} True if valid box, false if NOT.
+ */
+
+ }, {
+ key: 'box',
+ value: function box(objectToTest) {
+
+ if (!(objectToTest !== null && typeof objectToTest !== 'undefined' && objectToTest.hasOwnProperty('center') && this.vector3(objectToTest.center) && objectToTest.hasOwnProperty('halfDimensions') && this.vector3(objectToTest.halfDimensions) && objectToTest.halfDimensions.x >= 0 && objectToTest.halfDimensions.y >= 0 && objectToTest.halfDimensions.z >= 0)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Validates a ray.
+ *
+ * @example
+ * // a ray is defined as
+ * let ray = {
+ * postion: THREE.Vector3,
+ * direction: THREE.Vector3
+ * }
+ *
+ * @param {Object} objectToTest - The object to be tested.
+ * @return {boolean} True if valid ray, false if NOT.
+ */
+
+ }, {
+ key: 'ray',
+ value: function ray(objectToTest) {
+
+ if (!(objectToTest !== null && typeof objectToTest !== 'undefined' && objectToTest.hasOwnProperty('position') && this.vector3(objectToTest.position) && objectToTest.hasOwnProperty('direction') && this.vector3(objectToTest.direction))) {
+ return false;
+ }
+
+ return true;
+ }
+ }]);
+
+ return Validators;
+}();
+
+exports.default = Validators;
+
+},{}],66:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _geometries = require('./geometries.slice');
+
+var _geometries2 = _interopRequireDefault(_geometries);
+
+var _geometries3 = require('./geometries.voxel');
+
+var _geometries4 = _interopRequireDefault(_geometries3);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+/**
+ * @module geometries
+ */
+
+exports.default = {
+ Slice: _geometries2.default,
+ Voxel: _geometries4.default
+};
+
+},{"./geometries.slice":67,"./geometries.voxel":68}],67:[function(require,module,exports){
+'use strict';
+
+Object.defineProperty(exports, "__esModule", {
+ value: true
+});
+
+var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
+
+var _core = require('../../src/core/core.intersections');
+
+var _core2 = _interopRequireDefault(_core);
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
+
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*** Imports ***/
+
+
+/**
+ *
+ * It is typically used for creating an irregular 3D planar shape given a box and the cut-plane.
+ *
+ * Demo: {@link https://fnndsc.github.io/vjs#geometry_slice}
+ *
+ * @module geometries/slice
+ *
+ * @param {THREE.Vector3} halfDimensions - Half-dimensions of the box to be sliced.
+ * @param {THREE.Vector3} center - Center of the box to be sliced.
+ * @param {THREE.Vector3} orientation - Orientation of the box to be sliced. (might not be necessary..?)
+ * @param {THREE.Vector3} position - Position of the cutting plane.
+ * @param {THREE.Vector3} direction - Cross direction of the cutting plane.
+ *
+ * @example
+ * // Define box to be sliced
+ * let halfDimensions = new THREE.Vector(123, 45, 67);
+ * let center = new THREE.Vector3(0, 0, 0);
+ * let orientation = new THREE.Vector3(
+ * new THREE.Vector3(1, 0, 0),
+ * new THREE.Vector3(0, 1, 0),
+ * new THREE.Vector3(0, 0, 1)
+ * );
+ *
+ * // Define slice plane
+ * let position = center.clone();
+ * let direction = new THREE.Vector3(-0.2, 0.5, 0.3);
+ *
+ * // Create the slice geometry & materials
+ * let sliceGeometry = new VJS.geometries.slice(halfDimensions, center, orientation, position, direction);
+ * let sliceMaterial = new THREE.MeshBasicMaterial({
+ * 'side': THREE.DoubleSide,
+ * 'color': 0xFF5722
+ * });
+ *
+ * // Create mesh and add it to the scene
+ * let slice = new THREE.Mesh(sliceGeometry, sliceMaterial);
+ * scene.add(slice);
+ */
+
+var GeometriesSlice = function (_THREE$ShapeGeometry) {
+ _inherits(GeometriesSlice, _THREE$ShapeGeometry);
+
+ function GeometriesSlice(halfDimensions, center, position, direction) {
+ var toAABB = arguments.length <= 4 || arguments[4] === undefined ? new THREE.Matrix4() : arguments[4];
+
+ _classCallCheck(this, GeometriesSlice);
+
+ //
+ // prepare data for the shape!
+ //
+ var aabb = {
+ halfDimensions: halfDimensions,
+ center: center,
+ toAABB: toAABB
+ };
+
+ var plane = {
+ position: position,
+ direction: direction
+ };
+
+ // BOOM!
+ var intersections = _core2.default.aabbPlane(aabb, plane);
+
+ // can not exist before calling the constructor
+ if (intersections.length < 3) {
+ window.console.log('WARNING: Less than 3 intersections between AABB and Plane.');
+ window.console.log('AABB');
+ window.console.log(aabb);
+ window.console.log('Plane');
+ window.console.log(plane);
+ window.console.log('exiting...');
+ // or throw error?
+ throw 'geometries.slice has less than 3 intersections, can not create a valid geometry.';
+ }
+
+ var orderedIntersections = GeometriesSlice.orderIntersections(intersections, direction);
+ var sliceShape = GeometriesSlice.shape(orderedIntersections);
+
+ //
+ // Generate Geometry from shape
+ // It does triangulation for us!
+ //
+
+ var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(GeometriesSlice).call(this, sliceShape));
+
+ _this.type = 'SliceGeometry';
+
+ // update real position of each vertex! (not in 2d)
+ _this.vertices = orderedIntersections;
+ _this.verticesNeedUpdate = true;
+ return _this;
+ }
+
+ _createClass(GeometriesSlice, null, [{
+ key: 'shape',
+ value: function shape(points) {
+ //
+ // Create Shape
+ //
+ var shape = new THREE.Shape();
+ // move to first point!
+ shape.moveTo(points[0].xy.x, points[0].xy.y);
+
+ // loop through all points!
+ for (var l = 1; l < points.length; l++) {
+ // project each on plane!
+ shape.lineTo(points[l].xy.x, points[l].xy.y);
+ }
+
+ // close the shape!
+ shape.lineTo(points[0].xy.x, points[0].xy.y);
+ return shape;
+ }
+
+ /**
+ *
+ * Convenience function to extract center of mass from list of points.
+ *
+ * @private
+ *
+ * @param {Array} points - Set of points from which we want to extract the center of mass.
+ *
+ * @returns {THREE.Vector3} Center of mass from given points.
+ */
+
+ }, {
+ key: 'centerOfMass',
+ value: function centerOfMass(points) {
+ var centerOfMass = new THREE.Vector3(0, 0, 0);
+ for (var i = 0; i < points.length; i++) {
+ centerOfMass.x += points[i].x;
+ centerOfMass.y += points[i].y;
+ centerOfMass.z += points[i].z;
+ }
+ centerOfMass.divideScalar(points.length);
+
+ return centerOfMass;
+ }
+
+ /**
+ *
+ * Order 3D planar points around a refence point.
+ *
+ * @private
+ *
+ * @param {Array} points - Set of planar 3D points to be ordered.
+ * @param {THREE.Vector3} direction - Direction of the plane in which points and reference are sitting.
+ *
+ * @returns {Array