From d925cdf3a157c684639ea13f5899fb9e1addbab3 Mon Sep 17 00:00:00 2001 From: Legokichi Duckscallion Date: Tue, 13 Feb 2024 18:18:09 +0900 Subject: [PATCH] modernize toolchains --- .eslintrc.json | 103 + .github/workflows/ci.yml | 8 +- .gitignore | 4 +- .npmignore | 5 +- .nvmrc | 1 + .prettierrc.json | 5 + dist/EBML.js | 5531 +- dist/EBML.min.js | 1 + doc/assets/main.js | 8 +- doc/assets/navigation.js | 2 +- doc/assets/search.js | 2 +- doc/assets/style.css | 61 +- doc/classes/EBMLReader.default.html | 40 - doc/classes/index.Decoder.html | 3 - doc/classes/index.Encoder.html | 3 - ...ex.tools.VP8BitStreamToRiffWebPBuffer.html | 5 - .../index.tools.WebPBlockFilter.html | 2 - .../index.tools.WebPFrameFilter.html | 4 - doc/functions/index.tools.concat.html | 1 - .../index.tools.convertEBMLDateToJSDate.html | 1 - .../index.tools.createFloatBuffer.html | 1 - .../index.tools.createIntBuffer.html | 1 - .../index.tools.createRIFFChunk.html | 2 - .../index.tools.createUIntBuffer.html | 1 - doc/functions/index.tools.ebmlBlock.html | 1 - doc/functions/index.tools.encodeTag.html | 1 - .../index.tools.encodeValueToBuffer.html | 1 - doc/functions/index.tools.extractElement.html | 5 - .../index.tools.makeMetadataSeekable.html | 4 - .../index.tools.putRefinedMetaData.html | 3 - doc/functions/index.tools.readBlock.html | 1 - doc/functions/index.tools.readVint.html | 1 - doc/functions/index.tools.removeElement.html | 5 - doc/functions/index.tools.writeVint.html | 1 - doc/index.html | 26 +- doc/interfaces/EBMLReader.CueInfo.html | 5 - doc/interfaces/EBMLReader.DurationInfo.html | 3 - doc/interfaces/EBMLReader.SegmentInfo.html | 2 - doc/interfaces/EBMLReader.ThumbnailInfo.html | 3 - doc/interfaces/index.BinaryElement.html | 4 - doc/interfaces/index.ChildElement.html | 3 - doc/interfaces/index.ChildElementValue.html | 4 - doc/interfaces/index.DateElement.html | 6 - doc/interfaces/index.ElementDetail.html | 24 - doc/interfaces/index.IElement.html | 3 - doc/interfaces/index.MasterElement.html | 5 - doc/interfaces/index.NumberElement.html | 4 - doc/interfaces/index.Schema.html | 5 - doc/interfaces/index.SimpleBlock.html | 7 - doc/interfaces/index.StringElement.html | 4 - doc/modules/EBMLReader.html | 6 - doc/modules/index.html | 23 - doc/modules/index.tools.html | 20 - doc/types/index.ChildElementBuffer.html | 1 - doc/types/index.ChildElementsValue.html | 1 - doc/types/index.EBMLElementBuffer.html | 1 - doc/types/index.EBMLElementBufferValue.html | 1 - doc/types/index.EBMLElementDetail.html | 1 - doc/types/index.EBMLElementValue.html | 1 - doc/variables/index.version.html | 1 - lib/EBML.d.ts | 9 +- lib/EBMLDecoder.d.ts | 11 +- lib/EBMLDecoder.js | 261 +- lib/EBMLEncoder.js | 129 +- lib/EBMLReader.d.ts | 6 +- lib/EBMLReader.js | 436 +- lib/cli.js | 120 +- lib/example_mediasource.d.ts | 6 - lib/example_mediasource.js | 308 - lib/example_seekable.js | 273 - lib/index.js | 25 +- lib/{example_seekable.d.ts => run_test.d.ts} | 0 lib/run_test.js | 52 + lib/test.js | 1548 +- lib/tools.d.ts | 10 +- lib/tools.js | 505 +- package-lock.json | 3953 -- package.json | 56 +- playwright.config.js | 7 +- readme.md | 22 +- src/EBML.ts | 38 +- src/EBMLDecoder.ts | 282 +- src/EBMLEncoder.ts | 95 +- src/EBMLReader.ts | 424 +- src/cli.ts | 141 +- src/example_mediasource.ts | 238 - src/example_seekable.ts | 221 - src/index.ts | 12 +- src/run_test.ts | 88 +- src/test.ts | 451 +- src/tools.ts | 725 +- test/example_mediasource.html | 309 +- test/example_mediasource_from_file.html | 266 +- test/example_seekable.html | 249 +- test/run_test.mjs | 33 - test/test.html | 3 +- test/test.js | 42683 ---------------- tsconfig.json | 96 +- tslint.json | 29 - typedoc.json | 4 +- 100 files changed, 6881 insertions(+), 53225 deletions(-) create mode 100644 .eslintrc.json create mode 100644 .nvmrc create mode 100644 .prettierrc.json create mode 100644 dist/EBML.min.js delete mode 100644 doc/classes/EBMLReader.default.html delete mode 100644 doc/classes/index.Decoder.html delete mode 100644 doc/classes/index.Encoder.html delete mode 100644 doc/functions/index.tools.VP8BitStreamToRiffWebPBuffer.html delete mode 100644 doc/functions/index.tools.WebPBlockFilter.html delete mode 100644 doc/functions/index.tools.WebPFrameFilter.html delete mode 100644 doc/functions/index.tools.concat.html delete mode 100644 doc/functions/index.tools.convertEBMLDateToJSDate.html delete mode 100644 doc/functions/index.tools.createFloatBuffer.html delete mode 100644 doc/functions/index.tools.createIntBuffer.html delete mode 100644 doc/functions/index.tools.createRIFFChunk.html delete mode 100644 doc/functions/index.tools.createUIntBuffer.html delete mode 100644 doc/functions/index.tools.ebmlBlock.html delete mode 100644 doc/functions/index.tools.encodeTag.html delete mode 100644 doc/functions/index.tools.encodeValueToBuffer.html delete mode 100644 doc/functions/index.tools.extractElement.html delete mode 100644 doc/functions/index.tools.makeMetadataSeekable.html delete mode 100644 doc/functions/index.tools.putRefinedMetaData.html delete mode 100644 doc/functions/index.tools.readBlock.html delete mode 100644 doc/functions/index.tools.readVint.html delete mode 100644 doc/functions/index.tools.removeElement.html delete mode 100644 doc/functions/index.tools.writeVint.html delete mode 100644 doc/interfaces/EBMLReader.CueInfo.html delete mode 100644 doc/interfaces/EBMLReader.DurationInfo.html delete mode 100644 doc/interfaces/EBMLReader.SegmentInfo.html delete mode 100644 doc/interfaces/EBMLReader.ThumbnailInfo.html delete mode 100644 doc/interfaces/index.BinaryElement.html delete mode 100644 doc/interfaces/index.ChildElement.html delete mode 100644 doc/interfaces/index.ChildElementValue.html delete mode 100644 doc/interfaces/index.DateElement.html delete mode 100644 doc/interfaces/index.ElementDetail.html delete mode 100644 doc/interfaces/index.IElement.html delete mode 100644 doc/interfaces/index.MasterElement.html delete mode 100644 doc/interfaces/index.NumberElement.html delete mode 100644 doc/interfaces/index.Schema.html delete mode 100644 doc/interfaces/index.SimpleBlock.html delete mode 100644 doc/interfaces/index.StringElement.html delete mode 100644 doc/modules/EBMLReader.html delete mode 100644 doc/modules/index.html delete mode 100644 doc/modules/index.tools.html delete mode 100644 doc/types/index.ChildElementBuffer.html delete mode 100644 doc/types/index.ChildElementsValue.html delete mode 100644 doc/types/index.EBMLElementBuffer.html delete mode 100644 doc/types/index.EBMLElementBufferValue.html delete mode 100644 doc/types/index.EBMLElementDetail.html delete mode 100644 doc/types/index.EBMLElementValue.html delete mode 100644 doc/variables/index.version.html delete mode 100644 lib/example_mediasource.d.ts delete mode 100644 lib/example_mediasource.js delete mode 100644 lib/example_seekable.js rename lib/{example_seekable.d.ts => run_test.d.ts} (100%) create mode 100644 lib/run_test.js delete mode 100644 package-lock.json delete mode 100644 src/example_mediasource.ts delete mode 100644 src/example_seekable.ts delete mode 100644 test/run_test.mjs delete mode 100644 test/test.js delete mode 100644 tslint.json diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..4d6878f --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,103 @@ +{ + "root": true, + "env": { + "browser": true, + "es2019": true + }, + "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + "plugin:@typescript-eslint/strict", + "plugin:@typescript-eslint/strict-type-checked", + "prettier" + ], + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaFeatures": {}, + "ecmaVersion": 13, + "sourceType": "module", + "project": "./tsconfig.json" + }, + "plugins": [ + "@typescript-eslint" + ], + "rules": { + // possible problems + "array-callback-return": "error", + "no-await-in-loop": "off", + "no-constant-binary-expression": "error", + "no-constructor-return": "error", + "no-constant-condition": "off", + "no-duplicate-imports": "error", + "no-new-native-nonconstructor": "error", + "no-self-compare": "error", + "no-template-curly-in-string": "error", + "no-unmodified-loop-condition": "error", + "no-unreachable-loop": "error", + "no-unused-private-class-members": "error", + "no-unused-vars": [ + "off", + { + "argsIgnorePattern": "^_" + } + ], + "no-use-before-define": "off", + "require-atomic-updates": "error", + // suggestions + "accessor-pairs": "error", + "arrow-body-style": "error", + "block-scoped-var": "error", + "camelcase": "off", + "class-methods-use-this": "error", + "complexity": "off", + "consistent-return": "error", + "consistent-this": "error", + "curly": "error", + "default-case": "off", + "default-case-last": "off", + "default-param-last": "error", + "dot-notation": "off", + "eqeqeq": ["error", "smart"], + "func-name-matching": "error", + "func-names": ["error", "always"], + "func-style": ["error", "declaration"], + "grouped-accessor-pairs": "error", + "guard-for-in": "error", + "id-denylist": "off", + "id-length": "off", + "id-match": "off", + "init-declarations": ["error", "always"], + "logical-assignment-operators": ["error", "always"], + + "prefer-spread": "off", + + "no-unused-labels": "error", + "no-labels": "off", + "no-empty-pattern": "off", + "no-inner-declarations": "off", + "no-extra-label": "off", + + "radix": "error", + "require-await": "off", + + // Layout & Formatting + "line-comment-position": ["error", { "position": "above" }], + "unicode-bom": ["error", "always"], + + "@typescript-eslint/no-unused-vars": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/ban-types": "error", + "@typescript-eslint/no-non-null-assertion": "off", + "@typescript-eslint/no-var-requires": "off", + "@typescript-eslint/no-unsafe-assignment": "off", + "@typescript-eslint/no-unnecessary-condition": "off", + "@typescript-eslint/no-unsafe-member-access": "off", + "@typescript-eslint/no-unsafe-call": "off", + "@typescript-eslint/no-unsafe-argument": "off", + "@typescript-eslint/consistent-type-assertions": ["error", { "assertionStyle": "as", "objectLiteralTypeAssertions": "allow" }], + "@typescript-eslint/no-unsafe-return": "off", + "@typescript-eslint/prefer-promise-reject-errors": "off", + "@typescript-eslint/unified-signatures": "off" + } +} \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a9f505..b09faef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,10 +22,10 @@ jobs: node-version: ${{ matrix.node-version }} - name: Init - run: npm run init + run: npm ci - name: Build - run: npm run build + run: npm run build && npm run build_test - name: Lint run: npm run lint @@ -36,5 +36,5 @@ jobs: - name: Test run: npm test - - name: Examples - run: npm run examples + - name: Diff + run: git diff --exit-code \ No newline at end of file diff --git a/.gitignore b/.gitignore index 320c107..79657b2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ node_modules/ -dist/ -package-lock.json +dist/test.js +test-results/ diff --git a/.npmignore b/.npmignore index 9b33168..7b0dcff 100644 --- a/.npmignore +++ b/.npmignore @@ -2,10 +2,11 @@ *.log .DS_Store log.txt* -dist/ +dist/test.js matroska-test-files/ mkclean-*/ mkvalidator-*/ node_modules/ test/ -test/.DS_Store \ No newline at end of file +test/.DS_Store +test-results/ \ No newline at end of file diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..85aee5a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +v20 \ No newline at end of file diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..6abba94 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,5 @@ +{ + "arrowParens": "always", + "trailingComma": "none", + "proseWrap": "never" +} \ No newline at end of file diff --git a/dist/EBML.js b/dist/EBML.js index c4b1245..3e4a1c4 100644 --- a/dist/EBML.js +++ b/dist/EBML.js @@ -3,23 +3,46 @@ Object.defineProperty(exports, "__esModule", { value: true }); },{}],2:[function(require,module,exports){ +(function (Buffer){(function (){ "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", { value: true }); -var tools_1 = require("./tools"); -var int64_buffer_1 = require("int64-buffer"); -var tools = require("./tools"); -var schema = require("matroska-schema"); -var byEbmlID = schema.byEbmlID; -// https://www.matroska.org/technical/specs/index.html +const bigint_buffer_1 = require("bigint-buffer"); +const tools_1 = require("./tools"); +const tools = __importStar(require("./tools")); +const schema = require("matroska-schema"); +const { byEbmlID } = schema; var State; (function (State) { State[State["STATE_TAG"] = 1] = "STATE_TAG"; State[State["STATE_SIZE"] = 2] = "STATE_SIZE"; State[State["STATE_CONTENT"] = 3] = "STATE_CONTENT"; })(State || (State = {})); -var EBMLDecoder = /** @class */ (function () { - function EBMLDecoder() { - this._buffer = new tools_1.Buffer(0); +class EBMLDecoder { + constructor() { + this._buffer = Buffer.alloc(0); this._tag_stack = []; this._state = State.STATE_TAG; this._cursor = 0; @@ -27,17 +50,18 @@ var EBMLDecoder = /** @class */ (function () { this._schema = byEbmlID; this._result = []; } - EBMLDecoder.prototype.decode = function (chunk) { + decode(chunk) { this.readChunk(chunk); - var diff = this._result; + const diff = this._result; this._result = []; return diff; - }; - EBMLDecoder.prototype.readChunk = function (chunk) { - // 読みかけの(読めなかった) this._buffer と 新しい chunk を合わせて読み直す - this._buffer = tools.concat([this._buffer, new tools_1.Buffer(chunk)]); + } + readChunk(chunk) { + // Re-read the _buffer that was unreadable and the new chunk together. + // console.log(this._buffer, Buffer.from(chunk)); + this._buffer = tools.concat([this._buffer, Buffer.from(chunk)]); while (this._cursor < this._buffer.length) { - // console.log(this._cursor, this._total, this._tag_stack); + // console.log(this._state, this._cursor, this._total, this._tag_stack); if (this._state === State.STATE_TAG && !this.readTag()) { break; } @@ -48,41 +72,45 @@ var EBMLDecoder = /** @class */ (function () { break; } } - }; - EBMLDecoder.prototype.getSchemaInfo = function (tagNum) { - return this._schema[tagNum] || { - name: "unknown", - level: -1, - type: "unknown", - description: "unknown" - }; - }; + } + getSchemaInfo(tagNum) { + if (this._schema[tagNum] != null) { + return this._schema[tagNum]; + } + else { + return { + name: "unknown", + level: -1, + type: "unknown", + description: "unknown" + }; + } + } /** - * vint された parsing tag + * parsing vint-ed tag * @return - return false when waiting for more data */ - EBMLDecoder.prototype.readTag = function () { - // tag.length が buffer の外にある + readTag() { + // tag.length is out of the buffer if (this._cursor >= this._buffer.length) { return false; } // read ebml id vint without first byte - var tag = (0, tools_1.readVint)(this._buffer, this._cursor); - // tag が読めなかった + const tag = (0, tools_1.readVint)(this._buffer, this._cursor); + // cannot parse tag if (tag == null) { return false; } - // >>>>>>>>> - // tag 識別子 + // read tag id + // Hacks to avoid using parseInt //const tagStr = this._buffer.toString("hex", this._cursor, this._cursor + tag.length); //const tagNum = parseInt(tagStr, 16); - // 上と等価 - var buf = this._buffer.slice(this._cursor, this._cursor + tag.length); - var tagNum = buf.reduce(function (o, v, i, arr) { return o + v * Math.pow(16, 2 * (arr.length - 1 - i)); }, 0); - var schema = this.getSchemaInfo(tagNum); - var tagObj = { + const buf = this._buffer.subarray(this._cursor, this._cursor + tag.length); + const tagNum = buf.reduce((o, v, i, arr) => o + v * Math.pow(16, 2 * (arr.length - 1 - i)), 0); + const schema = this.getSchemaInfo(tagNum); + const tagObj = { EBML_ID: tagNum.toString(16), - schema: schema, + schema, type: schema.type, name: schema.name, level: schema.level, @@ -95,34 +123,37 @@ var EBMLDecoder = /** @class */ (function () { dataSize: null, data: null }; + // +-----------+------------+--------------------+ // | tag: vint | size: vint | data: Buffer(size) | + // +-----------+------------+--------------------+ this._tag_stack.push(tagObj); - // <<<<<<<< - // ポインタを進める + // advance the pointer this._cursor += tag.length; this._total += tag.length; - // 読み込み状態変更 + // change read status this._state = State.STATE_SIZE; return true; - }; + } /** - * vint された現在のタグの内容の大きさを読み込む + * Reads the size of the vint-ed current tag content * @return - return false when waiting for more data */ - EBMLDecoder.prototype.readSize = function () { - // tag.length が buffer の外にある + readSize() { + // tag.length is outside the buffer if (this._cursor >= this._buffer.length) { return false; } // read ebml datasize vint without first byte - var size = (0, tools_1.readVint)(this._buffer, this._cursor); - // まだ読めない + const size = (0, tools_1.readVint)(this._buffer, this._cursor); + // still can't read it. if (size == null) { return false; } - // >>>>>>>>> - // current tag の data size 決定 - var tagObj = this._tag_stack[this._tag_stack.length - 1]; + // decide data size for current tag + const tagObj = this._tag_stack[this._tag_stack.length - 1]; + if (tagObj == null) { + return false; + } tagObj.sizeEnd = tagObj.sizeStart + size.length; tagObj.dataStart = tagObj.sizeEnd; tagObj.dataSize = size.value; @@ -136,30 +167,31 @@ var EBMLDecoder = /** @class */ (function () { else { tagObj.dataEnd = tagObj.sizeEnd + size.value; } - // <<<<<<<< - // ポインタを進める + // advance the pointer this._cursor += size.length; this._total += size.length; this._state = State.STATE_CONTENT; return true; - }; - /** - * データ読み込み - */ - EBMLDecoder.prototype.readContent = function () { - var tagObj = this._tag_stack[this._tag_stack.length - 1]; - // master element は子要素を持つので生データはない - if (tagObj.type === 'm') { + } + readContent() { + const tagObj = this._tag_stack[this._tag_stack.length - 1]; + if (tagObj == null) { + return false; + } + // master element does not have raw data buffer + // because it has child elements + if (tagObj.type === "m") { // console.log('content should be tags'); tagObj.isEnd = false; this._result.push(tagObj); this._state = State.STATE_TAG; - // この Mastert Element は空要素か + // if this Mastert Element empty if (tagObj.dataSize === 0) { - // 即座に終了タグを追加 - var elm = Object.assign({}, tagObj, { isEnd: true }); + // then add the end tag immediately + const elm = Object.assign({}, tagObj, { isEnd: true }); this._result.push(elm); - this._tag_stack.pop(); // スタックからこのタグを捨てる + // pop out the tag from tag stack + this._tag_stack.pop(); } return true; } @@ -167,64 +199,91 @@ var EBMLDecoder = /** @class */ (function () { if (this._buffer.length < this._cursor + tagObj.dataSize) { return false; } - // タグの中身の生データ - var data = this._buffer.slice(this._cursor, this._cursor + tagObj.dataSize); + // raw data of tag content + const data = this._buffer.subarray(this._cursor, this._cursor + tagObj.dataSize); // 読み終わったバッファを捨てて読み込んでいる部分のバッファのみ残す - this._buffer = this._buffer.slice(this._cursor + tagObj.dataSize); + this._buffer = this._buffer.subarray(this._cursor + tagObj.dataSize); tagObj.data = data; - // >>>>>>>>> switch (tagObj.type) { - //case "m": break; - // Master-Element - contains other EBML sub-elements of the next lower level - case "u": - tagObj.value = data.readUIntBE(0, data.length); + // case "m": { + // // Master-Element - contains other EBML sub-elements of the next lower level + // throw new Error("never"); + // } + case "u": { + // Unsigned Integer - Big-endian, any size from 1 to 8 octets + if (data.length > 6) { + // feross/buffer shim can read over 7 octets + // but nodejs buffer only can read under 6 octets + // so use bigint-buffer + tagObj.value = Number((0, bigint_buffer_1.toBigIntBE)(data)); + } + else { + tagObj.value = data.readUIntBE(0, data.length); + } break; - // Unsigned Integer - Big-endian, any size from 1 to 8 octets - case "i": + } + case "i": { + // Signed Integer - Big-endian, any size from 1 to 8 octets tagObj.value = data.readIntBE(0, data.length); break; - // Signed Integer - Big-endian, any size from 1 to 8 octets - case "f": - tagObj.value = tagObj.dataSize === 4 ? data.readFloatBE(0) : - tagObj.dataSize === 8 ? data.readDoubleBE(0) : - (console.warn("cannot read ".concat(tagObj.dataSize, " octets float. failback to 0")), 0); + } + case "f": { + // Float - Big-endian, defined for 4 and 8 octets (32, 64 bits) + if (tagObj.dataSize === 4) { + tagObj.value = data.readFloatBE(0); + } + else if (tagObj.dataSize === 8) { + tagObj.value = data.readDoubleBE(0); + } + else { + console.warn(`cannot read ${tagObj.dataSize} octets float. failback to 0`); + tagObj.value = 0; + } break; - // Float - Big-endian, defined for 4 and 8 octets (32, 64 bits) - case "s": + } + case "s": { + // Printable ASCII (0x20 to 0x7E), zero-padded when needed tagObj.value = data.toString("ascii"); - break; // ascii - // Printable ASCII (0x20 to 0x7E), zero-padded when needed - case "8": + break; + } + case "8": { + // Unicode string, zero padded when needed (RFC 2279) tagObj.value = data.toString("utf8"); break; - // Unicode string, zero padded when needed (RFC 2279) - case "b": + } + case "b": { + // Binary - not interpreted by the parser tagObj.value = data; break; - // Binary - not interpreted by the parser - case "d": - tagObj.value = (0, tools_1.convertEBMLDateToJSDate)(new int64_buffer_1.Int64BE(data).toNumber()); + } + case "d": { + // nano second; Date.UTC(2001,1,1,0,0,0,0) === 980985600000 + // Date - signed 8 octets integer in nanoseconds with 0 indicating + // the precise beginning of the millennium (at 2001-01-01T00:00:00,000000000 UTC) + tagObj.value = (0, tools_1.convertEBMLDateToJSDate)(Number((0, bigint_buffer_1.toBigIntBE)(data))); break; - // nano second; Date.UTC(2001,1,1,0,0,0,0) === 980985600000 - // Date - signed 8 octets integer in nanoseconds with 0 indicating - // the precise beginning of the millennium (at 2001-01-01T00:00:00,000000000 UTC) + } } if (tagObj.value === null) { throw new Error("unknown tag type:" + tagObj.type); } this._result.push(tagObj); - // <<<<<<<< - // ポインタを進める + // advance the pointer this._total += tagObj.dataSize; - // タグ待ちモードに変更 + // change state to waiting next tag this._state = State.STATE_TAG; this._cursor = 0; - this._tag_stack.pop(); // remove the object from the stack + // remove the object from the stack + this._tag_stack.pop(); while (this._tag_stack.length > 0) { - var topEle = this._tag_stack[this._tag_stack.length - 1]; + const topEle = this._tag_stack[this._tag_stack.length - 1]; + if (topEle == null) { + return false; + } // 親が不定長サイズなので閉じタグは期待できない if (topEle.dataEnd < 0) { - this._tag_stack.pop(); // 親タグを捨てる + // remove parent tag + this._tag_stack.pop(); return true; } // 閉じタグの来るべき場所まで来たかどうか @@ -235,36 +294,56 @@ var EBMLDecoder = /** @class */ (function () { if (topEle.type !== "m") { throw new Error("parent element is not master element"); } - var elm = Object.assign({}, topEle, { isEnd: true }); + const elm = Object.assign({}, topEle, { isEnd: true }); this._result.push(elm); this._tag_stack.pop(); } return true; - }; - return EBMLDecoder; -}()); + } +} exports.default = EBMLDecoder; -},{"./tools":6,"int64-buffer":17,"matroska-schema":18}],3:[function(require,module,exports){ +}).call(this)}).call(this,require("buffer").Buffer) +},{"./tools":6,"bigint-buffer":8,"buffer":9,"matroska-schema":20}],3:[function(require,module,exports){ +(function (Buffer){(function (){ "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", { value: true }); -var tools = require("./tools"); -var tools_1 = require("./tools"); -var schema = require("matroska-schema"); -var byEbmlID = schema.byEbmlID; -var EBMLEncoder = /** @class */ (function () { - function EBMLEncoder() { +const tools = __importStar(require("./tools")); +const schema = require("matroska-schema"); +const { byEbmlID } = schema; +class EBMLEncoder { + constructor() { this._schema = byEbmlID; this._buffers = []; this._stack = []; } - EBMLEncoder.prototype.encode = function (elms) { - var _this = this; - return tools.concat(elms.reduce(function (lst, elm) { - return lst.concat(_this.encodeChunk(elm)); - }, [])).buffer; - }; - EBMLEncoder.prototype.encodeChunk = function (elm) { + encode(elms) { + return tools.concat(elms.reduce((lst, elm) => lst.concat(this.encodeChunk(elm)), [])).buffer; + } + encodeChunk(elm) { if (elm.type === "m") { if (!elm.isEnd) { this.startTag(elm); @@ -275,67 +354,61 @@ var EBMLEncoder = /** @class */ (function () { } else { // ensure that we are working with an internal `Buffer` instance - elm.data = tools_1.Buffer.from(elm.data); + elm.data = Buffer.from(elm.data); this.writeTag(elm); } return this.flush(); - }; - EBMLEncoder.prototype.flush = function () { - var ret = this._buffers; + } + flush() { + const ret = this._buffers; this._buffers = []; return ret; - }; - EBMLEncoder.prototype.getSchemaInfo = function (tagName) { - var tagNums = Object.keys(this._schema).map(Number); - for (var i = 0; i < tagNums.length; i++) { - var tagNum = tagNums[i]; - if (this._schema[tagNum].name === tagName) { - return new tools_1.Buffer(tagNum.toString(16), 'hex'); + } + getSchemaInfo(tagName) { + for (const [tagNum, tagVal] of Object.entries(this._schema)) { + if (tagVal.name === tagName) { + return Buffer.from(Number(tagNum).toString(16), "hex"); } } return null; - }; - EBMLEncoder.prototype.writeTag = function (elm) { - var tagName = elm.name; - var tagId = this.getSchemaInfo(tagName); - var tagData = elm.data; + } + writeTag(elm) { + const tagName = elm.name; + const tagId = this.getSchemaInfo(tagName); + const tagData = elm.data; if (tagId == null) { - throw new Error('No schema entry found for ' + tagName); + throw new Error("No schema entry found for " + tagName); } - var data = tools.encodeTag(tagId, tagData); - /** - * 親要素が閉じタグあり(isEnd)なら閉じタグが来るまで待つ(children queに入る) - */ + const data = tools.encodeTag(tagId, tagData); + // 親要素が閉じタグあり(isEnd)なら閉じタグが来るまで待つ(children queに入る) if (this._stack.length > 0) { - var last = this._stack[this._stack.length - 1]; + const last = this._stack[this._stack.length - 1]; last.children.push({ - tagId: tagId, - elm: elm, + tagId, + elm, children: [], - data: data + data }); return; } this._buffers = this._buffers.concat(data); return; - }; - EBMLEncoder.prototype.startTag = function (elm) { - var tagName = elm.name; - var tagId = this.getSchemaInfo(tagName); + } + startTag(elm) { + const tagName = elm.name; + const tagId = this.getSchemaInfo(tagName); if (tagId == null) { - throw new Error('No schema entry found for ' + tagName); + throw new Error("No schema entry found for " + tagName); } - /** - * 閉じタグ不定長の場合はスタックに積まずに即時バッファに書き込む - */ + // 閉じタグ不定長の場合はスタックに積まずに即時バッファに書き込む if (elm.unknownSize) { - var data = tools.encodeTag(tagId, new tools_1.Buffer(0), elm.unknownSize); + const data = tools.encodeTag(tagId, Buffer.alloc(0), elm.unknownSize); this._buffers = this._buffers.concat(data); return; } - var tag = { - tagId: tagId, - elm: elm, + const tag = { + tagId, + elm, children: [], data: null }; @@ -343,23 +416,22 @@ var EBMLEncoder = /** @class */ (function () { this._stack[this._stack.length - 1].children.push(tag); } this._stack.push(tag); - }; - EBMLEncoder.prototype.endTag = function (elm) { - var tagName = elm.name; - var tag = this._stack.pop(); + } + endTag(elm) { + const tag = this._stack.pop(); if (tag == null) { throw new Error("EBML structure is broken"); } if (tag.elm.name !== elm.name) { throw new Error("EBML structure is broken"); } - var childTagDataBuffers = tag.children.reduce(function (lst, child) { + const childTagDataBuffers = tag.children.reduce((lst, child) => { if (child.data === null) { throw new Error("EBML structure is broken"); } return lst.concat(child.data); }, []); - var childTagDataBuffer = tools.concat(childTagDataBuffers); + const childTagDataBuffer = tools.concat(childTagDataBuffers); if (tag.elm.type === "m") { tag.data = tools.encodeTag(tag.tagId, childTagDataBuffer, tag.elm.unknownSize); } @@ -369,73 +441,85 @@ var EBMLEncoder = /** @class */ (function () { if (this._stack.length < 1) { this._buffers = this._buffers.concat(tag.data); } - }; - return EBMLEncoder; -}()); + } +} exports.default = EBMLEncoder; -},{"./tools":6,"matroska-schema":18}],4:[function(require,module,exports){ +}).call(this)}).call(this,require("buffer").Buffer) +},{"./tools":6,"buffer":9,"matroska-schema":20}],4:[function(require,module,exports){ "use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", { value: true }); -var events_1 = require("events"); -var tools = require("./tools"); +const events_1 = require("events"); +const tools = __importStar(require("./tools")); /** * This is an informal code for reference. * EBMLReader is a class for getting information to enable seeking Webm recorded by MediaRecorder. * So please do not use for regular WebM files. */ -var EBMLReader = /** @class */ (function (_super) { - __extends(EBMLReader, _super); - function EBMLReader() { - var _this = _super.call(this) || this; - _this.logGroup = ""; - _this.hasLoggingStarted = false; - _this.metadataloaded = false; - _this.chunks = []; - _this.stack = []; - _this.segmentOffset = 0; - _this.last2SimpleBlockVideoTrackTimestamp = [0, 0]; - _this.last2SimpleBlockAudioTrackTimestamp = [0, 0]; - _this.lastClusterTimestamp = 0; - _this.lastClusterPosition = 0; - _this.timestampScale = 1000000; // webm default TimestampScale is 1ms - _this.metadataSize = 0; - _this.metadatas = []; - _this.cues = []; - _this.firstVideoBlockRead = false; - _this.firstAudioBlockRead = false; - _this.currentTrack = { TrackNumber: -1, TrackType: -1, DefaultDuration: null, CodecDelay: null }; - _this.trackTypes = []; - _this.trackDefaultDuration = []; - _this.trackCodecDelay = []; - _this.trackInfo = { type: "nothing" }; - _this.ended = false; - _this.logging = false; - _this.use_duration_every_simpleblock = false; - _this.use_webp = false; - _this.use_segment_info = true; - _this.drop_default_duration = true; - return _this; +class EBMLReader extends events_1.EventEmitter { + constructor() { + super(); + this.logGroup = ""; + this.hasLoggingStarted = false; + this.metadataloaded = false; + this.chunks = []; + this.stack = []; + this.segmentOffset = 0; + this.last2SimpleBlockVideoTrackTimestamp = [0, 0]; + this.last2SimpleBlockAudioTrackTimestamp = [0, 0]; + this.lastClusterTimestamp = 0; + this.lastClusterPosition = 0; + // webm default TimestampScale is 1ms + this.timestampScale = 1000000; + this.metadataSize = 0; + this.metadatas = []; + this.cues = []; + this.firstVideoBlockRead = false; + this.firstAudioBlockRead = false; + this.currentTrack = { + TrackNumber: -1, + TrackType: -1, + DefaultDuration: null, + CodecDelay: null + }; + this.trackTypes = []; + this.trackDefaultDuration = []; + this.trackCodecDelay = []; + this.trackInfo = { type: "nothing" }; + this.ended = false; + this.logging = false; + this.use_duration_every_simpleblock = false; + this.use_webp = false; + this.use_segment_info = true; + this.drop_default_duration = true; } /** * emit final state. */ - EBMLReader.prototype.stop = function () { + stop() { this.ended = true; this.emit_segment_info(); // clean up any unclosed Master Elements at the end of the stream. @@ -449,41 +533,46 @@ var EBMLReader = /** @class */ (function (_super) { if (this.logging && this.hasLoggingStarted && this.logGroup) { console.groupEnd(); } - }; + } /** * emit chunk info */ - EBMLReader.prototype.emit_segment_info = function () { - var data = this.chunks; + emit_segment_info() { + const data = this.chunks; this.chunks = []; if (!this.metadataloaded) { this.metadataloaded = true; this.metadatas = data; - var videoTrackNum = this.trackTypes.indexOf(1); // find first video track - var audioTrackNum = this.trackTypes.indexOf(2); // find first audio track - this.trackInfo = videoTrackNum >= 0 && audioTrackNum >= 0 ? { type: "both", trackNumber: videoTrackNum } - : videoTrackNum >= 0 ? { type: "video", trackNumber: videoTrackNum } - : audioTrackNum >= 0 ? { type: "audio", trackNumber: audioTrackNum } - : { type: "nothing" }; + // find first video track + const videoTrackNum = this.trackTypes.indexOf(1); + // find first audio track + const audioTrackNum = this.trackTypes.indexOf(2); + this.trackInfo = + videoTrackNum >= 0 && audioTrackNum >= 0 + ? { type: "both", trackNumber: videoTrackNum } + : videoTrackNum >= 0 + ? { type: "video", trackNumber: videoTrackNum } + : audioTrackNum >= 0 + ? { type: "audio", trackNumber: audioTrackNum } + : { type: "nothing" }; if (!this.use_segment_info) { return; } - this.emit("metadata", { data: data, metadataSize: this.metadataSize }); + this.emit("metadata", { data, metadataSize: this.metadataSize }); } else { if (!this.use_segment_info) { return; } - var timestamp = this.lastClusterTimestamp; - var duration = this.duration; - var timestampScale = this.timestampScale; - this.emit("cluster", { timestamp: timestamp, data: data }); - this.emit("duration", { timestampScale: timestampScale, duration: duration }); + const timestamp = this.lastClusterTimestamp; + const duration = this.duration; + const timestampScale = this.timestampScale; + this.emit("cluster", { timestamp, data }); + this.emit("duration", { timestampScale, duration }); } - }; - EBMLReader.prototype.read = function (elm) { - var _this = this; - var drop = false; + } + read(elm) { + let drop = false; if (this.ended) { // reader is finished return; @@ -494,8 +583,8 @@ var EBMLReader = /** @class */ (function (_super) { this.stack.pop(); } else { - var parent_1 = this.stack[this.stack.length - 1]; - if (parent_1 != null && parent_1.level >= elm.level) { + const parent = this.stack[this.stack.length - 1]; + if (parent != null && parent.level >= elm.level) { // 閉じタグなしでレベルが下がったら閉じタグを挿入 this.stack.pop(); // From http://w3c.github.io/media-source/webm-byte-stream-format.html#webm-media-segments @@ -503,73 +592,107 @@ var EBMLReader = /** @class */ (function (_super) { if (this.logging) { console.groupEnd(); } - parent_1.dataEnd = elm.dataEnd; - parent_1.dataSize = elm.dataEnd - parent_1.dataStart; - parent_1.unknownSize = false; - var o = Object.assign({}, parent_1, { name: parent_1.name, type: parent_1.type, isEnd: true }); + parent.dataEnd = elm.dataEnd; + parent.dataSize = elm.dataEnd - parent.dataStart; + parent.unknownSize = false; + const o = Object.assign({}, parent, { + name: parent.name, + type: parent.type, + isEnd: true + }); this.chunks.push(o); } this.stack.push(elm); } } - if (elm.type === "m" && elm.name == "Segment") { - if (this.segmentOffset != 0) { + if (elm.type === "m" && elm.name === "Segment") { + if (this.segmentOffset !== 0) { console.warn("Multiple segments detected!"); } this.segmentOffset = elm.dataStart; this.emit("segment_offset", this.segmentOffset); } else if (elm.type === "b" && elm.name === "SimpleBlock") { - var _a = tools.ebmlBlock(elm.data), timestamp = _a.timecode, trackNumber = _a.trackNumber, frames_1 = _a.frames; - if (this.trackTypes[trackNumber] === 1) { // trackType === 1 => video track + const { timecode: timestamp, trackNumber, frames } = tools.ebmlBlock(elm.data); + if (this.trackTypes[trackNumber] === 1) { + // trackType === 1 => video track if (!this.firstVideoBlockRead) { this.firstVideoBlockRead = true; - if (this.trackInfo.type === "both" || this.trackInfo.type === "video") { - var CueTime = this.lastClusterTimestamp + timestamp; - this.cues.push({ CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: CueTime }); + if (this.trackInfo.type === "both" || + this.trackInfo.type === "video") { + const CueTime = this.lastClusterTimestamp + timestamp; + this.cues.push({ + CueTrack: trackNumber, + CueClusterPosition: this.lastClusterPosition, + CueTime + }); this.emit("cue_info", { CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: this.lastClusterTimestamp }); - this.emit("cue", { CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: CueTime }); + this.emit("cue", { + CueTrack: trackNumber, + CueClusterPosition: this.lastClusterPosition, + CueTime + }); } } - this.last2SimpleBlockVideoTrackTimestamp = [this.last2SimpleBlockVideoTrackTimestamp[1], timestamp]; + this.last2SimpleBlockVideoTrackTimestamp = [ + this.last2SimpleBlockVideoTrackTimestamp[1], + timestamp + ]; } - else if (this.trackTypes[trackNumber] === 2) { // trackType === 2 => audio track + else if (this.trackTypes[trackNumber] === 2) { + // trackType === 2 => audio track if (!this.firstAudioBlockRead) { this.firstAudioBlockRead = true; if (this.trackInfo.type === "audio") { - var CueTime = this.lastClusterTimestamp + timestamp; - this.cues.push({ CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: CueTime }); + const CueTime = this.lastClusterTimestamp + timestamp; + this.cues.push({ + CueTrack: trackNumber, + CueClusterPosition: this.lastClusterPosition, + CueTime + }); this.emit("cue_info", { CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: this.lastClusterTimestamp }); - this.emit("cue", { CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: CueTime }); + this.emit("cue", { + CueTrack: trackNumber, + CueClusterPosition: this.lastClusterPosition, + CueTime + }); } } - this.last2SimpleBlockAudioTrackTimestamp = [this.last2SimpleBlockAudioTrackTimestamp[1], timestamp]; + this.last2SimpleBlockAudioTrackTimestamp = [ + this.last2SimpleBlockAudioTrackTimestamp[1], + timestamp + ]; } if (this.use_duration_every_simpleblock) { - this.emit("duration", { timestampScale: this.timestampScale, duration: this.duration }); + this.emit("duration", { + timestampScale: this.timestampScale, + duration: this.duration + }); } if (this.use_webp) { - frames_1.forEach(function (frame) { - var startcode = frame.slice(3, 6).toString("hex"); + for (const frame of frames) { + const startcode = frame.subarray(3, 6).toString("hex"); + // this is not a good way to detect VP8 + // see rfc6386 -- VP8 Data Format and Decoding Guide if (startcode !== "9d012a") { - return; - } // VP8 の場合 - var webpBuf = tools.VP8BitStreamToRiffWebPBuffer(frame); - var webp = new Blob([webpBuf], { type: "image/webp" }); - var currentTime = _this.duration; - _this.emit("webp", { currentTime: currentTime, webp: webp }); - }); + break; + } + const webpBuf = tools.VP8BitStreamToRiffWebPBuffer(frame); + const webp = new Blob([webpBuf], { type: "image/webp" }); + const currentTime = this.duration; + this.emit("webp", { currentTime, webp }); + } } } - else if (elm.type === "m" && elm.name === "Cluster" && elm.isEnd === false) { + else if (elm.type === "m" && elm.name === "Cluster" && !elm.isEnd) { this.firstVideoBlockRead = false; this.firstAudioBlockRead = false; this.emit_segment_info(); @@ -584,12 +707,20 @@ var EBMLReader = /** @class */ (function (_super) { } else if (elm.type === "m" && elm.name === "TrackEntry") { if (elm.isEnd) { - this.trackTypes[this.currentTrack.TrackNumber] = this.currentTrack.TrackType; - this.trackDefaultDuration[this.currentTrack.TrackNumber] = this.currentTrack.DefaultDuration; - this.trackCodecDelay[this.currentTrack.TrackNumber] = this.currentTrack.CodecDelay; + this.trackTypes[this.currentTrack.TrackNumber] = + this.currentTrack.TrackType; + this.trackDefaultDuration[this.currentTrack.TrackNumber] = + this.currentTrack.DefaultDuration; + this.trackCodecDelay[this.currentTrack.TrackNumber] = + this.currentTrack.CodecDelay; } else { - this.currentTrack = { TrackNumber: -1, TrackType: -1, DefaultDuration: null, CodecDelay: null }; + this.currentTrack = { + TrackNumber: -1, + TrackType: -1, + DefaultDuration: null, + CodecDelay: null + }; } } else if (elm.type === "u" && elm.name === "TrackType") { @@ -626,90 +757,102 @@ var EBMLReader = /** @class */ (function (_super) { if (this.logging) { this.put(elm); } - }; - Object.defineProperty(EBMLReader.prototype, "duration", { - /** - * DefaultDuration が定義されている場合は最後のフレームのdurationも考慮する - * 単位 timestampScale - * - * !!! if you need duration with seconds !!! - * ```js - * const nanosec = reader.duration * reader.timestampScale; - * const sec = nanosec / 1000 / 1000 / 1000; - * ``` - */ - get: function () { - if (this.trackInfo.type === "nothing") { - console.warn("no video, no audio track"); - return 0; - } - // defaultDuration は 生の nano sec - var defaultDuration = 0; - // nanoseconds - var codecDelay = 0; - var lastTimestamp = 0; - var _defaultDuration = this.trackDefaultDuration[this.trackInfo.trackNumber]; - if (typeof _defaultDuration === "number") { - defaultDuration = _defaultDuration; - } - else { - // https://bugs.chromium.org/p/chromium/issues/detail?id=606000#c22 - // default duration がないときに使う delta - if (this.trackInfo.type === "both") { - if (this.last2SimpleBlockAudioTrackTimestamp[1] > this.last2SimpleBlockVideoTrackTimestamp[1]) { - // audio diff - defaultDuration = (this.last2SimpleBlockAudioTrackTimestamp[1] - - this.last2SimpleBlockAudioTrackTimestamp[0]) * this.timestampScale; - // audio delay - var delay = this.trackCodecDelay[this.trackTypes.indexOf(2)]; // 2 => audio - if (typeof delay === "number") { - codecDelay = delay; - } - // audio timestamp - lastTimestamp = this.last2SimpleBlockAudioTrackTimestamp[1]; - } - else { - // video diff - defaultDuration = (this.last2SimpleBlockVideoTrackTimestamp[1] - - this.last2SimpleBlockVideoTrackTimestamp[0]) * this.timestampScale; - // video delay - var delay = this.trackCodecDelay[this.trackTypes.indexOf(1)]; // 1 => video - if (typeof delay === "number") { - codecDelay = delay; - } - // video timestamp - lastTimestamp = this.last2SimpleBlockVideoTrackTimestamp[1]; - } - } - else if (this.trackInfo.type === "video") { - defaultDuration = (this.last2SimpleBlockVideoTrackTimestamp[1] - this.last2SimpleBlockVideoTrackTimestamp[0]) * this.timestampScale; - var delay = this.trackCodecDelay[this.trackInfo.trackNumber]; // 2 => audio + } + /** + * DefaultDuration が定義されている場合は最後のフレームのdurationも考慮する + * 単位 timestampScale + * + * !!! if you need duration with seconds !!! + * ```js + * const nanosec = reader.duration * reader.timestampScale; + * const sec = nanosec / 1000 / 1000 / 1000; + * ``` + */ + get duration() { + if (this.trackInfo.type === "nothing") { + console.warn("no video, no audio track"); + return 0; + } + // defaultDuration は 生の nano sec + let defaultDuration = 0; + // nanoseconds + let codecDelay = 0; + let lastTimestamp = 0; + const _defaultDuration = this.trackDefaultDuration[this.trackInfo.trackNumber]; + if (typeof _defaultDuration === "number") { + defaultDuration = _defaultDuration; + } + else { + // https://bugs.chromium.org/p/chromium/issues/detail?id=606000#c22 + // default duration がないときに使う delta + if (this.trackInfo.type === "both") { + if (this.last2SimpleBlockAudioTrackTimestamp[1] > + this.last2SimpleBlockVideoTrackTimestamp[1]) { + // audio diff + defaultDuration = + (this.last2SimpleBlockAudioTrackTimestamp[1] - + this.last2SimpleBlockAudioTrackTimestamp[0]) * + this.timestampScale; + // audio delay + // 2 => audio + const delay = this.trackCodecDelay[this.trackTypes.indexOf(2)]; if (typeof delay === "number") { codecDelay = delay; } - lastTimestamp = this.last2SimpleBlockVideoTrackTimestamp[1]; + // audio timestamp + lastTimestamp = this.last2SimpleBlockAudioTrackTimestamp[1]; } - else if (this.trackInfo.type === "audio") { - defaultDuration = (this.last2SimpleBlockAudioTrackTimestamp[1] - this.last2SimpleBlockAudioTrackTimestamp[0]) * this.timestampScale; - var delay = this.trackCodecDelay[this.trackInfo.trackNumber]; // 1 => video + else { + // video diff + defaultDuration = + (this.last2SimpleBlockVideoTrackTimestamp[1] - + this.last2SimpleBlockVideoTrackTimestamp[0]) * + this.timestampScale; + // video delay + // 1 => video + const delay = this.trackCodecDelay[this.trackTypes.indexOf(1)]; if (typeof delay === "number") { codecDelay = delay; } - lastTimestamp = this.last2SimpleBlockAudioTrackTimestamp[1]; - } // else { not reached } + // video timestamp + lastTimestamp = this.last2SimpleBlockVideoTrackTimestamp[1]; + } } - // convert to timestampscale - var duration_nanosec = ((this.lastClusterTimestamp + lastTimestamp) * this.timestampScale) + defaultDuration - codecDelay; - var duration = duration_nanosec / this.timestampScale; - return Math.floor(duration); - }, - enumerable: false, - configurable: true - }); - EBMLReader.prototype.addListener = function (event, listener) { - return _super.prototype.addListener.call(this, event, listener); - }; - EBMLReader.prototype.put = function (elm) { + else if (this.trackInfo.type === "video") { + defaultDuration = + (this.last2SimpleBlockVideoTrackTimestamp[1] - + this.last2SimpleBlockVideoTrackTimestamp[0]) * + this.timestampScale; + const delay = this.trackCodecDelay[this.trackInfo.trackNumber]; + if (typeof delay === "number") { + codecDelay = delay; + } + lastTimestamp = this.last2SimpleBlockVideoTrackTimestamp[1]; + } + else if (this.trackInfo.type === "audio") { + defaultDuration = + (this.last2SimpleBlockAudioTrackTimestamp[1] - + this.last2SimpleBlockAudioTrackTimestamp[0]) * + this.timestampScale; + const delay = this.trackCodecDelay[this.trackInfo.trackNumber]; + if (typeof delay === "number") { + codecDelay = delay; + } + lastTimestamp = this.last2SimpleBlockAudioTrackTimestamp[1]; + } + // else { never } + } + // convert to timestampscale + const duration_nanosec = (this.lastClusterTimestamp + lastTimestamp) * this.timestampScale + + defaultDuration - + codecDelay; + const duration = duration_nanosec / this.timestampScale; + return Math.floor(duration); + } + addListener(event, listener) { + return super.addListener(event, listener); + } + put(elm) { if (!this.hasLoggingStarted) { this.hasLoggingStarted = true; if (this.logging && this.logGroup) { @@ -736,12 +879,11 @@ var EBMLReader = /** @class */ (function (_super) { else { console.log(elm.name, elm.tagStart, elm.type, elm.value); } - }; - return EBMLReader; -}(events_1.EventEmitter)); + } +} exports.default = EBMLReader; -},{"./tools":6,"events":15}],5:[function(require,module,exports){ +},{"./tools":6,"events":17}],5:[function(require,module,exports){ "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -754,52 +896,66 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi if (k2 === undefined) k2 = k; o[k2] = m[k]; })); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", { value: true }); exports.tools = exports.Reader = exports.Encoder = exports.Decoder = exports.version = void 0; __exportStar(require("./EBML"), exports); -var EBMLDecoder_1 = require("./EBMLDecoder"); +const EBMLDecoder_1 = __importDefault(require("./EBMLDecoder")); exports.Decoder = EBMLDecoder_1.default; -var EBMLEncoder_1 = require("./EBMLEncoder"); +const EBMLEncoder_1 = __importDefault(require("./EBMLEncoder")); exports.Encoder = EBMLEncoder_1.default; -var EBMLReader_1 = require("./EBMLReader"); +const EBMLReader_1 = __importDefault(require("./EBMLReader")); exports.Reader = EBMLReader_1.default; -var tools = require("./tools"); +const tools = __importStar(require("./tools")); exports.tools = tools; -var version = require("../package.json").version; +const version = require("../package.json").version; exports.version = version; -},{"../package.json":21,"./EBML":1,"./EBMLDecoder":2,"./EBMLEncoder":3,"./EBMLReader":4,"./tools":6}],6:[function(require,module,exports){ +},{"../package.json":22,"./EBML":1,"./EBMLDecoder":2,"./EBMLEncoder":3,"./EBMLReader":4,"./tools":6}],6:[function(require,module,exports){ +(function (Buffer){(function (){ "use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertEBMLDateToJSDate = exports.createFloatBuffer = exports.createIntBuffer = exports.createUIntBuffer = exports.encodeValueToBuffer = exports.concat = exports.putRefinedMetaData = exports.extractElement = exports.removeElement = exports.makeMetadataSeekable = exports.createRIFFChunk = exports.VP8BitStreamToRiffWebPBuffer = exports.WebPBlockFilter = exports.WebPFrameFilter = exports.encodeTag = exports.readBlock = exports.ebmlBlock = exports.writeVint = exports.readVint = exports.Buffer = void 0; -/// -var int64_buffer_1 = require("int64-buffer"); -var EBMLEncoder_1 = require("./EBMLEncoder"); -var buffer_1 = require("buffer"); -var ebml_1 = require('ebml/lib/ebml.js'); -var _block = require("ebml-block"); -var buffer_2 = require("buffer"); -Object.defineProperty(exports, "Buffer", { enumerable: true, get: function () { return buffer_2.Buffer; } }); -exports.readVint = ebml_1.tools.readVint; -exports.writeVint = ebml_1.tools.writeVint; +exports.convertEBMLDateToJSDate = exports.createFloatBuffer = exports.createIntBuffer = exports.createUIntBuffer = exports.encodeValueToBuffer = exports.concat = exports.putRefinedMetaData = exports.extractElement = exports.removeElement = exports.makeMetadataSeekable = exports.createRIFFChunk = exports.VP8BitStreamToRiffWebPBuffer = exports.WebPBlockFilter = exports.WebPFrameFilter = exports.encodeTag = exports.readBlock = exports.ebmlBlock = exports.writeVint = exports.readVint = void 0; +const int64_buffer_1 = require("int64-buffer"); +const EBMLEncoder_1 = __importDefault(require("./EBMLEncoder")); +const { tools: _tools } = require('ebml/lib/ebml.js'); +const _block = require("ebml-block"); +exports.readVint = _tools.readVint; +exports.writeVint = _tools.writeVint; exports.ebmlBlock = _block; function readBlock(buf) { - return (0, exports.ebmlBlock)(new buffer_1.Buffer(buf)); + return (0, exports.ebmlBlock)(Buffer.from(buf)); } exports.readBlock = readBlock; /** - * @param end - if end === false then length is unknown - */ -function encodeTag(tagId, tagData, unknownSize) { - if (unknownSize === void 0) { unknownSize = false; } + * @param end - if end === false then length is unknown + */ +function encodeTag(tagId, tagData, unknownSize = false) { return concat([ tagId, - unknownSize ? - new buffer_1.Buffer('01ffffffffffffff', 'hex') : - (0, exports.writeVint)(tagData.length), + unknownSize + ? Buffer.from("01ffffffffffffff", "hex") + : (0, exports.writeVint)(tagData.length), tagData ]); } @@ -808,12 +964,12 @@ exports.encodeTag = encodeTag; * @return - SimpleBlock to WebP Filter */ function WebPFrameFilter(elms) { - return WebPBlockFilter(elms).reduce(function (lst, elm) { - var o = (0, exports.ebmlBlock)(elm.data); - return o.frames.reduce(function (lst, frame) { + return WebPBlockFilter(elms).reduce((lst, elm) => { + const o = (0, exports.ebmlBlock)(elm.data); + return o.frames.reduce((lst, frame) => { // https://developers.Blob.com/speed/webp/docs/riff_container - var webpBuf = VP8BitStreamToRiffWebPBuffer(frame); - var webp = new Blob([webpBuf], { type: "image/webp" }); + const webpBuf = VP8BitStreamToRiffWebPBuffer(frame); + const webp = new Blob([webpBuf], { type: "image/webp" }); return lst.concat(webp); }, lst); }, []); @@ -823,17 +979,17 @@ exports.WebPFrameFilter = WebPFrameFilter; * WebP ファイルにできる SimpleBlock の パスフィルタ */ function WebPBlockFilter(elms) { - return elms.reduce(function (lst, elm) { + return elms.reduce((lst, elm) => { if (elm.type !== "b") { return lst; } if (elm.name !== "SimpleBlock") { return lst; } - var o = (0, exports.ebmlBlock)(elm.data); - var hasWebP = o.frames.some(function (frame) { + const o = (0, exports.ebmlBlock)(elm.data); + const hasWebP = o.frames.some((frame) => { // https://tools.ietf.org/html/rfc6386#section-19.1 - var startcode = frame.slice(3, 6).toString("hex"); + const startcode = frame.subarray(3, 6).toString("hex"); return startcode === "9d012a"; }); if (!hasWebP) { @@ -848,11 +1004,8 @@ exports.WebPBlockFilter = WebPBlockFilter; * @return - WebP ファイルの ArrayBuffer */ function VP8BitStreamToRiffWebPBuffer(frame) { - var VP8Chunk = createRIFFChunk("VP8 ", frame); - var WebPChunk = concat([ - new buffer_1.Buffer("WEBP", "ascii"), - VP8Chunk - ]); + const VP8Chunk = createRIFFChunk("VP8 ", frame); + const WebPChunk = concat([Buffer.from("WEBP", "ascii"), VP8Chunk]); return createRIFFChunk("RIFF", WebPChunk); } exports.VP8BitStreamToRiffWebPBuffer = VP8BitStreamToRiffWebPBuffer; @@ -860,13 +1013,14 @@ exports.VP8BitStreamToRiffWebPBuffer = VP8BitStreamToRiffWebPBuffer; * RIFF データチャンクを作る */ function createRIFFChunk(FourCC, chunk) { - var chunkSize = new buffer_1.Buffer(4); + const chunkSize = Buffer.alloc(4); chunkSize.writeUInt32LE(chunk.byteLength, 0); return concat([ - new buffer_1.Buffer(FourCC.substr(0, 4), "ascii"), + Buffer.from(FourCC.substring(0, 4), "ascii"), chunkSize, chunk, - new buffer_1.Buffer(chunk.byteLength % 2 === 0 ? 0 : 1) // padding + // padding + Buffer.alloc(chunk.byteLength % 2 === 0 ? 0 : 1) ]); } exports.createRIFFChunk = createRIFFChunk; @@ -976,116 +1130,165 @@ exports.createRIFFChunk = createRIFFChunk; * @param cuesOffset - extra space to leave before cue points * @param cuesPosition - location for cue points (if zero, put after tracks metadata) */ -function makeMetadataSeekable(originalMetadata, duration, cuesInfo, cuesOffset, cuesPosition) { - if (cuesOffset === void 0) { cuesOffset = 0; } - if (cuesPosition === void 0) { cuesPosition = 0; } +function makeMetadataSeekable(originalMetadata, duration, cuesInfo, cuesOffset = 0, cuesPosition = 0) { // extract the header, we can reuse this as-is - var header = extractElement("EBML", originalMetadata); - var headerSize = encodedSizeOfEbml(header); + const header = extractElement("EBML", originalMetadata); + const headerSize = encodedSizeOfEbml(header); //console.error("Header size: " + headerSize); //printElementIds(header); // After the header comes the Segment open tag, which in this implementation is always 12 bytes (4 byte id, 8 byte 'unknown length') // After that the segment content starts. All SeekPositions and CueClusterPosition must be relative to segmentContentStartPos - var segmentContentStartPos = headerSize + 12; - //console.error("segmentContentStartPos: " + segmentContentStartPos); + const segmentContentStartPos = headerSize + 12; + //console.error("segmentContentStartPos: " + segmentContentStartPos); // find the original metadata size, and adjust it for header size and Segment start element // so we can keep all positions relative to segmentContentStartPos - var originalMetadataSize = originalMetadata[originalMetadata.length - 1].dataEnd - segmentContentStartPos; + const originalMetadataSize = originalMetadata[originalMetadata.length - 1].dataEnd - + segmentContentStartPos; //console.error("Original Metadata size: " + originalMetadataSize); //printElementIds(originalMetadata); // extract the segment info, remove the potentially existing Duration element, and add our own one. - var info = extractElement("Info", originalMetadata); + const info = extractElement("Info", originalMetadata); removeElement("Duration", info); - info.splice(1, 0, { name: "Duration", type: "f", data: createFloatBuffer(duration, 8) }); - var infoSize = encodedSizeOfEbml(info); + info.splice(1, 0, { + name: "Duration", + type: "f", + data: createFloatBuffer(duration, 8) + }); + const infoSize = encodedSizeOfEbml(info); //console.error("Info size: " + infoSize); - //printElementIds(info); + //printElementIds(info); // extract the track info, we can re-use this as is - var tracks = extractElement("Tracks", originalMetadata); - var tracksSize = encodedSizeOfEbml(tracks); + const tracks = extractElement("Tracks", originalMetadata); + const tracksSize = encodedSizeOfEbml(tracks); //console.error("Tracks size: " + tracksSize); - //printElementIds(tracks); - var seekHeadSize = 47; // Initial best guess, but could be slightly larger if the Cues element is huge. - var seekHead = []; - var cuesSize = 5 + cuesInfo.length * 15; // very rough initial approximation, - // depends a lot on file size and number of CuePoints - var cues = []; - var lastSizeDifference = -1; // + //printElementIds(tracks); + // Initial best guess, but could be slightly larger if the Cues element is huge. + let seekHeadSize = 47; + let seekHead = []; + // very rough initial approximation, + let cuesSize = 5 + cuesInfo.length * 15; + // depends a lot on file size and number of CuePoints + let cues = []; + let lastSizeDifference = -1; // The size of SeekHead and Cues elements depends on how many bytes the offsets values can be encoded in. // The actual offsets in CueClusterPosition depend on the final size of the SeekHead and Cues elements // We need to iteratively converge to a stable solution. - var maxIterations = 10; - var _loop_1 = function (i) { + const maxIterations = 10; + for (let i = 0; i < maxIterations; i++) { // SeekHead starts at 0 - var infoStart = seekHeadSize; // Info comes directly after SeekHead - var tracksStart = infoStart + infoSize; // Tracks comes directly after Info - var cuesStart = void 0; - var newMetadataSize = void 0; + // Info comes directly after SeekHead + const infoStart = seekHeadSize; + // Tracks comes directly after Info + const tracksStart = infoStart + infoSize; + let cuesStart = 0; + let newMetadataSize = 0; if (cuesPosition) { - cuesStart = cuesPosition - segmentContentStartPos; // Cues position is before segment open tag - newMetadataSize = tracksStart + tracksSize; // Cues outside initial metadata + // Cues position is before segment open tag + cuesStart = cuesPosition - segmentContentStartPos; + // Cues outside initial metadata + newMetadataSize = tracksStart + tracksSize; } else { - cuesStart = tracksStart + tracksSize; // Cues starts directly after - newMetadataSize = cuesStart + cuesSize; // total size of metadata + // Cues starts directly after + cuesStart = tracksStart + tracksSize; + // total size of metadata + newMetadataSize = cuesStart + cuesSize; } // This is the offset all CueClusterPositions should be adjusted by due to the metadata size changing. - var sizeDifference = newMetadataSize - originalMetadataSize; + const sizeDifference = newMetadataSize - originalMetadataSize; // console.error(`infoStart: ${infoStart}, infoSize: ${infoSize}`); // console.error(`tracksStart: ${tracksStart}, tracksSize: ${tracksSize}`); // console.error(`cuesStart: ${cuesStart}, cuesSize: ${cuesSize}`); // tslint:disable-next-line:max-line-length - // console.error(`originalMetadataSize: ${originalMetadataSize}, ` + `newMetadataSize: ${newMetadataSize}, sizeDifference: ${sizeDifference}`); + // console.error(`originalMetadataSize: ${originalMetadataSize}, ` + `newMetadataSize: ${newMetadataSize}, sizeDifference: ${sizeDifference}`); // create the SeekHead element seekHead = []; seekHead.push({ name: "SeekHead", type: "m", isEnd: false }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); - seekHead.push({ name: "SeekID", type: "b", data: new buffer_1.Buffer([0x15, 0x49, 0xA9, 0x66]) }); // Info - seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(infoStart) }); + // Info + seekHead.push({ + name: "SeekID", + type: "b", + data: Buffer.from([0x15, 0x49, 0xa9, 0x66]) + }); + seekHead.push({ + name: "SeekPosition", + type: "u", + data: createUIntBuffer(infoStart) + }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); - seekHead.push({ name: "SeekID", type: "b", data: new buffer_1.Buffer([0x16, 0x54, 0xAE, 0x6B]) }); // Tracks - seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(tracksStart) }); + // Tracks + seekHead.push({ + name: "SeekID", + type: "b", + data: Buffer.from([0x16, 0x54, 0xae, 0x6b]) + }); + seekHead.push({ + name: "SeekPosition", + type: "u", + data: createUIntBuffer(tracksStart) + }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "Seek", type: "m", isEnd: false }); - seekHead.push({ name: "SeekID", type: "b", data: new buffer_1.Buffer([0x1C, 0x53, 0xBB, 0x6B]) }); // Cues - seekHead.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(cuesStart) }); + // Cues + seekHead.push({ + name: "SeekID", + type: "b", + data: Buffer.from([0x1c, 0x53, 0xbb, 0x6b]) + }); + seekHead.push({ + name: "SeekPosition", + type: "u", + data: createUIntBuffer(cuesStart) + }); seekHead.push({ name: "Seek", type: "m", isEnd: true }); seekHead.push({ name: "SeekHead", type: "m", isEnd: true }); seekHeadSize = encodedSizeOfEbml(seekHead); //console.error("SeekHead size: " + seekHeadSize); - //printElementIds(seekHead); + //printElementIds(seekHead); // create the Cues element cues = []; cues.push({ name: "Cues", type: "m", isEnd: false }); - cuesInfo.forEach(function (_a) { - var CueTrack = _a.CueTrack, CueClusterPosition = _a.CueClusterPosition, CueTime = _a.CueTime; + for (const { CueTrack, CueClusterPosition, CueTime } of cuesInfo) { cues.push({ name: "CuePoint", type: "m", isEnd: false }); - cues.push({ name: "CueTime", type: "u", data: createUIntBuffer(CueTime) }); + cues.push({ + name: "CueTime", + type: "u", + data: createUIntBuffer(CueTime) + }); cues.push({ name: "CueTrackPositions", type: "m", isEnd: false }); - cues.push({ name: "CueTrack", type: "u", data: createUIntBuffer(CueTrack) }); + cues.push({ + name: "CueTrack", + type: "u", + data: createUIntBuffer(CueTrack) + }); // tslint:disable-next-line:max-line-length //console.error(`CueClusterPosition: ${CueClusterPosition}, Corrected to: ${CueClusterPosition - segmentContentStartPos} , offset by ${sizeDifference} to become ${(CueClusterPosition - segmentContentStartPos) + sizeDifference - segmentContentStartPos}`); // EBMLReader returns CueClusterPosition with absolute byte offsets. // The Cues section expects them as offsets from the first level 1 element of the Segment, so we need to adjust it. - CueClusterPosition -= segmentContentStartPos; + let _CueClusterPosition = CueClusterPosition - segmentContentStartPos; if (cuesOffset) { // Leave space before cues. - CueClusterPosition += cuesOffset; + _CueClusterPosition += cuesOffset; } else { // We also need to adjust to take into account the change in metadata size from when EBMLReader read the original metadata. - CueClusterPosition += sizeDifference; + _CueClusterPosition += sizeDifference; } - cues.push({ name: "CueClusterPosition", type: "u", data: createUIntBuffer(CueClusterPosition) }); + cues.push({ + name: "CueClusterPosition", + type: "u", + data: createUIntBuffer(_CueClusterPosition) + }); cues.push({ name: "CueTrackPositions", type: "m", isEnd: true }); cues.push({ name: "CuePoint", type: "m", isEnd: true }); - }); + } cues.push({ name: "Cues", type: "m", isEnd: true }); cuesSize = encodedSizeOfEbml(cues); - //console.error("Cues size: " + cuesSize); + //console.error("Cues size: " + cuesSize); //console.error("Cue count: " + cuesInfo.length); - //printElementIds(cues); + //printElementIds(cues); // If the new MetadataSize is not the same as the previous iteration, we need to run once more. if (lastSizeDifference !== sizeDifference) { lastSizeDifference = sizeDifference; @@ -1094,15 +1297,12 @@ function makeMetadataSeekable(originalMetadata, duration, cuesInfo, cuesOffset, } } else { - return "break"; - } - }; - for (var i = 0; i < maxIterations; i++) { - var state_1 = _loop_1(i); - if (state_1 === "break") + // We're done! Construct the new metadata from all individual components and return. + //console.error(`Final size: ${newMetadataSize}, difference: ${sizeDifference}`); break; + } } - var finalMetadata = [].concat.apply([], [ + const finalMetadata = [].concat.apply([], [ header, { name: "Segment", type: "m", isEnd: false, unknownSize: true }, seekHead, @@ -1110,7 +1310,7 @@ function makeMetadataSeekable(originalMetadata, duration, cuesInfo, cuesOffset, tracks, cuesPosition ? [] : cues ]); - var result = new EBMLEncoder_1.default().encode(finalMetadata); + const result = new EBMLEncoder_1.default().encode(finalMetadata); //printElementIds(finalMetadata); //console.error(`Final metadata buffer size: ${result.byteLength}`); //console.error(`Final metadata buffer size without header and segment: ${result.byteLength-segmentContentStartPos}`); @@ -1139,10 +1339,10 @@ export function printElementIds(metadata: EBML.EBMLElementBuffer[]) { * @param metadata - array of EBML elements to search */ function removeElement(idName, metadata) { - var result = []; - var start = -1; - for (var i = 0; i < metadata.length; i++) { - var element = metadata[i]; + // const result: EBML.EBMLElementBuffer[] = []; + let start = -1; + for (let i = 0; i < metadata.length; i++) { + const element = metadata[i]; if (element.name === idName) { // if it's a Master element, extract the start and end element, and everything in between if (element.type === "m") { @@ -1151,8 +1351,8 @@ function removeElement(idName, metadata) { } else { // we've reached the end, extract the whole thing - if (start == -1) { - throw new Error("Detected ".concat(idName, " closing element before finding the start")); + if (start === -1) { + throw new Error(`Detected ${idName} closing element before finding the start`); } metadata.splice(start, i - start + 1); return; @@ -1174,10 +1374,10 @@ exports.removeElement = removeElement; * @param metadata - array of EBML elements to search */ function extractElement(idName, metadata) { - var result = []; - var start = -1; - for (var i = 0; i < metadata.length; i++) { - var element = metadata[i]; + let result = []; + let start = -1; + for (let i = 0; i < metadata.length; i++) { + const element = metadata[i]; if (element.name === idName) { // if it's a Master element, extract the start and end element, and everything in between if (element.type === "m") { @@ -1186,8 +1386,8 @@ function extractElement(idName, metadata) { } else { // we've reached the end, extract the whole thing - if (start == -1) { - throw new Error("Detected ".concat(idName, " closing element before finding the start")); + if (start === -1) { + throw new Error(`Detected ${idName} closing element before finding the start`); } result = metadata.slice(start, i + 1); break; @@ -1217,15 +1417,16 @@ function putRefinedMetaData(metadata, info) { console.warn("putRefinedMetaData: info.cueInfos property is deprecated. please use info.cues"); info.cues = info.cueInfos; } - var ebml = []; - var payload = []; - for (var i_1 = 0; i_1 < metadata.length; i_1++) { - var elm = metadata[i_1]; + let ebml = []; + let payload = []; + for (let i = 0; i < metadata.length; i++) { + const elm = metadata[i]; if (elm.type === "m" && elm.name === "Segment") { - ebml = metadata.slice(0, i_1); - payload = metadata.slice(i_1); + ebml = metadata.slice(0, i); + payload = metadata.slice(i); if (elm.unknownSize) { - payload.shift(); // remove segment tag + // remove segment tag + payload.shift(); break; } throw new Error("this metadata is not streaming webm file"); @@ -1246,61 +1447,72 @@ function putRefinedMetaData(metadata, info) { if (!(payload[payload.length - 1].dataEnd > 0)) { throw new Error("metadata dataEnd has wrong number"); } - var originalPayloadOffsetEnd = payload[payload.length - 1].dataEnd; // = first cluster ptr - var ebmlSize = ebml[ebml.length - 1].dataEnd; // = first segment ptr - var refinedEBMLSize = new EBMLEncoder_1.default().encode(ebml).byteLength; - var offsetDiff = refinedEBMLSize - ebmlSize; - var payloadSize = originalPayloadOffsetEnd - payload[0].tagStart; - var segmentSize = payload[0].tagStart - ebmlSize; - var segmentOffset = payload[0].tagStart; - var segmentTagBuf = new buffer_1.Buffer([0x18, 0x53, 0x80, 0x67]); // Segment + // first cluster ptr + const originalPayloadOffsetEnd = payload[payload.length - 1].dataEnd; + // first segment ptr + const ebmlSize = ebml[ebml.length - 1].dataEnd; + const refinedEBMLSize = new EBMLEncoder_1.default().encode(ebml).byteLength; + const offsetDiff = refinedEBMLSize - ebmlSize; + const payloadSize = originalPayloadOffsetEnd - payload[0].tagStart; + // const segmentSize = payload[0].tagStart - ebmlSize; + // const segmentOffset = payload[0].tagStart; + // Segment + const segmentTagBuf = Buffer.from([0x18, 0x53, 0x80, 0x67]); // Segmentの最後の位置は無数の Cluster 依存なので。 writeVint(newPayloadSize).byteLength ではなく、 infinity. - var segmentSizeBuf = new buffer_1.Buffer('01ffffffffffffff', 'hex'); - var _segmentSize = segmentTagBuf.byteLength + segmentSizeBuf.byteLength; // == segmentSize - var newPayloadSize = payloadSize; + const segmentSizeBuf = Buffer.from("01ffffffffffffff", "hex"); + // _segmentSize === segmentSize + const _segmentSize = segmentTagBuf.byteLength + segmentSizeBuf.byteLength; + let newPayloadSize = payloadSize; // We need the size to be stable between two refinements in order for our offsets to be correct // Bound the number of possible refinements so we can't go infinate if something goes wrong - var i; - for (i = 1; i < 20; i++) { - var newPayloadOffsetEnd = ebmlSize + _segmentSize + newPayloadSize; - var offsetEndDiff = newPayloadOffsetEnd - originalPayloadOffsetEnd; - var sizeDiff = offsetDiff + offsetEndDiff; - var refined = refineMetadata(payload, sizeDiff, info); - var newNewRefinedSize = new EBMLEncoder_1.default().encode(refined).byteLength; // 一旦 seekhead を作って自身のサイズを調べる + const count = 20; + for (let i = 1; i < count; i++) { + const newPayloadOffsetEnd = ebmlSize + _segmentSize + newPayloadSize; + const offsetEndDiff = newPayloadOffsetEnd - originalPayloadOffsetEnd; + const sizeDiff = offsetDiff + offsetEndDiff; + const refined = refineMetadata(payload, sizeDiff, info); + // 一旦 seekhead を作って自身のサイズを調べる + const newNewRefinedSize = new EBMLEncoder_1.default().encode(refined).byteLength; if (newNewRefinedSize === newPayloadSize) { // Size is stable return new EBMLEncoder_1.default().encode([].concat(ebml, [{ type: "m", name: "Segment", isEnd: false, unknownSize: true }], refined)); } newPayloadSize = newNewRefinedSize; } - throw new Error("unable to refine metadata, stable size could not be found in " + i + " iterations!"); + throw new Error("unable to refine metadata, stable size could not be found in " + + count + + " iterations!"); } exports.putRefinedMetaData = putRefinedMetaData; // Given a list of EBMLElementBuffers, returns their encoded size in bytes function encodedSizeOfEbml(refinedMetaData) { - var encorder = new EBMLEncoder_1.default(); - return refinedMetaData.reduce(function (lst, elm) { return lst.concat(encorder.encode([elm])); }, []).reduce(function (o, buf) { return o + buf.byteLength; }, 0); + const encorder = new EBMLEncoder_1.default(); + return refinedMetaData + .reduce((lst, elm) => lst.concat(encorder.encode([elm])), []) + .reduce((o, buf) => o + buf.byteLength, 0); } function refineMetadata(mesetadata, sizeDiff, info) { - var duration = info.duration, clusterPtrs = info.clusterPtrs, cues = info.cues; - var _metadata = mesetadata.slice(0); + const { duration, clusterPtrs, cues } = info; + const _metadata = mesetadata.slice(0); if (typeof duration === "number") { // duration を追加する - var overwrited_1 = false; - _metadata.forEach(function (elm) { + let overwrited = false; + for (const elm of _metadata) { if (elm.type === "f" && elm.name === "Duration") { - overwrited_1 = true; + overwrited = true; elm.data = createFloatBuffer(duration, 8); } - }); - if (!overwrited_1) { - insertTag(_metadata, "Info", [{ name: "Duration", type: "f", data: createFloatBuffer(duration, 8) }]); + } + if (!overwrited) { + insertTag(_metadata, "Info", [ + { name: "Duration", type: "f", data: createFloatBuffer(duration, 8) } + ]); } } if (Array.isArray(cues)) { insertTag(_metadata, "Cues", create_cue(cues, sizeDiff)); } - var seekhead_children = []; + let seekhead_children = []; if (Array.isArray(clusterPtrs)) { console.warn("append cluster pointers to seekhead is deprecated. please use cues"); seekhead_children = create_seek_from_clusters(clusterPtrs, sizeDiff); @@ -1317,63 +1529,103 @@ function refineMetadata(mesetadata, sizeDiff, info) { insertTag(_metadata, "SeekHead", seekhead_children, true); return _metadata; } -function create_seekhead(metadata, sizeDiff) { - var seeks = []; - ["Info", "Tracks", "Cues"].forEach(function (tagName) { - var tagStarts = metadata.filter(function (elm) { return elm.type === "m" && elm.name === tagName && elm.isEnd === false; }).map(function (elm) { return elm["tagStart"]; }); - var tagStart = tagStarts[0]; - if (typeof tagStart !== "number") { - return; - } - seeks.push({ name: "Seek", type: "m", isEnd: false }); - switch (tagName) { - case "Info": - seeks.push({ name: "SeekID", type: "b", data: new buffer_1.Buffer([0x15, 0x49, 0xA9, 0x66]) }); - break; - case "Tracks": - seeks.push({ name: "SeekID", type: "b", data: new buffer_1.Buffer([0x16, 0x54, 0xAE, 0x6B]) }); - break; - case "Cues": - seeks.push({ name: "SeekID", type: "b", data: new buffer_1.Buffer([0x1C, 0x53, 0xBB, 0x6B]) }); - break; - } - seeks.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(tagStart + sizeDiff) }); - seeks.push({ name: "Seek", type: "m", isEnd: true }); +/* +function create_seekhead( + metadata: (EBML.EBMLElementDetail | EBML.EBMLElementBuffer)[], + sizeDiff: number +): EBML.EBMLElementBuffer[] { + const seeks: EBML.EBMLElementBuffer[] = []; + ["Info", "Tracks", "Cues"].forEach((tagName) => { + const tagStarts = metadata + .filter( + (elm) => elm.type === "m" && elm.name === tagName && elm.isEnd === false + ) + .map((elm) => elm["tagStart"]); + const tagStart = tagStarts[0]; + if (typeof tagStart !== "number") { + return; + } + seeks.push({ name: "Seek", type: "m", isEnd: false }); + switch (tagName) { + case "Info": + seeks.push({ + name: "SeekID", + type: "b", + data: Buffer.from([0x15, 0x49, 0xa9, 0x66]) + }); + break; + case "Tracks": + seeks.push({ + name: "SeekID", + type: "b", + data: Buffer.from([0x16, 0x54, 0xae, 0x6b]) + }); + break; + case "Cues": + seeks.push({ + name: "SeekID", + type: "b", + data: Buffer.from([0x1c, 0x53, 0xbb, 0x6b]) + }); + break; + } + seeks.push({ + name: "SeekPosition", + type: "u", + data: createUIntBuffer(tagStart + sizeDiff) }); - return seeks; + seeks.push({ name: "Seek", type: "m", isEnd: true }); + }); + return seeks; } +*/ function create_seek_from_clusters(clusterPtrs, sizeDiff) { - var seeks = []; - clusterPtrs.forEach(function (start) { + const seeks = []; + for (const start of clusterPtrs) { seeks.push({ name: "Seek", type: "m", isEnd: false }); // [0x1F, 0x43, 0xB6, 0x75] で Cluster 意 - seeks.push({ name: "SeekID", type: "b", data: new buffer_1.Buffer([0x1F, 0x43, 0xB6, 0x75]) }); - seeks.push({ name: "SeekPosition", type: "u", data: createUIntBuffer(start + sizeDiff) }); + seeks.push({ + name: "SeekID", + type: "b", + data: Buffer.from([0x1f, 0x43, 0xb6, 0x75]) + }); + seeks.push({ + name: "SeekPosition", + type: "u", + data: createUIntBuffer(start + sizeDiff) + }); seeks.push({ name: "Seek", type: "m", isEnd: true }); - }); + } return seeks; } function create_cue(cueInfos, sizeDiff) { - var cues = []; - cueInfos.forEach(function (_a) { - var CueTrack = _a.CueTrack, CueClusterPosition = _a.CueClusterPosition, CueTime = _a.CueTime; + const cues = []; + for (const { CueTrack, CueClusterPosition, CueTime } of cueInfos) { cues.push({ name: "CuePoint", type: "m", isEnd: false }); cues.push({ name: "CueTime", type: "u", data: createUIntBuffer(CueTime) }); cues.push({ name: "CueTrackPositions", type: "m", isEnd: false }); - cues.push({ name: "CueTrack", type: "u", data: createUIntBuffer(CueTrack) }); // video track - cues.push({ name: "CueClusterPosition", type: "u", data: createUIntBuffer(CueClusterPosition + sizeDiff) }); + // video track + cues.push({ + name: "CueTrack", + type: "u", + data: createUIntBuffer(CueTrack) + }); + cues.push({ + name: "CueClusterPosition", + type: "u", + data: createUIntBuffer(CueClusterPosition + sizeDiff) + }); cues.push({ name: "CueTrackPositions", type: "m", isEnd: true }); cues.push({ name: "CuePoint", type: "m", isEnd: true }); - }); + } return cues; } -function insertTag(_metadata, tagName, children, insertHead) { - if (insertHead === void 0) { insertHead = false; } +function insertTag(_metadata, tagName, children, insertHead = false) { // find the tagname from _metadata - var idx = -1; - for (var i = 0; i < _metadata.length; i++) { - var elm = _metadata[i]; - if (elm.type === "m" && elm.name === tagName && elm.isEnd === false) { + let idx = -1; + for (let i = 0; i < _metadata.length; i++) { + const elm = _metadata[i]; + if (elm.type === "m" && elm.name === tagName && !elm.isEnd) { idx = i; break; } @@ -1383,22 +1635,28 @@ function insertTag(_metadata, tagName, children, insertHead) { Array.prototype.splice.apply(_metadata, [idx + 1, 0].concat(children)); } else if (insertHead) { - [].concat([{ name: tagName, type: "m", isEnd: false }], children, [{ name: tagName, type: "m", isEnd: true }]).reverse().forEach(function (elm) { _metadata.unshift(elm); }); + const elms = [].concat([{ name: tagName, type: "m", isEnd: false }], children, [{ name: tagName, type: "m", isEnd: true }]); + elms.reverse(); + for (const elm of elms) { + _metadata.unshift(elm); + } } else { // metadata 末尾に を追加 // insert _metadata.push({ name: tagName, type: "m", isEnd: false }); - children.forEach(function (elm) { _metadata.push(elm); }); + for (const elm of children) { + _metadata.push(elm); + } _metadata.push({ name: tagName, type: "m", isEnd: true }); } } function concat(list) { - return buffer_1.Buffer.concat(list); + return Buffer.concat(list); } exports.concat = concat; function encodeValueToBuffer(elm) { - var data = new buffer_1.Buffer(0); + let data = Buffer.alloc(0); if (elm.type === "m") { return elm; } @@ -1413,10 +1671,10 @@ function encodeValueToBuffer(elm) { data = createFloatBuffer(elm.value); break; case "s": - data = new buffer_1.Buffer(elm.value, 'ascii'); + data = Buffer.from(elm.value, "ascii"); break; case "8": - data = new buffer_1.Buffer(elm.value, 'utf8'); + data = Buffer.from(elm.value, "utf8"); break; case "b": data = elm.value; @@ -1425,19 +1683,21 @@ function encodeValueToBuffer(elm) { data = new int64_buffer_1.Int64BE(elm.value.getTime().toString()).toBuffer(); break; } - return Object.assign({}, elm, { data: data }); + return Object.assign({}, elm, { data }); } exports.encodeValueToBuffer = encodeValueToBuffer; function createUIntBuffer(value) { // Big-endian, any size from 1 to 8 // but js number is float64, so max 6 bit octets - var bytes = 1; - for (; value >= Math.pow(2, 8 * bytes); bytes++) { } + let bytes = 1; + for (; value >= Math.pow(2, 8 * bytes); bytes++) { + void 0; + } if (bytes >= 7) { console.warn("7bit or more bigger uint not supported."); return new int64_buffer_1.Uint64BE(value).toBuffer(); } - var data = new buffer_1.Buffer(bytes); + const data = Buffer.alloc(bytes); data.writeUIntBE(value, 0, bytes); return data; } @@ -1445,30 +1705,30 @@ exports.createUIntBuffer = createUIntBuffer; function createIntBuffer(value) { // Big-endian, any size from 1 to 8 octets // but js number is float64, so max 6 bit - var bytes = 1; + let bytes = 1; + /* eslint no-empty: off */ for (; value >= Math.pow(2, 8 * bytes); bytes++) { } if (bytes >= 7) { console.warn("7bit or more bigger uint not supported."); return new int64_buffer_1.Int64BE(value).toBuffer(); } - var data = new buffer_1.Buffer(bytes); + const data = Buffer.alloc(bytes); data.writeIntBE(value, 0, bytes); return data; } exports.createIntBuffer = createIntBuffer; -function createFloatBuffer(value, bytes) { - if (bytes === void 0) { bytes = 8; } +function createFloatBuffer(value, bytes = 8) { // Big-endian, defined for 4 and 8 octets (32, 64 bits) // js number is float64 so 8 bytes. if (bytes === 8) { // 64bit - var data = new buffer_1.Buffer(8); + const data = Buffer.alloc(8); data.writeDoubleBE(value, 0); return data; } else if (bytes === 4) { // 32bit - var data = new buffer_1.Buffer(4); + const data = Buffer.alloc(4); data.writeFloatBE(value, 0); return data; } @@ -1481,11 +1741,13 @@ function convertEBMLDateToJSDate(int64str) { if (int64str instanceof Date) { return int64str; } - return new Date(new Date("2001-01-01T00:00:00.000Z").getTime() + (Number(int64str) / 1000 / 1000)); + return new Date(new Date("2001-01-01T00:00:00.000Z").getTime() + + Number(int64str) / 1000 / 1000); } exports.convertEBMLDateToJSDate = convertEBMLDateToJSDate; -},{"./EBMLEncoder":3,"buffer":8,"ebml-block":11,"ebml/lib/ebml.js":14,"int64-buffer":17}],7:[function(require,module,exports){ +}).call(this)}).call(this,require("buffer").Buffer) +},{"./EBMLEncoder":3,"buffer":9,"ebml-block":10,"ebml/lib/ebml.js":13,"int64-buffer":19}],7:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -1639,6 +1901,79 @@ function fromByteArray (uint8) { },{}],8:[function(require,module,exports){ (function (Buffer){(function (){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { value: true }); +let converter; +/** + * Convert a little-endian buffer into a BigInt. + * @param buf The little-endian buffer to convert + * @returns A BigInt with the little-endian representation of buf. + */ +function toBigIntLE(buf) { + { + const reversed = Buffer.from(buf); + reversed.reverse(); + const hex = reversed.toString('hex'); + if (hex.length === 0) { + return BigInt(0); + } + return BigInt(`0x${hex}`); + } + return converter.toBigInt(buf, false); +} +exports.toBigIntLE = toBigIntLE; +/** + * Convert a big-endian buffer into a BigInt + * @param buf The big-endian buffer to convert. + * @returns A BigInt with the big-endian representation of buf. + */ +function toBigIntBE(buf) { + { + const hex = buf.toString('hex'); + if (hex.length === 0) { + return BigInt(0); + } + return BigInt(`0x${hex}`); + } + return converter.toBigInt(buf, true); +} +exports.toBigIntBE = toBigIntBE; +/** + * Convert a BigInt to a little-endian buffer. + * @param num The BigInt to convert. + * @param width The number of bytes that the resulting buffer should be. + * @returns A little-endian buffer representation of num. + */ +function toBufferLE(num, width) { + { + const hex = num.toString(16); + const buffer = Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex'); + buffer.reverse(); + return buffer; + } + // Allocation is done here, since it is slower using napi in C + return converter.fromBigInt(num, Buffer.allocUnsafe(width), false); +} +exports.toBufferLE = toBufferLE; +/** + * Convert a BigInt to a big-endian buffer. + * @param num The BigInt to convert. + * @param width The number of bytes that the resulting buffer should be. + * @returns A big-endian buffer representation of num. + */ +function toBufferBE(num, width) { + { + const hex = num.toString(16); + return Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex'); + } + return converter.fromBigInt(num, Buffer.allocUnsafe(width), true); +} +exports.toBufferBE = toBufferBE; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"buffer":9}],9:[function(require,module,exports){ +(function (Buffer){(function (){ /*! * The buffer module from node.js, for the browser. * @@ -3418,2086 +3753,1779 @@ function numberIsNaN (obj) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":7,"buffer":8,"ieee754":16}],9:[function(require,module,exports){ -(function (process){(function (){ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +},{"base64-js":7,"buffer":9,"ieee754":18}],10:[function(require,module,exports){ +var BufferReader = require('./lib/buffer-reader') -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); +var XIPH_LACING = 1 +var EBML_LACING = 3 +var FIXED_SIZE_LACING = 2 -/** - * Colors. - */ +module.exports = function (buffer) { + var block = {} + var reader = new BufferReader(buffer) -exports.colors = [ - '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', - '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', - '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', - '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', - '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', - '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', - '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', - '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', - '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', - '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', - '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' -]; + block.trackNumber = reader.nextUIntV() + block.timecode = reader.nextInt16BE() -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + var flags = reader.nextUInt8() -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } + block.invisible = !!(flags & 0x8) - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + // only valid for SimpleBlock + block.keyframe = !!(flags & 0x80) + block.discardable = !!(flags & 0x1) - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + var lacing = (flags & 0x6) >> 1 -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + block.frames = readLacedData(reader, lacing) -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; + return block +} +function readLacedData (reader, lacing) { + if (!lacing) return [reader.nextBuffer()] -/** - * Colorize log arguments if enabled. - * - * @api public - */ + var i, frameSize + var frames = [] + var framesNum = reader.nextUInt8() + 1 // number of frames -function formatArgs(args) { - var useColors = this.useColors; + if (lacing === FIXED_SIZE_LACING) { + // remaining data should be divisible by the number of frames + if (reader.length % framesNum !== 0) throw new Error('Fixed-Size Lacing Error') - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + frameSize = reader.length / framesNum + for (i = 0; i < framesNum; i++) { + frames.push(reader.nextBuffer(frameSize)) + } + return frames + } - if (!useColors) return; + var frameSizes = [] - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + if (lacing === XIPH_LACING) { + for (i = 0; i < framesNum - 1; i++) { + var val + frameSize = 0 + do { + val = reader.nextUInt8() + frameSize += val + } while (val === 0xff) + frameSizes.push(frameSize) + } + } else if (lacing === EBML_LACING) { + // first frame + frameSize = reader.nextUIntV() + frameSizes.push(frameSize) - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; + // middle frames + for (i = 1; i < framesNum - 1; i++) { + frameSize += reader.nextIntV() + frameSizes.push(frameSize) } - }); + } - args.splice(lastC, 0, c); -} + for (i = 0; i < framesNum - 1; i++) { + frames.push(reader.nextBuffer(frameSizes[i])) + } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ + // last frame (remaining buffer) + frames.push(reader.nextBuffer()) -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); + return frames } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +},{"./lib/buffer-reader":11}],11:[function(require,module,exports){ +var vint = require('./vint') -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} +function BufferReader (buffer) { + this.buffer = buffer + this.offset = 0 } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; +// a super limited subset of the node buffer API +BufferReader.prototype.nextInt16BE = function () { + var value = this.buffer.readInt16BE(this.offset) + this.offset += 2 + return value } -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ +BufferReader.prototype.nextUInt8 = function () { + var value = this.buffer.readUInt8(this.offset) + this.offset += 1 + return value +} -exports.enable(load()); +// EBML variable sized integers +BufferReader.prototype.nextUIntV = function () { + var v = vint(this.buffer, this.offset) + this.offset += v.length + return v.value +} -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +BufferReader.prototype.nextIntV = function () { + var v = vint(this.buffer, this.offset, true) + this.offset += v.length + return v.value +} -function localstorage() { - try { - return window.localStorage; - } catch (e) {} +// buffer slice +BufferReader.prototype.nextBuffer = function (length) { + var buffer = length + ? this.buffer.slice(this.offset, this.offset + length) + : this.buffer.slice(this.offset) + this.offset += length || this.length + return buffer } -}).call(this)}).call(this,require('_process')) -},{"./debug":10,"_process":20}],10:[function(require,module,exports){ +// remaining bytes to read +Object.defineProperty(BufferReader.prototype, 'length', { + get: function () { return this.buffer.length - this.offset } +}) -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); - -/** - * Active `debug` instances. - */ -exports.instances = []; - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; +module.exports = BufferReader -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ +},{"./vint":12}],12:[function(require,module,exports){ +// https://github.com/themasch/node-ebml/blob/master/lib/ebml/tools.js +module.exports = function (buffer, start, signed) { + start = start || 0 + for (var length = 1; length <= 8; length++) { + if (buffer[start] >= Math.pow(2, 8 - length)) { + break + } + } + if (length > 8) { + throw new Error('Unrepresentable length: ' + length + ' ' + + buffer.toString('hex', start, start + length)) + } + if (start + length > buffer.length) { + return null + } + var i + var value = buffer[start] & (1 << (8 - length)) - 1 + for (i = 1; i < length; i++) { + if (i === 7) { + if (value >= Math.pow(2, 53 - 8) && buffer[start + 7] > 0) { + return { + length: length, + value: -1 + } + } + } + value *= Math.pow(2, 8) + value += buffer[start + i] + } + if (signed) { + value -= Math.pow(2, length * 7 - 1) - 1 + } + return { + length: length, + value: value + } +} -exports.formatters = {}; +},{}],13:[function(require,module,exports){ +(function (global,Buffer){(function (){ +'use strict'; -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ +Object.defineProperty(exports, '__esModule', { value: true }); -function selectColor(namespace) { - var hash = 0, i; +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; } - return exports.colors[Math.abs(hash) % exports.colors.length]; + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; - var prevTime; + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - function debug() { - // disabled? - if (!debug.enabled) return; + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - var self = debug; + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } + var L = 0; - args[0] = exports.coerce(args[0]); + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + return arr +} - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); +function fromByteArray (uint8) { + if (!inited) { + init(); } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; } - exports.instances.push(debug); + parts.push(output); - return debug; + return parts.join('') } -function destroy () { - var index = exports.instances.indexOf(this); - if (index !== -1) { - exports.instances.splice(index, 1); - return true; - } else { - return false; - } -} +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ + i += d; -function enable(namespaces) { - exports.save(namespaces); + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - exports.names = []; - exports.skips = []; + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - var i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} - for (i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; } else { - exports.names.push(new RegExp('^' + namespaces + '$')); + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; } - } - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } } -} -/** - * Disable debug output. - * - * @api public - */ + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} -function disable() { - exports.enable(''); + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; } +var toString = {}.toString; + +var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + /** - * Returns true if the given mode name is enabled, false otherwise. + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) * - * @param {String} name - * @return {Boolean} - * @api public + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; -function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); } + that.length = length; } - return false; + + return that } /** - * Coerce `val`. + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. * - * @param {Mixed} val - * @return {Mixed} - * @api private + * The `Uint8Array` prototype remains unmodified. */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) } -},{"ms":19}],11:[function(require,module,exports){ -var BufferReader = require('./lib/buffer-reader') +Buffer.poolSize = 8192; // not used by this implementation -var XIPH_LACING = 1 -var EBML_LACING = 3 -var FIXED_SIZE_LACING = 2 +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; -module.exports = function (buffer) { - var block = {} - var reader = new BufferReader(buffer) +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } - block.trackNumber = reader.nextUIntV() - block.timecode = reader.nextInt16BE() + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } - var flags = reader.nextUInt8() + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } - block.invisible = !!(flags & 0x8) + return fromObject(that, value) +} - // only valid for SimpleBlock - block.keyframe = !!(flags & 0x80) - block.discardable = !!(flags & 0x1) +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; - var lacing = (flags & 0x6) >> 1 +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; +} - block.frames = readLacedData(reader, lacing) +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} - return block +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) } -function readLacedData (reader, lacing) { - if (!lacing) return [reader.nextBuffer()] - - var i, frameSize - var frames = [] - var framesNum = reader.nextUInt8() + 1 // number of frames - - if (lacing === FIXED_SIZE_LACING) { - // remaining data should be divisible by the number of frames - if (reader.length % framesNum !== 0) throw new Error('Fixed-Size Lacing Error') +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; - frameSize = reader.length / framesNum - for (i = 0; i < framesNum; i++) { - frames.push(reader.nextBuffer(frameSize)) +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; } - return frames } + return that +} - var frameSizes = [] - - if (lacing === XIPH_LACING) { - for (i = 0; i < framesNum - 1; i++) { - var val - frameSize = 0 - do { - val = reader.nextUInt8() - frameSize += val - } while (val === 0xff) - frameSizes.push(frameSize) - } - } else if (lacing === EBML_LACING) { - // first frame - frameSize = reader.nextUIntV() - frameSizes.push(frameSize) +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; - // middle frames - for (i = 1; i < framesNum - 1; i++) { - frameSize += reader.nextIntV() - frameSizes.push(frameSize) - } +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; } - for (i = 0; i < framesNum - 1; i++) { - frames.push(reader.nextBuffer(frameSizes[i])) + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') } - // last frame (remaining buffer) - frames.push(reader.nextBuffer()) + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); - return frames -} + var actual = that.write(string, encoding); -},{"./lib/buffer-reader":12}],12:[function(require,module,exports){ -var vint = require('./vint') + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } -function BufferReader (buffer) { - this.buffer = buffer - this.offset = 0 + return that } -// a super limited subset of the node buffer API -BufferReader.prototype.nextInt16BE = function () { - var value = this.buffer.readInt16BE(this.offset) - this.offset += 2 - return value +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that } -BufferReader.prototype.nextUInt8 = function () { - var value = this.buffer.readUInt8(this.offset) - this.offset += 1 - return value -} +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer -// EBML variable sized integers -BufferReader.prototype.nextUIntV = function () { - var v = vint(this.buffer, this.offset) - this.offset += v.length - return v.value -} + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } -BufferReader.prototype.nextIntV = function () { - var v = vint(this.buffer, this.offset, true) - this.offset += v.length - return v.value -} + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } -// buffer slice -BufferReader.prototype.nextBuffer = function (length) { - var buffer = length - ? this.buffer.slice(this.offset, this.offset + length) - : this.buffer.slice(this.offset) - this.offset += length || this.length - return buffer -} + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } -// remaining bytes to read -Object.defineProperty(BufferReader.prototype, 'length', { - get: function () { return this.buffer.length - this.offset } -}) + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} -module.exports = BufferReader +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); -},{"./vint":13}],13:[function(require,module,exports){ -// https://github.com/themasch/node-ebml/blob/master/lib/ebml/tools.js -module.exports = function (buffer, start, signed) { - start = start || 0 - for (var length = 1; length <= 8; length++) { - if (buffer[start] >= Math.pow(2, 8 - length)) { - break + if (that.length === 0) { + return that } + + obj.copy(that, 0, 0, len); + return that } - if (length > 8) { - throw new Error('Unrepresentable length: ' + length + ' ' + - buffer.toString('hex', start, start + length)) - } - if (start + length > buffer.length) { - return null - } - var i - var value = buffer[start] & (1 << (8 - length)) - 1 - for (i = 1; i < length; i++) { - if (i === 7) { - if (value >= Math.pow(2, 53 - 8) && buffer[start + 7] > 0) { - return { - length: length, - value: -1 - } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) } + return fromArrayLike(that, obj) } - value *= Math.pow(2, 8) - value += buffer[start + i] - } - if (signed) { - value -= Math.pow(2, length * 7 - 1) - 1 - } - return { - length: length, - value: value - } -} - -},{}],14:[function(require,module,exports){ -(function (global,Buffer){(function (){ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); -var lookup = []; -var revLookup = []; -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; -var inited = false; -function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } } - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } -function toByteArray (b64) { - if (!inited) { - init(); +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; + return length | 0 +} +Buffer.isBuffer = isBuffer; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + if (a === b) return 0 - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); + var x = a.length; + var y = b.length; - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } - var L = 0; + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false } +}; - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') } - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); + if (list.length === 0) { + return Buffer.alloc(0) } - return output.join('') -} -function fromByteArray (uint8) { - if (!inited) { - init(); + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; } + return buffer +}; - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; } - parts.push(output); + var len = string.length; + if (len === 0) return 0 - return parts.join('') + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } } +Buffer.byteLength = byteLength; -function read (buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} +function slowToString (encoding, start, end) { + var loweredCase = false; - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} -function write (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + if (end === undefined || end > this.length) { + end = this.length; + } - value = Math.abs(value); + if (end <= 0) { + return '' + } - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } + if (end <= start) { + return '' } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + if (!encoding) encoding = 'utf8'; - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - buffer[offset + i - d] |= s * 128; -} + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) -var toString = {}.toString; - -var isArray = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - -var INSPECT_MAX_BYTES = 50; + case 'ascii': + return asciiSlice(this, start, end) -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; + case 'base64': + return base64Slice(this, start, end) -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length); + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; } - that.length = length; } - - return that } -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; } -Buffer.poolSize = 8192; // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype; - return arr +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this }; -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); } + return this +}; - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; - return fromObject(that, value) -} +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 }; -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype; - Buffer.__proto__ = Uint8Array; -} +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') } -} -function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) + if (start === undefined) { + start = 0; } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) + if (end === undefined) { + end = target ? target.length : 0; } - return createBuffer(that, size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -}; - -function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; } - return that -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -}; -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -}; -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') } - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 } - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - var actual = that.write(string, encoding); + if (this === target) return 0 - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - return that -} + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } } - return that -} -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 } - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } - return that + + throw new TypeError('val must be string, number or Buffer') } -function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; - if (that.length === 0) { - return that + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; } + } - obj.copy(that, 0, 0, len); - return that + function read$$1 (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } } - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read$$1(arr, i) === read$$1(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; } - return fromArrayLike(that, obj) } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read$$1(arr, i + j) !== read$$1(val, j)) { + found = false; + break + } + } + if (found) return i } } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} - -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} -Buffer.isBuffer = isBuffer; -function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) + return -1 } -Buffer.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; - if (a === b) return 0 +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; - var x = a.length; - var y = b.length; +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; } } - if (x < y) return -1 - if (y < x) return 1 - return 0 -}; + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false + if (length > strLen / 2) { + length = strLen / 2; } -}; - -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; } + return i +} - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer -}; - -function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } -Buffer.byteLength = byteLength; -function slowToString (encoding, start, end) { - var loweredCase = false; +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} - if (end === undefined || end > this.length) { - end = this.length; - } +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} - if (end <= 0) { - return '' +Buffer.prototype.write = function write$$1 (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) } - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - if (end <= start) { - return '' + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8'; - while (true) { + var loweredCase = false; + for (;;) { switch (encoding) { case 'hex': - return hexSlice(this, start, end) + return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': - return utf8Slice(this, start, end) + return utf8Write(this, string, offset, length) case 'ascii': - return asciiSlice(this, start, end) + return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': - return latin1Slice(this, start, end) + return latin1Write(this, string, offset, length) case 'base64': - return base64Slice(this, start, end) + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': - return utf16leSlice(this, start, end) + return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); + encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true; - -function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this }; -Buffer.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) } - return this }; -Buffer.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) } - return this -}; - -Buffer.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -}; +} -Buffer.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -}; +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; -Buffer.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' -}; + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 + res.push(codePoint); + i += bytesPerSequence; } - if (start >= end) { - return 1 + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} - if (this === target) return 0 +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); } + return ret +} - if (x < y) return -1 - if (y < x) return 1 - return 0 -}; +function hexSlice (buf, start, end) { + var len = buf.length; -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } + return res +} - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; } - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding); + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; } - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } - throw new TypeError('val must be string, number or Buffer') + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; } - function read$$1 (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); } - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read$$1(arr, i) === read$$1(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read$$1(arr, i + j) !== read$$1(val, j)) { - found = false; - break - } - } - if (found) return i - } + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; } - return -1 -} + return val +}; -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] }; -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) }; -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] }; -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i -} +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} + if (val >= mul) val -= Math.pow(2, 8 * byteLength); -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} + return val +}; -Buffer.prototype.write = function write$$1 (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; } + mul *= 0x80; - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } + return val +}; - if (!encoding) encoding = 'utf8'; +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; - case 'ascii': - return asciiWrite(this, string, offset, length) +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) }; -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) }; -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } -} +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray(res) +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') } -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000; - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); } - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; + var mul = 1; var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; } - return res -} -function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + return offset + byteLength +}; - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; } - return ret -} -function hexSlice (buf, start, end) { - var len = buf.length; + return offset + byteLength +}; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; } - return out } -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; + return offset + 2 +}; - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); } + return offset + 2 +}; - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; } +} - if (end < start) end = start; - - var newBuf; +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer.prototype; + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); } else { - var sliceLen = end - start; - newBuf = new Buffer(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } + objectWriteUInt32(this, value, offset, true); } - - return newBuf + return offset + 4 }; -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); } - - return val + return offset + 4 }; -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; offset = offset | 0; - byteLength = byteLength | 0; if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } + var limit = Math.pow(2, 8 * byteLength - 1); - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; + checkInt(this, value, offset, byteLength, limit - 1, -limit); } - return val -}; - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] -}; - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) -}; - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] -}; - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -}; - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -}; - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val -}; - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val -}; - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -}; - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val -}; - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val -}; - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -}; - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -}; - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) -}; - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) -}; - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) -}; - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) -}; - -function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - var mul = 1; - var i = 0; + var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } return offset + byteLength }; -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; - byteLength = byteLength | 0; if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; + var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } return offset + byteLength }; -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); @@ -5507,10 +5535,10 @@ Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert return offset + 2 }; -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); @@ -5520,32 +5548,26 @@ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert return offset + 2 }; -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); } else { objectWriteUInt32(this, value, offset, true); } return offset + 4 }; -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); @@ -5557,143 +5579,30 @@ Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert return offset + 4 }; -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} - checkInt(this, value, offset, byteLength, limit - 1, -limit); +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; - return offset + byteLength +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) }; -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; +function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength -}; - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 -}; - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 -}; - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 -}; - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 -}; - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 -}; - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -}; - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -}; - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); } write(buf, value, offset, littleEndian, 52, 8); return offset + 8 @@ -13668,58 +13577,638 @@ function (_Transform) { this.bufferAndFlush(tag.data.buffer); } - this.end(); - } - }, { - key: "buffer", - get: function get() { - return this.mBuffer; - }, - set: function set(buffer) { - this.mBuffer = buffer; - } - }, { - key: "corked", - get: function get() { - return this.mCorked; - }, - set: function set(corked) { - this.mCorked = corked; - } - }, { - key: "stack", - get: function get() { - return this.mStack; - }, - set: function set(stak) { - this.mStack = stak; - } - }], [{ - key: "getSchemaInfo", - value: function getSchemaInfo(tagName) { - var tagId = Array.from(schema.keys()).find(function (str) { - return schema.get(str).name === tagName; - }); + this.end(); + } + }, { + key: "buffer", + get: function get() { + return this.mBuffer; + }, + set: function set(buffer) { + this.mBuffer = buffer; + } + }, { + key: "corked", + get: function get() { + return this.mCorked; + }, + set: function set(corked) { + this.mCorked = corked; + } + }, { + key: "stack", + get: function get() { + return this.mStack; + }, + set: function set(stak) { + this.mStack = stak; + } + }], [{ + key: "getSchemaInfo", + value: function getSchemaInfo(tagName) { + var tagId = Array.from(schema.keys()).find(function (str) { + return schema.get(str).name === tagName; + }); + + if (tagId) { + return tagId; + } + + return null; + } + }]); + + return EbmlEncoder; +}(Transform); + +exports.tools = Tools; +exports.schema = schema; +exports.Decoder = EbmlDecoder; +exports.Encoder = EbmlEncoder; + + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"buffer":9,"debug":14}],14:[function(require,module,exports){ +(function (process){(function (){ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', + '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', + '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', + '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', + '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', + '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', + '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', + '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', + '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', + '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', + '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} + +}).call(this)}).call(this,require('_process')) +},{"./debug":15,"_process":21}],15:[function(require,module,exports){ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * Active `debug` instances. + */ +exports.instances = []; + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + var prevTime; + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + exports.instances.push(debug); + + return debug; +} + +function destroy () { + var index = exports.instances.indexOf(this); + if (index !== -1) { + exports.instances.splice(index, 1); + return true; + } else { + return false; + } +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < exports.instances.length; i++) { + var instance = exports.instances[i]; + instance.enabled = exports.enabled(instance.namespace); + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +},{"ms":16}],16:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - if (tagId) { - return tagId; - } +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} - return null; - } - }]); +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - return EbmlEncoder; -}(Transform); +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} -exports.tools = Tools; -exports.schema = schema; -exports.Decoder = EbmlDecoder; -exports.Encoder = EbmlEncoder; +/** + * Pluralization helper. + */ +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"buffer":8,"debug":9}],15:[function(require,module,exports){ +},{}],17:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -14218,7 +14707,7 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) { } } -},{}],16:[function(require,module,exports){ +},{}],18:[function(require,module,exports){ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m @@ -14305,7 +14794,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],17:[function(require,module,exports){ +},{}],19:[function(require,module,exports){ (function (Buffer){(function (){ // int64-buffer.js @@ -14615,7 +15104,7 @@ var Uint64BE, Int64BE, Uint64LE, Int64LE; }(typeof exports === 'object' && typeof exports.nodeName !== 'string' ? exports : (this || {})); }).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":8}],18:[function(require,module,exports){ +},{"buffer":9}],20:[function(require,module,exports){ module.exports = { byEbmlID: { 0x80: { @@ -18002,161 +18491,7 @@ module.exports = { } }; -},{}],19:[function(require,module,exports){ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -},{}],20:[function(require,module,exports){ +},{}],21:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -18342,31 +18677,21 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],21:[function(require,module,exports){ +},{}],22:[function(require,module,exports){ module.exports={ "name": "ts-ebml", - "version": "2.0.2", + "version": "3.0.0", "description": "ebml decoder and encoder", "scripts": { - "init": "npm run update && npm run mkdir && npm run build", - "update": "npm run reset && npm update && playwright install", - "reset": "rm -rf node_modules", - "mkdir": "mkdir -p lib dist", - "clean": "rm -rf lib/* dist/* test/*.js && mkdir -p dist", - "build": "npm run clean && tsc -p . && npm run browserify", - "start": "http-server . -s & tsc -w -p .& watchify lib/example_seekable.js -o test/example_seekable.js", - "stop": "pkill -f 'http-server|tsc -w|watchify'", - "browserify": "browserify lib/index.js --standalone EBML -o dist/EBML.js", - "watchify": "watchify lib/index.js --standalone EBML -o dist/EBML.js -v", - "build_tests": "tsc && espower lib/test.js > lib/test.tmp && mv -f lib/test.tmp lib/test.js && tsc src/run_test.ts --outDir test --target esnext --moduleresolution node && mv test/run_test.js test/run_test.mjs && browserify lib/test.js -o test/test.js", - "run_tests": "playwright test", - "test": "npm run build_tests && npm run run_tests", - "example": "tsc && browserify lib/example_seekable.js -o test/example_seekable.js", - "examples": "tsc && for file in `find lib -name 'example_*.js' -type f -printf '%f\\n'`; do browserify lib/$file -o test/$file; done", - "examples_bsd": "tsc && for file in `find lib -name 'example_*.js' -type f -print`; do browserify lib/$(basename $file) -o test/$(basename $file); done", - "check": "tsc -w --noEmit -p ./", - "lint": "tslint -c ./tslint.json --project ./tsconfig.json", - "doc": "typedoc src/index.ts src/EBMLReader.ts" + "clean": "rimraf lib/* dist/* test/*.js", + "build": "npm run clean && tsc -p . && npm run _build_standalone && npm run _build_test", + "_build_standalone": "browserify lib/index.js --standalone EBML -o dist/EBML.js && uglifyjs dist/EBML.js > dist/EBML.min.js", + "_build_test": "espower lib/test.js > lib/test.tmp && mv -f lib/test.tmp lib/test.js && browserify lib/test.js -o dist/test.js", + "test": "playwright install && playwright test", + "serve": "http-server", + "lint": "eslint src", + "fmt": "prettier --write 'src/**/*.ts'", + "doc": "typedoc src/index.ts" }, "repository": { "type": "git", @@ -18386,33 +18711,39 @@ module.exports={ }, "homepage": "https://github.com/legokichi/ts-ebml#readme", "dependencies": { - "buffer": "^6.0.3", - "commander": "^11.1.0", + "bigint-buffer": "^1.1.5", + "commander": "^12.0.0", "ebml": "^3.0.0", "ebml-block": "^1.1.2", "events": "^3.3.0", "int64-buffer": "^1.0.1", + "matroska": "^2.2.5", "matroska-schema": "^2.1.0" }, "devDependencies": { - "@playwright/test": "^1.39.0", - "@types/commander": "^2.12.0", - "@types/node": "^20.9.0", - "@types/qunit": "^2.19.8", + "@playwright/test": "^1.41.2", + "@types/empower": "^1.2.35", + "@types/node": "^20.11.19", + "@types/qunit": "^2.19.10", + "@typescript-eslint/eslint-plugin": "^7.0.1", + "@typescript-eslint/parser": "^7.0.1", "aliasify": "^2.1.0", "browserify": "^17.0.0", "empower": "^1.3.1", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.1.0", "espower-cli": "^1.1.0", "http-server": "^14.1.1", "power-assert": "^1.6.1", "power-assert-formatter": "^1.4.1", - "qunit-tap": "^1.5.1", + "prettier": "^3.2.5", "qunit": "^2.20.0", - "tslint": "^5.20.1", + "qunit-tap": "^1.5.1", + "rimraf": "^5.0.5", "typedoc": "^0.25.3", "typedoc-plugin-missing-exports": "^2.1.0", "typescript": "^5.2.2", - "watchify": "^4.0.0" + "uglify-js": "^3.17.4" }, "bin": "./lib/cli.js", "main": "./lib/index.js", diff --git a/dist/EBML.min.js b/dist/EBML.min.js new file mode 100644 index 0000000..bd91719 --- /dev/null +++ b/dist/EBML.min.js @@ -0,0 +1 @@ +(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.EBML=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i=this._buffer.length){return false}const tag=(0,tools_1.readVint)(this._buffer,this._cursor);if(tag==null){return false}const buf=this._buffer.subarray(this._cursor,this._cursor+tag.length);const tagNum=buf.reduce((o,v,i,arr)=>o+v*Math.pow(16,2*(arr.length-1-i)),0);const schema=this.getSchemaInfo(tagNum);const tagObj={EBML_ID:tagNum.toString(16),schema:schema,type:schema.type,name:schema.name,level:schema.level,tagStart:this._total,tagEnd:this._total+tag.length,sizeStart:this._total+tag.length,sizeEnd:null,dataStart:null,dataEnd:null,dataSize:null,data:null};this._tag_stack.push(tagObj);this._cursor+=tag.length;this._total+=tag.length;this._state=State.STATE_SIZE;return true}readSize(){if(this._cursor>=this._buffer.length){return false}const size=(0,tools_1.readVint)(this._buffer,this._cursor);if(size==null){return false}const tagObj=this._tag_stack[this._tag_stack.length-1];if(tagObj==null){return false}tagObj.sizeEnd=tagObj.sizeStart+size.length;tagObj.dataStart=tagObj.sizeEnd;tagObj.dataSize=size.value;if(size.value===-1){tagObj.dataEnd=-1;if(tagObj.type==="m"){tagObj.unknownSize=true}}else{tagObj.dataEnd=tagObj.sizeEnd+size.value}this._cursor+=size.length;this._total+=size.length;this._state=State.STATE_CONTENT;return true}readContent(){const tagObj=this._tag_stack[this._tag_stack.length-1];if(tagObj==null){return false}if(tagObj.type==="m"){tagObj.isEnd=false;this._result.push(tagObj);this._state=State.STATE_TAG;if(tagObj.dataSize===0){const elm=Object.assign({},tagObj,{isEnd:true});this._result.push(elm);this._tag_stack.pop()}return true}if(this._buffer.length6){tagObj.value=Number((0,bigint_buffer_1.toBigIntBE)(data))}else{tagObj.value=data.readUIntBE(0,data.length)}break}case"i":{tagObj.value=data.readIntBE(0,data.length);break}case"f":{if(tagObj.dataSize===4){tagObj.value=data.readFloatBE(0)}else if(tagObj.dataSize===8){tagObj.value=data.readDoubleBE(0)}else{console.warn(`cannot read ${tagObj.dataSize} octets float. failback to 0`);tagObj.value=0}break}case"s":{tagObj.value=data.toString("ascii");break}case"8":{tagObj.value=data.toString("utf8");break}case"b":{tagObj.value=data;break}case"d":{tagObj.value=(0,tools_1.convertEBMLDateToJSDate)(Number((0,bigint_buffer_1.toBigIntBE)(data)));break}}if(tagObj.value===null){throw new Error("unknown tag type:"+tagObj.type)}this._result.push(tagObj);this._total+=tagObj.dataSize;this._state=State.STATE_TAG;this._cursor=0;this._tag_stack.pop();while(this._tag_stack.length>0){const topEle=this._tag_stack[this._tag_stack.length-1];if(topEle==null){return false}if(topEle.dataEnd<0){this._tag_stack.pop();return true}if(this._totallst.concat(this.encodeChunk(elm)),[])).buffer}encodeChunk(elm){if(elm.type==="m"){if(!elm.isEnd){this.startTag(elm)}else{this.endTag(elm)}}else{elm.data=Buffer.from(elm.data);this.writeTag(elm)}return this.flush()}flush(){const ret=this._buffers;this._buffers=[];return ret}getSchemaInfo(tagName){for(const[tagNum,tagVal]of Object.entries(this._schema)){if(tagVal.name===tagName){return Buffer.from(Number(tagNum).toString(16),"hex")}}return null}writeTag(elm){const tagName=elm.name;const tagId=this.getSchemaInfo(tagName);const tagData=elm.data;if(tagId==null){throw new Error("No schema entry found for "+tagName)}const data=tools.encodeTag(tagId,tagData);if(this._stack.length>0){const last=this._stack[this._stack.length-1];last.children.push({tagId:tagId,elm:elm,children:[],data:data});return}this._buffers=this._buffers.concat(data);return}startTag(elm){const tagName=elm.name;const tagId=this.getSchemaInfo(tagName);if(tagId==null){throw new Error("No schema entry found for "+tagName)}if(elm.unknownSize){const data=tools.encodeTag(tagId,Buffer.alloc(0),elm.unknownSize);this._buffers=this._buffers.concat(data);return}const tag={tagId:tagId,elm:elm,children:[],data:null};if(this._stack.length>0){this._stack[this._stack.length-1].children.push(tag)}this._stack.push(tag)}endTag(elm){const tag=this._stack.pop();if(tag==null){throw new Error("EBML structure is broken")}if(tag.elm.name!==elm.name){throw new Error("EBML structure is broken")}const childTagDataBuffers=tag.children.reduce((lst,child)=>{if(child.data===null){throw new Error("EBML structure is broken")}return lst.concat(child.data)},[]);const childTagDataBuffer=tools.concat(childTagDataBuffers);if(tag.elm.type==="m"){tag.data=tools.encodeTag(tag.tagId,childTagDataBuffer,tag.elm.unknownSize)}else{tag.data=tools.encodeTag(tag.tagId,childTagDataBuffer)}if(this._stack.length<1){this._buffers=this._buffers.concat(tag.data)}}}exports.default=EBMLEncoder}).call(this)}).call(this,require("buffer").Buffer)},{"./tools":6,buffer:9,"matroska-schema":20}],4:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}:function(o,v){o["default"]=v});var __importStar=this&&this.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)if(k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k))__createBinding(result,mod,k);__setModuleDefault(result,mod);return result};Object.defineProperty(exports,"__esModule",{value:true});const events_1=require("events");const tools=__importStar(require("./tools"));class EBMLReader extends events_1.EventEmitter{constructor(){super();this.logGroup="";this.hasLoggingStarted=false;this.metadataloaded=false;this.chunks=[];this.stack=[];this.segmentOffset=0;this.last2SimpleBlockVideoTrackTimestamp=[0,0];this.last2SimpleBlockAudioTrackTimestamp=[0,0];this.lastClusterTimestamp=0;this.lastClusterPosition=0;this.timestampScale=1e6;this.metadataSize=0;this.metadatas=[];this.cues=[];this.firstVideoBlockRead=false;this.firstAudioBlockRead=false;this.currentTrack={TrackNumber:-1,TrackType:-1,DefaultDuration:null,CodecDelay:null};this.trackTypes=[];this.trackDefaultDuration=[];this.trackCodecDelay=[];this.trackInfo={type:"nothing"};this.ended=false;this.logging=false;this.use_duration_every_simpleblock=false;this.use_webp=false;this.use_segment_info=true;this.drop_default_duration=true}stop(){this.ended=true;this.emit_segment_info();while(this.stack.length){this.stack.pop();if(this.logging){console.groupEnd()}}if(this.logging&&this.hasLoggingStarted&&this.logGroup){console.groupEnd()}}emit_segment_info(){const data=this.chunks;this.chunks=[];if(!this.metadataloaded){this.metadataloaded=true;this.metadatas=data;const videoTrackNum=this.trackTypes.indexOf(1);const audioTrackNum=this.trackTypes.indexOf(2);this.trackInfo=videoTrackNum>=0&&audioTrackNum>=0?{type:"both",trackNumber:videoTrackNum}:videoTrackNum>=0?{type:"video",trackNumber:videoTrackNum}:audioTrackNum>=0?{type:"audio",trackNumber:audioTrackNum}:{type:"nothing"};if(!this.use_segment_info){return}this.emit("metadata",{data:data,metadataSize:this.metadataSize})}else{if(!this.use_segment_info){return}const timestamp=this.lastClusterTimestamp;const duration=this.duration;const timestampScale=this.timestampScale;this.emit("cluster",{timestamp:timestamp,data:data});this.emit("duration",{timestampScale:timestampScale,duration:duration})}}read(elm){let drop=false;if(this.ended){return}if(elm.type==="m"){if(elm.isEnd){this.stack.pop()}else{const parent=this.stack[this.stack.length-1];if(parent!=null&&parent.level>=elm.level){this.stack.pop();if(this.logging){console.groupEnd()}parent.dataEnd=elm.dataEnd;parent.dataSize=elm.dataEnd-parent.dataStart;parent.unknownSize=false;const o=Object.assign({},parent,{name:parent.name,type:parent.type,isEnd:true});this.chunks.push(o)}this.stack.push(elm)}}if(elm.type==="m"&&elm.name==="Segment"){if(this.segmentOffset!==0){console.warn("Multiple segments detected!")}this.segmentOffset=elm.dataStart;this.emit("segment_offset",this.segmentOffset)}else if(elm.type==="b"&&elm.name==="SimpleBlock"){const{timecode:timestamp,trackNumber,frames}=tools.ebmlBlock(elm.data);if(this.trackTypes[trackNumber]===1){if(!this.firstVideoBlockRead){this.firstVideoBlockRead=true;if(this.trackInfo.type==="both"||this.trackInfo.type==="video"){const CueTime=this.lastClusterTimestamp+timestamp;this.cues.push({CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:CueTime});this.emit("cue_info",{CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:this.lastClusterTimestamp});this.emit("cue",{CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:CueTime})}}this.last2SimpleBlockVideoTrackTimestamp=[this.last2SimpleBlockVideoTrackTimestamp[1],timestamp]}else if(this.trackTypes[trackNumber]===2){if(!this.firstAudioBlockRead){this.firstAudioBlockRead=true;if(this.trackInfo.type==="audio"){const CueTime=this.lastClusterTimestamp+timestamp;this.cues.push({CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:CueTime});this.emit("cue_info",{CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:this.lastClusterTimestamp});this.emit("cue",{CueTrack:trackNumber,CueClusterPosition:this.lastClusterPosition,CueTime:CueTime})}}this.last2SimpleBlockAudioTrackTimestamp=[this.last2SimpleBlockAudioTrackTimestamp[1],timestamp]}if(this.use_duration_every_simpleblock){this.emit("duration",{timestampScale:this.timestampScale,duration:this.duration})}if(this.use_webp){for(const frame of frames){const startcode=frame.subarray(3,6).toString("hex");if(startcode!=="9d012a"){break}const webpBuf=tools.VP8BitStreamToRiffWebPBuffer(frame);const webp=new Blob([webpBuf],{type:"image/webp"});const currentTime=this.duration;this.emit("webp",{currentTime:currentTime,webp:webp})}}}else if(elm.type==="m"&&elm.name==="Cluster"&&!elm.isEnd){this.firstVideoBlockRead=false;this.firstAudioBlockRead=false;this.emit_segment_info();this.emit("cluster_ptr",elm.tagStart);this.lastClusterPosition=elm.tagStart}else if(elm.type==="u"&&elm.name==="Timestamp"){this.lastClusterTimestamp=elm.value}else if(elm.type==="u"&&elm.name==="TimestampScale"){this.timestampScale=elm.value}else if(elm.type==="m"&&elm.name==="TrackEntry"){if(elm.isEnd){this.trackTypes[this.currentTrack.TrackNumber]=this.currentTrack.TrackType;this.trackDefaultDuration[this.currentTrack.TrackNumber]=this.currentTrack.DefaultDuration;this.trackCodecDelay[this.currentTrack.TrackNumber]=this.currentTrack.CodecDelay}else{this.currentTrack={TrackNumber:-1,TrackType:-1,DefaultDuration:null,CodecDelay:null}}}else if(elm.type==="u"&&elm.name==="TrackType"){this.currentTrack.TrackType=elm.value}else if(elm.type==="u"&&elm.name==="TrackNumber"){this.currentTrack.TrackNumber=elm.value}else if(elm.type==="u"&&elm.name==="CodecDelay"){this.currentTrack.CodecDelay=elm.value}else if(elm.type==="u"&&elm.name==="DefaultDuration"){if(this.drop_default_duration){console.warn("DefaultDuration detected!, remove it");drop=true}else{this.currentTrack.DefaultDuration=elm.value}}else if(elm.name==="unknown"){console.warn(elm)}if(!this.metadataloaded&&elm.dataEnd>0){this.metadataSize=elm.dataEnd}if(!drop){this.chunks.push(elm)}if(this.logging){this.put(elm)}}get duration(){if(this.trackInfo.type==="nothing"){console.warn("no video, no audio track");return 0}let defaultDuration=0;let codecDelay=0;let lastTimestamp=0;const _defaultDuration=this.trackDefaultDuration[this.trackInfo.trackNumber];if(typeof _defaultDuration==="number"){defaultDuration=_defaultDuration}else{if(this.trackInfo.type==="both"){if(this.last2SimpleBlockAudioTrackTimestamp[1]>this.last2SimpleBlockVideoTrackTimestamp[1]){defaultDuration=(this.last2SimpleBlockAudioTrackTimestamp[1]-this.last2SimpleBlockAudioTrackTimestamp[0])*this.timestampScale;const delay=this.trackCodecDelay[this.trackTypes.indexOf(2)];if(typeof delay==="number"){codecDelay=delay}lastTimestamp=this.last2SimpleBlockAudioTrackTimestamp[1]}else{defaultDuration=(this.last2SimpleBlockVideoTrackTimestamp[1]-this.last2SimpleBlockVideoTrackTimestamp[0])*this.timestampScale;const delay=this.trackCodecDelay[this.trackTypes.indexOf(1)];if(typeof delay==="number"){codecDelay=delay}lastTimestamp=this.last2SimpleBlockVideoTrackTimestamp[1]}}else if(this.trackInfo.type==="video"){defaultDuration=(this.last2SimpleBlockVideoTrackTimestamp[1]-this.last2SimpleBlockVideoTrackTimestamp[0])*this.timestampScale;const delay=this.trackCodecDelay[this.trackInfo.trackNumber];if(typeof delay==="number"){codecDelay=delay}lastTimestamp=this.last2SimpleBlockVideoTrackTimestamp[1]}else if(this.trackInfo.type==="audio"){defaultDuration=(this.last2SimpleBlockAudioTrackTimestamp[1]-this.last2SimpleBlockAudioTrackTimestamp[0])*this.timestampScale;const delay=this.trackCodecDelay[this.trackInfo.trackNumber];if(typeof delay==="number"){codecDelay=delay}lastTimestamp=this.last2SimpleBlockAudioTrackTimestamp[1]}}const duration_nanosec=(this.lastClusterTimestamp+lastTimestamp)*this.timestampScale+defaultDuration-codecDelay;const duration=duration_nanosec/this.timestampScale;return Math.floor(duration)}addListener(event,listener){return super.addListener(event,listener)}put(elm){if(!this.hasLoggingStarted){this.hasLoggingStarted=true;if(this.logging&&this.logGroup){console.groupCollapsed(this.logGroup)}}if(elm.type==="m"){if(elm.isEnd){console.groupEnd()}else{console.group(elm.name+":"+elm.tagStart)}}else if(elm.type==="b"){console.log(elm.name,elm.type)}else{console.log(elm.name,elm.tagStart,elm.type,elm.value)}}}exports.default=EBMLReader},{"./tools":6,events:17}],5:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}:function(o,v){o["default"]=v});var __exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports,p))__createBinding(exports,m,p)};var __importStar=this&&this.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)if(k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k))__createBinding(result,mod,k);__setModuleDefault(result,mod);return result};var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.tools=exports.Reader=exports.Encoder=exports.Decoder=exports.version=void 0;__exportStar(require("./EBML"),exports);const EBMLDecoder_1=__importDefault(require("./EBMLDecoder"));exports.Decoder=EBMLDecoder_1.default;const EBMLEncoder_1=__importDefault(require("./EBMLEncoder"));exports.Encoder=EBMLEncoder_1.default;const EBMLReader_1=__importDefault(require("./EBMLReader"));exports.Reader=EBMLReader_1.default;const tools=__importStar(require("./tools"));exports.tools=tools;const version=require("../package.json").version;exports.version=version},{"../package.json":22,"./EBML":1,"./EBMLDecoder":2,"./EBMLEncoder":3,"./EBMLReader":4,"./tools":6}],6:[function(require,module,exports){(function(Buffer){(function(){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.convertEBMLDateToJSDate=exports.createFloatBuffer=exports.createIntBuffer=exports.createUIntBuffer=exports.encodeValueToBuffer=exports.concat=exports.putRefinedMetaData=exports.extractElement=exports.removeElement=exports.makeMetadataSeekable=exports.createRIFFChunk=exports.VP8BitStreamToRiffWebPBuffer=exports.WebPBlockFilter=exports.WebPFrameFilter=exports.encodeTag=exports.readBlock=exports.ebmlBlock=exports.writeVint=exports.readVint=void 0;const int64_buffer_1=require("int64-buffer");const EBMLEncoder_1=__importDefault(require("./EBMLEncoder"));const{tools:_tools}=require("ebml/lib/ebml.js");const _block=require("ebml-block");exports.readVint=_tools.readVint;exports.writeVint=_tools.writeVint;exports.ebmlBlock=_block;function readBlock(buf){return(0,exports.ebmlBlock)(Buffer.from(buf))}exports.readBlock=readBlock;function encodeTag(tagId,tagData,unknownSize=false){return concat([tagId,unknownSize?Buffer.from("01ffffffffffffff","hex"):(0,exports.writeVint)(tagData.length),tagData])}exports.encodeTag=encodeTag;function WebPFrameFilter(elms){return WebPBlockFilter(elms).reduce((lst,elm)=>{const o=(0,exports.ebmlBlock)(elm.data);return o.frames.reduce((lst,frame)=>{const webpBuf=VP8BitStreamToRiffWebPBuffer(frame);const webp=new Blob([webpBuf],{type:"image/webp"});return lst.concat(webp)},lst)},[])}exports.WebPFrameFilter=WebPFrameFilter;function WebPBlockFilter(elms){return elms.reduce((lst,elm)=>{if(elm.type!=="b"){return lst}if(elm.name!=="SimpleBlock"){return lst}const o=(0,exports.ebmlBlock)(elm.data);const hasWebP=o.frames.some(frame=>{const startcode=frame.subarray(3,6).toString("hex");return startcode==="9d012a"});if(!hasWebP){return lst}return lst.concat(elm)},[])}exports.WebPBlockFilter=WebPBlockFilter;function VP8BitStreamToRiffWebPBuffer(frame){const VP8Chunk=createRIFFChunk("VP8 ",frame);const WebPChunk=concat([Buffer.from("WEBP","ascii"),VP8Chunk]);return createRIFFChunk("RIFF",WebPChunk)}exports.VP8BitStreamToRiffWebPBuffer=VP8BitStreamToRiffWebPBuffer;function createRIFFChunk(FourCC,chunk){const chunkSize=Buffer.alloc(4);chunkSize.writeUInt32LE(chunk.byteLength,0);return concat([Buffer.from(FourCC.substring(0,4),"ascii"),chunkSize,chunk,Buffer.alloc(chunk.byteLength%2===0?0:1)])}exports.createRIFFChunk=createRIFFChunk;function makeMetadataSeekable(originalMetadata,duration,cuesInfo,cuesOffset=0,cuesPosition=0){const header=extractElement("EBML",originalMetadata);const headerSize=encodedSizeOfEbml(header);const segmentContentStartPos=headerSize+12;const originalMetadataSize=originalMetadata[originalMetadata.length-1].dataEnd-segmentContentStartPos;const info=extractElement("Info",originalMetadata);removeElement("Duration",info);info.splice(1,0,{name:"Duration",type:"f",data:createFloatBuffer(duration,8)});const infoSize=encodedSizeOfEbml(info);const tracks=extractElement("Tracks",originalMetadata);const tracksSize=encodedSizeOfEbml(tracks);let seekHeadSize=47;let seekHead=[];let cuesSize=5+cuesInfo.length*15;let cues=[];let lastSizeDifference=-1;const maxIterations=10;for(let i=0;i0)){throw new Error("metadata dataEnd has wrong number")}const originalPayloadOffsetEnd=payload[payload.length-1].dataEnd;const ebmlSize=ebml[ebml.length-1].dataEnd;const refinedEBMLSize=(new EBMLEncoder_1.default).encode(ebml).byteLength;const offsetDiff=refinedEBMLSize-ebmlSize;const payloadSize=originalPayloadOffsetEnd-payload[0].tagStart;const segmentTagBuf=Buffer.from([24,83,128,103]);const segmentSizeBuf=Buffer.from("01ffffffffffffff","hex");const _segmentSize=segmentTagBuf.byteLength+segmentSizeBuf.byteLength;let newPayloadSize=payloadSize;const count=20;for(let i=1;ilst.concat(encorder.encode([elm])),[]).reduce((o,buf)=>o+buf.byteLength,0)}function refineMetadata(mesetadata,sizeDiff,info){const{duration,clusterPtrs,cues}=info;const _metadata=mesetadata.slice(0);if(typeof duration==="number"){let overwrited=false;for(const elm of _metadata){if(elm.type==="f"&&elm.name==="Duration"){overwrited=true;elm.data=createFloatBuffer(duration,8)}}if(!overwrited){insertTag(_metadata,"Info",[{name:"Duration",type:"f",data:createFloatBuffer(duration,8)}])}}if(Array.isArray(cues)){insertTag(_metadata,"Cues",create_cue(cues,sizeDiff))}let seekhead_children=[];if(Array.isArray(clusterPtrs)){console.warn("append cluster pointers to seekhead is deprecated. please use cues");seekhead_children=create_seek_from_clusters(clusterPtrs,sizeDiff)}insertTag(_metadata,"SeekHead",seekhead_children,true);return _metadata}function create_seek_from_clusters(clusterPtrs,sizeDiff){const seeks=[];for(const start of clusterPtrs){seeks.push({name:"Seek",type:"m",isEnd:false});seeks.push({name:"SeekID",type:"b",data:Buffer.from([31,67,182,117])});seeks.push({name:"SeekPosition",type:"u",data:createUIntBuffer(start+sizeDiff)});seeks.push({name:"Seek",type:"m",isEnd:true})}return seeks}function create_cue(cueInfos,sizeDiff){const cues=[];for(const{CueTrack,CueClusterPosition,CueTime}of cueInfos){cues.push({name:"CuePoint",type:"m",isEnd:false});cues.push({name:"CueTime",type:"u",data:createUIntBuffer(CueTime)});cues.push({name:"CueTrackPositions",type:"m",isEnd:false});cues.push({name:"CueTrack",type:"u",data:createUIntBuffer(CueTrack)});cues.push({name:"CueClusterPosition",type:"u",data:createUIntBuffer(CueClusterPosition+sizeDiff)});cues.push({name:"CueTrackPositions",type:"m",isEnd:true});cues.push({name:"CuePoint",type:"m",isEnd:true})}return cues}function insertTag(_metadata,tagName,children,insertHead=false){let idx=-1;for(let i=0;i<_metadata.length;i++){const elm=_metadata[i];if(elm.type==="m"&&elm.name===tagName&&!elm.isEnd){idx=i;break}}if(idx>=0){Array.prototype.splice.apply(_metadata,[idx+1,0].concat(children))}else if(insertHead){const elms=[].concat([{name:tagName,type:"m",isEnd:false}],children,[{name:tagName,type:"m",isEnd:true}]);elms.reverse();for(const elm of elms){_metadata.unshift(elm)}}else{_metadata.push({name:tagName,type:"m",isEnd:false});for(const elm of children){_metadata.push(elm)}_metadata.push({name:tagName,type:"m",isEnd:true})}}function concat(list){return Buffer.concat(list)}exports.concat=concat;function encodeValueToBuffer(elm){let data=Buffer.alloc(0);if(elm.type==="m"){return elm}switch(elm.type){case"u":data=createUIntBuffer(elm.value);break;case"i":data=createIntBuffer(elm.value);break;case"f":data=createFloatBuffer(elm.value);break;case"s":data=Buffer.from(elm.value,"ascii");break;case"8":data=Buffer.from(elm.value,"utf8");break;case"b":data=elm.value;break;case"d":data=new int64_buffer_1.Int64BE(elm.value.getTime().toString()).toBuffer();break}return Object.assign({},elm,{data:data})}exports.encodeValueToBuffer=encodeValueToBuffer;function createUIntBuffer(value){let bytes=1;for(;value>=Math.pow(2,8*bytes);bytes++){void 0}if(bytes>=7){console.warn("7bit or more bigger uint not supported.");return new int64_buffer_1.Uint64BE(value).toBuffer()}const data=Buffer.alloc(bytes);data.writeUIntBE(value,0,bytes);return data}exports.createUIntBuffer=createUIntBuffer;function createIntBuffer(value){let bytes=1;for(;value>=Math.pow(2,8*bytes);bytes++){}if(bytes>=7){console.warn("7bit or more bigger uint not supported.");return new int64_buffer_1.Int64BE(value).toBuffer()}const data=Buffer.alloc(bytes);data.writeIntBE(value,0,bytes);return data}exports.createIntBuffer=createIntBuffer;function createFloatBuffer(value,bytes=8){if(bytes===8){const data=Buffer.alloc(8);data.writeDoubleBE(value,0);return data}else if(bytes===4){const data=Buffer.alloc(4);data.writeFloatBE(value,0);return data}else{throw new Error("float type bits must 4bytes or 8bytes")}}exports.createFloatBuffer=createFloatBuffer;function convertEBMLDateToJSDate(int64str){if(int64str instanceof Date){return int64str}return new Date(new Date("2001-01-01T00:00:00.000Z").getTime()+Number(int64str)/1e3/1e3)}exports.convertEBMLDateToJSDate=convertEBMLDateToJSDate}).call(this)}).call(this,require("buffer").Buffer)},{"./EBMLEncoder":3,buffer:9,"ebml-block":10,"ebml/lib/ebml.js":13,"int64-buffer":19}],7:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],8:[function(require,module,exports){(function(Buffer){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});let converter;function toBigIntLE(buf){{const reversed=Buffer.from(buf);reversed.reverse();const hex=reversed.toString("hex");if(hex.length===0){return BigInt(0)}return BigInt(`0x${hex}`)}return converter.toBigInt(buf,false)}exports.toBigIntLE=toBigIntLE;function toBigIntBE(buf){{const hex=buf.toString("hex");if(hex.length===0){return BigInt(0)}return BigInt(`0x${hex}`)}return converter.toBigInt(buf,true)}exports.toBigIntBE=toBigIntBE;function toBufferLE(num,width){{const hex=num.toString(16);const buffer=Buffer.from(hex.padStart(width*2,"0").slice(0,width*2),"hex");buffer.reverse();return buffer}return converter.fromBigInt(num,Buffer.allocUnsafe(width),false)}exports.toBufferLE=toBufferLE;function toBufferBE(num,width){{const hex=num.toString(16);return Buffer.from(hex.padStart(width*2,"0").slice(0,width*2),"hex")}return converter.fromBigInt(num,Buffer.allocUnsafe(width),true)}exports.toBufferBE=toBufferBE}).call(this)}).call(this,require("buffer").Buffer)},{buffer:9}],9:[function(require,module,exports){(function(Buffer){(function(){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function"){console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.")}function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayLike(value)}if(value==null){throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase){return mustMatch?-1:utf8ToBytes(string).length}encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;imax)str+=" ... ";return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target)}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}else if(typeof val==="number"){val=val&255}if(start<0||this.length>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":7,buffer:9,ieee754:18}],10:[function(require,module,exports){var BufferReader=require("./lib/buffer-reader");var XIPH_LACING=1;var EBML_LACING=3;var FIXED_SIZE_LACING=2;module.exports=function(buffer){var block={};var reader=new BufferReader(buffer);block.trackNumber=reader.nextUIntV();block.timecode=reader.nextInt16BE();var flags=reader.nextUInt8();block.invisible=!!(flags&8);block.keyframe=!!(flags&128);block.discardable=!!(flags&1);var lacing=(flags&6)>>1;block.frames=readLacedData(reader,lacing);return block};function readLacedData(reader,lacing){if(!lacing)return[reader.nextBuffer()];var i,frameSize;var frames=[];var framesNum=reader.nextUInt8()+1;if(lacing===FIXED_SIZE_LACING){if(reader.length%framesNum!==0)throw new Error("Fixed-Size Lacing Error");frameSize=reader.length/framesNum;for(i=0;i=Math.pow(2,8-length)){break}}if(length>8){throw new Error("Unrepresentable length: "+length+" "+buffer.toString("hex",start,start+length))}if(start+length>buffer.length){return null}var i;var value=buffer[start]&(1<<8-length)-1;for(i=1;i=Math.pow(2,53-8)&&buffer[start+7]>0){return{length:length,value:-1}}}value*=Math.pow(2,8);value+=buffer[start+i]}if(signed){value-=Math.pow(2,length*7-1)-1}return{length:length,value:value}}},{}],13:[function(require,module,exports){(function(global,Buffer){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var global$1=typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var inited=false;function init(){inited=true;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}placeHolders=b64[len-2]==="="?2:b64[len-1]==="="?1:0;arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}function read(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)}function write(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}var toString={}.toString;var isArray=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"};var INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global$1.TYPED_ARRAY_SUPPORT!==undefined?global$1.TYPED_ARRAY_SUPPORT:true;function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}Buffer.isBuffer=isBuffer;function internalIsBuffer(b){return!!(b!=null&&b._isBuffer)}Buffer.compare=function compare(a,b){if(!internalIsBuffer(a)||!internalIsBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!internalIsBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(internalIsBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read$$1(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return fromByteArray(buf)}else{return fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!internalIsBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}function isBuffer(obj){return obj!=null&&(!!obj._isBuffer||isFastBuffer(obj)||isSlowBuffer(obj))}function isFastBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isFastBuffer(obj.slice(0,0))}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i=0)continue;target[key]=source[key]}return target}function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key]}}return target}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return self}function _possibleConstructorReturn(self,call){if(call&&(typeof call==="object"||typeof call==="function")){return call}return _assertThisInitialized(self)}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_nonIterableRest()}function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_nonIterableSpread()}function _arrayWithoutHoles(arr){if(Array.isArray(arr)){for(var i=0,arr2=new Array(arr.length);i0?floor:ceil)(it)};var min=Math.min;var _toLength=function(it){return it>0?min(_toInteger(it),9007199254740991):0};var _defined=function(it){if(it==undefined)throw TypeError("Can't call method on "+it);return it};var _stringRepeat=function repeat(count){var str=String(_defined(this));var res="";var n=_toInteger(count);if(n<0||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res};var _stringPad=function(that,maxLength,fillString,left){var S=String(_defined(that));var stringLength=S.length;var fillStr=fillString===undefined?" ":String(fillString);var intMaxLength=_toLength(maxLength);if(intMaxLength<=stringLength||fillStr=="")return S;var fillLen=intMaxLength-stringLength;var stringFiller=_stringRepeat.call(fillStr,Math.ceil(fillLen/fillStr.length));if(stringFiller.length>fillLen)stringFiller=stringFiller.slice(0,fillLen);return left?stringFiller+S:S+stringFiller};var navigator=_global.navigator;var _userAgent=navigator&&navigator.userAgent||"";_export(_export.P+_export.F*/Version\/10\.\d+(\.\d+)? Safari\//.test(_userAgent),"String",{padStart:function padStart(maxLength){return _stringPad(this,maxLength,arguments.length>1?arguments[1]:undefined,true)}});var toString$1={}.toString;var _cof=function(it){return toString$1.call(it).slice(8,-1)};var f$1={}.propertyIsEnumerable;var _objectPie={f:f$1};var _iobject=Object("z").propertyIsEnumerable(0)?Object:function(it){return _cof(it)=="String"?it.split(""):Object(it)};var _toIobject=function(it){return _iobject(_defined(it))};var gOPD=Object.getOwnPropertyDescriptor;var f$2=_descriptors?gOPD:function getOwnPropertyDescriptor(O,P){O=_toIobject(O);P=_toPrimitive(P,true);if(_ie8DomDefine)try{return gOPD(O,P)}catch(e){}if(_has(O,P))return _propertyDesc(!_objectPie.f.call(O,P),O[P])};var _objectGopd={f:f$2};var check=function(O,proto){_anObject(O);if(!_isObject(proto)&&proto!==null)throw TypeError(proto+": can't set as prototype!")};var _setProto={set:Object.setPrototypeOf||("__proto__"in{}?function(test,buggy,set){try{set=_ctx(Function.call,_objectGopd.f(Object.prototype,"__proto__").set,2);set(test,[]);buggy=!(test instanceof Array)}catch(e){buggy=true}return function setPrototypeOf(O,proto){check(O,proto);if(buggy)O.__proto__=proto;else set(O,proto);return O}}({},false):undefined),check:check};var setPrototypeOf=_setProto.set;var _inheritIfRequired=function(that,target,C){var S=target.constructor;var P;if(S!==C&&typeof S=="function"&&(P=S.prototype)!==C.prototype&&_isObject(P)&&setPrototypeOf){setPrototypeOf(that,P)}return that};var max=Math.max;var min$1=Math.min;var _toAbsoluteIndex=function(index,length){index=_toInteger(index);return index<0?max(index+length,0):min$1(index,length)};var _arrayIncludes=function(IS_INCLUDES){return function($this,el,fromIndex){var O=_toIobject($this);var length=_toLength(O.length);var index=_toAbsoluteIndex(fromIndex,length);var value;if(IS_INCLUDES&&el!=el)while(length>index){value=O[index++];if(value!=value)return true}else for(;length>index;index++)if(IS_INCLUDES||index in O){if(O[index]===el)return IS_INCLUDES||index||0}return!IS_INCLUDES&&-1}};var _library=false;var _shared=createCommonjsModule(function(module){var SHARED="__core-js_shared__";var store=_global[SHARED]||(_global[SHARED]={});(module.exports=function(key,value){return store[key]||(store[key]=value!==undefined?value:{})})("versions",[]).push({version:_core.version,mode:_library?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})});var shared=_shared("keys");var _sharedKey=function(key){return shared[key]||(shared[key]=_uid(key))};var arrayIndexOf$1=_arrayIncludes(false);var IE_PROTO=_sharedKey("IE_PROTO");var _objectKeysInternal=function(object,names){var O=_toIobject(object);var i=0;var result=[];var key;for(key in O)if(key!=IE_PROTO)_has(O,key)&&result.push(key);while(names.length>i)if(_has(O,key=names[i++])){~arrayIndexOf$1(result,key)||result.push(key)}return result};var _enumBugKeys="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",");var hiddenKeys=_enumBugKeys.concat("length","prototype");var f$3=Object.getOwnPropertyNames||function getOwnPropertyNames(O){return _objectKeysInternal(O,hiddenKeys)};var _objectGopn={f:f$3};var _stringWs="\t\n\v\f\r   ᠎    "+"          \u2028\u2029\ufeff";var space="["+_stringWs+"]";var non="​…";var ltrim=RegExp("^"+space+space+"*");var rtrim=RegExp(space+space+"*$");var exporter=function(KEY,exec,ALIAS){var exp={};var FORCE=_fails(function(){return!!_stringWs[KEY]()||non[KEY]()!=non});var fn=exp[KEY]=FORCE?exec(trim):_stringWs[KEY];if(ALIAS)exp[ALIAS]=fn;_export(_export.P+_export.F*FORCE,"String",exp)};var trim=exporter.trim=function(string,TYPE){string=String(_defined(string));if(TYPE&1)string=string.replace(ltrim,"");if(TYPE&2)string=string.replace(rtrim,"");return string};var _stringTrim=exporter;var _objectKeys=Object.keys||function keys(O){return _objectKeysInternal(O,_enumBugKeys)};var _objectDps=_descriptors?Object.defineProperties:function defineProperties(O,Properties){_anObject(O);var keys=_objectKeys(Properties);var length=keys.length;var i=0;var P;while(length>i)_objectDp.f(O,P=keys[i++],Properties[P]);return O};var document$1=_global.document;var _html=document$1&&document$1.documentElement;var IE_PROTO$1=_sharedKey("IE_PROTO");var Empty=function(){};var PROTOTYPE$1="prototype";var createDict=function(){var iframe=_domCreate("iframe");var i=_enumBugKeys.length;var lt="<";var gt=">";var iframeDocument;iframe.style.display="none";_html.appendChild(iframe);iframe.src="javascript:";iframeDocument=iframe.contentWindow.document;iframeDocument.open();iframeDocument.write(lt+"script"+gt+"document.F=Object"+lt+"/script"+gt);iframeDocument.close();createDict=iframeDocument.F;while(i--)delete createDict[PROTOTYPE$1][_enumBugKeys[i]];return createDict()};var _objectCreate=Object.create||function create(O,Properties){var result;if(O!==null){Empty[PROTOTYPE$1]=_anObject(O);result=new Empty;Empty[PROTOTYPE$1]=null;result[IE_PROTO$1]=O}else result=createDict();return Properties===undefined?result:_objectDps(result,Properties)};var gOPN=_objectGopn.f;var gOPD$1=_objectGopd.f;var dP$2=_objectDp.f;var $trim=_stringTrim.trim;var NUMBER="Number";var $Number=_global[NUMBER];var Base=$Number;var proto=$Number.prototype;var BROKEN_COF=_cof(_objectCreate(proto))==NUMBER;var TRIM="trim"in String.prototype;var toNumber=function(argument){var it=_toPrimitive(argument,false);if(typeof it=="string"&&it.length>2){it=TRIM?it.trim():$trim(it,3);var first=it.charCodeAt(0);var third,radix,maxCode;if(first===43||first===45){third=it.charCodeAt(2);if(third===88||third===120)return NaN}else if(first===48){switch(it.charCodeAt(1)){case 66:case 98:radix=2;maxCode=49;break;case 79:case 111:radix=8;maxCode=55;break;default:return+it}for(var digits=it.slice(2),i=0,l=digits.length,code;imaxCode)return NaN}return parseInt(digits,radix)}}return+it};if(!$Number(" 0o1")||!$Number("0b1")||$Number("+0x1")){$Number=function Number(value){var it=arguments.length<1?0:value;var that=this;return that instanceof $Number&&(BROKEN_COF?_fails(function(){proto.valueOf.call(that)}):_cof(that)!=NUMBER)?_inheritIfRequired(new Base(toNumber(it)),that,$Number):toNumber(it)};for(var keys=_descriptors?gOPN(Base):("MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,"+"EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,"+"MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger").split(","),j=0,key;keys.length>j;j++){if(_has(Base,key=keys[j])&&!_has($Number,key)){dP$2($Number,key,gOPD$1(Base,key))}}$Number.prototype=proto;proto.constructor=$Number;_redefine(_global,NUMBER,$Number)}var _flags=function(){var that=_anObject(this);var result="";if(that.global)result+="g";if(that.ignoreCase)result+="i";if(that.multiline)result+="m";if(that.unicode)result+="u";if(that.sticky)result+="y";return result};if(_descriptors&&/./g.flags!="g")_objectDp.f(RegExp.prototype,"flags",{configurable:true,get:_flags});var TO_STRING="toString";var $toString=/./[TO_STRING];var define=function(fn){_redefine(RegExp.prototype,TO_STRING,fn,true)};if(_fails(function(){return $toString.call({source:"a",flags:"b"})!="/a/b"})){define(function toString(){var R=_anObject(this);return"/".concat(R.source,"/","flags"in R?R.flags:!_descriptors&&R instanceof RegExp?_flags.call(R):undefined)})}else if($toString.name!=TO_STRING){define(function toString(){return $toString.call(this)})}var _toObject=function(it){return Object(_defined(it))};var _iterCall=function(iterator,fn,value,entries){try{return entries?fn(_anObject(value)[0],value[1]):fn(value)}catch(e){var ret=iterator["return"];if(ret!==undefined)_anObject(ret.call(iterator));throw e}};var _iterators={};var _wks=createCommonjsModule(function(module){var store=_shared("wks");var Symbol=_global.Symbol;var USE_SYMBOL=typeof Symbol=="function";var $exports=module.exports=function(name){return store[name]||(store[name]=USE_SYMBOL&&Symbol[name]||(USE_SYMBOL?Symbol:_uid)("Symbol."+name))};$exports.store=store});var ITERATOR=_wks("iterator");var ArrayProto=Array.prototype;var _isArrayIter=function(it){return it!==undefined&&(_iterators.Array===it||ArrayProto[ITERATOR]===it)};var _createProperty=function(object,index,value){if(index in object)_objectDp.f(object,index,_propertyDesc(0,value));else object[index]=value};var TAG=_wks("toStringTag");var ARG=_cof(function(){return arguments}())=="Arguments";var tryGet=function(it,key){try{return it[key]}catch(e){}};var _classof=function(it){var O,T,B;return it===undefined?"Undefined":it===null?"Null":typeof(T=tryGet(O=Object(it),TAG))=="string"?T:ARG?_cof(O):(B=_cof(O))=="Object"&&typeof O.callee=="function"?"Arguments":B};var ITERATOR$1=_wks("iterator");var core_getIteratorMethod=_core.getIteratorMethod=function(it){if(it!=undefined)return it[ITERATOR$1]||it["@@iterator"]||_iterators[_classof(it)]};var ITERATOR$2=_wks("iterator");var SAFE_CLOSING=false;try{var riter=[7][ITERATOR$2]();riter["return"]=function(){SAFE_CLOSING=true}}catch(e){}var _iterDetect=function(exec,skipClosing){if(!skipClosing&&!SAFE_CLOSING)return false;var safe=false;try{var arr=[7];var iter=arr[ITERATOR$2]();iter.next=function(){return{done:safe=true}};arr[ITERATOR$2]=function(){return iter};exec(arr)}catch(e){}return safe};_export(_export.S+_export.F*!_iterDetect(function(iter){}),"Array",{from:function from(arrayLike){var O=_toObject(arrayLike);var C=typeof this=="function"?this:Array;var aLen=arguments.length;var mapfn=aLen>1?arguments[1]:undefined;var mapping=mapfn!==undefined;var index=0;var iterFn=core_getIteratorMethod(O);var length,result,step,iterator;if(mapping)mapfn=_ctx(mapfn,aLen>2?arguments[2]:undefined,2);if(iterFn!=undefined&&!(C==Array&&_isArrayIter(iterFn))){for(iterator=iterFn.call(O),result=new C;!(step=iterator.next()).done;index++){_createProperty(result,index,mapping?_iterCall(iterator,mapfn,[step.value,index],true):step.value)}}else{length=_toLength(O.length);for(result=new C(length);length>index;index++){_createProperty(result,index,mapping?mapfn(O[index],index):O[index])}}result.length=index;return result}});_export(_export.S,"Math",{log2:function log2(x){return Math.log(x)/Math.LN2}});var Tools=function(){function Tools(){_classCallCheck(this,Tools)}_createClass(Tools,null,[{key:"readVint",value:function readVint(buffer){var start=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var length=8-Math.floor(Math.log2(buffer[start]));if(length>8){var number=Tools.readHexString(buffer,start,start+length);throw new Error("Unrepresentable length: ".concat(length," ").concat(number))}if(start+length>buffer.length){return null}var value=buffer[start]&(1<<8-length)-1;for(var i=1;i=Math.pow(2,8)&&buffer[start+7]>0){return{length:length,value:-1}}}value*=Math.pow(2,8);value+=buffer[start+i]}return{length:length,value:value}}},{key:"writeVint",value:function writeVint(value){if(value<0||value>Math.pow(2,53)){throw new Error("Unrepresentable value: ".concat(value))}var length=1;for(length=1;length<=8;length+=1){if(value1&&arguments[1]!==undefined?arguments[1]:0;var end=arguments.length>2&&arguments[2]!==undefined?arguments[2]:buff.byteLength;return Array.from(buff.slice(start,end)).map(function(q){return Number(q).toString(16)}).reduce(function(acc,current){return"".concat(acc).concat(current.padStart(2,"0"))},"")}},{key:"readUtf8",value:function readUtf8(buff){try{return Buffer.from(buff).toString("utf8")}catch(exception){return null}}},{key:"readUnsigned",value:function readUnsigned(buff){var b=new DataView(buff.buffer,buff.byteOffset,buff.byteLength);switch(buff.byteLength){case 1:return b.getUint8(0);case 2:return b.getUint16(0);case 4:return b.getUint32(0);default:break}if(buff.byteLength<=6){return buff.reduce(function(acc,current){return acc*256+current},0)}return Tools.readHexString(buff,0,buff.byteLength)}},{key:"readSigned",value:function readSigned(buff){var b=new DataView(buff.buffer,buff.byteOffset,buff.byteLength);switch(buff.byteLength){case 1:return b.getInt8(0);case 2:return b.getInt16(0);case 4:return b.getInt32(0);default:return NaN}}},{key:"readFloat",value:function readFloat(buff){var b=new DataView(buff.buffer,buff.byteOffset,buff.byteLength);switch(buff.byteLength){case 4:return b.getFloat32(0);case 8:return b.getFloat64(0);default:return NaN}}},{key:"readDataFromTag",value:function readDataFromTag(tagObj,data){var type=tagObj.type,name=tagObj.name;var track=tagObj.track;var discardable=tagObj.discardable||false;var keyframe=tagObj.keyframe||false;var payload=null;var value;switch(type){case"u":value=Tools.readUnsigned(data);break;case"f":value=Tools.readFloat(data);break;case"i":value=Tools.readSigned(data);break;case"s":value=String.fromCharCode.apply(String,_toConsumableArray(data));break;case"8":value=Tools.readUtf8(data);break;default:break}if(name==="SimpleBlock"||name==="Block"){var p=0;var _Tools$readVint=Tools.readVint(data,p),length=_Tools$readVint.length,trak=_Tools$readVint.value;p+=length;track=trak;value=Tools.readSigned(data.subarray(p,p+2));p+=2;if(name==="SimpleBlock"){keyframe=Boolean(data[length+2]&128);discardable=Boolean(data[length+2]&1)}p+=1;payload=data.subarray(p)}return _objectSpread({},tagObj,{data:data,discardable:discardable,keyframe:keyframe,payload:payload,track:track,value:value})}}]);return Tools}();var UNSCOPABLES=_wks("unscopables");var ArrayProto$1=Array.prototype;if(ArrayProto$1[UNSCOPABLES]==undefined)_hide(ArrayProto$1,UNSCOPABLES,{});var _addToUnscopables=function(key){ArrayProto$1[UNSCOPABLES][key]=true};var _iterStep=function(done,value){return{value:value,done:!!done}};var def=_objectDp.f;var TAG$1=_wks("toStringTag");var _setToStringTag=function(it,tag,stat){if(it&&!_has(it=stat?it:it.prototype,TAG$1))def(it,TAG$1,{configurable:true,value:tag})};var IteratorPrototype={};_hide(IteratorPrototype,_wks("iterator"),function(){return this});var _iterCreate=function(Constructor,NAME,next){Constructor.prototype=_objectCreate(IteratorPrototype,{next:_propertyDesc(1,next)});_setToStringTag(Constructor,NAME+" Iterator")};var IE_PROTO$2=_sharedKey("IE_PROTO");var ObjectProto=Object.prototype;var _objectGpo=Object.getPrototypeOf||function(O){O=_toObject(O);if(_has(O,IE_PROTO$2))return O[IE_PROTO$2];if(typeof O.constructor=="function"&&O instanceof O.constructor){return O.constructor.prototype}return O instanceof Object?ObjectProto:null};var ITERATOR$3=_wks("iterator");var BUGGY=!([].keys&&"next"in[].keys());var FF_ITERATOR="@@iterator";var KEYS="keys";var VALUES="values";var returnThis=function(){return this};var _iterDefine=function(Base,NAME,Constructor,next,DEFAULT,IS_SET,FORCED){_iterCreate(Constructor,NAME,next);var getMethod=function(kind){if(!BUGGY&&kind in proto)return proto[kind];switch(kind){case KEYS:return function keys(){return new Constructor(this,kind)};case VALUES:return function values(){return new Constructor(this,kind)}}return function entries(){return new Constructor(this,kind)}};var TAG=NAME+" Iterator";var DEF_VALUES=DEFAULT==VALUES;var VALUES_BUG=false;var proto=Base.prototype;var $native=proto[ITERATOR$3]||proto[FF_ITERATOR]||DEFAULT&&proto[DEFAULT];var $default=$native||getMethod(DEFAULT);var $entries=DEFAULT?!DEF_VALUES?$default:getMethod("entries"):undefined;var $anyNative=NAME=="Array"?proto.entries||$native:$native;var methods,key,IteratorPrototype;if($anyNative){IteratorPrototype=_objectGpo($anyNative.call(new Base));if(IteratorPrototype!==Object.prototype&&IteratorPrototype.next){_setToStringTag(IteratorPrototype,TAG,true);if(!_library&&typeof IteratorPrototype[ITERATOR$3]!="function")_hide(IteratorPrototype,ITERATOR$3,returnThis)}}if(DEF_VALUES&&$native&&$native.name!==VALUES){VALUES_BUG=true;$default=function values(){return $native.call(this)}}if((!_library||FORCED)&&(BUGGY||VALUES_BUG||!proto[ITERATOR$3])){_hide(proto,ITERATOR$3,$default)}_iterators[NAME]=$default;_iterators[TAG]=returnThis;if(DEFAULT){methods={values:DEF_VALUES?$default:getMethod(VALUES),keys:IS_SET?$default:getMethod(KEYS),entries:$entries};if(FORCED)for(key in methods){if(!(key in proto))_redefine(proto,key,methods[key])}else _export(_export.P+_export.F*(BUGGY||VALUES_BUG),NAME,methods)}return methods};var es6_array_iterator=_iterDefine(Array,"Array",function(iterated,kind){this._t=_toIobject(iterated);this._i=0;this._k=kind},function(){var O=this._t;var kind=this._k;var index=this._i++;if(!O||index>=O.length){this._t=undefined;return _iterStep(1)}if(kind=="keys")return _iterStep(0,index);if(kind=="values")return _iterStep(0,O[index]);return _iterStep(0,[index,O[index]])},"values");_iterators.Arguments=_iterators.Array;_addToUnscopables("keys");_addToUnscopables("values");_addToUnscopables("entries");var ITERATOR$4=_wks("iterator");var TO_STRING_TAG=_wks("toStringTag");var ArrayValues=_iterators.Array;var DOMIterables={CSSRuleList:true,CSSStyleDeclaration:false,CSSValueList:false,ClientRectList:false,DOMRectList:false,DOMStringList:false,DOMTokenList:true,DataTransferItemList:false,FileList:false,HTMLAllCollection:false,HTMLCollection:false,HTMLFormElement:false,HTMLSelectElement:false,MediaList:true,MimeTypeArray:false,NamedNodeMap:false,NodeList:true,PaintRequestList:false,Plugin:false,PluginArray:false,SVGLengthList:false,SVGNumberList:false,SVGPathSegList:false,SVGPointList:false,SVGStringList:false,SVGTransformList:false,SourceBufferList:false,StyleSheetList:true,TextTrackCueList:false,TextTrackList:false,TouchList:false};for(var collections=_objectKeys(DOMIterables),i=0;iindex;index++){result=entries?f(_anObject(step=iterable[index])[0],step[1]):f(iterable[index]);if(result===BREAK||result===RETURN)return result}else for(iterator=iterFn.call(iterable);!(step=iterator.next()).done;){result=_iterCall(iterator,f,step.value,entries);if(result===BREAK||result===RETURN)return result}};exports.BREAK=BREAK;exports.RETURN=RETURN});var SPECIES=_wks("species");var _setSpecies=function(KEY){var C=_global[KEY];if(_descriptors&&C&&!C[SPECIES])_objectDp.f(C,SPECIES,{configurable:true,get:function(){return this}})};var _meta=createCommonjsModule(function(module){var META=_uid("meta");var setDesc=_objectDp.f;var id=0;var isExtensible=Object.isExtensible||function(){return true};var FREEZE=!_fails(function(){return isExtensible(Object.preventExtensions({}))});var setMeta=function(it){setDesc(it,META,{value:{i:"O"+ ++id,w:{}}})};var fastKey=function(it,create){if(!_isObject(it))return typeof it=="symbol"?it:(typeof it=="string"?"S":"P")+it;if(!_has(it,META)){if(!isExtensible(it))return"F";if(!create)return"E";setMeta(it)}return it[META].i};var getWeak=function(it,create){if(!_has(it,META)){if(!isExtensible(it))return true;if(!create)return false;setMeta(it)}return it[META].w};var onFreeze=function(it){if(FREEZE&&meta.NEED&&isExtensible(it)&&!_has(it,META))setMeta(it);return it};var meta=module.exports={KEY:META,NEED:false,fastKey:fastKey,getWeak:getWeak,onFreeze:onFreeze}});var _meta_1=_meta.KEY;var _meta_2=_meta.NEED;var _meta_3=_meta.fastKey;var _meta_4=_meta.getWeak;var _meta_5=_meta.onFreeze;var _validateCollection=function(it,TYPE){if(!_isObject(it)||it._t!==TYPE)throw TypeError("Incompatible receiver, "+TYPE+" required!");return it};var dP$3=_objectDp.f;var fastKey=_meta.fastKey;var SIZE=_descriptors?"_s":"size";var getEntry=function(that,key){var index=fastKey(key);var entry;if(index!=="F")return that._i[index];for(entry=that._f;entry;entry=entry.n){if(entry.k==key)return entry}};var _collectionStrong={getConstructor:function(wrapper,NAME,IS_MAP,ADDER){var C=wrapper(function(that,iterable){_anInstance(that,C,NAME,"_i");that._t=NAME;that._i=_objectCreate(null);that._f=undefined;that._l=undefined;that[SIZE]=0;if(iterable!=undefined)_forOf(iterable,IS_MAP,that[ADDER],that)});_redefineAll(C.prototype,{clear:function clear(){for(var that=_validateCollection(this,NAME),data=that._i,entry=that._f;entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that._f=that._l=undefined;that[SIZE]=0},delete:function(key){var that=_validateCollection(this,NAME);var entry=getEntry(that,key);if(entry){var next=entry.n;var prev=entry.p;delete that._i[entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that._f==entry)that._f=next;if(that._l==entry)that._l=prev;that[SIZE]--}return!!entry},forEach:function forEach(callbackfn){_validateCollection(this,NAME);var f=_ctx(callbackfn,arguments.length>1?arguments[1]:undefined,3);var entry;while(entry=entry?entry.n:this._f){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function has(key){return!!getEntry(_validateCollection(this,NAME),key)}});if(_descriptors)dP$3(C.prototype,"size",{get:function(){return _validateCollection(this,NAME)[SIZE]}});return C},def:function(that,key,value){var entry=getEntry(that,key);var prev,index;if(entry){entry.v=value}else{that._l=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that._l,n:undefined,r:false};if(!that._f)that._f=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!=="F")that._i[index]=entry}return that},getEntry:getEntry,setStrong:function(C,NAME,IS_MAP){_iterDefine(C,NAME,function(iterated,kind){this._t=_validateCollection(iterated,NAME);this._k=kind;this._l=undefined},function(){var that=this;var kind=that._k;var entry=that._l;while(entry&&entry.r)entry=entry.p;if(!that._t||!(that._l=entry=entry?entry.n:that._t._f)){that._t=undefined;return _iterStep(1)}if(kind=="keys")return _iterStep(0,entry.k);if(kind=="values")return _iterStep(0,entry.v);return _iterStep(0,[entry.k,entry.v])},IS_MAP?"entries":"values",!IS_MAP,true);_setSpecies(NAME)}};var _collection=function(NAME,wrapper,methods,common,IS_MAP,IS_WEAK){var Base=_global[NAME];var C=Base;var ADDER=IS_MAP?"set":"add";var proto=C&&C.prototype;var O={};var fixMethod=function(KEY){var fn=proto[KEY];_redefine(proto,KEY,KEY=="delete"?function(a){return IS_WEAK&&!_isObject(a)?false:fn.call(this,a===0?0:a)}:KEY=="has"?function has(a){return IS_WEAK&&!_isObject(a)?false:fn.call(this,a===0?0:a)}:KEY=="get"?function get(a){return IS_WEAK&&!_isObject(a)?undefined:fn.call(this,a===0?0:a)}:KEY=="add"?function add(a){fn.call(this,a===0?0:a);return this}:function set(a,b){fn.call(this,a===0?0:a,b);return this})};if(typeof C!="function"||!(IS_WEAK||proto.forEach&&!_fails(function(){(new C).entries().next()}))){C=common.getConstructor(wrapper,NAME,IS_MAP,ADDER);_redefineAll(C.prototype,methods);_meta.NEED=true}else{var instance=new C;var HASNT_CHAINING=instance[ADDER](IS_WEAK?{}:-0,1)!=instance;var THROWS_ON_PRIMITIVES=_fails(function(){instance.has(1)});var ACCEPT_ITERABLES=_iterDetect(function(iter){new C(iter)});var BUGGY_ZERO=!IS_WEAK&&_fails(function(){var $instance=new C;var index=5;while(index--)$instance[ADDER](index,index);return!$instance.has(-0)});if(!ACCEPT_ITERABLES){C=wrapper(function(target,iterable){_anInstance(target,C,NAME);var that=_inheritIfRequired(new Base,target,C);if(iterable!=undefined)_forOf(iterable,IS_MAP,that[ADDER],that);return that});C.prototype=proto;proto.constructor=C}if(THROWS_ON_PRIMITIVES||BUGGY_ZERO){fixMethod("delete");fixMethod("has");IS_MAP&&fixMethod("get")}if(BUGGY_ZERO||HASNT_CHAINING)fixMethod(ADDER);if(IS_WEAK&&proto.clear)delete proto.clear}_setToStringTag(C,NAME);O[NAME]=C;_export(_export.G+_export.W+_export.F*(C!=Base),O);if(!IS_WEAK)common.setStrong(C,NAME,IS_MAP);return C};var MAP="Map";var es6_map=_collection(MAP,function(get){return function Map(){return get(this,arguments.length>0?arguments[0]:undefined)}},{get:function get(key){var entry=_collectionStrong.getEntry(_validateCollection(this,MAP),key);return entry&&entry.v},set:function set(key,value){return _collectionStrong.def(_validateCollection(this,MAP),key===0?0:key,value)}},_collectionStrong,true);var schema=new Map([[128,{name:"ChapterDisplay",level:4,type:"m",multiple:true,minver:1,webm:true,description:"Contains all possible strings to use for the chapter display."}],[131,{name:"TrackType",level:3,type:"u",multiple:false,mandatory:true,minver:1,range:"1-254",description:"A set of track types coded on 8 bits (1: video, 2: audio, 3: complex, 0x10: logo, 0x11: subtitle, 0x12: buttons, 0x20: control).",webm:false}],[133,{name:"ChapString",cppname:"ChapterString",level:5,type:"8",multiple:false,mandatory:true,minver:1,webm:true,description:"Contains the string to use as the chapter atom."}],[134,{name:"CodecID",level:3,type:"s",mandatory:true,minver:1,description:"An ID corresponding to the codec, see the codec page for more info.",multiple:false,webm:false}],[136,{name:"FlagDefault",cppname:"TrackFlagDefault",level:3,type:"u",mandatory:true,minver:1,default:1,range:"0-1",description:"Set if that track (audio, video or subs) SHOULD be active if no language found matches the user preference. (1 bit)",multiple:false,webm:false}],[137,{name:"ChapterTrackNumber",level:5,type:"u",mandatory:true,multiple:true,minver:1,webm:false,range:"not 0",description:"UID of the Track to apply this chapter too. In the absense of a control track, choosing this chapter will select the listed Tracks and deselect unlisted tracks. Absense of this element indicates that the Chapter should be applied to any currently used Tracks."}],[145,{name:"ChapterTimeStart",level:4,type:"u",mandatory:true,minver:1,webm:true,description:"Timestamp of the start of Chapter (not scaled).",multiple:false}],[146,{name:"ChapterTimeEnd",level:4,type:"u",minver:1,webm:false,description:"Timestamp of the end of Chapter (timestamp excluded, not scaled).",multiple:false}],[150,{name:"CueRefTime",level:5,type:"u",mandatory:true,minver:2,webm:false,description:"Timestamp of the referenced Block.",multiple:false}],[151,{name:"CueRefCluster",level:5,type:"u",mandatory:true,webm:false,description:"The Position of the Cluster containing the referenced Block.",minver:0,multiple:false}],[152,{name:"ChapterFlagHidden",level:4,type:"u",mandatory:true,minver:1,webm:false,default:0,range:"0-1",description:"If a chapter is hidden (1), it should not be available to the user interface (but still to Control Tracks; see flag notes). (1 bit)",multiple:false}],[16980,{name:"ContentCompAlgo",level:6,type:"u",mandatory:true,minver:1,webm:false,default:0,br:["","","",""],del:["1 - bzlib,","2 - lzo1x"],description:"The compression algorithm used. Algorithms that have been specified so far are: 0 - zlib, 3 - Header Stripping",multiple:false}],[16981,{name:"ContentCompSettings",level:6,type:"b",minver:1,webm:false,description:"Settings that might be needed by the decompressor. For Header Stripping (ContentCompAlgo=3), the bytes that were removed from the beggining of each frames of the track.",multiple:false}],[17026,{name:"DocType",level:1,type:"s",mandatory:true,default:"matroska",minver:1,description:"A string that describes the type of document that follows this EBML header. 'matroska' in our case or 'webm' for webm files.",multiple:false,webm:false}],[17029,{name:"DocTypeReadVersion",level:1,type:"u",mandatory:true,default:1,minver:1,description:"The minimum DocType version an interpreter has to support to read this file.",multiple:false,webm:false}],[17030,{name:"EBMLVersion",level:1,type:"u",mandatory:true,default:1,minver:1,description:"The version of EBML parser used to create the file.",multiple:false,webm:false}],[17031,{name:"DocTypeVersion",level:1,type:"u",mandatory:true,default:1,minver:1,description:"The version of DocType interpreter used to create the file.",multiple:false,webm:false}],[17476,{name:"SegmentFamily",level:2,type:"b",multiple:true,minver:1,webm:false,bytesize:16,description:"A randomly generated unique ID that all segments related to each other must use (128 bits)."}],[17505,{name:"DateUTC",level:2,type:"d",minver:1,description:"Date of the origin of timestamp (value 0), i.e. production date.",multiple:false,webm:false}],[17540,{name:"TagDefault",level:4,type:"u",mandatory:true,minver:1,webm:false,default:1,range:"0-1",description:"Indication to know if this is the default/original language to use for the given tag. (1 bit)",multiple:false}],[17541,{name:"TagBinary",level:4,type:"b",minver:1,webm:false,description:"The values of the Tag if it is binary. Note that this cannot be used in the same SimpleTag as TagString.",multiple:false}],[17543,{name:"TagString",level:4,type:"8",minver:1,webm:false,description:"The value of the Tag.",multiple:false}],[17545,{name:"Duration",level:2,type:"f",minver:1,range:"> 0",description:"Duration of the segment (based on TimecodeScale).",multiple:false,webm:false}],[17816,{name:"ChapterFlagEnabled",level:4,type:"u",mandatory:true,minver:1,webm:false,default:1,range:"0-1",description:"Specify wether the chapter is enabled. It can be enabled/disabled by a Control Track. When disabled, the movie should skip all the content between the TimeStart and TimeEnd of this chapter (see flag notes). (1 bit)",multiple:false}],[18016,{name:"FileMimeType",level:3,type:"s",mandatory:true,minver:1,webm:false,description:"MIME type of the file.",multiple:false}],[18017,{name:"FileUsedStartTime",level:3,type:"u",divx:true,description:"DivX font extension",multiple:false}],[18018,{name:"FileUsedEndTime",level:3,type:"u",divx:true,multiple:false,description:"DivX font extension"}],[18037,{name:"FileReferral",level:3,type:"b",webm:false,description:"A binary value that a track/codec can refer to when the attachment is needed.",multiple:false}],[20529,{name:"ContentEncodingOrder",level:5,type:"u",mandatory:true,minver:1,webm:false,default:0,multiple:false,description:"Tells when this modification was used during encoding/muxing starting with 0 and counting upwards. The decoder/demuxer has to start with the highest order number it finds and work its way down. This value has to be unique over all ContentEncodingOrder elements in the segment."}],[20530,{name:"ContentEncodingScope",level:5,type:"u",mandatory:true,minver:1,webm:false,default:1,range:"not 0",br:["","",""],description:"A bit field that describes which elements have been modified in this way. Values (big endian) can be OR'ed. Possible values: 1 - all frame contents, 2 - the track's private data, 4 - the next ContentEncoding (next ContentEncodingOrder. Either the data inside ContentCompression and/or ContentEncryption)",multiple:false}],[20531,{name:"ContentEncodingType",level:5,type:"u",mandatory:true,minver:1,webm:false,default:0,br:["",""],description:"A value describing what kind of transformation has been done. Possible values: 0 - compression, 1 - encryption",multiple:false}],[20532,{name:"ContentCompression",level:5,type:"m",minver:1,webm:false,description:"Settings describing the compression used. Must be present if the value of ContentEncodingType is 0 and absent otherwise. Each block must be decompressable even if no previous block is available in order not to prevent seeking.",multiple:false}],[20533,{name:"ContentEncryption",level:5,type:"m",minver:1,webm:false,description:"Settings describing the encryption used. Must be present if the value of ContentEncodingType is 1 and absent otherwise.",multiple:false}],[21368,{name:"CueBlockNumber",level:4,type:"u",minver:1,default:1,range:"not 0",description:"Number of the Block in the specified Cluster.",multiple:false}],[22100,{name:"ChapterStringUID",level:4,type:"8",mandatory:false,minver:3,webm:true,description:"A unique string ID to identify the Chapter. Use for WebVTT cue identifier storage.",multiple:false}],[22337,{name:"WritingApp",level:2,type:"8",mandatory:true,minver:1,multiple:false,description:'Writing application ("mkvmerge-0.3.3").'}],[22612,{name:"SilentTracks",cppname:"ClusterSilentTracks",level:2,type:"m",minver:1,multiple:false,webm:false,description:"The list of tracks that are not used in that part of the stream. It is useful when using overlay tracks on seeking. Then you should decide what track to use."}],[25152,{name:"ContentEncoding",level:4,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"Settings for one content encoding like compression or encryption."}],[25188,{name:"BitDepth",cppname:"AudioBitDepth",level:4,type:"u",minver:1,range:"not 0",multiple:false,description:"Bits per sample, mostly used for PCM."}],[25906,{name:"SignedElement",level:3,type:"b",multiple:true,webm:false,description:"An element ID whose data will be used to compute the signature."}],[26148,{name:"TrackTranslate",level:3,type:"m",multiple:true,minver:1,webm:false,description:"The track identification for the given Chapter Codec."}],[26897,{name:"ChapProcessCommand",cppname:"ChapterProcessCommand",level:5,type:"m",multiple:true,minver:1,webm:false,description:"Contains all the commands associated to the Atom."}],[26914,{name:"ChapProcessTime",cppname:"ChapterProcessTime",level:6,type:"u",mandatory:true,minver:1,webm:false,description:"Defines when the process command should be handled (0: during the whole chapter, 1: before starting playback, 2: after playback of the chapter)."}],[26916,{name:"ChapterTranslate",level:2,type:"m",multiple:true,minver:1,webm:false,description:"A tuple of corresponding ID used by chapter codecs to represent this segment."}],[26931,{name:"ChapProcessData",cppname:"ChapterProcessData",level:6,type:"b",mandatory:true,minver:1,webm:false,description:"Contains the command information. The data should be interpreted depending on the ChapProcessCodecID value. For ChapProcessCodecID = 1, the data correspond to the binary DVD cell pre/post commands."}],[26948,{name:"ChapProcess",cppname:"ChapterProcess",level:4,type:"m",multiple:true,minver:1,webm:false,description:"Contains all the commands associated to the Atom."}],[26965,{name:"ChapProcessCodecID",cppname:"ChapterProcessCodecID",level:5,type:"u",mandatory:true,minver:1,webm:false,default:0,description:"Contains the type of the codec used for the processing. A value of 0 means native Matroska processing (to be defined), a value of 1 means the DVD command set is used. More codec IDs can be added later."}],[29555,{name:"Tag",level:2,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"Element containing elements specific to Tracks/Chapters."}],[29572,{name:"SegmentFilename",level:2,type:"8",minver:1,webm:false,description:"A filename corresponding to this segment."}],[29766,{name:"AttachmentLink",cppname:"TrackAttachmentLink",level:3,type:"u",minver:1,webm:false,range:"not 0",description:"The UID of an attachment that is used by this codec."}],[2459272,{name:"CodecName",level:3,type:"8",minver:1,description:"A human-readable string specifying the codec."}],[408125543,{name:"Segment",level:0,type:"m",mandatory:true,multiple:true,minver:1,description:"This element contains all other top-level (level 1) elements. Typically a Matroska file is composed of 1 segment."}],[17530,{name:"TagLanguage",level:4,type:"s",mandatory:true,minver:1,webm:false,default:"und",description:"Specifies the language of the tag specified, in the Matroska languages form."}],[17827,{name:"TagName",level:4,type:"8",mandatory:true,minver:1,webm:false,description:"The name of the Tag that is going to be stored."}],[26568,{name:"SimpleTag",cppname:"TagSimple",level:3,recursive:true,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"Contains general information about the target."}],[25542,{name:"TagAttachmentUID",level:4,type:"u",multiple:true,minver:1,webm:false,default:0,description:"A unique ID to identify the Attachment(s) the tags belong to. If the value is 0 at this level, the tags apply to all the attachments in the Segment."}],[25540,{name:"TagChapterUID",level:4,type:"u",multiple:true,minver:1,webm:false,default:0,description:"A unique ID to identify the Chapter(s) the tags belong to. If the value is 0 at this level, the tags apply to all chapters in the Segment."}],[25545,{name:"TagEditionUID",level:4,type:"u",multiple:true,minver:1,webm:false,default:0,description:"A unique ID to identify the EditionEntry(s) the tags belong to. If the value is 0 at this level, the tags apply to all editions in the Segment."}],[25541,{name:"TagTrackUID",level:4,type:"u",multiple:true,minver:1,webm:false,default:0,description:"A unique ID to identify the Track(s) the tags belong to. If the value is 0 at this level, the tags apply to all tracks in the Segment."}],[25546,{name:"TargetType",cppname:"TagTargetType",level:4,type:"s",minver:1,webm:false,strong:"informational",description:'An string that can be used to display the logical level of the target like "ALBUM", "TRACK", "MOVIE", "CHAPTER", etc (see TargetType).'}],[26826,{name:"TargetTypeValue",cppname:"TagTargetTypeValue",level:4,type:"u",minver:1,webm:false,default:50,description:"A number to indicate the logical level of the target (see TargetType)."}],[25536,{name:"Targets",cppname:"TagTargets",level:3,type:"m",mandatory:true,minver:1,webm:false,description:"Contain all UIDs where the specified meta data apply. It is empty to describe everything in the segment."}],[307544935,{name:"Tags",level:1,type:"m",multiple:true,minver:1,webm:false,description:"Element containing elements specific to Tracks/Chapters. A list of valid tags can be found here."}],[17677,{name:"ChapProcessPrivate",cppname:"ChapterProcessPrivate",level:5,type:"b",minver:1,webm:false,description:'Some optional data attached to the ChapProcessCodecID information. For ChapProcessCodecID = 1, it is the "DVD level" equivalent.'}],[17278,{name:"ChapCountry",cppname:"ChapterCountry",level:5,type:"s",multiple:true,minver:1,webm:false,description:"The countries corresponding to the string, same 2 octets as in Internet domains."}],[17276,{name:"ChapLanguage",cppname:"ChapterLanguage",level:5,type:"s",mandatory:true,multiple:true,minver:1,webm:true,default:"eng",description:"The languages corresponding to the string, in the bibliographic ISO-639-2 form."}],[143,{name:"ChapterTrack",level:4,type:"m",minver:1,webm:false,description:"List of tracks on which the chapter applies. If this element is not present, all tracks apply"}],[25539,{name:"ChapterPhysicalEquiv",level:4,type:"u",minver:1,webm:false,description:'Specify the physical equivalent of this ChapterAtom like "DVD" (60) or "SIDE" (50), see complete list of values.'}],[28348,{name:"ChapterSegmentEditionUID",level:4,type:"u",minver:1,webm:false,range:"not 0",description:"The EditionUID to play from the segment linked in ChapterSegmentUID."}],[28263,{name:"ChapterSegmentUID",level:4,type:"b",minver:1,webm:false,range:">0",bytesize:16,description:"A segment to play in place of this chapter. Edition ChapterSegmentEditionUID should be used for this segment, otherwise no edition is used."}],[29636,{name:"ChapterUID",level:4,type:"u",mandatory:true,minver:1,webm:true,range:"not 0",description:"A unique ID to identify the Chapter."}],[182,{name:"ChapterAtom",level:3,recursive:true,type:"m",mandatory:true,multiple:true,minver:1,webm:true,description:"Contains the atom information to use as the chapter atom (apply to all tracks)."}],[17885,{name:"EditionFlagOrdered",level:3,type:"u",minver:1,webm:false,default:0,range:"0-1",description:"Specify if the chapters can be defined multiple times and the order to play them is enforced. (1 bit)"}],[17883,{name:"EditionFlagDefault",level:3,type:"u",mandatory:true,minver:1,webm:false,default:0,range:"0-1",description:"If a flag is set (1) the edition should be used as the default one. (1 bit)"}],[17853,{name:"EditionFlagHidden",level:3,type:"u",mandatory:true,minver:1,webm:false,default:0,range:"0-1",description:"If an edition is hidden (1), it should not be available to the user interface (but still to Control Tracks; see flag notes). (1 bit)"}],[17852,{name:"EditionUID",level:3,type:"u",minver:1,webm:false,range:"not 0",description:"A unique ID to identify the edition. It's useful for tagging an edition."}],[17849,{name:"EditionEntry",level:2,type:"m",mandatory:true,multiple:true,minver:1,webm:true,description:"Contains all information about a segment edition."}],[272869232,{name:"Chapters",level:1,type:"m",minver:1,webm:true,description:"A system to define basic menus and partition data. For more detailed information, look at the Chapters Explanation."}],[18094,{name:"FileUID",level:3,type:"u",mandatory:true,minver:1,webm:false,range:"not 0",description:"Unique ID representing the file, as random as possible."}],[18012,{name:"FileData",level:3,type:"b",mandatory:true,minver:1,webm:false,description:"The data of the file."}],[18030,{name:"FileName",level:3,type:"8",mandatory:true,minver:1,webm:false,description:"Filename of the attached file."}],[18046,{name:"FileDescription",level:3,type:"8",minver:1,webm:false,description:"A human-friendly name for the attached file."}],[24999,{name:"AttachedFile",level:2,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"An attached file."}],[423732329,{name:"Attachments",level:1,type:"m",minver:1,webm:false,description:"Contain attached files."}],[235,{name:"CueRefCodecState",level:5,type:"u",webm:false,default:0,description:"The position of the Codec State corresponding to this referenced element. 0 means that the data is taken from the initial Track Entry."}],[21343,{name:"CueRefNumber",level:5,type:"u",webm:false,default:1,range:"not 0",description:"Number of the referenced Block of Track X in the specified Cluster."}],[219,{name:"CueReference",level:4,type:"m",multiple:true,minver:2,webm:false,description:"The Clusters containing the required referenced Blocks."}],[234,{name:"CueCodecState",level:4,type:"u",minver:2,webm:false,default:0,description:"The position of the Codec State corresponding to this Cue element. 0 means that the data is taken from the initial Track Entry."}],[178,{name:"CueDuration",level:4,type:"u",mandatory:false,minver:4,webm:false,description:"The duration of the block according to the segment time base. If missing the track's DefaultDuration does not apply and no duration information is available in terms of the cues."}],[240,{name:"CueRelativePosition",level:4,type:"u",mandatory:false,minver:4,webm:false,description:"The relative position of the referenced block inside the cluster with 0 being the first possible position for an element inside that cluster."}],[241,{name:"CueClusterPosition",level:4,type:"u",mandatory:true,minver:1,description:"The position of the Cluster containing the required Block."}],[247,{name:"CueTrack",level:4,type:"u",mandatory:true,minver:1,range:"not 0",description:"The track for which a position is given."}],[183,{name:"CueTrackPositions",level:3,type:"m",mandatory:true,multiple:true,minver:1,description:"Contain positions for different tracks corresponding to the timestamp."}],[179,{name:"CueTime",level:3,type:"u",mandatory:true,minver:1,description:"Absolute timestamp according to the segment time base."}],[187,{name:"CuePoint",level:2,type:"m",mandatory:true,multiple:true,minver:1,description:"Contains all information relative to a seek point in the segment."}],[475249515,{name:"Cues",level:1,type:"m",minver:1,description:'A top-level element to speed seeking access. All entries are local to the segment. Should be mandatory for non "live" streams.'}],[18406,{name:"ContentSigHashAlgo",level:6,type:"u",minver:1,webm:false,default:0,br:["",""],description:"The hash algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: 1 - SHA1-160 2 - MD5"}],[18405,{name:"ContentSigAlgo",level:6,type:"u",minver:1,webm:false,default:0,br:"",description:"The algorithm used for the signature. A value of '0' means that the contents have not been signed but only encrypted. Predefined values: 1 - RSA"}],[18404,{name:"ContentSigKeyID",level:6,type:"b",minver:1,webm:false,description:"This is the ID of the private key the data was signed with."}],[18403,{name:"ContentSignature",level:6,type:"b",minver:1,webm:false,description:"A cryptographic signature of the contents."}],[18402,{name:"ContentEncKeyID",level:6,type:"b",minver:1,webm:false,description:"For public key algorithms this is the ID of the public key the the data was encrypted with."}],[18401,{name:"ContentEncAlgo",level:6,type:"u",minver:1,webm:false,default:0,br:"",description:"The encryption algorithm used. The value '0' means that the contents have not been encrypted but only signed. Predefined values: 1 - DES, 2 - 3DES, 3 - Twofish, 4 - Blowfish, 5 - AES"}],[28032,{name:"ContentEncodings",level:3,type:"m",minver:1,webm:false,description:"Settings for several content encoding mechanisms like compression or encryption."}],[196,{name:"TrickMasterTrackSegmentUID",level:3,type:"b",divx:true,bytesize:16,description:"DivX trick track extenstions"}],[199,{name:"TrickMasterTrackUID",level:3,type:"u",divx:true,description:"DivX trick track extenstions"}],[198,{name:"TrickTrackFlag",level:3,type:"u",divx:true,default:0,description:"DivX trick track extenstions"}],[193,{name:"TrickTrackSegmentUID",level:3,type:"b",divx:true,bytesize:16,description:"DivX trick track extenstions"}],[192,{name:"TrickTrackUID",level:3,type:"u",divx:true,description:"DivX trick track extenstions"}],[237,{name:"TrackJoinUID",level:5,type:"u",mandatory:true,multiple:true,minver:3,webm:false,range:"not 0",description:"The trackUID number of a track whose blocks are used to create this virtual track."}],[233,{name:"TrackJoinBlocks",level:4,type:"m",minver:3,webm:false,description:"Contains the list of all tracks whose Blocks need to be combined to create this virtual track"}],[230,{name:"TrackPlaneType",level:6,type:"u",mandatory:true,minver:3,webm:false,description:"The kind of plane this track corresponds to (0: left eye, 1: right eye, 2: background)."}],[229,{name:"TrackPlaneUID",level:6,type:"u",mandatory:true,minver:3,webm:false,range:"not 0",description:"The trackUID number of the track representing the plane."}],[228,{name:"TrackPlane",level:5,type:"m",mandatory:true,multiple:true,minver:3,webm:false,description:"Contains a video plane track that need to be combined to create this 3D track"}],[227,{name:"TrackCombinePlanes",level:4,type:"m",minver:3,webm:false,description:"Contains the list of all video plane tracks that need to be combined to create this 3D track"}],[226,{name:"TrackOperation",level:3,type:"m",minver:3,webm:false,description:"Operation that needs to be applied on tracks to create this virtual track. For more details look at the Specification Notes on the subject."}],[32123,{name:"ChannelPositions",cppname:"AudioPosition",level:4,type:"b",webm:false,description:"Table of horizontal angles for each successive channel, see appendix."}],[159,{name:"Channels",cppname:"AudioChannels",level:4,type:"u",mandatory:true,minver:1,default:1,range:"not 0",description:"Numbers of channels in the track."}],[30901,{name:"OutputSamplingFrequency",cppname:"AudioOutputSamplingFreq",level:4,type:"f",minver:1,default:"Sampling Frequency",range:"> 0",description:"Real output sampling frequency in Hz (used for SBR techniques)."}],[181,{name:"SamplingFrequency",cppname:"AudioSamplingFreq",level:4,type:"f",mandatory:true,minver:1,default:"8000.0",range:"> 0",description:"Sampling frequency in Hz."}],[225,{name:"Audio",cppname:"TrackAudio",level:3,type:"m",minver:1,description:"Audio settings."}],[2327523,{name:"FrameRate",cppname:"VideoFrameRate",level:4,type:"f",range:"> 0",strong:"Informational",description:"Number of frames per second. only."}],[3126563,{name:"GammaValue",cppname:"VideoGamma",level:4,type:"f",webm:false,range:"> 0",description:"Gamma Value."}],[3061028,{name:"ColourSpace",cppname:"VideoColourSpace",level:4,type:"b",minver:1,webm:false,bytesize:4,description:"Same value as in AVI (32 bits)."}],[21683,{name:"AspectRatioType",cppname:"VideoAspectRatio",level:4,type:"u",minver:1,default:0,description:"Specify the possible modifications to the aspect ratio (0: free resizing, 1: keep aspect ratio, 2: fixed)."}],[21682,{name:"DisplayUnit",cppname:"VideoDisplayUnit",level:4,type:"u",minver:1,default:0,description:"How DisplayWidth & DisplayHeight should be interpreted (0: pixels, 1: centimeters, 2: inches, 3: Display Aspect Ratio)."}],[21690,{name:"DisplayHeight",cppname:"VideoDisplayHeight",level:4,type:"u",minver:1,default:"PixelHeight",range:"not 0",description:"Height of the video frames to display. The default value is only valid when DisplayUnit is 0."}],[21680,{name:"DisplayWidth",cppname:"VideoDisplayWidth",level:4,type:"u",minver:1,default:"PixelWidth",range:"not 0",description:"Width of the video frames to display. The default value is only valid when DisplayUnit is 0."}],[21725,{name:"PixelCropRight",cppname:"VideoPixelCropRight",level:4,type:"u",minver:1,default:0,description:"The number of video pixels to remove on the right of the image."}],[21708,{name:"PixelCropLeft",cppname:"VideoPixelCropLeft",level:4,type:"u",minver:1,default:0,description:"The number of video pixels to remove on the left of the image."}],[21691,{name:"PixelCropTop",cppname:"VideoPixelCropTop",level:4,type:"u",minver:1,default:0,description:"The number of video pixels to remove at the top of the image."}],[21674,{name:"PixelCropBottom",cppname:"VideoPixelCropBottom",level:4,type:"u",minver:1,default:0,description:"The number of video pixels to remove at the bottom of the image (for HDTV content)."}],[186,{name:"PixelHeight",cppname:"VideoPixelHeight",level:4,type:"u",mandatory:true,minver:1,range:"not 0",description:"Height of the encoded video frames in pixels."}],[176,{name:"PixelWidth",cppname:"VideoPixelWidth",level:4,type:"u",mandatory:true,minver:1,range:"not 0",description:"Width of the encoded video frames in pixels."}],[21433,{name:"OldStereoMode",level:4,type:"u",maxver:"0",webm:false,divx:false,description:"DEPRECATED, DO NOT USE. Bogus StereoMode value used in old versions of libmatroska. (0: mono, 1: right eye, 2: left eye, 3: both eyes)."}],[21440,{name:"AlphaMode",cppname:"VideoAlphaMode",level:4,type:"u",minver:3,webm:true,default:0,description:"Alpha Video Mode. Presence of this element indicates that the BlockAdditional element could contain Alpha data."}],[21432,{name:"StereoMode",cppname:"VideoStereoMode",level:4,type:"u",minver:3,webm:true,default:0,description:"Stereo-3D video mode (0: mono, 1: side by side (left eye is first), 2: top-bottom (right eye is first), 3: top-bottom (left eye is first), 4: checkboard (right is first), 5: checkboard (left is first), 6: row interleaved (right is first), 7: row interleaved (left is first), 8: column interleaved (right is first), 9: column interleaved (left is first), 10: anaglyph (cyan/red), 11: side by side (right eye is first), 12: anaglyph (green/magenta), 13 both eyes laced in one Block (left eye is first), 14 both eyes laced in one Block (right eye is first)) . There are some more details on 3D support in the Specification Notes."}],[154,{name:"FlagInterlaced",cppname:"VideoFlagInterlaced",level:4,type:"u",mandatory:true,minver:2,webm:true,default:0,range:"0-1",description:"Set if the video is interlaced. (1 bit)"}],[224,{name:"Video",cppname:"TrackVideo",level:3,type:"m",minver:1,description:"Video settings."}],[26277,{name:"TrackTranslateTrackID",level:4,type:"b",mandatory:true,minver:1,webm:false,description:"The binary value used to represent this track in the chapter codec data. The format depends on the ChapProcessCodecID used."}],[26303,{name:"TrackTranslateCodec",level:4,type:"u",mandatory:true,minver:1,webm:false,description:"The chapter codec using this ID (0: Matroska Script, 1: DVD-menu)."}],[26364,{name:"TrackTranslateEditionUID",level:4,type:"u",multiple:true,minver:1,webm:false,description:"Specify an edition UID on which this translation applies. When not specified, it means for all editions found in the segment."}],[22203,{name:"SeekPreRoll",level:3,type:"u",mandatory:true,multiple:false,default:0,minver:4,webm:true,description:"After a discontinuity, SeekPreRoll is the duration in nanoseconds of the data the decoder must decode before the decoded data is valid."}],[22186,{name:"CodecDelay",level:3,type:"u",multiple:false,default:0,minver:4,webm:true,description:"CodecDelay is The codec-built-in delay in nanoseconds. This value must be subtracted from each block timestamp in order to get the actual timestamp. The value should be small so the muxing of tracks with the same actual timestamp are in the same Cluster."}],[28587,{name:"TrackOverlay",level:3,type:"u",multiple:true,minver:1,webm:false,description:"Specify that this track is an overlay track for the Track specified (in the u-integer). That means when this track has a gap (see SilentTracks) the overlay track should be used instead. The order of multiple TrackOverlay matters, the first one is the one that should be used. If not found it should be the second, etc."}],[170,{name:"CodecDecodeAll",level:3,type:"u",mandatory:true,minver:2,webm:false,default:1,range:"0-1",description:"The codec can decode potentially damaged data (1 bit)."}],[2536e3,{name:"CodecDownloadURL",level:3,type:"s",multiple:true,webm:false,description:"A URL to download about the codec used."}],[3883072,{name:"CodecInfoURL",level:3,type:"s",multiple:true,webm:false,description:"A URL to find information about the codec used."}],[3839639,{name:"CodecSettings",level:3,type:"8",webm:false,description:"A string describing the encoding setting used."}],[25506,{name:"CodecPrivate",level:3,type:"b",minver:1,description:"Private data only known to the codec."}],[2274716,{name:"Language",cppname:"TrackLanguage",level:3,type:"s",minver:1,default:"eng",description:"Specifies the language of the track in the Matroska languages form."}],[21358,{name:"Name",cppname:"TrackName",level:3,type:"8",minver:1,description:"A human-readable track name."}],[21998,{name:"MaxBlockAdditionID",level:3,type:"u",mandatory:true,minver:1,webm:false,default:0,description:"The maximum value of BlockAdditions for this track."}],[21375,{name:"TrackOffset",level:3,type:"i",webm:false,default:0,description:"A value to add to the Block's Timestamp. This can be used to adjust the playback offset of a track."}],[2306383,{name:"TrackTimecodeScale",level:3,type:"f",mandatory:true,minver:1,maxver:"3",webm:false,default:"1.0",range:"> 0",description:"DEPRECATED, DO NOT USE. The scale to apply on this track to work at normal speed in relation with other tracks (mostly used to adjust video speed when the audio length differs)."}],[2313850,{name:"DefaultDecodedFieldDuration",cppname:"TrackDefaultDecodedFieldDuration",level:3,type:"u",minver:4,range:"not 0",description:"The period in nanoseconds (not scaled by TimcodeScale)\nbetween two successive fields at the output of the decoding process (see the notes)"}],[2352003,{name:"DefaultDuration",cppname:"TrackDefaultDuration",level:3,type:"u",minver:1,range:"not 0",description:"Number of nanoseconds (not scaled via TimecodeScale) per frame ('frame' in the Matroska sense -- one element put into a (Simple)Block)."}],[28152,{name:"MaxCache",cppname:"TrackMaxCache",level:3,type:"u",minver:1,webm:false,description:"The maximum cache size required to store referenced frames in and the current frame. 0 means no cache is needed."}],[28135,{name:"MinCache",cppname:"TrackMinCache",level:3,type:"u",mandatory:true,minver:1,webm:false,default:0,description:"The minimum number of frames a player should be able to cache during playback. If set to 0, the reference pseudo-cache system is not used."}],[156,{name:"FlagLacing",cppname:"TrackFlagLacing",level:3,type:"u",mandatory:true,minver:1,default:1,range:"0-1",description:"Set if the track may contain blocks using lacing. (1 bit)"}],[21930,{name:"FlagForced",cppname:"TrackFlagForced",level:3,type:"u",mandatory:true,minver:1,default:0,range:"0-1",description:"Set if that track MUST be active during playback. There can be many forced track for a kind (audio, video or subs), the player should select the one which language matches the user preference or the default + forced track. Overlay MAY happen between a forced and non-forced track of the same kind. (1 bit)"}],[185,{name:"FlagEnabled",cppname:"TrackFlagEnabled",level:3,type:"u",mandatory:true,minver:2,webm:true,default:1,range:"0-1",description:"Set if the track is usable. (1 bit)"}],[29637,{name:"TrackUID",level:3,type:"u",mandatory:true,minver:1,range:"not 0",description:"A unique ID to identify the Track. This should be kept the same when making a direct stream copy of the Track to another file."}],[215,{name:"TrackNumber",level:3,type:"u",mandatory:true,minver:1,range:"not 0",description:"The track number as used in the Block Header (using more than 127 tracks is not encouraged, though the design allows an unlimited number)."}],[174,{name:"TrackEntry",level:2,type:"m",mandatory:true,multiple:true,minver:1,description:"Describes a track with all elements."}],[374648427,{name:"Tracks",level:1,type:"m",multiple:true,minver:1,description:"A top-level block of information with many tracks described."}],[175,{name:"EncryptedBlock",level:2,type:"b",multiple:true,webm:false,description:"Similar to EncryptedBlock Structure)"}],[202,{name:"ReferenceTimeCode",level:4,type:"u",multiple:false,mandatory:true,minver:0,webm:false,divx:true,description:"DivX trick track extenstions"}],[201,{name:"ReferenceOffset",level:4,type:"u",multiple:false,mandatory:true,minver:0,webm:false,divx:true,description:"DivX trick track extenstions"}],[200,{name:"ReferenceFrame",level:3,type:"m",multiple:false,minver:0,webm:false,divx:true,description:"DivX trick track extenstions"}],[207,{name:"SliceDuration",level:5,type:"u",default:0,description:"The (scaled) duration to apply to the element."}],[206,{name:"Delay",cppname:"SliceDelay",level:5,type:"u",default:0,description:"The (scaled) delay to apply to the element."}],[203,{name:"BlockAdditionID",cppname:"SliceBlockAddID",level:5,type:"u",default:0,description:"The ID of the BlockAdditional element (0 is the main Block)."}],[205,{name:"FrameNumber",cppname:"SliceFrameNumber",level:5,type:"u",default:0,description:"The number of the frame to generate from this lace with this delay (allow you to generate many frames from the same Block/Frame)."}],[204,{name:"LaceNumber",cppname:"SliceLaceNumber",level:5,type:"u",minver:1,default:0,divx:false,description:"The reverse number of the frame in the lace (0 is the last frame, 1 is the next to last, etc). While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback."}],[232,{name:"TimeSlice",level:4,type:"m",multiple:true,minver:1,divx:false,description:"Contains extra time information about the data contained in the Block. While there are a few files in the wild with this element, it is no longer in use and has been deprecated. Being able to interpret this element is not required for playback."}],[142,{name:"Slices",level:3,type:"m",minver:1,divx:false,description:"Contains slices description."}],[30114,{name:"DiscardPadding",level:3,type:"i",minver:4,webm:true,description:"Duration in nanoseconds of the silent data added to the Block (padding at the end of the Block for positive value, at the beginning of the Block for negative value). The duration of DiscardPadding is not calculated in the duration of the TrackEntry and should be discarded during playback."}],[164,{name:"CodecState",level:3,type:"b",minver:2,webm:false,description:"The new codec state to use. Data interpretation is private to the codec. This information should always be referenced by a seek entry."}],[253,{name:"ReferenceVirtual",level:3,type:"i",webm:false,description:"Relative position of the data that should be in position of the virtual block."}],[251,{name:"ReferenceBlock",level:3,type:"i",multiple:true,minver:1,description:"Timestamp of another frame used as a reference (ie: B or P frame). The timestamp is relative to the block it's attached to."}],[250,{name:"ReferencePriority",cppname:"FlagReferenced",level:3,type:"u",mandatory:true,minver:1,webm:false,default:0,description:"This frame is referenced and has the specified cache priority. In cache only a frame of the same or higher priority can replace this frame. A value of 0 means the frame is not referenced."}],[155,{name:"BlockDuration",level:3,type:"u",minver:1,default:"TrackDuration",description:'The duration of the Block (based on TimecodeScale). This element is mandatory when DefaultDuration is set for the track (but can be omitted as other default values). When not written and with no DefaultDuration, the value is assumed to be the difference between the timestamp of this Block and the timestamp of the next Block in "display" order (not coding order). This element can be useful at the end of a Track (as there is not other Block available), or when there is a break in a track like for subtitle tracks. When set to 0 that means the frame is not a keyframe.'}],[165,{name:"BlockAdditional",level:5,type:"b",mandatory:true,minver:1,webm:false,description:"Interpreted by the codec as it wishes (using the BlockAddID)."}],[238,{name:"BlockAddID",level:5,type:"u",mandatory:true,minver:1,webm:false,default:1,range:"not 0",description:"An ID to identify the BlockAdditional level."}],[166,{name:"BlockMore",level:4,type:"m",mandatory:true,multiple:true,minver:1,webm:false,description:"Contain the BlockAdditional and some parameters."}],[30113,{name:"BlockAdditions",level:3,type:"m",minver:1,webm:false,description:"Contain additional blocks to complete the main one. An EBML parser that has no knowledge of the Block structure could still see and use/skip these data."}],[162,{name:"BlockVirtual",level:3,type:"b",webm:false,description:"A Block with no data. It must be stored in the stream at the place the real Block should be in display order. (see Block Virtual)"}],[161,{name:"Block",level:3,type:"b",mandatory:true,minver:1,description:"Block containing the actual data to be rendered and a timestamp relative to the Cluster Timecode. (see Block Structure)"}],[160,{name:"BlockGroup",level:2,type:"m",multiple:true,minver:1,description:"Basic container of information containing a single Block or BlockVirtual, and information specific to that Block/VirtualBlock."}],[163,{name:"SimpleBlock",level:2,type:"b",multiple:true,minver:2,webm:true,divx:true,description:"Similar to SimpleBlock Structure)"}],[171,{name:"PrevSize",cppname:"ClusterPrevSize",level:2,type:"u",minver:1,description:"Size of the previous Cluster, in octets. Can be useful for backward playing."}],[167,{name:"Position",cppname:"ClusterPosition",level:2,type:"u",minver:1,webm:false,description:"The Position of the Cluster in the segment (0 in live broadcast streams). It might help to resynchronise offset on damaged streams."}],[22743,{name:"SilentTrackNumber",cppname:"ClusterSilentTrackNumber",level:3,type:"u",multiple:true,minver:1,webm:false,description:"One of the track number that are not used from now on in the stream. It could change later if not specified as silent in a further Cluster."}],[231,{name:"Timecode",cppname:"ClusterTimecode",level:2,type:"u",mandatory:true,minver:1,description:"Absolute timestamp of the cluster (based on TimecodeScale)."}],[524531317,{name:"Cluster",level:1,type:"m",multiple:true,minver:1,description:"The lower level element containing the (monolithic) Block structure."}],[19840,{name:"MuxingApp",level:2,type:"8",mandatory:true,minver:1,description:'Muxing application or library ("libmatroska-0.4.3").'}],[31657,{name:"Title",level:2,type:"8",minver:1,webm:false,description:"General name of the segment."}],[2807730,{name:"TimecodeScaleDenominator",level:2,type:"u",mandatory:true,minver:4,default:1e9,description:"Timestamp scale numerator, see TimecodeScale."}],[2807729,{name:"TimecodeScale",level:2,type:"u",mandatory:true,minver:1,default:1e6,description:"Timestamp scale in nanoseconds (1.000.000 means all timestamps in the segment are expressed in milliseconds)."}],[27045,{name:"ChapterTranslateID",level:3,type:"b",mandatory:true,minver:1,webm:false,description:"The binary value used to represent this segment in the chapter codec data. The format depends on the ChapProcessCodecID used."}],[27071,{name:"ChapterTranslateCodec",level:3,type:"u",mandatory:true,minver:1,webm:false,description:"The chapter codec using this ID (0: Matroska Script, 1: DVD-menu)."}],[27132,{name:"ChapterTranslateEditionUID",level:3,type:"u",multiple:true,minver:1,webm:false,description:"Specify an edition UID on which this correspondance applies. When not specified, it means for all editions found in the segment."}],[4096955,{name:"NextFilename",level:2,type:"8",minver:1,webm:false,description:"An escaped filename corresponding to the next segment."}],[4110627,{name:"NextUID",level:2,type:"b",minver:1,webm:false,bytesize:16,description:"A unique ID to identify the next chained segment (128 bits)."}],[3965867,{name:"PrevFilename",level:2,type:"8",minver:1,webm:false,description:"An escaped filename corresponding to the previous segment."}],[3979555,{name:"PrevUID",level:2,type:"b",minver:1,webm:false,bytesize:16,description:"A unique ID to identify the previous chained segment (128 bits)."}],[29604,{name:"SegmentUID",level:2,type:"b",minver:1,webm:false,range:"not 0",bytesize:16,description:"A randomly generated unique ID to identify the current segment between many others (128 bits)."}],[357149030,{name:"Info",level:1,type:"m",mandatory:true,multiple:true,minver:1,description:"Contains miscellaneous general information and statistics on the file."}],[21420,{name:"SeekPosition",level:3,type:"u",mandatory:true,minver:1,description:"The position of the element in the segment in octets (0 = first level 1 element)."}],[21419,{name:"SeekID",level:3,type:"b",mandatory:true,minver:1,description:"The binary ID corresponding to the element name."}],[19899,{name:"Seek",cppname:"SeekPoint",level:2,type:"m",mandatory:true,multiple:true,minver:1,description:"Contains a single seek entry to an EBML element."}],[290298740,{name:"SeekHead",cppname:"SeekHeader",level:1,type:"m",multiple:true,minver:1,description:"Contains the position of other level 1 elements."}],[32379,{name:"SignatureElementList",level:2,type:"m",multiple:true,webm:false,i:"Cluster|Block|BlockAdditional",description:"A list consists of a number of consecutive elements that represent one case where data is used in signature. Ex: means that the BlockAdditional of all Blocks in all Clusters is used for encryption."}],[32347,{name:"SignatureElements",level:1,type:"m",webm:false,description:"Contains elements that will be used to compute the signature."}],[32437,{name:"Signature",level:1,type:"b",webm:false,description:"The signature of the data (until a new."}],[32421,{name:"SignaturePublicKey",level:1,type:"b",webm:false,description:"The public key to use with the algorithm (in the case of a PKI-based signature)."}],[32410,{name:"SignatureHash",level:1,type:"u",webm:false,description:"Hash algorithm used (1=SHA1-160, 2=MD5)."}],[32394,{name:"SignatureAlgo",level:1,type:"u",webm:false,description:"Signature algorithm used (1=RSA, 2=elliptic)."}],[458458727,{name:"SignatureSlot",level:-1,type:"m",multiple:true,webm:false,description:"Contain signature of some (coming) elements in the stream."}],[191,{name:"CRC-32",level:-1,type:"b",minver:1,webm:false,description:"The CRC is computed on all the data of the Master element it's in. The CRC element should be the first in it's parent master for easier reading. All level 1 elements should include a CRC-32. The CRC in use is the IEEE CRC32 Little Endian"}],[236,{name:"Void",level:-1,type:"b",minver:1,description:"Used to void damaged data, to avoid unexpected behaviors when using damaged data. The content is discarded. Also used to reserve space in a sub-element for later use."}],[17139,{name:"EBMLMaxSizeLength",level:1,type:"u",mandatory:true,default:8,minver:1,description:"The maximum length of the sizes you'll find in this file (8 or less in Matroska). This does not override the element size indicated at the beginning of an element. Elements that have an indicated size which is larger than what is allowed by EBMLMaxSizeLength shall be considered invalid."}],[17138,{name:"EBMLMaxIDLength",level:1,type:"u",mandatory:true,default:4,minver:1,description:"The maximum length of the IDs you'll find in this file (4 or less in Matroska)."}],[17143,{name:"EBMLReadVersion",level:1,type:"u",mandatory:true,default:1,minver:1,description:"The minimum EBML version a parser has to support to read this file."}],[440786851,{name:"EBML",level:0,type:"m",mandatory:true,multiple:true,minver:1,description:"Set the EBML characteristics of the data to follow. Each EBML document has to start with this."}]]);var floor$1=Math.floor;var _isInteger=function isInteger(it){return!_isObject(it)&&isFinite(it)&&floor$1(it)===it};_export(_export.S,"Number",{isInteger:_isInteger});var $parseInt=_global.parseInt;var $trim$1=_stringTrim.trim;var hex=/^[-+]?0[xX]/;var _parseInt=$parseInt(_stringWs+"08")!==8||$parseInt(_stringWs+"0x16")!==22?function parseInt(str,radix){var string=$trim$1(String(str),3);return $parseInt(string,radix>>>0||(hex.test(string)?16:10))}:$parseInt;_export(_export.S+_export.F*(Number.parseInt!=_parseInt),"Number",{parseInt:_parseInt});var domain;function EventHandlers(){}EventHandlers.prototype=Object.create(null);function EventEmitter(){EventEmitter.init.call(this)}EventEmitter.EventEmitter=EventEmitter;EventEmitter.usingDomains=false;EventEmitter.prototype.domain=undefined;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.init=function(){this.domain=null;if(EventEmitter.usingDomains){if(domain.active&&!(this instanceof domain.Domain));}if(!this._events||this._events===Object.getPrototypeOf(this)._events){this._events=new EventHandlers;this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||isNaN(n))throw new TypeError('"n" argument must be a positive number');this._maxListeners=n;return this};function $getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return $getMaxListeners(this)};function emitNone(handler,isFn,self){if(isFn)handler.call(self);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i0&&existing.length>m){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+type+" listeners added. "+"Use emitter.setMaxListeners() to increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;emitWarning(w)}}}return target}function emitWarning(e){typeof console.warn==="function"?console.warn(e):console.log(e)}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function _onceWrap(target,type,listener){var fired=false;function g(){target.removeListener(type,g);if(!fired){fired=true;listener.apply(target,arguments)}}g.listener=listener;return g}EventEmitter.prototype.once=function once(type,listener){if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;if(typeof listener!=="function")throw new TypeError('"listener" argument must be a function');events=this._events;if(!events)return this;list=events[type];if(!list)return this;if(list===listener||list.listener&&list.listener===listener){if(--this._eventsCount===0)this._events=new EventHandlers;else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(list.length===1){list[0]=undefined;if(--this._eventsCount===0){this._events=new EventHandlers;return this}else{delete events[type]}}else{spliceOne(list,position)}if(events.removeListener)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events;events=this._events;if(!events)return this;if(!events.removeListener){if(arguments.length===0){this._events=new EventHandlers;this._eventsCount=0}else if(events[type]){if(--this._eventsCount===0)this._events=new EventHandlers;else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);for(var i=0,key;i0?Reflect.ownKeys(this._events):[]};function spliceOne(list,index){for(var i=index,k=i+1,n=list.length;k1){for(var i=1;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=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){_extend(ctx,opts)}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)}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]};inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+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){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}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=["{","}"];if(isArray$1(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}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");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-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 length=output.reduce(function(prev,cur){if(cur.indexOf("\n")>=0);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]}function isArray$1(ar){return Array.isArray(ar)}function isBoolean(arg){return typeof arg==="boolean"}function isNull(arg){return arg===null}function isNumber(arg){return typeof arg==="number"}function isString(arg){return typeof arg==="string"}function isUndefined(arg){return arg===void 0}function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}function isFunction(arg){return typeof arg==="function"}function objectToString(o){return Object.prototype.toString.call(o)}function _extend(origin,add){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$1(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}function BufferList(){this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function(v){var entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return Buffer.alloc(0);if(this.length===1)return this.head.data;var ret=Buffer.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret};var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}function StringDecoder(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0}StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}Readable.ReadableState=ReadableState;var debug=debuglog("stream");inherits$1(Readable,EventEmitter);function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function"){return emitter.prependListener(event,fn)}else{if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(Array.isArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}}function listenerCount$1(emitter,type){return emitter.listeners(type).length}function ReadableState(options,stream){options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.readableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.buffer=new BufferList;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;if(options&&typeof options.read==="function")this._read=options.read;EventEmitter.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(!state.objectMode&&typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=Buffer.from(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};Readable.prototype.isPaused=function(){return this._readableState.flowing===false};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null){state.reading=false;onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)nextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;nextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(listenerCount$1(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&src.listeners("data").length){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var _i=0;_i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;nextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=Buffer.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,EbmlDecoder);_this=_possibleConstructorReturn(this,_getPrototypeOf(EbmlDecoder).call(this,_objectSpread({},options,{readableObjectMode:true})));_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)),"mBuffer",null);_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)),"mTagStack",[]);_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)),"mState",STATE_TAG);_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)),"mCursor",0);_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)),"mTotal",0);return _this}_createClass(EbmlDecoder,[{key:"_transform",value:function _transform(chunk,enc,done){if(!this.buffer){this.buffer=Buffer.from(chunk)}else{this.buffer=Tools.concatenate(this.buffer,Buffer.from(chunk))}while(this.cursor=this.buffer.length){if(debug$1.enabled){debug$1("waiting for more data")}return false}var start=this.total;var tag=Tools.readVint(this.buffer,this.cursor);if(tag==null){if(debug$1.enabled){debug$1("waiting for more data")}return false}var tagStr=Tools.readHexString(this.buffer,this.cursor,this.cursor+tag.length);var tagNum=Number.parseInt(tagStr,16);this.cursor+=tag.length;this.total+=tag.length;this.state=STATE_SIZE;var tagObj={tag:tag.value,tagStr:tagStr,type:EbmlDecoder.getSchemaInfo(tagNum).type,name:EbmlDecoder.getSchemaInfo(tagNum).name,start:start,end:start+tag.length};this.tagStack.push(tagObj);if(debug$1.enabled){debug$1("read tag: ".concat(tagStr))}return true}},{key:"readSize",value:function readSize(){var tagObj=this.tagStack[this.tagStack.length-1];if(debug$1.enabled){debug$1("parsing size for tag: ".concat(tagObj.tagStr))}if(this.cursor>=this.buffer.length){if(debug$1.enabled){debug$1("waiting for more data")}return false}var size=Tools.readVint(this.buffer,this.cursor);if(size==null){if(debug$1.enabled){debug$1("waiting for more data")}return false}this.cursor+=size.length;this.total+=size.length;this.state=STATE_CONTENT;tagObj.dataSize=size.value;if(size.value===-1){tagObj.end=-1}else{tagObj.end+=size.value+size.length}if(debug$1.enabled){debug$1("read size: ".concat(size.value))}return true}},{key:"readContent",value:function readContent(){var _this$tagStack=this.tagStack[this.tagStack.length-1],tagStr=_this$tagStack.tagStr,type=_this$tagStack.type,dataSize=_this$tagStack.dataSize,rest=_objectWithoutProperties(_this$tagStack,["tagStr","type","dataSize"]);if(debug$1.enabled){debug$1("parsing content for tag: ".concat(tagStr))}if(type==="m"){if(debug$1.enabled){debug$1("content should be tags")}this.push(["start",_objectSpread({tagStr:tagStr,type:type,dataSize:dataSize},rest)]);this.state=STATE_TAG;return true}if(this.buffer.length0){var topEle=this.tagStack[this.tagStack.length-1];if(this.totalindex;index++)if(NO_HOLES||index in self){val=self[index];res=f(val,index,O);if(TYPE){if(IS_MAP)result[index]=res;else if(res)switch(TYPE){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(IS_EVERY)return false}}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:result}};var $find=_arrayMethods(5);var KEY="find";var forced=true;if(KEY in[])Array(1)[KEY](function(){forced=false});_export(_export.P+_export.F*forced,"Array",{find:function find(callbackfn){return $find(this,callbackfn,arguments.length>1?arguments[1]:undefined)}});_addToUnscopables(KEY);var buffers=Buffers;function Buffers(bufs){if(!(this instanceof Buffers))return new Buffers(bufs);this.buffers=bufs||[];this.length=this.buffers.reduce(function(size,buf){return size+buf.length},0)}Buffers.prototype.push=function(){for(var i=0;i=0?i:this.length-i;var reps=[].slice.call(arguments,2);if(howMany===undefined){howMany=this.length-index}else if(howMany>this.length-index){howMany=this.length-index}for(var i=0;i0){var start=index-startBytes;if(start+howMany0){var reps_=reps.slice();reps_.unshift(buf0);reps_.push(buf1);buffers.splice.apply(buffers,[ii,1].concat(reps_));ii+=reps_.length;reps=[]}else{buffers.splice(ii,1,buf0,buf1);ii+=2}}else{removed.push(buffers[ii].slice(start));buffers[ii]=buffers[ii].slice(0,start);ii++}}if(reps.length>0){buffers.splice.apply(buffers,[ii,0].concat(reps));ii+=reps.length}while(removed.lengththis.length)j=this.length;var startBytes=0;for(var si=0;si=j-i?Math.min(start+(j-i)-ti,len):len;buffers[ii].copy(target,ti,start,end);ti+=end-start}return target};Buffers.prototype.pos=function(i){if(i<0||i>=this.length)throw new Error("oob");var l=i,bi=0,bu=null;for(;;){bu=this.buffers[bi];if(l=this.buffers[i].length){j=0;i++;if(i>=this.buffers.length){return-1}}var char=this.buffers[i][j];if(char==needle[match]){if(match==0){mstart={i:i,j:j,pos:pos}}match++;if(match==needle.length){return mstart.pos}}else if(match!=0){i=mstart.i;j=mstart.j;pos=mstart.pos;match=0}j++;pos++}};Buffers.prototype.toBuffer=function(){return this.slice()};Buffers.prototype.toString=function(encoding,start,end){return this.slice(start,end).toString(encoding)};var debug$2=require("debug")("ebml:encoder");function encodeTag(tagId,tagData,end){if(end===-1){return buffers([tagId,Buffer.from("01ffffffffffffff","hex"),tagData])}return buffers([tagId,Tools.writeVint(tagData.length),tagData])}var EbmlEncoder=function(_Transform){_inherits(EbmlEncoder,_Transform);function EbmlEncoder(){var _this;var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,EbmlEncoder);_this=_possibleConstructorReturn(this,_getPrototypeOf(EbmlEncoder).call(this,_objectSpread({},options,{writableObjectMode:true})));_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)),"mBuffer",null);_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)),"mCorked",false);_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)),"mStack",[]);return _this}_createClass(EbmlEncoder,[{key:"_transform",value:function _transform(chunk,enc,done){var _chunk=_slicedToArray(chunk,2),tag=_chunk[0],_chunk$=_chunk[1],data=_chunk$.data,name=_chunk$.name,rest=_objectWithoutProperties(_chunk$,["data","name"]);if(debug$2.enabled){debug$2("encode ".concat(tag," ").concat(name))}switch(tag){case"start":this.startTag(name,_objectSpread({name:name,data:data},rest));break;case"tag":this.writeTag(name,data);break;case"end":this.endTag();break;default:break}done()}},{key:"flush",value:function flush(){var done=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){};if(!this.buffer||this.corked){if(debug$2.enabled){debug$2("no buffer/nothing pending")}done();return}if(debug$2.enabled){debug$2("writing ".concat(this.buffer.length," bytes"))}var chunk=Buffer.from(this.buffer);this.buffer=null;this.push(chunk);done()}},{key:"bufferAndFlush",value:function bufferAndFlush(buffer){if(this.buffer){this.buffer=Tools.concatenate(this.buffer,buffer)}else{this.buffer=buffers(buffer)}this.flush()}},{key:"_flush",value:function _flush(){var done=arguments.length>0&&arguments[0]!==undefined?arguments[0]:function(){};this.flush(done)}},{key:"_bufferAndFlush",value:function _bufferAndFlush(buffer){this.bufferAndFlush(buffer)}},{key:"cork",value:function cork(){this.corked=true}},{key:"uncork",value:function uncork(){this.corked=false;this.flush()}},{key:"writeTag",value:function writeTag(tagName,tagData){var tagId=EbmlEncoder.getSchemaInfo(tagName);if(!tagId){throw new Error("No schema entry found for ".concat(tagName))}if(tagData){var data=encodeTag(tagId,tagData);if(this.stack.length>0){this.stack[this.stack.length-1].children.push({data:data})}else{this.bufferAndFlush(data.buffer)}}}},{key:"startTag",value:function startTag(tagName,_ref){var end=_ref.end;var tagId=EbmlEncoder.getSchemaInfo(tagName);if(!tagId){throw new Error("No schema entry found for ".concat(tagName))}var tag={data:null,id:tagId,name:tagName,end:end,children:[]};if(this.stack.length>0){this.stack[this.stack.length-1].children.push(tag)}this.stack.push(tag)}},{key:"endTag",value:function endTag(){var tag=this.stack.pop();var childTagDataBuffers=tag.children.map(function(child){return child.data});tag.data=encodeTag(tag.id,buffers(childTagDataBuffers),tag.end);if(this.stack.length<1){this.bufferAndFlush(tag.data.buffer)}this.end()}},{key:"buffer",get:function get(){return this.mBuffer},set:function set(buffer){this.mBuffer=buffer}},{key:"corked",get:function get(){return this.mCorked},set:function set(corked){this.mCorked=corked}},{key:"stack",get:function get(){return this.mStack},set:function set(stak){this.mStack=stak}}],[{key:"getSchemaInfo",value:function getSchemaInfo(tagName){var tagId=Array.from(schema.keys()).find(function(str){return schema.get(str).name===tagName});if(tagId){return tagId}return null}}]);return EbmlEncoder}(Transform);exports.tools=Tools;exports.schema=schema;exports.Decoder=EbmlDecoder;exports.Encoder=EbmlEncoder}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{buffer:9,debug:14}],14:[function(require,module,exports){(function(process){(function(){exports=module.exports=require("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:localstorage();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&window.process.type==="renderer"){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}};function formatArgs(args){var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return;var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0;var lastC=0;args[0].replace(/%[a-zA-Z%]/g,function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c)}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){exports.storage.removeItem("debug")}else{exports.storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=exports.storage.debug}catch(e){}if(!r&&typeof process!=="undefined"&&"env"in process){r=process.env.DEBUG}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}}).call(this)}).call(this,require("_process"))},{"./debug":15,_process:21}],15:[function(require,module,exports){exports=module.exports=createDebug.debug=createDebug["default"]=createDebug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.instances=[];exports.names=[];exports.skips=[];exports.formatters={};function selectColor(namespace){var hash=0,i;for(i in namespace){hash=(hash<<5)-hash+namespace.charCodeAt(i);hash|=0}return exports.colors[Math.abs(hash)%exports.colors.length]}function createDebug(namespace){var prevTime;function debug(){if(!debug.enabled)return;var self=debug;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;var args=new Array(arguments.length);for(var i=0;i0){return parse(val)}else if(type==="number"&&isNaN(val)===false){return options.long?fmtLong(val):fmtShort(val)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse(str){str=String(str);if(str.length>100){return}var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(!match){return}var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return undefined}}function fmtShort(ms){if(ms>=d){return Math.round(ms/d)+"d"}if(ms>=h){return Math.round(ms/h)+"h"}if(ms>=m){return Math.round(ms/m)+"m"}if(ms>=s){return Math.round(ms/s)+"s"}return ms+"ms"}function fmtLong(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],19:[function(require,module,exports){(function(Buffer){(function(){var Uint64BE,Int64BE,Uint64LE,Int64LE;!function(exports){var UNDEFINED="undefined";var BUFFER=UNDEFINED!==typeof Buffer&&Buffer;var UINT8ARRAY=UNDEFINED!==typeof Uint8Array&&Uint8Array;var ARRAYBUFFER=UNDEFINED!==typeof ArrayBuffer&&ArrayBuffer;var ZERO=[0,0,0,0,0,0,0,0];var isArray=Array.isArray||_isArray;var BIT32=4294967296;var BIT24=16777216;var storage;Uint64BE=factory("Uint64BE",true,true);Int64BE=factory("Int64BE",true,false);Uint64LE=factory("Uint64LE",false,true);Int64LE=factory("Int64LE",false,false);function factory(name,bigendian,unsigned){var posH=bigendian?0:4;var posL=bigendian?4:0;var pos0=bigendian?0:3;var pos1=bigendian?1:2;var pos2=bigendian?2:1;var pos3=bigendian?3:0;var fromPositive=bigendian?fromPositiveBE:fromPositiveLE;var fromNegative=bigendian?fromNegativeBE:fromNegativeLE;var proto=Int64.prototype;var isName="is"+name;var _isInt64="_"+isName;proto.buffer=void 0;proto.offset=0;proto[_isInt64]=true;proto.toNumber=toNumber;proto.toString=toString;proto.toJSON=toNumber;proto.toArray=toArray;if(BUFFER)proto.toBuffer=toBuffer;if(UINT8ARRAY)proto.toArrayBuffer=toArrayBuffer;Int64[isName]=isInt64;exports[name]=Int64;return Int64;function Int64(buffer,offset,value,raddix){if(!(this instanceof Int64))return new Int64(buffer,offset,value,raddix);return init(this,buffer,offset,value,raddix)}function isInt64(b){return!!(b&&b[_isInt64])}function init(that,buffer,offset,value,raddix){if(UINT8ARRAY&&ARRAYBUFFER){if(buffer instanceof ARRAYBUFFER)buffer=new UINT8ARRAY(buffer);if(value instanceof ARRAYBUFFER)value=new UINT8ARRAY(value)}if(!buffer&&!offset&&!value&&!storage){that.buffer=newArray(ZERO,0);return}if(!isValidBuffer(buffer,offset)){var _storage=storage||Array;raddix=offset;value=buffer;offset=0;buffer=storage===BUFFER?BUFFER.alloc(8):new _storage(8)}that.buffer=buffer;that.offset=offset|=0;if(UNDEFINED===typeof value)return;if("string"===typeof value){fromString(buffer,offset,value,raddix||10)}else if(isValidBuffer(value,raddix)){fromArray(buffer,offset,value,raddix)}else if("number"===typeof raddix){writeInt32(buffer,offset+posH,value);writeInt32(buffer,offset+posL,raddix)}else if(value>0){fromPositive(buffer,offset,value)}else if(value<0){fromNegative(buffer,offset,value)}else{fromArray(buffer,offset,ZERO,0)}}function fromString(buffer,offset,str,raddix){var pos=0;var len=str.length;var high=0;var low=0;if(str[0]==="-")pos++;var sign=pos;while(pos=0))break;low=low*raddix+chr;high=high*raddix+Math.floor(low/BIT32);low%=BIT32}if(sign){high=~high;if(low){low=BIT32-low}else{high++}}writeInt32(buffer,offset+posH,high);writeInt32(buffer,offset+posL,low)}function toNumber(){var buffer=this.buffer;var offset=this.offset;var high=readInt32(buffer,offset+posH);var low=readInt32(buffer,offset+posL);if(!unsigned)high|=0;return high?high*BIT32+low:low}function toString(radix){var buffer=this.buffer;var offset=this.offset;var high=readInt32(buffer,offset+posH);var low=readInt32(buffer,offset+posL);var str="";var sign=!unsigned&&high&2147483648;if(sign){high=~high;low=BIT32-low}radix=radix||10;while(1){var mod=high%radix*BIT32+low;high=Math.floor(high/radix);low=Math.floor(mod/radix);str=(mod%radix).toString(radix)+str;if(!high&&!low)break}if(sign){str="-"+str}return str}function writeInt32(buffer,offset,value){buffer[offset+pos3]=value&255;value=value>>8;buffer[offset+pos2]=value&255;value=value>>8;buffer[offset+pos1]=value&255;value=value>>8;buffer[offset+pos0]=value&255}function readInt32(buffer,offset){return buffer[offset+pos0]*BIT24+(buffer[offset+pos1]<<16)+(buffer[offset+pos2]<<8)+buffer[offset+pos3]}}function toArray(raw){var buffer=this.buffer;var offset=this.offset;storage=null;if(raw!==false&&isArray(buffer)){return buffer.length===8?buffer:buffer.slice(offset,offset+8)}return newArray(buffer,offset)}function toBuffer(raw){var buffer=this.buffer;var offset=this.offset;storage=BUFFER;if(raw!==false&&BUFFER.isBuffer(buffer)){return buffer.length===8?buffer:buffer.slice(offset,offset+8)}return BUFFER.from(toArrayBuffer.call(this,raw))}function toArrayBuffer(raw){var buffer=this.buffer;var offset=this.offset;var arrbuf=buffer.buffer;storage=UINT8ARRAY;if(raw!==false&&!buffer.offset&&arrbuf instanceof ARRAYBUFFER){return arrbuf.byteLength===8?arrbuf:arrbuf.slice(offset,offset+8)}var dest=new UINT8ARRAY(8);fromArray(dest,0,buffer,offset);return dest.buffer}function isValidBuffer(buffer,offset){var len=buffer&&buffer.length;offset|=0;return len&&offset+8<=len&&"string"!==typeof buffer[offset]}function fromArray(destbuf,destoff,srcbuf,srcoff){destoff|=0;srcoff|=0;for(var i=0;i<8;i++){destbuf[destoff++]=srcbuf[srcoff++]&255}}function newArray(buffer,offset){return Array.prototype.slice.call(buffer,offset,offset+8)}function fromPositiveBE(buffer,offset,value){var pos=offset+8;while(pos>offset){buffer[--pos]=value&255;value/=256}}function fromNegativeBE(buffer,offset,value){var pos=offset+8;value++;while(pos>offset){buffer[--pos]=-value&255^255;value/=256}}function fromPositiveLE(buffer,offset,value){var end=offset+8;while(offset