diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 60a5d349..aaf9c998 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,7 @@ Personal support issues **are not allowed** on the issue tracker, so please seek ## Issue tracker -The [issue tracker](https://www.github.com/gopro/gopro-forgejs-src/issues) is the best place to report a bug, suggest a new feature for the player, request documentation (support) and contribute with code to the project. Please make sure to check the following guide on how to use the issue tracker : +The [issue tracker](https://github.com/gopro/forgejs/issues) is the best place to report a bug, suggest a new feature for the player, request documentation (support) and contribute with code to the project. Please make sure to check the following guide on how to use the issue tracker : ### Reporting a bug diff --git a/Gruntfile.js b/Gruntfile.js index 45dc6e62..4e4117ce 100755 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -34,6 +34,8 @@ module.exports = function(grunt) "src/media/MediaType.js", "src/media/MediaFormat.js", + "src/media/MediaStore.js", + "src/media/MediaTexture.js", "src/media/Media.js", "src/render/RenderManager.js", @@ -45,6 +47,7 @@ module.exports = function(grunt) "src/render/background/BackgroundRenderer.js", "src/render/background/BackgroundType.js", "src/render/background/BackgroundMeshRenderer.js", + "src/render/background/BackgroundPyramidRenderer.js", "src/render/background/BackgroundShaderRenderer.js", "src/render/postProcessing/PostProcessing.js", @@ -78,14 +81,17 @@ module.exports = function(grunt) "src/3d/Raycaster.js", "src/3d/PickingDrawPass.js", "src/3d/PickingManager.js", + "src/3d/Tile.js", "src/hotspots/HotspotManager.js", + "src/hotspots/HotspotDOM.js", "src/hotspots/Hotspot3D.js", "src/hotspots/HotspotSound.js", "src/hotspots/HotspotMaterial.js", "src/hotspots/HotspotGeometry.js", "src/hotspots/HotspotGeometryType.js", "src/hotspots/HotspotTransform.js", + "src/hotspots/HotspotTransformValues.js", "src/hotspots/HotspotAnimation.js", "src/hotspots/HotspotAnimationTrack.js", "src/hotspots/HotspotStates.js", @@ -101,6 +107,7 @@ module.exports = function(grunt) "src/controllers/ControllerPointer.js", "src/controllers/ControllerKeyboard.js", "src/controllers/ControllerGyroscope.js", + "src/controllers/ControllerGamepad.js", "src/audio/SoundManager.js", "src/audio/SoundType.js", @@ -131,11 +138,16 @@ module.exports = function(grunt) "src/i18n/LocaleString.js", "src/i18n/Locale.js", + "src/input/binding/BaseBinding.js", + "src/input/binding/KeyBinding.js", + "src/input/binding/ButtonBinding.js", + "src/input/binding/AxisBinding.js", "src/input/Keyboard.js", - "src/input/KeyBinding.js", "src/input/Drag.js", "src/input/Pointer.js", "src/input/Gyroscope.js", + "src/input/GamepadsManager.js", + "src/input/Gamepad.js", "src/display/DisplayList.js", "src/display/DisplayObject.js", @@ -164,7 +176,6 @@ module.exports = function(grunt) "src/loader/Cache.js", "src/loader/File.js", "src/loader/Loader.js", - "src/loader/DependencyManager.js", "src/time/Clock.js", "src/time/Timer.js", @@ -187,7 +198,7 @@ module.exports = function(grunt) //The same array excluding FORGE.js for jshint var sourceFilesForJSHint = sourceFiles.slice(1); - var threeVersion = "83"; + var threeVersion = "86"; var customThree = [ @@ -312,20 +323,6 @@ module.exports = function(grunt) ] }, - karma: - { - files: - [ - { - expand: true, - flatten: false, - cwd: "tools/karma/fixtures/json/", - src: "*.json", - dest: "tools/karma/fixtures/json/min/" - } - ] - }, - doc: { files: @@ -438,14 +435,6 @@ module.exports = function(grunt) } }, - "json-minify": - { - karma: - { - files: "tools/karma/fixtures/json/min/*.json" - } - }, - jshint: { beforeconcat: sourceFilesForJSHint, @@ -517,16 +506,17 @@ module.exports = function(grunt) karma: { - watch: + run: { - configFile: "tools/karma/karma.conf.js", + configFile: "test/karma.conf.js", autoWatch: false, - background: true + background: false, + singleRun: true }, - standalone: + watch: { - configFile: "tools/karma/karma.conf.js", + configFile: "test/karma.conf.js", autoWatch: true, background: false } @@ -534,19 +524,6 @@ module.exports = function(grunt) watch: { - karma: - { - files: - [ - "src/**/*.js", - "tools/karma/tests/*.js", - "tools/karma/fixtures/html/*.html", - "tools/karma/fixtures/json/*.json" - ], - - tasks: ["clear", "clean:karma", "copy:karma", "json-minify:karma", "karma:watch:run"], - }, - build: { files: @@ -678,13 +655,12 @@ module.exports = function(grunt) grunt.loadNpmTasks("grunt-contrib-copy"); grunt.loadNpmTasks("grunt-contrib-concat"); grunt.loadNpmTasks("grunt-text-replace"); - grunt.loadNpmTasks("grunt-json-minify"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-jscs"); grunt.loadNpmTasks("grunt-jsdoc"); grunt.loadNpmTasks("grunt-clear"); - // grunt.loadNpmTasks("grunt-karma"); + grunt.loadNpmTasks("grunt-karma"); // Only build the documentation grunt.registerTask("doc", ["clean:docCurrent", "clean:docTmp", "referenceConcat", "referenceGeneration", "jsdoc", "copy:doc", "replace:doc", "clean:docTmp"]); @@ -693,7 +669,7 @@ module.exports = function(grunt) grunt.registerTask("lint", ["jshint:beforeconcat", "jscs"]); // Run a watcher for karma testing - // grunt.registerTask("test", ["karma:watch:start", "watch"]); + grunt.registerTask("test", ["karma:run"]); // Main build task grunt.registerTask("build", @@ -712,9 +688,9 @@ module.exports = function(grunt) ]); // Build with closure compiler - grunt.registerTask("min", "Compile the source with closure compiler", function(arg1) + grunt.registerTask("min", "Compile the source with closure compiler", function() { - var debug = (arg1 === "debug"); + var noTest = grunt.option("no-test"); var tasks = [ @@ -728,7 +704,7 @@ module.exports = function(grunt) "replace:log", "copy:license", "copy:closure", - "closureExport:build:" + debug, + "closureExport:build", "referenceConcat:build", "externsGeneration:build", "concat:closure", @@ -741,9 +717,11 @@ module.exports = function(grunt) "clean:buildTmp" ]; - //grunt.option("force", true); + if (noTest !== true) + { + tasks.push("karma:run"); + } grunt.task.run(tasks); }); - }; diff --git a/README.md b/README.md index 11785eff..4316fe23 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@ ForgeJS is a modern web-based engine built on standard technologies (HTML5, Javascript and WebGL) that runs on every modern browser to unleash immersive VR content experiences. It's not only a VR engine, it's a framework for authoring VR content. You can use ForgeJS even if you do not have advanced programming skills: ForgeJS is able to read a configuration file and create the experience from it. -## Ressources +## Resources -Many documentation ressources are available online: +Many documentation resources are available online: - [API Documentation ](https://releases.forgejs.org/latest/doc/jsdoc) describes all public methods, interfaces, properties and events. - [JSON reference](https://releases.forgejs.org/latest/doc/json) explains how to describe your project in the json configuration file. - [Samples](https://forgejs.org/samples) demonstrates how to build your experience in the config.json file. @@ -16,6 +16,12 @@ Many documentation ressources are available online: - [Known issues and limitations](https://forgejs.org/known-issues-and-limitations). - [Frequently asked questions](https://forgejs.org/faq). +## Repositories + +Linked project repositories for the ForgeJS javascript framework. +- [Plugins](https://github.com/gopro/forgejs-plugins) +- [Samples](https://github.com/gopro/forgejs-samples) + ## Get the build The latest build is available online on our [ForgeJS download page](https://forgejs.org/download). @@ -26,10 +32,10 @@ ForgeJS is licensed under [Apache 2.0](http://www.apache.org/licenses/LICENSE-2. ForgeJS has the following dependencies: -- [three.js](https://threejs.org/) r83 ([MIT license](https://github.com/mrdoob/three.js/blob/dev/LICENSE)) +- [three.js](https://threejs.org/) r86 ([MIT license](https://github.com/mrdoob/three.js/blob/dev/LICENSE)) - [hammer.js](http://hammerjs.github.io/) 2.0.8 ([MIT license](https://github.com/hammerjs/hammer.js/blob/master/LICENSE.md)) -- [omnitone](http://googlechrome.github.io/omnitone/#home) 0.1.8 ([Apache 2.0 license](https://github.com/GoogleChrome/omnitone/blob/master/LICENSE)) -- [dash.js](https://github.com/Dash-Industry-Forum/dash.js) 2.3.0 ([BSD license](https://github.com/Dash-Industry-Forum/dash.js/blob/development/LICENSE.md)) +- [omnitone](http://googlechrome.github.io/omnitone/#home) 1.0.1 ([Apache 2.0 license](https://github.com/GoogleChrome/omnitone/blob/master/LICENSE)) +- [dash.js](https://github.com/Dash-Industry-Forum/dash.js) 2.6.0 ([BSD license](https://github.com/Dash-Industry-Forum/dash.js/blob/development/LICENSE.md)) > NOTE: We made a custom build of three.js with some classes concatenated to it. These classes are included in the original three.js repository but not concatenated in the main build. We added EffectComposer, RenderPass, ClearPass, MaskPass, ShaderPass, TexturePass and CopyShader in our three.custom.min.js. @@ -58,7 +64,8 @@ grunt build Build a minified build of ForgeJS: ``` grunt min // without logs on FORGE.DEBUG = true -grunt min:debug // with logs +grunt min --keep-log // with logs +grunt min --no-test // without tests ``` Generate the documentation and the json reference: diff --git a/externs/forge/camera.ext.js b/externs/forge/camera.ext.js index 22cf67be..b4104e91 100644 --- a/externs/forge/camera.ext.js +++ b/externs/forge/camera.ext.js @@ -5,3 +5,13 @@ * @property {number} min */ var CameraBoundaries; + +/** + * @typedef {{yaw:boolean, pitch:boolean, roll:boolean, fov:boolean}} + * @name CameraBoundaries + * @property {boolean} yaw + * @property {boolean} pitch + * @property {boolean} roll + * @property {boolean} fov + */ +var CameraChangelog; diff --git a/externs/forge/core.ext.js b/externs/forge/core.ext.js index b1bc2cac..bcf2863f 100644 --- a/externs/forge/core.ext.js +++ b/externs/forge/core.ext.js @@ -1,5 +1,5 @@ /** - * @typedef {{boot:function(), update:function()}} + * @typedef {{boot:function(), update:function(), beforeRender:function(), afterRender:function()}} * @name ViewerCallbacks * @property {function} boot * @property {function} update diff --git a/externs/forge/hotspot.ext.js b/externs/forge/hotspot.ext.js index 7de88602..c2ff855e 100644 --- a/externs/forge/hotspot.ext.js +++ b/externs/forge/hotspot.ext.js @@ -1,6 +1,6 @@ /** - * @typedef {{x:number, y:number, z:number}} + * @typedef {{x:(number|undefined), y:(number|undefined), z:(number|undefined), radius:(number|undefined), theta:(number|undefined), phi:(number|undefined)}} */ var HotspotTransformPosition; @@ -14,6 +14,16 @@ var HotspotTransformRotation; */ var HotspotTransformScale; +/** + * @typedef {{x:number, y:number, z:number}} + */ +var HotspotTransformValuesConfig; + +/** + * @typedef {{x:number, y:number}} + */ +var HotspotDomOffset; + /** * @typedef {{points:(Array|undefined)}} */ @@ -37,4 +47,9 @@ var HotspotGeometrySphere; /** * @typedef {{radiusTop:(number|undefined), radiusBottom:(number|undefined), height:(number|undefined), radiusSegments:(number|undefined), heightSegments:(number|undefined), openEnded:(boolean|undefined), thetaStart:(number|undefined), thetaLength:(number|undefined)}} */ -var HotspotGeometryCylinder; \ No newline at end of file +var HotspotGeometryCylinder; + +/** + * @typedef {{x:number, y:number, z: number}} + */ +var HotspotGeometryOffset; \ No newline at end of file diff --git a/externs/forge/math.ext.js b/externs/forge/math.ext.js index 48ab816d..6ecc3552 100644 --- a/externs/forge/math.ext.js +++ b/externs/forge/math.ext.js @@ -5,4 +5,14 @@ * @property {number} pitch - pitch euler angle (x axis) [radians] * @property {number} roll - roll euler angle (z axis) [radians] */ -var TEuler; \ No newline at end of file +var TEuler; + +/** + * @typedef {{x:number, y:number, z:number}} + */ +var CartesianCoordinates; + +/** + * @typedef {{radius:number, theta:number, phi:number}} + */ +var SphericalCoordinates; diff --git a/externs/forge/render.ext.js b/externs/forge/render.ext.js index 942623a3..9a329552 100644 --- a/externs/forge/render.ext.js +++ b/externs/forge/render.ext.js @@ -58,4 +58,29 @@ var TUniform; * @typedef {{downDegrees:number, leftDegrees:number, rightDegrees:number, upDegrees:number}} * @name VRFieldOfViewObject */ -var VRFieldOfViewObject; \ No newline at end of file +var VRFieldOfViewObject; + +/** + * @typedef {{load:Promise, cancelled:boolean}} + * @name TexturePromiseObject + */ +var TexturePromiseObject; + +/** + * @typedef {{front:string, left:string, back:string, right:string, up:string, down:string}} + * @name CubeFaceObject + * @property {string} front + * @property {string} left + * @property {string} back + * @property {string} right + * @property {string} up + * @property {string} down + */ +var CubeFaceObject; + +/** + * @typedef {{x:number, y:number}} + * @name TilesOnLevel + */ +var TilesOnLevel; + diff --git a/externs/lib/dash.ext.js b/externs/lib/dash.ext.js index 7a61989c..8d8b2f77 100644 --- a/externs/lib/dash.ext.js +++ b/externs/lib/dash.ext.js @@ -135,6 +135,18 @@ MediaPlayer.prototype.getBitrateInfoListFor = function(type) {}; */ MediaPlayer.prototype.setAutoSwitchQualityFor = function(type, value) {}; +/** + * @param {boolean} value + * @default false + */ +MediaPlayer.prototype.setFastSwitchEnabled = function(value) {}; + +/** + * @param {boolean} value + * @default {boolean} true + */ +MediaPlayer.prototype.setScheduleWhilePaused = function(value) {}; + /** * @param {boolean} value * @default false diff --git a/externs/lib/three.ext.js b/externs/lib/three.ext.js index 77202a84..6580e214 100644 --- a/externs/lib/three.ext.js +++ b/externs/lib/three.ext.js @@ -445,6 +445,12 @@ THREE.Vector2.prototype.subVectors = function(arg1, arg2) {}; */ THREE.Vector2.prototype.divideScalar = function(arg1) {}; +/** + * @param {THREE.Vector2} arg1 + * @return {THREE.Vector2} + */ +THREE.Vector2.prototype.divide = function(arg1) {}; + /** * @return {number} */ @@ -468,6 +474,12 @@ THREE.Vector2.prototype.setX = function(arg1) {}; */ THREE.Vector2.prototype.setY = function(arg1) {}; +/** + * @param {THREE.Vector2} arg1 + * @return {THREE.Vector2} + */ +THREE.Vector2.prototype.dot = function(arg1) {}; + /** * @constructor * @param {number=} arg1 @@ -536,6 +548,17 @@ THREE.Vector3.prototype.setFromSpherical = function(arg1) {}; */ THREE.Vector3.prototype.applyQuaternion = function(arg1) {}; +/** + * @param {THREE.Euler} arg1 + * @return {THREE.Vector3} + */ +THREE.Vector3.prototype.applyEuler = function(arg1) {}; + +/** + * @return {THREE.Vector3} + */ +THREE.Vector3.prototype.normalize = function() {}; + /** * @constructor * @param {number=} arg1 @@ -621,6 +644,13 @@ THREE.Matrix4.prototype.transpose = function() {}; */ THREE.Matrix4.prototype.set = function(arg1, arg2) {}; +/** + * @param {THREE.Matrix4} arg1 + * @param {THREE.Matrix4} arg2 + * @return {THREE.Matrix4} + */ +THREE.Matrix4.prototype.multiplyMatrices = function(arg1, arg2) {}; + /** * @param {THREE.Matrix4} arg1 * @return {THREE.Matrix4} @@ -823,10 +853,6 @@ THREE.Euler.prototype.set = function(arg1, arg2, arg3, arg4) {}; */ THREE.Line = function(arg1, arg2) {}; -/** - */ -THREE.Geometry.prototype.dispose = function() {}; - /** * @constructor * @param {number} arg1 @@ -1052,6 +1078,9 @@ THREE.Mesh.prototype.material; /** @type {?string} */ THREE.Mesh.prototype.name; +/** @type {?number} */ +THREE.Mesh.prototype.renderOrder; + /** * @param {number} arg1 * @return {THREE.Mesh} @@ -1171,6 +1200,11 @@ THREE.Raycaster.prototype.intersectObjects = function(arg1) {}; */ THREE.Scene = function() {}; +/** + * @param {THREE.Object3D} arg1 + */ +THREE.Scene.prototype.getObjectByName = function(arg1) {}; + /** * @constructor * @param {(Element|HTMLElement)=} arg1 @@ -1218,15 +1252,42 @@ THREE.Texture.prototype.needsUpdate; */ THREE.Texture.prototype.dispose = function() {}; +/** + * @constructor + * @return {!THREE.Frustum} + */ +THREE.Frustum = function() {}; + +/** + * @param {THREE.Matrix4} arg1 + */ +THREE.Frustum.prototype.setFromMatrix = function(arg1) {}; + +/** + * @param {THREE.Object3D} arg1 + */ +THREE.Frustum.prototype.intersectsObject = function(arg1) {}; + /** * @constructor * @return {!THREE.Geometry} */ THREE.Geometry = function() {}; -/** @type {Array} */ +/** + * @type {Array} + */ THREE.Geometry.prototype.vertices; +/** + * @param {THREE.Matrix4} arg1 + */ +THREE.Geometry.prototype.applyMatrix = function(arg1) {}; + +/** + */ +THREE.Geometry.prototype.dispose = function() {}; + /** * @constructor * @return {!THREE.BufferGeometry} @@ -1236,6 +1297,11 @@ THREE.BufferGeometry = function() {}; /** @type {{position:(THREE.BufferAttribute|undefined), normal:(THREE.BufferAttribute|undefined), color:(THREE.BufferAttribute|undefined), index:(THREE.BufferAttribute|undefined), uv:(THREE.BufferAttribute|undefined)}} */ THREE.BufferGeometry.prototype.attributes; +/** + * @param {THREE.Matrix4} arg1 + */ +THREE.BufferGeometry.prototype.applyMatrix = function(arg1) {}; + /** * @param {number} arg1 * @param {number} arg2 @@ -1251,9 +1317,38 @@ THREE.BufferGeometry.prototype.scale = function(arg1, arg2, arg3) {}; */ THREE.WireframeGeometry = function(arg1) {}; +/** + * @constructor + * @return {THREE.Curve} + */ +THREE.Curve = function() {}; + +/** + * @constructor + * @return {THREE.LineCurve} + * @extends {THREE.Curve} + */ +THREE.LineCurve = function() {}; + +/** @type {THREE.Vector2} */ +THREE.LineCurve.prototype.v1; + +/** @type {THREE.Vector2} */ +THREE.LineCurve.prototype.v2; + +/** + * @constructor + * @return {THREE.CurvePath} + */ +THREE.CurvePath = function() {}; + +/** @type {Array} */ +THREE.CurvePath.prototype.curves; + /** * @constructor * @param {Array} points + * @extends {THREE.CurvePath} * @return {!THREE.Shape} */ THREE.Path = function(points) {}; @@ -1266,6 +1361,9 @@ THREE.Path = function(points) {}; */ THREE.Shape = function(arg1) {}; +/** @type {THREE.LineCurve} */ +THREE.Shape.prototype.curves; + /** * @constructor * @param {TypedArray} array @@ -1307,6 +1405,9 @@ THREE.BufferAttribute.prototype.set = function(arg1) {}; */ THREE.ShapeBufferGeometry = function(arg1, arg2) {}; +/** @typedef {{shapes: (THREE.Shape|Array)}} */ +THREE.ShapeBufferGeometry.prototype.parameters; + /** * @constructor * @param {number=} arg1 @@ -1321,6 +1422,9 @@ THREE.ShapeBufferGeometry = function(arg1, arg2) {}; */ THREE.SphereBufferGeometry = function(arg1, arg2, arg3, arg4, arg5, arg6, arg7) {}; +/** @typedef {{radius:number, widthSegments:number, heightSegments:number, phiStart:number, phiLength:number, thetaStart:number, thetaLength:number}} */ +THREE.SphereBufferGeometry.prototype.parameters; + /** * @constructor * @param {number=} arg1 @@ -1336,6 +1440,9 @@ THREE.SphereBufferGeometry = function(arg1, arg2, arg3, arg4, arg5, arg6, arg7) */ THREE.CylinderBufferGeometry = function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) {}; +/** @typedef {{radiusTop:number, radiusBottom:number, height:number, radiusSegments:number, heightSegments:number, openEnded:boolean, thetaStart:number, thetaLength:number}} */ +THREE.CylinderBufferGeometry.prototype.parameters; + /** * @constructor * @param {number=} arg1 @@ -1347,6 +1454,9 @@ THREE.CylinderBufferGeometry = function(arg1, arg2, arg3, arg4, arg5, arg6, arg7 */ THREE.PlaneBufferGeometry = function(arg1, arg2, arg3, arg4) {}; +/** @typedef {{width: number, height:number, widthSegments:number, heightSegments:number}} */ +THREE.PlaneBufferGeometry.prototype.parameters; + /** * @constructor * @param {number} arg1 @@ -1360,9 +1470,12 @@ THREE.PlaneBufferGeometry = function(arg1, arg2, arg3, arg4) {}; */ THREE.BoxBufferGeometry = function(arg1, arg2, arg3, arg4, arg5, arg6) {}; -/** @type {{position:(THREE.BufferAttribute|undefined), normal:(THREE.BufferAttribute|undefined), color:(THREE.BufferAttribute|undefined), index:(THREE.BufferAttribute|undefined), uv:(THREE.BufferAttribute|undefined)}} */ +/** @typedef {{position:(THREE.BufferAttribute|undefined), normal:(THREE.BufferAttribute|undefined), color:(THREE.BufferAttribute|undefined), index:(THREE.BufferAttribute|undefined), uv:(THREE.BufferAttribute|undefined)}} */ THREE.BoxBufferGeometry.prototype.attributes; +/** @typedef {{width: number, height:number, depth:number, widthSegments:number, heightSegments:number, depthSegments:number}} */ +THREE.BoxBufferGeometry.prototype.parameters; + /** * @param {string} name * @param {THREE.BufferAttribute} attribute @@ -1419,7 +1532,7 @@ THREE.Layer.prototype.test = function(arg1) {}; // OTHER CUSTOM TYPES USED BY THREE =============================================================================================== /** - * @typedef {{opacity:(number|undefined), transparent:(boolean|undefined), color:(number|string|undefined), side:(number|undefined)}} + * @typedef {{opacity:(number|undefined), transparent:(boolean|undefined), depthTest:(boolean|undefined), color:(THREE.Color|number|string|undefined), side:(number|undefined)}} */ var MeshBasicMaterialOptions; diff --git a/externs/lib/w3c.gamepad-extension.ext.js b/externs/lib/w3c.gamepad-extension.ext.js new file mode 100644 index 00000000..c491464f --- /dev/null +++ b/externs/lib/w3c.gamepad-extension.ext.js @@ -0,0 +1,62 @@ +/** + * Externs file for the Gamepad API extension, as it is a working draft and not implemented in + * the Closure Compiler. + * https://w3c.github.io/gamepad/extensions.html + */ + +/** + * @constructor + * @return {GamepadHapticActuator} + */ +var GamepadHapticActuator = function() {}; + +/** @type {string} */ +GamepadHapticActuator.prototype.type; + +/** + * @param {number} value + * @param {number} duration + * @return {Promise} + */ +GamepadHapticActuator.prototype.pulse = function(value, duration) {}; + +/** + * @constructor + * @return {GamepadPose} + */ +var GamepadPose = function() {}; + +/** @type {boolean} */ +GamepadPose.prototype.hasOrientation; + +/** @type {boolean} */ +GamepadPose.prototype.hasPosition; + +/** @type {?Float32Array} */ +GamepadPose.prototype.position; + +/** @type {?Float32Array} */ +GamepadPose.prototype.linearVelocity; + +/** @type {?Float32Array} */ +GamepadPose.prototype.linearAcceleration; + +/** @type {?Float32Array} */ +GamepadPose.prototype.orientation; + +/** @type {?Float32Array} */ +GamepadPose.prototype.angularVelocity; + +/** @type {?Float32Array} */ +GamepadPose.prototype.angularAcceleration; + +//// Partial interface + +/** @type {string} */ +Gamepad.prototype.hand; + +/** @type {GamepadHapticActuator} */ +Gamepad.prototype.hapticActuators; + +/** @type {?GamepadPose} */ +Gamepad.prototype.pose; diff --git a/lib/dash.js/dash.all.debug.js b/lib/dash.js/dash.all.debug.js index f730cc98..48adb803 100644 --- a/lib/dash.js/dash.all.debug.js +++ b/lib/dash.js/dash.all.debug.js @@ -1016,6 +1016,14 @@ if (typeof exports !== 'undefined') { for (var i = 0; i < byteList.length; i += 2) { a = byteList[i] & 0x7f; b = byteList[i + 1] & 0x7f; + + if (a >= 0x10 && a <= 0x1f && a === this.lastCmdA && b === this.lastCmdB) { + this.lastCmdA = null; + this.lastCmdB = null; + logger.log("DEBUG", "Repeated command (" + numArrayToHexArray([a, b]) + ") is dropped"); + continue; // Repeated commands are dropped (once) + } + if (a === 0 && b === 0) { this.dataCounters.padding += 2; continue; @@ -1061,28 +1069,21 @@ if (typeof exports !== 'undefined') { parseCmd: function parseCmd(a, b) { var chNr = null; - var cond1 = (a === 0x14 || a === 0x1C) && 0x20 <= b && b <= 0x2F; + var cond1 = (a === 0x14 || a === 0x15 || a === 0x1C || a === 0x1D) && 0x20 <= b && b <= 0x2F; var cond2 = (a === 0x17 || a === 0x1F) && 0x21 <= b && b <= 0x23; if (!(cond1 || cond2)) { return false; } - if (a === this.lastCmdA && b === this.lastCmdB) { - this.lastCmdA = null; - this.lastCmdB = null; // Repeated commands are dropped (once) - logger.log("DEBUG", "Repeated command (" + numArrayToHexArray([a, b]) + ") is dropped"); - return true; - } - - if (a === 0x14 || a === 0x17) { + if (a === 0x14 || a === 0x15 || a === 0x17) { chNr = 1; } else { - chNr = 2; // (a === 0x1C || a=== 0x1f) + chNr = 2; // (a === 0x1C || a === 0x1D || a=== 0x1f) } var channel = this.channels[chNr - 1]; - if (a === 0x14 || a === 0x1C) { + if (a === 0x14 || a === 0x15 || a === 0x1C || a === 0x1D) { if (b === 0x20) { channel.cc_RCL(); } else if (b === 0x21) { @@ -1144,8 +1145,12 @@ if (typeof exports !== 'undefined') { return false; } var channel = this.channels[chNr - 1]; + // cea608 spec says midrow codes should inject a space + channel.insertChars([0x20]); channel.cc_MIDROW(b); logger.log("DEBUG", "MIDROW (" + numArrayToHexArray([a, b]) + ")"); + this.lastCmdA = a; + this.lastCmdB = b; return true; } return false; @@ -1165,12 +1170,6 @@ if (typeof exports !== 'undefined') { return false; } - if (a === this.lastCmdA && b === this.lastCmdB) { - this.lastCmdA = null; - this.lastCmdB = null; - return true; // Repeated commands are dropped (once) - } - chNr = a <= 0x17 ? 1 : 2; if (0x40 <= b && b <= 0x5F) { @@ -1243,14 +1242,16 @@ if (typeof exports !== 'undefined') { } logger.log("INFO", "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr); charCodes = [oneCode]; + this.lastCmdA = a; + this.lastCmdB = b; } else if (0x20 <= a && a <= 0x7f) { charCodes = b === 0 ? [a] : [a, b]; + this.lastCmdA = null; + this.lastCmdB = null; } if (charCodes) { var hexCodes = numArrayToHexArray(charCodes); logger.log("DEBUG", "Char codes = " + hexCodes.join(",")); - this.lastCmdA = null; - this.lastCmdB = null; } return charCodes; }, @@ -1285,8 +1286,8 @@ if (typeof exports !== 'undefined') { chNr = a < 0x18 ? 1 : 2; channel = this.channels[chNr - 1]; channel.setBkgData(bkgData); - this.lastCmdA = null; - this.lastCmdB = null; + this.lastCmdA = a; + this.lastCmdB = b; return true; }, @@ -1622,7 +1623,7 @@ module.exports = exports['default']; },{}],4:[function(_dereq_,module,exports){ /* - Copyright 2011 Abdulla Abdurakhmanov + Copyright 2011-2013 Abdulla Abdurakhmanov Original sources are available at https://code.google.com/p/x2js/ Licensed under the Apache License, Version 2.0 (the "License"); @@ -1639,373 +1640,525 @@ module.exports = exports['default']; */ /* - Modified to keep track of children nodes in order in attribute __children. + Further modified for dashjs to: + - keep track of children nodes in order in attribute __children. + - add type conversion matchers + - re-add ignoreRoot + - allow zero-length attributePrefix + - don't add white-space text nodes + - remove explicit RequireJS support */ "use strict"; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); -function X2JS(matchers, attrPrefix, ignoreRoot) { - if (attrPrefix === null || attrPrefix === undefined) { - attrPrefix = "_"; - } - - if (ignoreRoot === null || ignoreRoot === undefined) { - ignoreRoot = false; - } - - var VERSION = "1.0.11"; - var escapeMode = false; - - var DOMNodeTypes = { - ELEMENT_NODE: 1, - TEXT_NODE: 3, - CDATA_SECTION_NODE: 4, - COMMENT_NODE: 8, - DOCUMENT_NODE: 9 - }; - - function getNodeLocalName(node) { - var nodeLocalName = node.localName; - if (nodeLocalName == null) // Yeah, this is IE!! - nodeLocalName = node.baseName; - if (nodeLocalName == null || nodeLocalName == "") // =="" is IE too - nodeLocalName = node.nodeName; - return nodeLocalName; - } - - function getNodePrefix(node) { - return node.prefix; - } - - function escapeXmlChars(str) { - if (typeof str == "string") return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g, '/');else return str; - } - - function unescapeXmlChars(str) { - return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(///g, '\/'); - } - - function parseDOMChildren(node) { - if (node.nodeType == DOMNodeTypes.DOCUMENT_NODE) { - var result, - child = node.firstChild, - i, - len; - - // get the first node that isn't a comment - for (i = 0, len = node.childNodes.length; i < len; i += 1) { - if (node.childNodes[i].nodeType !== DOMNodeTypes.COMMENT_NODE) { - child = node.childNodes[i]; - break; - } - } - - if (ignoreRoot) { - result = parseDOMChildren(child); - } else { - result = {}; - var childName = getNodeLocalName(child); - result[childName] = parseDOMChildren(child); - } - - return result; - } else if (node.nodeType == DOMNodeTypes.ELEMENT_NODE) { - var result = new Object(); - result.__cnt = 0; - - var children = []; - - var nodeChildren = node.childNodes; - - // Children nodes - for (var cidx = 0; cidx < nodeChildren.length; cidx++) { - var child = nodeChildren.item(cidx); // nodeChildren[cidx]; - var childName = getNodeLocalName(child); - - result.__cnt++; - if (result[childName] == null) { - var c = parseDOMChildren(child); - if (childName != "#text" || /[^\s]/.test(c)) { - var o = {}; - o[childName] = c; - children.push(o); - } - result[childName] = c; - result[childName + "_asArray"] = new Array(1); - result[childName + "_asArray"][0] = result[childName]; - } else { - if (result[childName] != null) { - if (!(result[childName] instanceof Array)) { - var tmpObj = result[childName]; - result[childName] = new Array(); - result[childName][0] = tmpObj; - - result[childName + "_asArray"] = result[childName]; - } - } - var aridx = 0; - while (result[childName][aridx] != null) aridx++; - - var c = parseDOMChildren(child); - if (childName != "#text" || /[^\s]/.test(c)) { - // Don't add white-space text nodes - var o = {}; - o[childName] = c; - children.push(o); - } - result[childName][aridx] = c; - } - } - - result.__children = children; - - // Attributes - for (var aidx = 0; aidx < node.attributes.length; aidx++) { - var attr = node.attributes.item(aidx); // [aidx]; - result.__cnt++; - - var value2 = attr.value; - for (var m = 0, ml = matchers.length; m < ml; m++) { - var matchobj = matchers[m]; - if (matchobj.test(attr)) { - value2 = matchobj.converter(attr.value); - } - } - - result[attrPrefix + attr.name] = value2; - } - - // Node namespace prefix - var nodePrefix = getNodePrefix(node); - if (nodePrefix != null && nodePrefix != "") { - result.__cnt++; - result.__prefix = nodePrefix; - } - - if (result.__cnt == 1 && result["#text"] != null) { - result = result["#text"]; - } - - if (result["#text"] != null) { - result.__text = result["#text"]; - if (escapeMode) result.__text = unescapeXmlChars(result.__text); - delete result["#text"]; - delete result["#text_asArray"]; - } - if (result["#cdata-section"] != null) { - result.__cdata = result["#cdata-section"]; - delete result["#cdata-section"]; - delete result["#cdata-section_asArray"]; - } - - if (result.__text != null || result.__cdata != null) { - result.toString = function () { - return (this.__text != null ? this.__text : '') + (this.__cdata != null ? this.__cdata : ''); - }; - } - return result; - } else if (node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) { - return node.nodeValue; - } else if (node.nodeType == DOMNodeTypes.COMMENT_NODE) { - return null; - } - } - - function startTag(jsonObj, element, attrList, closed) { - var resultStr = "<" + (jsonObj != null && jsonObj.__prefix != null ? jsonObj.__prefix + ":" : "") + element; - if (attrList != null) { - for (var aidx = 0; aidx < attrList.length; aidx++) { - var attrName = attrList[aidx]; - var attrVal = jsonObj[attrName]; - resultStr += " " + attrName.substr(1) + "='" + attrVal + "'"; - } - } - if (!closed) resultStr += ">";else resultStr += "/>"; - return resultStr; - } - - function endTag(jsonObj, elementName) { - return ""; - } - - function endsWith(str, suffix) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; - } - - function jsonXmlSpecialElem(jsonObj, jsonObjField) { - if (endsWith(jsonObjField.toString(), "_asArray") || jsonObjField.toString().indexOf("_") == 0 || jsonObj[jsonObjField] instanceof Function) return true;else return false; - } - - function jsonXmlElemCount(jsonObj) { - var elementsCnt = 0; - if (jsonObj instanceof Object) { - for (var it in jsonObj) { - if (jsonXmlSpecialElem(jsonObj, it)) continue; - elementsCnt++; - } - } - return elementsCnt; - } - - function parseJSONAttributes(jsonObj) { - var attrList = []; - if (jsonObj instanceof Object) { - for (var ait in jsonObj) { - if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf("_") == 0) { - attrList.push(ait); - } - } - } - return attrList; - } - - function parseJSONTextAttrs(jsonTxtObj) { - var result = ""; - - if (jsonTxtObj.__cdata != null) { - result += ""; - } - - if (jsonTxtObj.__text != null) { - if (escapeMode) result += escapeXmlChars(jsonTxtObj.__text);else result += jsonTxtObj.__text; - } - return result; - } - - function parseJSONTextObject(jsonTxtObj) { - var result = ""; - - if (jsonTxtObj instanceof Object) { - result += parseJSONTextAttrs(jsonTxtObj); - } else if (jsonTxtObj != null) { - if (escapeMode) result += escapeXmlChars(jsonTxtObj);else result += jsonTxtObj; - } - - return result; - } - - function parseJSONArray(jsonArrRoot, jsonArrObj, attrList) { - var result = ""; - if (jsonArrRoot.length == 0) { - result += startTag(jsonArrRoot, jsonArrObj, attrList, true); - } else { - for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) { - result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false); - result += parseJSONObject(jsonArrRoot[arIdx]); - result += endTag(jsonArrRoot[arIdx], jsonArrObj); - } - } - return result; - } - - function parseJSONObject(jsonObj) { - var result = ""; - - var elementsCnt = jsonXmlElemCount(jsonObj); - - if (elementsCnt > 0) { - for (var it in jsonObj) { - - if (jsonXmlSpecialElem(jsonObj, it)) continue; - - var subObj = jsonObj[it]; - - var attrList = parseJSONAttributes(subObj); - - if (subObj == null || subObj == undefined) { - result += startTag(subObj, it, attrList, true); - } else if (subObj instanceof Object) { - - if (subObj instanceof Array) { - result += parseJSONArray(subObj, it, attrList); - } else { - var subObjElementsCnt = jsonXmlElemCount(subObj); - if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) { - result += startTag(subObj, it, attrList, false); - result += parseJSONObject(subObj); - result += endTag(subObj, it); - } else { - result += startTag(subObj, it, attrList, true); - } - } - } else { - result += startTag(subObj, it, attrList, false); - result += parseJSONTextObject(subObj); - result += endTag(subObj, it); - } - } - } - result += parseJSONTextObject(jsonObj); - - return result; - } - - this.parseXmlString = function (xmlDocStr) { - var xmlDoc, parser, ns; - - if (window.DOMParser) { - parser = new window.DOMParser(); - - try { - ns = parser.parseFromString('<', 'text/xml').getElementsByTagName("parsererror")[0].namespaceURI; - } catch (e) { - // IE11 will definitely throw SyntaxError here - // ns will be undefined - } - - try { - xmlDoc = parser.parseFromString(xmlDocStr, "text/xml"); - - if (ns) { - if (xmlDoc.getElementsByTagNameNS(ns, 'parsererror').length) { - xmlDoc = undefined; - } - } - } catch (e) { - // IE11 may throw SyntaxError here if xmlDocStr is - // not well formed. xmlDoc will be undefined - } - } else { - // IE :( - if (xmlDocStr.indexOf("") + 2); - } - xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); - xmlDoc.async = "false"; - xmlDoc.loadXML(xmlDocStr); - } - return xmlDoc; - }; - - this.xml2json = function (xmlDoc) { - return parseDOMChildren(xmlDoc); - }; - - this.xml_str2json = function (xmlDocStr) { - var xmlDoc = this.parseXmlString(xmlDocStr); - return xmlDoc ? this.xml2json(xmlDoc) : undefined; - }; - - this.json2xml_str = function (jsonObj) { - return parseJSONObject(jsonObj); - }; - - this.json2xml = function (jsonObj) { - var xmlDocStr = this.json2xml_str(jsonObj); - return this.parseXmlString(xmlDocStr); - }; - - this.getVersion = function () { - return VERSION; - }; - - this.escapeMode = function (enabled) { - escapeMode = enabled; - }; +function X2JS(config) { + 'use strict'; + + var VERSION = "1.2.0"; + + config = config || {}; + initConfigDefaults(); + initRequiredPolyfills(); + + function initConfigDefaults() { + if (config.escapeMode === undefined) { + config.escapeMode = true; + } + + if (config.attributePrefix === undefined) { + config.attributePrefix = "_"; + } + + config.arrayAccessForm = config.arrayAccessForm || "none"; + config.emptyNodeForm = config.emptyNodeForm || "text"; + + if (config.enableToStringFunc === undefined) { + config.enableToStringFunc = true; + } + config.arrayAccessFormPaths = config.arrayAccessFormPaths || []; + if (config.skipEmptyTextNodesForObj === undefined) { + config.skipEmptyTextNodesForObj = true; + } + if (config.stripWhitespaces === undefined) { + config.stripWhitespaces = true; + } + config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || []; + + if (config.useDoubleQuotes === undefined) { + config.useDoubleQuotes = false; + } + + config.xmlElementsFilter = config.xmlElementsFilter || []; + config.jsonPropertiesFilter = config.jsonPropertiesFilter || []; + + if (config.keepCData === undefined) { + config.keepCData = false; + } + + if (config.ignoreRoot === undefined) { + config.ignoreRoot = false; + } + } + + var DOMNodeTypes = { + ELEMENT_NODE: 1, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9 + }; + + function initRequiredPolyfills() {} + + function getNodeLocalName(node) { + var nodeLocalName = node.localName; + if (nodeLocalName == null) // Yeah, this is IE!! + nodeLocalName = node.baseName; + if (nodeLocalName == null || nodeLocalName == "") // =="" is IE too + nodeLocalName = node.nodeName; + return nodeLocalName; + } + + function getNodePrefix(node) { + return node.prefix; + } + + function escapeXmlChars(str) { + if (typeof str == "string") return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''');else return str; + } + + function unescapeXmlChars(str) { + return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); + } + + function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) { + var idx = 0; + for (; idx < stdFiltersArrayForm.length; idx++) { + var filterPath = stdFiltersArrayForm[idx]; + if (typeof filterPath === "string") { + if (filterPath == path) break; + } else if (filterPath instanceof RegExp) { + if (filterPath.test(path)) break; + } else if (typeof filterPath === "function") { + if (filterPath(obj, name, path)) break; + } + } + return idx != stdFiltersArrayForm.length; + } + + function toArrayAccessForm(obj, childName, path) { + switch (config.arrayAccessForm) { + case "property": + if (!(obj[childName] instanceof Array)) obj[childName + "_asArray"] = [obj[childName]];else obj[childName + "_asArray"] = obj[childName]; + break; + /*case "none": + break;*/ + } + + if (!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) { + if (checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) { + obj[childName] = [obj[childName]]; + } + } + } + + function fromXmlDateTime(prop) { + // Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object + // Improved to support full spec and optional parts + var bits = prop.split(/[-T:+Z]/g); + + var d = new Date(bits[0], bits[1] - 1, bits[2]); + var secondBits = bits[5].split("\."); + d.setHours(bits[3], bits[4], secondBits[0]); + if (secondBits.length > 1) d.setMilliseconds(secondBits[1]); + + // Get supplied time zone offset in minutes + if (bits[6] && bits[7]) { + var offsetMinutes = bits[6] * 60 + Number(bits[7]); + var sign = /\d\d-\d\d:\d\d$/.test(prop) ? '-' : '+'; + + // Apply the sign + offsetMinutes = 0 + (sign == '-' ? -1 * offsetMinutes : offsetMinutes); + + // Apply offset and local timezone + d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset()); + } else if (prop.indexOf("Z", prop.length - 1) !== -1) { + d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds())); + } + + // d is now a local time equivalent to the supplied time + return d; + } + + function checkFromXmlDateTimePaths(value, childName, fullPath) { + if (config.datetimeAccessFormPaths.length > 0) { + var path = fullPath.split("\.#")[0]; + if (checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) { + return fromXmlDateTime(value); + } else return value; + } else return value; + } + + function checkXmlElementsFilter(obj, childType, childName, childPath) { + if (childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) { + return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath); + } else return true; + } + + function parseDOMChildren(node, path) { + if (node.nodeType == DOMNodeTypes.DOCUMENT_NODE) { + var result = new Object(); + var nodeChildren = node.childNodes; + // Alternative for firstElementChild which is not supported in some environments + for (var cidx = 0; cidx < nodeChildren.length; cidx++) { + var child = nodeChildren[cidx]; + if (child.nodeType == DOMNodeTypes.ELEMENT_NODE) { + if (config.ignoreRoot) { + result = parseDOMChildren(child); + } else { + result = {}; + var childName = getNodeLocalName(child); + result[childName] = parseDOMChildren(child); + } + } + } + return result; + } else if (node.nodeType == DOMNodeTypes.ELEMENT_NODE) { + var result = new Object(); + result.__cnt = 0; + + var children = []; + var nodeChildren = node.childNodes; + + // Children nodes + for (var cidx = 0; cidx < nodeChildren.length; cidx++) { + var child = nodeChildren[cidx]; + var childName = getNodeLocalName(child); + + if (child.nodeType != DOMNodeTypes.COMMENT_NODE) { + var childPath = path + "." + childName; + if (checkXmlElementsFilter(result, child.nodeType, childName, childPath)) { + result.__cnt++; + if (result[childName] == null) { + var c = parseDOMChildren(child, childPath); + if (childName != "#text" || /[^\s]/.test(c)) { + var o = {}; + o[childName] = c; + children.push(o); + } + result[childName] = c; + toArrayAccessForm(result, childName, childPath); + } else { + if (result[childName] != null) { + if (!(result[childName] instanceof Array)) { + result[childName] = [result[childName]]; + toArrayAccessForm(result, childName, childPath); + } + } + + var c = parseDOMChildren(child, childPath); + if (childName != "#text" || /[^\s]/.test(c)) { + // Don't add white-space text nodes + var o = {}; + o[childName] = c; + children.push(o); + } + result[childName][result[childName].length] = c; + } + } + } + } + + result.__children = children; + + // Attributes + var nodeLocalName = getNodeLocalName(node); + for (var aidx = 0; aidx < node.attributes.length; aidx++) { + var attr = node.attributes[aidx]; + result.__cnt++; + + var value2 = attr.value; + for (var m = 0, ml = config.matchers.length; m < ml; m++) { + var matchobj = config.matchers[m]; + if (matchobj.test(attr, nodeLocalName)) value2 = matchobj.converter(attr.value); + } + + result[config.attributePrefix + attr.name] = value2; + } + + // Node namespace prefix + var nodePrefix = getNodePrefix(node); + if (nodePrefix != null && nodePrefix != "") { + result.__cnt++; + result.__prefix = nodePrefix; + } + + if (result["#text"] != null) { + result.__text = result["#text"]; + if (result.__text instanceof Array) { + result.__text = result.__text.join("\n"); + } + //if(config.escapeMode) + // result.__text = unescapeXmlChars(result.__text); + if (config.stripWhitespaces) result.__text = result.__text.trim(); + delete result["#text"]; + if (config.arrayAccessForm == "property") delete result["#text_asArray"]; + result.__text = checkFromXmlDateTimePaths(result.__text, childName, path + "." + childName); + } + if (result["#cdata-section"] != null) { + result.__cdata = result["#cdata-section"]; + delete result["#cdata-section"]; + if (config.arrayAccessForm == "property") delete result["#cdata-section_asArray"]; + } + + if (result.__cnt == 0 && config.emptyNodeForm == "text") { + result = ''; + } else if (result.__cnt == 1 && result.__text != null) { + result = result.__text; + } else if (result.__cnt == 1 && result.__cdata != null && !config.keepCData) { + result = result.__cdata; + } else if (result.__cnt > 1 && result.__text != null && config.skipEmptyTextNodesForObj) { + if (config.stripWhitespaces && result.__text == "" || result.__text.trim() == "") { + delete result.__text; + } + } + delete result.__cnt; + + if (config.enableToStringFunc && (result.__text != null || result.__cdata != null)) { + result.toString = function () { + return (this.__text != null ? this.__text : '') + (this.__cdata != null ? this.__cdata : ''); + }; + } + + return result; + } else if (node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) { + return node.nodeValue; + } + } + + function startTag(jsonObj, element, attrList, closed) { + var resultStr = "<" + (jsonObj != null && jsonObj.__prefix != null ? jsonObj.__prefix + ":" : "") + element; + if (attrList != null) { + for (var aidx = 0; aidx < attrList.length; aidx++) { + var attrName = attrList[aidx]; + var attrVal = jsonObj[attrName]; + if (config.escapeMode) attrVal = escapeXmlChars(attrVal); + resultStr += " " + attrName.substr(config.attributePrefix.length) + "="; + if (config.useDoubleQuotes) resultStr += '"' + attrVal + '"';else resultStr += "'" + attrVal + "'"; + } + } + if (!closed) resultStr += ">";else resultStr += "/>"; + return resultStr; + } + + function endTag(jsonObj, elementName) { + return ""; + } + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + function jsonXmlSpecialElem(jsonObj, jsonObjField) { + if (config.arrayAccessForm == "property" && endsWith(jsonObjField.toString(), "_asArray") || jsonObjField.toString().indexOf(config.attributePrefix) == 0 || jsonObjField.toString().indexOf("__") == 0 || jsonObj[jsonObjField] instanceof Function) return true;else return false; + } + + function jsonXmlElemCount(jsonObj) { + var elementsCnt = 0; + if (jsonObj instanceof Object) { + for (var it in jsonObj) { + if (jsonXmlSpecialElem(jsonObj, it)) continue; + elementsCnt++; + } + } + return elementsCnt; + } + + function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) { + return config.jsonPropertiesFilter.length == 0 || jsonObjPath == "" || checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath); + } + + function parseJSONAttributes(jsonObj) { + var attrList = []; + if (jsonObj instanceof Object) { + for (var ait in jsonObj) { + if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf(config.attributePrefix) == 0) { + attrList.push(ait); + } + } + } + return attrList; + } + + function parseJSONTextAttrs(jsonTxtObj) { + var result = ""; + + if (jsonTxtObj.__cdata != null) { + result += ""; + } + + if (jsonTxtObj.__text != null) { + if (config.escapeMode) result += escapeXmlChars(jsonTxtObj.__text);else result += jsonTxtObj.__text; + } + return result; + } + + function parseJSONTextObject(jsonTxtObj) { + var result = ""; + + if (jsonTxtObj instanceof Object) { + result += parseJSONTextAttrs(jsonTxtObj); + } else if (jsonTxtObj != null) { + if (config.escapeMode) result += escapeXmlChars(jsonTxtObj);else result += jsonTxtObj; + } + + return result; + } + + function getJsonPropertyPath(jsonObjPath, jsonPropName) { + if (jsonObjPath === "") { + return jsonPropName; + } else return jsonObjPath + "." + jsonPropName; + } + + function parseJSONArray(jsonArrRoot, jsonArrObj, attrList, jsonObjPath) { + var result = ""; + if (jsonArrRoot.length == 0) { + result += startTag(jsonArrRoot, jsonArrObj, attrList, true); + } else { + for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) { + result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false); + result += parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath, jsonArrObj)); + result += endTag(jsonArrRoot[arIdx], jsonArrObj); + } + } + return result; + } + + function parseJSONObject(jsonObj, jsonObjPath) { + var result = ""; + + var elementsCnt = jsonXmlElemCount(jsonObj); + + if (elementsCnt > 0) { + for (var it in jsonObj) { + + if (jsonXmlSpecialElem(jsonObj, it) || jsonObjPath != "" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath, it))) continue; + + var subObj = jsonObj[it]; + + var attrList = parseJSONAttributes(subObj); + + if (subObj == null || subObj == undefined) { + result += startTag(subObj, it, attrList, true); + } else if (subObj instanceof Object) { + + if (subObj instanceof Array) { + result += parseJSONArray(subObj, it, attrList, jsonObjPath); + } else if (subObj instanceof Date) { + result += startTag(subObj, it, attrList, false); + result += subObj.toISOString(); + result += endTag(subObj, it); + } else { + var subObjElementsCnt = jsonXmlElemCount(subObj); + if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) { + result += startTag(subObj, it, attrList, false); + result += parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath, it)); + result += endTag(subObj, it); + } else { + result += startTag(subObj, it, attrList, true); + } + } + } else { + result += startTag(subObj, it, attrList, false); + result += parseJSONTextObject(subObj); + result += endTag(subObj, it); + } + } + } + result += parseJSONTextObject(jsonObj); + + return result; + } + + this.parseXmlString = function (xmlDocStr) { + var isIEParser = window.ActiveXObject || "ActiveXObject" in window; + if (xmlDocStr === undefined) { + return null; + } + var xmlDoc; + if (window.DOMParser) { + var parser = new window.DOMParser(); + var parsererrorNS = null; + // IE9+ now is here + if (!isIEParser) { + try { + parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI; + } catch (err) { + parsererrorNS = null; + } + } + try { + xmlDoc = parser.parseFromString(xmlDocStr, "text/xml"); + if (parsererrorNS != null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) { + //throw new Error('Error parsing XML: '+xmlDocStr); + xmlDoc = null; + } + } catch (err) { + xmlDoc = null; + } + } else { + // IE :( + if (xmlDocStr.indexOf("") + 2); + } + xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); + xmlDoc.async = "false"; + xmlDoc.loadXML(xmlDocStr); + } + return xmlDoc; + }; + + this.asArray = function (prop) { + if (prop === undefined || prop == null) return [];else if (prop instanceof Array) return prop;else return [prop]; + }; + + this.toXmlDateTime = function (dt) { + if (dt instanceof Date) return dt.toISOString();else if (typeof dt === 'number') return new Date(dt).toISOString();else return null; + }; + + this.asDateTime = function (prop) { + if (typeof prop == "string") { + return fromXmlDateTime(prop); + } else return prop; + }; + + this.xml2json = function (xmlDoc) { + return parseDOMChildren(xmlDoc); + }; + + this.xml_str2json = function (xmlDocStr) { + var xmlDoc = this.parseXmlString(xmlDocStr); + if (xmlDoc != null) return this.xml2json(xmlDoc);else return null; + }; + + this.json2xml_str = function (jsonObj) { + return parseJSONObject(jsonObj, ""); + }; + + this.json2xml = function (jsonObj) { + var xmlDocStr = this.json2xml_str(jsonObj); + return this.parseXmlString(xmlDocStr); + }; + + this.getVersion = function () { + return VERSION; + }; } + exports["default"] = X2JS; module.exports = exports["default"]; @@ -2050,26 +2203,30 @@ Object.defineProperty(exports, '__esModule', { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } -var _srcStreamingMediaPlayer = _dereq_(51); +var _srcStreamingMediaPlayer = _dereq_(92); var _srcStreamingMediaPlayer2 = _interopRequireDefault(_srcStreamingMediaPlayer); -var _srcStreamingProtectionProtection = _dereq_(106); +var _srcCoreFactoryMaker = _dereq_(50); + +var _srcCoreFactoryMaker2 = _interopRequireDefault(_srcCoreFactoryMaker); + +var _srcStreamingProtectionProtection = _dereq_(146); var _srcStreamingProtectionProtection2 = _interopRequireDefault(_srcStreamingProtectionProtection); -var _srcStreamingMetricsMetricsReporting = _dereq_(75); +var _srcStreamingMetricsMetricsReporting = _dereq_(115); var _srcStreamingMetricsMetricsReporting2 = _interopRequireDefault(_srcStreamingMetricsMetricsReporting); -var _srcStreamingMediaPlayerFactory = _dereq_(53); +var _srcStreamingMediaPlayerFactory = _dereq_(94); var _srcStreamingMediaPlayerFactory2 = _interopRequireDefault(_srcStreamingMediaPlayerFactory); -var _srcCoreVersion = _dereq_(11); +var _srcCoreVersion = _dereq_(51); // Shove both of these into the global scope -var context = window || global; +var context = typeof window !== 'undefined' && window || global; var dashjs = context.dashjs; if (!dashjs) { @@ -2077,6 +2234,7 @@ if (!dashjs) { } dashjs.MediaPlayer = _srcStreamingMediaPlayer2['default']; +dashjs.FactoryMaker = _srcCoreFactoryMaker2['default']; dashjs.Protection = _srcStreamingProtectionProtection2['default']; dashjs.MetricsReporting = _srcStreamingMetricsMetricsReporting2['default']; dashjs.MediaPlayerFactory = _srcStreamingMediaPlayerFactory2['default']; @@ -2090,11249 +2248,23455 @@ exports.MediaPlayerFactory = _srcStreamingMediaPlayerFactory2['default']; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"106":106,"11":11,"51":51,"53":53,"75":75}],6:[function(_dereq_,module,exports){ -/*! codem-isoboxer v0.2.2 https://github.com/madebyhiro/codem-isoboxer/blob/master/LICENSE.txt */ -var ISOBoxer = {}; +},{"115":115,"146":146,"50":50,"51":51,"92":92,"94":94}],6:[function(_dereq_,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; -ISOBoxer.parseBuffer = function(arrayBuffer) { - return new ISOFile(arrayBuffer).parse(); +;(function (exports) { + 'use strict'; + + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array + + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + var PLUS_URL_SAFE = '-'.charCodeAt(0) + var SLASH_URL_SAFE = '_'.charCodeAt(0) + + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS || + code === PLUS_URL_SAFE) + return 62 // '+' + if (code === SLASH || + code === SLASH_URL_SAFE) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } + + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // 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 + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length + + var L = 0 + + function push (v) { + arr[L++] = v + } + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } + + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } + + return arr + } + + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length + + function encode (num) { + return lookup.charAt(num) + } + + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } + + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } + + return output + } + + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + +},{}],7:[function(_dereq_,module,exports){ + +},{}],8:[function(_dereq_,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = _dereq_(9).Buffer; + +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); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; }; -ISOBoxer.Utils = {}; -ISOBoxer.Utils.dataViewToString = function(dataView, encoding) { - var impliedEncoding = encoding || 'utf-8' - if (typeof TextDecoder !== 'undefined') { - return new TextDecoder(impliedEncoding).decode(dataView); + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; } - var a = []; - var i = 0; - - if (impliedEncoding === 'utf-8') { - /* The following algorithm is essentially a rewrite of the UTF8.decode at - http://bannister.us/weblog/2007/simple-base64-encodedecode-javascript/ - */ - - while (i < dataView.byteLength) { - var c = dataView.getUint8(i++); - if (c < 0x80) { - // 1-byte character (7 bits) - } else if (c < 0xe0) { - // 2-byte character (11 bits) - c = (c & 0x1f) << 6; - c |= (dataView.getUint8(i++) & 0x3f); - } else if (c < 0xf0) { - // 3-byte character (16 bits) - c = (c & 0xf) << 12; - c |= (dataView.getUint8(i++) & 0x3f) << 6; - c |= (dataView.getUint8(i++) & 0x3f); - } else { - // 4-byte character (21 bits) - c = (c & 0x7) << 18; - c |= (dataView.getUint8(i++) & 0x3f) << 12; - c |= (dataView.getUint8(i++) & 0x3f) << 6; - c |= (dataView.getUint8(i++) & 0x3f); - } - a.push(String.fromCharCode(c)); + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + 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); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + 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); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; } - } else { // Just map byte-by-byte (probably wrong) - while (i < dataView.byteLength) { - a.push(String.fromCharCode(dataView.getUint8(i++))); + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; } } - return a.join(''); + this.charReceived = i; }; -if (typeof exports !== 'undefined') { - exports.parseBuffer = ISOBoxer.parseBuffer; - exports.Utils = ISOBoxer.Utils; -}; -ISOBoxer.Cursor = function(initialOffset) { - this.offset = (typeof initialOffset == 'undefined' ? 0 : initialOffset); +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; }; -var ISOFile = function(arrayBuffer) { - this._raw = new DataView(arrayBuffer); - this._cursor = new ISOBoxer.Cursor(); - this.boxes = []; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); } -ISOFile.prototype.fetch = function(type) { - var result = this.fetchAll(type, true); - return (result.length ? result[0] : null); +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; } -ISOFile.prototype.fetchAll = function(type, returnEarly) { - var result = []; - ISOFile._sweep.call(this, type, result, returnEarly); - return result; +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; } -ISOFile.prototype.parse = function() { - this._cursor.offset = 0; - this.boxes = []; - while (this._cursor.offset < this._raw.byteLength) { - var box = ISOBox.parse(this); +},{"9":9}],9:[function(_dereq_,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ - // Box could not be parsed - if (typeof box.type === 'undefined') break; +'use strict' - this.boxes.push(box); - } - return this; -} +var base64 = _dereq_(6) +var ieee754 = _dereq_(16) +var isArray = _dereq_(26) -ISOFile._sweep = function(type, result, returnEarly) { - if (this.type && this.type == type) result.push(this); - for (var box in this.boxes) { - if (result.length && returnEarly) return; - ISOFile._sweep.call(this.boxes[box], type, result, returnEarly); +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 // not used by this implementation + +var rootParent = {} + +/** + * 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. + * + * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property + * on objects. + * + * - 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.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +function typedArraySupport () { + function Bar () {} + try { + var arr = new Uint8Array(1) + arr.foo = function () { return 42 } + arr.constructor = Bar + return arr.foo() === 42 && // typed array instances can be augmented + arr.constructor === Bar && // constructor can be set + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false } -}; -var ISOBox = function() { - this._cursor = new ISOBoxer.Cursor(); } -ISOBox.parse = function(parent) { - var newBox = new ISOBox(); - newBox._offset = parent._cursor.offset; - newBox._root = (parent._root ? parent._root : parent); - newBox._raw = parent._raw; - newBox._parent = parent; - newBox._parseBox(); - parent._cursor.offset = newBox._raw.byteOffset + newBox._raw.byteLength; - return newBox; +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff } -ISOBox.prototype._readInt = function(size) { - var result = null; - switch(size) { - case 8: - result = this._raw.getInt8(this._cursor.offset - this._raw.byteOffset); - break; - case 16: - result = this._raw.getInt16(this._cursor.offset - this._raw.byteOffset); - break; - case 32: - result = this._raw.getInt32(this._cursor.offset - this._raw.byteOffset); - break; - case 64: - // Warning: JavaScript cannot handle 64-bit integers natively. - // This will give unexpected results for integers >= 2^53 - var s1 = this._raw.getInt32(this._cursor.offset - this._raw.byteOffset); - var s2 = this._raw.getInt32(this._cursor.offset - this._raw.byteOffset + 4); - result = (s1 * Math.pow(2,32)) + s2; - break; +/** + * Class: Buffer + * ============= + * + * The Buffer constructor returns instances of `Uint8Array` that are augmented + * with function properties for all the node `Buffer` API functions. We use + * `Uint8Array` so that square bracket notation works as expected -- it returns + * a single octet. + * + * By augmenting the instances, we can avoid modifying the `Uint8Array` + * prototype. + */ +function Buffer (arg) { + if (!(this instanceof Buffer)) { + // Avoid going through an ArgumentsAdaptorTrampoline in the common case. + if (arguments.length > 1) return new Buffer(arg, arguments[1]) + return new Buffer(arg) } - this._cursor.offset += (size >> 3); - return result; -} -ISOBox.prototype._readUint = function(size) { - var result = null; - switch(size) { - case 8: - result = this._raw.getUint8(this._cursor.offset - this._raw.byteOffset); - break; - case 16: - result = this._raw.getUint16(this._cursor.offset - this._raw.byteOffset); - break; - case 24: - var s1 = this._raw.getUint16(this._cursor.offset - this._raw.byteOffset); - var s2 = this._raw.getUint8(this._cursor.offset - this._raw.byteOffset + 2); - result = (s1 << 8) + s2; - break; - case 32: - result = this._raw.getUint32(this._cursor.offset - this._raw.byteOffset); - break; - case 64: - // Warning: JavaScript cannot handle 64-bit integers natively. - // This will give unexpected results for integers >= 2^53 - var s1 = this._raw.getUint32(this._cursor.offset - this._raw.byteOffset); - var s2 = this._raw.getUint32(this._cursor.offset - this._raw.byteOffset + 4); - result = (s1 * Math.pow(2,32)) + s2; - break; + if (!Buffer.TYPED_ARRAY_SUPPORT) { + this.length = 0 + this.parent = undefined } - this._cursor.offset += (size >> 3); - return result; -} -ISOBox.prototype._readString = function(length) { - var str = ''; - for (var c = 0; c < length; c++) { - var char = this._readUint(8); - str += String.fromCharCode(char); + // Common case. + if (typeof arg === 'number') { + return fromNumber(this, arg) + } + + // Slightly less common case. + if (typeof arg === 'string') { + return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } - return str; + + // Unusual. + return fromObject(this, arg) } -ISOBox.prototype._readTerminatedString = function() { - var str = ''; - while (true) { - var char = this._readUint(8); - if (char == 0) break; - str += String.fromCharCode(char); +function fromNumber (that, length) { + that = allocate(that, length < 0 ? 0 : checked(length) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < length; i++) { + that[i] = 0 + } } - return str; + return that } -ISOBox.prototype._readTemplate = function(size) { - var pre = this._readUint(size / 2); - var post = this._readUint(size / 2); - return pre + (post / Math.pow(2, size / 2)); +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' + + // Assumption: byteLength() return value is always < kMaxLength. + var length = byteLength(string, encoding) | 0 + that = allocate(that, length) + + that.write(string, encoding) + return that } -ISOBox.prototype._parseBox = function() { - this._cursor.offset = this._offset; - - // return immediately if there are not enough bytes to read the header - if (this._offset + 8 > this._raw.buffer.byteLength) { - this._root._incomplete = true; - return; - } - - this.size = this._readUint(32); - this.type = this._readString(4); +function fromObject (that, object) { + if (Buffer.isBuffer(object)) return fromBuffer(that, object) - if (this.size == 1) { this.largesize = this._readUint(64); } - if (this.type == 'uuid') { this.usertype = this._readString(16); } + if (isArray(object)) return fromArray(that, object) - switch(this.size) { - case 0: - this._raw = new DataView(this._raw.buffer, this._offset, (this._raw.byteLength - this._cursor.offset)); - break; - case 1: - if (this._offset + this.size > this._raw.buffer.byteLength) { - this._incomplete = true; - this._root._incomplete = true; - } else { - this._raw = new DataView(this._raw.buffer, this._offset, this.largesize); + if (object == null) { + throw new TypeError('must start with number, buffer, array or string') + } + + if (typeof ArrayBuffer !== 'undefined') { + if (object.buffer instanceof ArrayBuffer) { + return fromTypedArray(that, object) } - break; - default: - if (this._offset + this.size > this._raw.buffer.byteLength) { - this._incomplete = true; - this._root._incomplete = true; - } else { - this._raw = new DataView(this._raw.buffer, this._offset, this.size); + if (object instanceof ArrayBuffer) { + return fromArrayBuffer(that, object) } } - // additional parsing - if (!this._incomplete && this._boxParsers[this.type]) this._boxParsers[this.type].call(this); + if (object.length) return fromArrayLike(that, object) + + return fromJsonObject(that, object) } -ISOBox.prototype._parseFullBox = function() { - this.version = this._readUint(8); - this.flags = this._readUint(24); +function fromBuffer (that, buffer) { + var length = checked(buffer.length) | 0 + that = allocate(that, length) + buffer.copy(that, 0, 0, length) + return that } -ISOBox.prototype._boxParsers = {};; -// Simple container boxes, all from ISO/IEC 14496-12:2012 except vttc which is from 14496-30. -[ - 'moov', 'trak', 'tref', 'mdia', 'minf', 'stbl', 'edts', 'dinf', - 'mvex', 'moof', 'traf', 'mfra', 'udta', 'meco', 'strk', 'vttc' -].forEach(function(boxType) { - ISOBox.prototype._boxParsers[boxType] = function() { - this.boxes = []; - while (this._cursor.offset - this._raw.byteOffset < this._raw.byteLength) { - this.boxes.push(ISOBox.parse(this)); - } - } -}) -; -// ISO/IEC 14496-12:2012 - 8.6.6 Edit List Box -ISOBox.prototype._boxParsers['elst'] = function() { - this._parseFullBox(); - this.entry_count = this._readUint(32); - this.entries = []; - - for (var i=1; i <= this.entry_count; i++) { - var entry = {}; - if (this.version == 1) { - entry.segment_duration = this._readUint(64); - entry.media_time = this._readInt(64); - } else { - entry.segment_duration = this._readUint(32); - entry.media_time = this._readInt(32); - } - entry.media_rate_integer = this._readInt(16); - entry.media_rate_fraction = this._readInt(16); - this.entries.push(entry); +function fromArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } -}; -// ISO/IEC 23009-1:2014 - 5.10.3.3 Event Message Box -ISOBox.prototype._boxParsers['emsg'] = function() { - this._parseFullBox(); - this.scheme_id_uri = this._readTerminatedString(); - this.value = this._readTerminatedString(); - this.timescale = this._readUint(32); - this.presentation_time_delta = this._readUint(32); - this.event_duration = this._readUint(32); - this.id = this._readUint(32); - this.message_data = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); -}; -// ISO/IEC 14496-12:2012 - 8.1.2 Free Space Box -ISOBox.prototype._boxParsers['free'] = ISOBox.prototype._boxParsers['skip'] = function() { - this.data = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); -}; -// ISO/IEC 14496-12:2012 - 4.3 File Type Box / 8.16.2 Segment Type Box -ISOBox.prototype._boxParsers['ftyp'] = ISOBox.prototype._boxParsers['styp'] = function() { - this.major_brand = this._readString(4); - this.minor_versions = this._readUint(32); - this.compatible_brands = []; - - while (this._cursor.offset - this._raw.byteOffset < this._raw.byteLength) { - this.compatible_brands.push(this._readString(4)); + return that +} + +// Duplicate of fromArray() to keep fromArray() monomorphic. +function fromTypedArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + // Truncating the elements is probably not what people expect from typed + // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior + // of the old Buffer constructor. + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } -}; -// ISO/IEC 14496-12:2012 - 8.4.3 Handler Reference Box -ISOBox.prototype._boxParsers['hdlr'] = function() { - this._parseFullBox(); - this.pre_defined = this._readUint(32); - this.handler_type = this._readString(4); - this.reserved = [this._readUint(32), this._readUint(32), this._readUint(32)] - this.name = this._readTerminatedString() -}; -// ISO/IEC 14496-12:2012 - 8.1.1 Media Data Box -ISOBox.prototype._boxParsers['mdat'] = function() { - this.data = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); -}; -// ISO/IEC 14496-12:2012 - 8.4.2 Media Header Box -ISOBox.prototype._boxParsers['mdhd'] = function() { - this._parseFullBox(); - if (this.version == 1) { - this.creation_time = this._readUint(64); - this.modification_time = this._readUint(64); - this.timescale = this._readUint(32); - this.duration = this._readUint(64); - } else { - this.creation_time = this._readUint(32); - this.modification_time = this._readUint(32); - this.timescale = this._readUint(32); - this.duration = this._readUint(32); - } - var language = this._readUint(16); - this.pad = (language >> 15); - this.language = String.fromCharCode( - ((language >> 10) & 0x1F) + 0x60, - ((language >> 5) & 0x1F) + 0x60, - (language & 0x1F) + 0x60 - ); - this.pre_defined = this._readUint(16); -}; -// ISO/IEC 14496-12:2012 - 8.8.5 Movie Fragment Header Box -ISOBox.prototype._boxParsers['mfhd'] = function() { - this._parseFullBox(); - this.sequence_number = this._readUint(32); -}; -// ISO/IEC 14496-12:2012 - 8.2.2 Movie Header Box -ISOBox.prototype._boxParsers['mvhd'] = function() { - this._parseFullBox(); - - if (this.version == 1) { - this.creation_time = this._readUint(64); - this.modification_time = this._readUint(64); - this.timescale = this._readUint(32); - this.duration = this._readUint(64); + return that +} + +function fromArrayBuffer (that, array) { + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + array.byteLength + that = Buffer._augment(new Uint8Array(array)) } else { - this.creation_time = this._readUint(32); - this.modification_time = this._readUint(32); - this.timescale = this._readUint(32); - this.duration = this._readUint(32); + // Fallback: Return an object instance of the Buffer class + that = fromTypedArray(that, new Uint8Array(array)) } - - this.rate = this._readTemplate(32); - this.volume = this._readTemplate(16); - this.reserved1 = this._readUint(16); - this.reserved2 = [ this._readUint(32), this._readUint(32) ]; - this.matrix = []; - for (var i=0; i<9; i++) { - this.matrix.push(this._readTemplate(32)); - } - this.pre_defined = []; - for (var i=0; i<6; i++) { - this.pre_defined.push(this._readUint(32)); - } - this.next_track_ID = this._readUint(32); -}; -// ISO/IEC 14496-30:2014 - WebVTT Cue Payload Box. -ISOBox.prototype._boxParsers['payl'] = function() { - var cue_text_raw = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); - this.cue_text = ISOBoxer.Utils.dataViewToString(cue_text_raw); + return that } -; -// ISO/IEC 14496-12:2012 - 8.16.3 Segment Index Box -ISOBox.prototype._boxParsers['sidx'] = function() { - this._parseFullBox(); - this.reference_ID = this._readUint(32); - this.timescale = this._readUint(32); - if (this.version == 0) { - this.earliest_presentation_time = this._readUint(32); - this.first_offset = this._readUint(32); - } else { - this.earliest_presentation_time = this._readUint(64); - this.first_offset = this._readUint(64); - } - this.reserved = this._readUint(16); - this.reference_count = this._readUint(16); - this.references = []; - for (var i=0; i> 31) & 0x1; - ref.referenced_size = reference & 0x7FFFFFFF; - ref.subsegment_duration = this._readUint(32); - var sap = this._readUint(32); - ref.starts_with_SAP = (sap >> 31) & 0x1; - ref.SAP_type = (sap >> 28) & 0x7; - ref.SAP_delta_time = sap & 0xFFFFFFF; - this.references.push(ref); + +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } -}; -// ISO/IEC 14496-12:2012 - 8.16.4 Subsegment Index Box -ISOBox.prototype._boxParsers['ssix'] = function() { - this._parseFullBox(); - this.subsegment_count = this._readUint(32); - this.subsegments = []; - - for (var i=0; i>> 1 + if (fromPool) that.parent = rootParent + + return that +} + +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') } -}; -// ISO/IEC 14496-30:2014 - WebVTT Source Label Box -ISOBox.prototype._boxParsers['vlab'] = function() { - var source_label_raw = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); - this.source_label = ISOBoxer.Utils.dataViewToString(source_label_raw); + return length | 0 } -; -// ISO/IEC 14496-30:2014 - WebVTT Configuration Box -ISOBox.prototype._boxParsers['vttC'] = function() { - var config_raw = new DataView(this._raw.buffer, this._cursor.offset, this._raw.byteLength - (this._cursor.offset - this._offset)); - this.config = ISOBoxer.Utils.dataViewToString(config_raw); + +function SlowBuffer (subject, encoding) { + if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) + + var buf = new Buffer(subject, encoding) + delete buf.parent + return buf } -; -// ISO/IEC 14496-30:2014 - WebVTT Empty Sample Box -ISOBox.prototype._boxParsers['vtte'] = function() { - // Nothing should happen here. + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) } -},{}],7:[function(_dereq_,module,exports){ -/** - * Decimal adjustment of a number. - * - * @param {String} type The type of adjustment. - * @param {Number} value The number. - * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). - * @returns {Number} The adjusted value. - */ -var decimalAdjust = exports.decimalAdjust = function(type, value, exp) { - // If the exp is undefined or zero... - if (typeof exp === 'undefined' || +exp === 0) { - return Math[type](value); - } - value = +value; - exp = +exp; - // If the value is not a number or the exp is not an integer... - if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { - return NaN; - } - // Shift - value = value.toString().split('e'); - value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); - // Shift back - value = value.toString().split('e'); - return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + var i = 0 + var len = Math.min(x, y) + while (i < len) { + if (a[i] !== b[i]) break + + ++i + } + + if (i !== len) { + x = a[i] + y = b[i] + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 } -module.exports = { - round10: function(value, exp) { - return decimalAdjust('round', value, exp); - }, - floor10: function(value, exp) { - return decimalAdjust('floor', value, exp); - }, - ceil10: function(value, exp) { - return decimalAdjust('ceil', value, exp); - }, -}; +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} -module.exports.polyfill = function() { - // Decimal round - if (!Math.round10) { - Math.round10 = module.exports.round10; - } - // Decimal floor - if (!Math.floor10) { - Math.floor10 = module.exports.floor10; +Buffer.concat = function concat (list, length) { + if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + + if (list.length === 0) { + return new Buffer(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; i++) { + length += list[i].length } - // Decimal ceil - if (!Math.ceil10) { - Math.ceil10 = module.exports.ceil10; + } + + var buf = new Buffer(length) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} + +function byteLength (string, encoding) { + 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 'binary': + // Deprecated + case 'raw': + case 'raws': + 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 utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true } -}; + } +} +Buffer.byteLength = byteLength -},{}],8:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -'use strict'; +function slowToString (encoding, start, end) { + var loweredCase = false -Object.defineProperty(exports, '__esModule', { - value: true -}); + start = start | 0 + end = end === undefined || end === Infinity ? this.length : end | 0 -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' -var _EventBus = _dereq_(9); + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) -var _EventBus2 = _interopRequireDefault(_EventBus); + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) -var _eventsEvents = _dereq_(13); + case 'ascii': + return asciiSlice(this, start, end) -var _eventsEvents2 = _interopRequireDefault(_eventsEvents); + case 'binary': + return binarySlice(this, start, end) -var _FactoryMaker = _dereq_(10); + case 'base64': + return base64Slice(this, start, end) -var _FactoryMaker2 = _interopRequireDefault(_FactoryMaker); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) -/** - * @module Debug - */ -function Debug() { + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} - var context = this.context; - var eventBus = (0, _EventBus2['default'])(context).getInstance(); +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) +} - var instance = undefined, - logToBrowserConsole = undefined, - showLogTimestamp = undefined, - startTime = undefined; +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} - function setup() { - logToBrowserConsole = true; - showLogTimestamp = true; - startTime = new Date().getTime(); - } +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} - /** - * Prepends a timestamp in milliseconds to each log message. - * @param {boolean} value Set to true if you want to see a timestamp in each log message. - * @default false - * @memberof module:Debug - * @instance - */ - function setLogTimestampVisible(value) { - showLogTimestamp = value; - } - /** - * Toggles logging to the browser's javascript console. If you set to false you will still receive a log event with the same message. - * @param {boolean} value Set to false if you want to turn off logging to the browser's console. - * @default true - * @memberof module:Debug - * @instance - */ - function setLogToBrowserConsole(value) { - logToBrowserConsole = value; +Buffer.prototype.compare = function compare (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return 0 + return Buffer.compare(this, b) +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset) { + if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff + else if (byteOffset < -0x80000000) byteOffset = -0x80000000 + byteOffset >>= 0 + + if (this.length === 0) return -1 + if (byteOffset >= this.length) return -1 + + // Negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + + if (typeof val === 'string') { + if (val.length === 0) return -1 // special case: looking for empty string always fails + return String.prototype.indexOf.call(this, val, byteOffset) + } + if (Buffer.isBuffer(val)) { + return arrayIndexOf(this, val, byteOffset) + } + if (typeof val === 'number') { + if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { + return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } - /** - * Use this method to get the state of logToBrowserConsole. - * @returns {boolean} The current value of logToBrowserConsole - * @memberof module:Debug - * @instance - */ - function getLogToBrowserConsole() { - return logToBrowserConsole; + return arrayIndexOf(this, [ val ], byteOffset) + } + + function arrayIndexOf (arr, val, byteOffset) { + var foundIndex = -1 + for (var i = 0; byteOffset + i < arr.length; i++) { + if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex + } else { + foundIndex = -1 + } } - /** - * This method will allow you send log messages to either the browser's console and/or dispatch an event to capture at the media player level. - * @param {...*} arguments The message you want to log. The Arguments object is supported for this method so you can send in comma separated logging items. - * @memberof module:Debug - * @instance - */ - function log() { + return -1 + } - var message = ''; - var logTime = null; + throw new TypeError('val must be string, number or Buffer') +} - if (showLogTimestamp) { - logTime = new Date().getTime(); - message += '[' + (logTime - startTime) + ']'; - } +// `get` is deprecated +Buffer.prototype.get = function get (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} - if (message.length > 0) { - message += ' '; - } +// `set` is deprecated +Buffer.prototype.set = function set (v, offset) { + console.log('.set() is deprecated. Access using array indexes instead.') + return this.writeUInt8(v, offset) +} - Array.apply(null, arguments).forEach(function (item) { - message += item + ' '; - }); +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 (logToBrowserConsole) { - console.log(message); - } + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') - eventBus.trigger(_eventsEvents2['default'].LOG, { message: message }); - } + 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)) throw new Error('Invalid hex string') + buf[offset + i] = parsed + } + return i +} - instance = { - log: log, - setLogTimestampVisible: setLogTimestampVisible, - setLogToBrowserConsole: setLogToBrowserConsole, - getLogToBrowserConsole: getLogToBrowserConsole - }; +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} - setup(); +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} - return instance; +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) } -Debug.__dashjs_factory_name = 'Debug'; -exports['default'] = _FactoryMaker2['default'].getSingletonFactory(Debug); -module.exports = exports['default']; +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} -},{"10":10,"13":13,"9":9}],9:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -'use strict'; +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} -Object.defineProperty(exports, '__esModule', { - value: true -}); +Buffer.prototype.write = function write (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 { + var swap = encoding + encoding = offset + offset = length | 0 + length = swap + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining -var _FactoryMaker = _dereq_(10); + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('attempt to write outside buffer bounds') + } -var _FactoryMaker2 = _interopRequireDefault(_FactoryMaker); + if (!encoding) encoding = 'utf8' -var EVENT_PRIORITY_LOW = 0; -var EVENT_PRIORITY_HIGH = 5000; + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) -function EventBus() { + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - var handlers = {}; + case 'ascii': + return asciiWrite(this, string, offset, length) - function on(type, listener, scope) { - var priority = arguments.length <= 3 || arguments[3] === undefined ? EVENT_PRIORITY_LOW : arguments[3]; + case 'binary': + return binaryWrite(this, string, offset, length) - if (!type) { - throw new Error('event type cannot be null or undefined'); - } - if (!listener || typeof listener !== 'function') { - throw new Error('listener must be a function: ' + listener); - } + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - if (getHandlerIdx(type, listener, scope) >= 0) return; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - handlers[type] = handlers[type] || []; + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} - var handler = { - callback: listener, - scope: scope, - priority: priority - }; +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} - var inserted = handlers[type].some(function (item, idx) { - if (priority > item.priority) { - handlers[type].splice(idx, 0, handler); - return true; - } - }); +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} - if (!inserted) { - handlers[type].push(handler); - } +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + 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 + } + } + } } - function off(type, listener, scope) { - if (!type || !listener || !handlers[type]) return; - var idx = getHandlerIdx(type, listener, scope); - if (idx < 0) return; - handlers[type].splice(idx, 1); + 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 } - function trigger(type, payload) { - if (!type || !handlers[type]) return; + res.push(codePoint) + i += bytesPerSequence + } - payload = payload || {}; + return decodeCodePointsArray(res) +} - if (payload.hasOwnProperty('type')) throw new Error('\'type\' is a reserved word for event dispatching'); +// 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 - payload.type = type; +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - handlers[type].forEach(function (handler) { - return handler.callback.call(handler.scope, payload); - }); - } + // 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 +} - function getHandlerIdx(type, listener, scope) { +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - var idx = -1; + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} - if (!handlers[type]) return idx; +function binarySlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - handlers[type].some(function (item, index) { - if (item.callback === listener && (!scope || scope === item.scope)) { - idx = index; - return true; - } - }); - return idx; - } + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret +} - function reset() { - handlers = {}; - } +function hexSlice (buf, start, end) { + var len = buf.length - var instance = { - on: on, - off: off, - trigger: trigger, - reset: reset - }; + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len - return instance; + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out } -EventBus.__dashjs_factory_name = 'EventBus'; -var factory = _FactoryMaker2['default'].getSingletonFactory(EventBus); -factory.EVENT_PRIORITY_LOW = EVENT_PRIORITY_LOW; -factory.EVENT_PRIORITY_HIGH = EVENT_PRIORITY_HIGH; -exports['default'] = factory; -module.exports = exports['default']; +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 +} -},{"10":10}],10:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/** - * @module FactoryMaker - */ -"use strict"; +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end -Object.defineProperty(exports, "__esModule", { - value: true -}); -var FactoryMaker = (function () { + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } - var instance = undefined; - var extensions = []; - var singletonContexts = []; + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } - function extend(name, childInstance, override, context) { - var extensionContext = getExtensionContext(context); - if (!extensionContext[name] && childInstance) { - extensionContext[name] = { instance: childInstance, override: override }; - } - } + if (end < start) end = start - /** - * Use this method from your extended object. this.factory is injected into your object. - * this.factory.getSingletonInstance(this.context, 'VideoModel') - * will return the video model for use in the extended object. - * - * @param {Object} context - injected into extended object as this.context - * @param {string} className - string name found in all dash.js objects - * with name __dashjs_factory_name Will be at the bottom. Will be the same as the object's name. - * @returns {*} Context aware instance of specified singleton name. - * @memberof module:FactoryMaker - * @instance - */ - function getSingletonInstance(context, className) { - for (var i in singletonContexts) { - var obj = singletonContexts[i]; - if (obj.context === context && obj.name === className) { - return obj.instance; - } - } - return null; + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = Buffer._augment(this.subarray(start, end)) + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] } + } - /** - * Use this method to add an singleton instance to the system. Useful for unit testing to mock objects etc. - * - * @param {Object} context - * @param {string} className - * @param {Object} instance - * @memberof module:FactoryMaker - * @instance - */ - function setSingletonInstance(context, className, instance) { - for (var i in singletonContexts) { - var obj = singletonContexts[i]; - if (obj.context === context && obj.name === className) { - singletonContexts[i].instance = instance; - return; - } - } - singletonContexts.push({ name: className, context: context, instance: instance }); - } + if (newBuf.length) newBuf.parent = this.parent || this - function getClassFactory(classConstructor) { - return function (context) { - if (context === undefined) { - context = {}; - } - return { - create: function create() { - return merge(classConstructor.__dashjs_factory_name, classConstructor.apply({ context: context }, arguments), context, arguments); - } - }; - }; - } + return newBuf +} - function getSingletonFactory(classConstructor) { - return function (context) { - var instance = undefined; - if (context === undefined) { - context = {}; - } - return { - getInstance: function getInstance() { - // If we don't have an instance yet check for one on the context - if (!instance) { - instance = getSingletonInstance(context, classConstructor.__dashjs_factory_name); - } - // If there's no instance on the context then create one - if (!instance) { - instance = merge(classConstructor.__dashjs_factory_name, classConstructor.apply({ context: context }, arguments), context, arguments); - singletonContexts.push({ name: classConstructor.__dashjs_factory_name, context: context, instance: instance }); - } - return instance; - } - }; - }; - } +/* + * 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 merge(name, classConstructor, context, args) { - var extensionContext = getExtensionContext(context); - var extensionObject = extensionContext[name]; - if (extensionObject) { - var extension = extensionObject.instance; - if (extensionObject.override) { - //Override public methods in parent but keep parent. - extension = extension.apply({ context: context, factory: instance, parent: classConstructor }, args); - for (var prop in extension) { - if (classConstructor.hasOwnProperty(prop)) { - classConstructor[prop] = extension[prop]; - } - } - } else { - //replace parent object completely with new object. Same as dijon. - return extension.apply({ context: context, factory: instance }, args); - } - } - return classConstructor; - } +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - function getExtensionContext(context) { - var extensionContext = undefined; - extensions.forEach(function (obj) { - if (obj === context) { - extensionContext = obj; - } - }); - if (!extensionContext) { - extensionContext = extensions.push(context); - } - return extensionContext; - } + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } - instance = { - extend: extend, - getSingletonInstance: getSingletonInstance, - setSingletonInstance: setSingletonInstance, - getSingletonFactory: getSingletonFactory, - getClassFactory: getClassFactory - }; + return val +} - return instance; -})(); +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } -exports["default"] = FactoryMaker; -module.exports = exports["default"]; + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } -},{}],11:[function(_dereq_,module,exports){ -'use strict'; + return val +} -Object.defineProperty(exports, '__esModule', { - value: true -}); -exports.getVersionString = getVersionString; -var VERSION = '2.3.0'; +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} -function getVersionString() { - return VERSION; +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) } -},{}],12:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -'use strict'; +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} -Object.defineProperty(exports, '__esModule', { - value: true -}); +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) -var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} -function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) -var _EventsBase2 = _dereq_(14); + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 -var _EventsBase3 = _interopRequireDefault(_EventsBase2); + if (val >= mul) val -= Math.pow(2, 8 * byteLength) -/** - * @class - * @ignore - */ + return val +} -var CoreEvents = (function (_EventsBase) { - _inherits(CoreEvents, _EventsBase); +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - function CoreEvents() { - _classCallCheck(this, CoreEvents); + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 - _get(Object.getPrototypeOf(CoreEvents.prototype), 'constructor', this).call(this); - this.AST_IN_FUTURE = 'astinfuture'; - this.BUFFERING_COMPLETED = 'bufferingCompleted'; - this.BUFFER_CLEARED = 'bufferCleared'; - this.BUFFER_LEVEL_UPDATED = 'bufferLevelUpdated'; - this.BYTES_APPENDED = 'bytesAppended'; - this.CHECK_FOR_EXISTENCE_COMPLETED = 'checkForExistenceCompleted'; - this.CHUNK_APPENDED = 'chunkAppended'; - this.CURRENT_TRACK_CHANGED = 'currenttrackchanged'; - this.DATA_UPDATE_COMPLETED = 'dataUpdateCompleted'; - this.DATA_UPDATE_STARTED = 'dataUpdateStarted'; - this.FRAGMENT_LOADING_COMPLETED = 'fragmentLoadingCompleted'; - this.FRAGMENT_LOADING_STARTED = 'fragmentLoadingStarted'; - this.FRAGMENT_LOADING_ABANDONED = 'fragmentLoadingAbandoned'; - this.INITIALIZATION_LOADED = 'initializationLoaded'; - this.INIT_FRAGMENT_LOADED = 'initFragmentLoaded'; - this.INIT_REQUESTED = 'initRequested'; - this.INTERNAL_MANIFEST_LOADED = 'internalManifestLoaded'; - this.LIVE_EDGE_SEARCH_COMPLETED = 'liveEdgeSearchCompleted'; - this.LOADING_COMPLETED = 'loadingCompleted'; - this.LOADING_PROGRESS = 'loadingProgress'; - this.MANIFEST_UPDATED = 'manifestUpdated'; - this.MEDIA_FRAGMENT_LOADED = 'mediaFragmentLoaded'; - this.QUOTA_EXCEEDED = 'quotaExceeded'; - this.REPRESENTATION_UPDATED = 'representationUpdated'; - this.SEGMENTS_LOADED = 'segmentsLoaded'; - this.SERVICE_LOCATION_BLACKLIST_CHANGED = 'serviceLocationBlacklistChanged'; - this.SOURCEBUFFER_APPEND_COMPLETED = 'sourceBufferAppendCompleted'; - this.SOURCEBUFFER_REMOVE_COMPLETED = 'sourceBufferRemoveCompleted'; - this.STREAMS_COMPOSED = 'streamsComposed'; - this.STREAM_BUFFERING_COMPLETED = 'streamBufferingCompleted'; - this.STREAM_COMPLETED = 'streamCompleted'; - this.STREAM_INITIALIZED = 'streaminitialized'; - this.STREAM_TEARDOWN_COMPLETE = 'streamTeardownComplete'; - this.TIMED_TEXT_REQUESTED = 'timedTextRequested'; - this.TIME_SYNCHRONIZATION_COMPLETED = 'timeSynchronizationComplete'; - this.URL_RESOLUTION_FAILED = 'urlResolutionFailed'; - this.WALLCLOCK_TIME_UPDATED = 'wallclockTimeUpdated'; - this.XLINK_ALL_ELEMENTS_LOADED = 'xlinkAllElementsLoaded'; - this.XLINK_ELEMENT_LOADED = 'xlinkElementLoaded'; - this.XLINK_READY = 'xlinkReady'; - } + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - return CoreEvents; -})(_EventsBase3['default']); + return val +} -exports['default'] = CoreEvents; -module.exports = exports['default']; +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) +} -},{"14":14}],13:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/** - * @class - * @ignore - */ -'use strict'; +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 +} -Object.defineProperty(exports, '__esModule', { - value: true -}); +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 +} -var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) -function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} -var _CoreEvents2 = _dereq_(12); +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} -var _CoreEvents3 = _interopRequireDefault(_CoreEvents2); +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} -var Events = (function (_CoreEvents) { - _inherits(Events, _CoreEvents); +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} - function Events() { - _classCallCheck(this, Events); +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} - _get(Object.getPrototypeOf(Events.prototype), 'constructor', this).apply(this, arguments); +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') + if (value > max || value < min) throw new RangeError('value 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) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF } - return Events; -})(_CoreEvents3['default']); + return offset + byteLength +} -var events = new Events(); -exports['default'] = events; -module.exports = exports['default']; +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } -},{"12":12}],14:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/** - * @class - * @ignore - */ -'use strict'; + return offset + byteLength +} -Object.defineProperty(exports, '__esModule', { - value: true -}); +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 _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); +function 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 + } +} -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } +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 offset + 2 +} -var EventsBase = (function () { - function EventsBase() { - _classCallCheck(this, EventsBase); - } +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 +} - _createClass(EventsBase, [{ - key: 'extend', - value: function extend(events, config) { - if (!events) return; +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 + } +} - var override = config ? config.override : false; - var publicOnly = config ? config.publicOnly : false; +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) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} - for (var evt in events) { - if (!events.hasOwnProperty(evt) || this[evt] && !override) continue; - if (publicOnly && events[evt].indexOf('public_') === -1) continue; - this[evt] = events[evt]; - } - } - }]); +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + 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 offset + 4 +} - return EventsBase; -})(); +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) -exports['default'] = EventsBase; -module.exports = exports['default']; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } -},{}],15:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ + var i = 0 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } -'use strict'; + return offset + byteLength +} -Object.defineProperty(exports, '__esModule', { - value: true -}); +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + var i = byteLength - 1 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } -var _streamingVoTrackInfo = _dereq_(172); + return offset + byteLength +} -var _streamingVoTrackInfo2 = _interopRequireDefault(_streamingVoTrackInfo); +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 +} -var _streamingVoMediaInfo = _dereq_(167); +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 +} -var _streamingVoMediaInfo2 = _interopRequireDefault(_streamingVoMediaInfo); +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 +} -var _streamingVoStreamInfo = _dereq_(169); +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 +} -var _streamingVoStreamInfo2 = _interopRequireDefault(_streamingVoStreamInfo); +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 +} -var _streamingVoManifestInfo = _dereq_(166); +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') + if (offset < 0) throw new RangeError('index out of range') +} -var _streamingVoManifestInfo2 = _interopRequireDefault(_streamingVoManifestInfo); +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} -var _voEvent = _dereq_(41); +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} -var _voEvent2 = _interopRequireDefault(_voEvent); +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} -var _coreFactoryMaker = _dereq_(10); +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} -var _coreFactoryMaker2 = _interopRequireDefault(_coreFactoryMaker); +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} -var _externalsCea608Parser = _dereq_(2); +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} -var _externalsCea608Parser2 = _interopRequireDefault(_externalsCea608Parser); +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +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 < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') -var _constantsDashMetricsList = _dereq_(20); + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } -var METRIC_LIST = _interopRequireWildcard(_constantsDashMetricsList); + var len = end - start + var i -function DashAdapter() { + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; i--) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; i++) { + target[i + targetStart] = this[i + start] + } + } else { + target._set(this.subarray(start, start + len), targetStart) + } - //let context = this.context; + return len +} - var instance = undefined, - dashManifestModel = undefined, - periods = undefined, - adaptations = undefined; +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function fill (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length - function setConfig(config) { - if (!config) return; + if (end < start) throw new RangeError('end < start') - if (config.dashManifestModel) { - dashManifestModel = config.dashManifestModel; - } - } + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return - function initialize() { - periods = []; - adaptations = {}; - } + if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') + if (end < 0 || end > this.length) throw new RangeError('end out of bounds') - function getRepresentationForTrackInfo(trackInfo, representationController) { - return representationController.getRepresentationForQuality(trackInfo.quality); + var i + if (typeof value === 'number') { + for (i = start; i < end; i++) { + this[i] = value + } + } else { + var bytes = utf8ToBytes(value.toString()) + var len = bytes.length + for (i = start; i < end; i++) { + this[i] = bytes[i % len] } + } - function getAdaptationForMediaInfo(mediaInfo) { - return adaptations[mediaInfo.streamInfo.id][mediaInfo.index]; + return this +} + +/** + * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. + * Added in Node 0.12. Only available in browsers that support ArrayBuffer. + */ +Buffer.prototype.toArrayBuffer = function toArrayBuffer () { + if (typeof Uint8Array !== 'undefined') { + if (Buffer.TYPED_ARRAY_SUPPORT) { + return (new Buffer(this)).buffer + } else { + var buf = new Uint8Array(this.length) + for (var i = 0, len = buf.length; i < len; i += 1) { + buf[i] = this[i] + } + return buf.buffer } + } else { + throw new TypeError('Buffer.toArrayBuffer not supported in this browser') + } +} - function getPeriodForStreamInfo(streamInfo) { - var ln = periods.length; +// HELPER FUNCTIONS +// ================ + +var BP = Buffer.prototype + +/** + * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods + */ +Buffer._augment = function _augment (arr) { + arr.constructor = Buffer + arr._isBuffer = true + + // save reference to original Uint8Array set method before overwriting + arr._set = arr.set + + // deprecated + arr.get = BP.get + arr.set = BP.set + + arr.write = BP.write + arr.toString = BP.toString + arr.toLocaleString = BP.toString + arr.toJSON = BP.toJSON + arr.equals = BP.equals + arr.compare = BP.compare + arr.indexOf = BP.indexOf + arr.copy = BP.copy + arr.slice = BP.slice + arr.readUIntLE = BP.readUIntLE + arr.readUIntBE = BP.readUIntBE + arr.readUInt8 = BP.readUInt8 + arr.readUInt16LE = BP.readUInt16LE + arr.readUInt16BE = BP.readUInt16BE + arr.readUInt32LE = BP.readUInt32LE + arr.readUInt32BE = BP.readUInt32BE + arr.readIntLE = BP.readIntLE + arr.readIntBE = BP.readIntBE + arr.readInt8 = BP.readInt8 + arr.readInt16LE = BP.readInt16LE + arr.readInt16BE = BP.readInt16BE + arr.readInt32LE = BP.readInt32LE + arr.readInt32BE = BP.readInt32BE + arr.readFloatLE = BP.readFloatLE + arr.readFloatBE = BP.readFloatBE + arr.readDoubleLE = BP.readDoubleLE + arr.readDoubleBE = BP.readDoubleBE + arr.writeUInt8 = BP.writeUInt8 + arr.writeUIntLE = BP.writeUIntLE + arr.writeUIntBE = BP.writeUIntBE + arr.writeUInt16LE = BP.writeUInt16LE + arr.writeUInt16BE = BP.writeUInt16BE + arr.writeUInt32LE = BP.writeUInt32LE + arr.writeUInt32BE = BP.writeUInt32BE + arr.writeIntLE = BP.writeIntLE + arr.writeIntBE = BP.writeIntBE + arr.writeInt8 = BP.writeInt8 + arr.writeInt16LE = BP.writeInt16LE + arr.writeInt16BE = BP.writeInt16BE + arr.writeInt32LE = BP.writeInt32LE + arr.writeInt32BE = BP.writeInt32BE + arr.writeFloatLE = BP.writeFloatLE + arr.writeFloatBE = BP.writeFloatBE + arr.writeDoubleLE = BP.writeDoubleLE + arr.writeDoubleBE = BP.writeDoubleBE + arr.fill = BP.fill + arr.inspect = BP.inspect + arr.toArrayBuffer = BP.toArrayBuffer + + return arr +} - for (var i = 0; i < ln; i++) { - var period = periods[i]; +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - if (streamInfo.id === period.id) return period; - } +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} - return null; - } +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} - function convertRepresentationToTrackInfo(manifest, representation) { - var trackInfo = new _streamingVoTrackInfo2['default'](); - var a = representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index]; - var r = dashManifestModel.getRepresentationFor(representation.index, a); - - trackInfo.id = representation.id; - trackInfo.quality = representation.index; - trackInfo.bandwidth = dashManifestModel.getBandwidth(r); - trackInfo.DVRWindow = representation.segmentAvailabilityRange; - trackInfo.fragmentDuration = representation.segmentDuration || (representation.segments && representation.segments.length > 0 ? representation.segments[0].duration : NaN); - trackInfo.MSETimeOffset = representation.MSETimeOffset; - trackInfo.useCalculatedLiveEdgeTime = representation.useCalculatedLiveEdgeTime; - trackInfo.mediaInfo = convertAdaptationToMediaInfo(manifest, representation.adaptation); +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} - return trackInfo; +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; i++) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') } + } - function convertAdaptationToMediaInfo(manifest, adaptation) { - var mediaInfo = new _streamingVoMediaInfo2['default'](); - var a = adaptation.period.mpd.manifest.Period_asArray[adaptation.period.index].AdaptationSet_asArray[adaptation.index]; - var viewpoint; + return bytes +} - mediaInfo.id = adaptation.id; - mediaInfo.index = adaptation.index; - mediaInfo.type = adaptation.type; - mediaInfo.streamInfo = convertPeriodToStreamInfo(manifest, adaptation.period); - mediaInfo.representationCount = dashManifestModel.getRepresentationCount(a); - mediaInfo.lang = dashManifestModel.getLanguageForAdaptation(a); - viewpoint = dashManifestModel.getViewpointForAdaptation(a); - mediaInfo.viewpoint = viewpoint ? viewpoint.value : undefined; - mediaInfo.accessibility = dashManifestModel.getAccessibilityForAdaptation(a).map(function (accessibility) { - var accessibilityValue = accessibility.value; - var accessibilityData = accessibilityValue; - if (accessibility.schemeIdUri && accessibility.schemeIdUri.search('cea-608') >= 0 && typeof _externalsCea608Parser2['default'] !== 'undefined') { - if (accessibilityValue) { - accessibilityData = 'cea-608:' + accessibilityValue; - } else { - accessibilityData = 'cea-608'; - } - mediaInfo.embeddedCaptions = true; - } - return accessibilityData; - }); - mediaInfo.audioChannelConfiguration = dashManifestModel.getAudioChannelConfigurationForAdaptation(a).map(function (audioChannelConfiguration) { - return audioChannelConfiguration.value; - }); - mediaInfo.roles = dashManifestModel.getRolesForAdaptation(a).map(function (role) { - return role.value; - }); - mediaInfo.codec = dashManifestModel.getCodec(a); - mediaInfo.mimeType = dashManifestModel.getMimeType(a); - mediaInfo.contentProtection = dashManifestModel.getContentProtectionData(a); - mediaInfo.bitrateList = dashManifestModel.getBitrateListForAdaptation(a); +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} - if (mediaInfo.contentProtection) { - mediaInfo.contentProtection.forEach(function (item) { - item.KID = dashManifestModel.getKID(item); - }); - } +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } - mediaInfo.isText = dashManifestModel.getIsTextTrack(mediaInfo.mimeType); + return byteArray +} - return mediaInfo; - } +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} - function convertVideoInfoToEmbeddedTextInfo(mediaInfo, channel, lang) { - mediaInfo.id = channel; // CC1, CC2, CC3, or CC4 - mediaInfo.index = 100 + parseInt(channel.substring(2, 3)); - mediaInfo.type = 'embeddedText'; - mediaInfo.codec = 'cea-608-in-SEI'; - mediaInfo.isText = true; - mediaInfo.isEmbedded = true; - mediaInfo.lang = channel + ' ' + lang; - mediaInfo.roles = ['caption']; - } +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} - function convertPeriodToStreamInfo(manifest, period) { - var streamInfo = new _streamingVoStreamInfo2['default'](); - var THRESHOLD = 1; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - streamInfo.id = period.id; - streamInfo.index = period.index; - streamInfo.start = period.start; - streamInfo.duration = period.duration; - streamInfo.manifestInfo = convertMpdToManifestInfo(manifest, period.mpd); - streamInfo.isLast = manifest.Period_asArray.length === 1 || Math.abs(streamInfo.start + streamInfo.duration - streamInfo.manifestInfo.duration) < THRESHOLD; - streamInfo.isFirst = manifest.Period_asArray.length === 1 || dashManifestModel.getRegularPeriods(manifest, dashManifestModel.getMpd(manifest))[0].id === period.id; +},{"16":16,"26":26,"6":6}],10:[function(_dereq_,module,exports){ +/*! codem-isoboxer v0.3.4 https://github.com/madebyhiro/codem-isoboxer/blob/master/LICENSE.txt */ +var ISOBoxer = {}; - return streamInfo; - } +ISOBoxer.parseBuffer = function(arrayBuffer) { + return new ISOFile(arrayBuffer).parse(); +}; - function convertMpdToManifestInfo(manifest, mpd) { - var manifestInfo = new _streamingVoManifestInfo2['default'](); +ISOBoxer.addBoxProcessor = function(type, parser) { + if (typeof type !== 'string' || typeof parser !== 'function') { + return; + } + ISOBox.prototype._boxProcessors[type] = parser; +}; - manifestInfo.DVRWindowSize = mpd.timeShiftBufferDepth; - manifestInfo.loadedTime = mpd.manifest.loadedTime; - manifestInfo.availableFrom = mpd.availabilityStartTime; - manifestInfo.minBufferTime = mpd.manifest.minBufferTime; - manifestInfo.maxFragmentDuration = mpd.maxSegmentDuration; - manifestInfo.duration = dashManifestModel.getDuration(manifest); - manifestInfo.isDynamic = dashManifestModel.getIsDynamic(manifest); +ISOBoxer.createFile = function() { + return new ISOFile(); +}; - return manifestInfo; - } +// See ISOBoxer.append() for 'pos' parameter syntax +ISOBoxer.createBox = function(type, parent, pos) { + var newBox = ISOBox.create(type); + if (parent) { + parent.append(newBox, pos); + } + return newBox; +}; - function getMediaInfoForType(manifest, streamInfo, type) { +// See ISOBoxer.append() for 'pos' parameter syntax +ISOBoxer.createFullBox = function(type, parent, pos) { + var newBox = ISOBoxer.createBox(type, parent, pos); + newBox.version = 0; + newBox.flags = 0; + return newBox; +}; - var data = dashManifestModel.getAdaptationForType(manifest, streamInfo.index, type, streamInfo); - if (!data) return null; +ISOBoxer.Utils = {}; +ISOBoxer.Utils.dataViewToString = function(dataView, encoding) { + var impliedEncoding = encoding || 'utf-8'; + if (typeof TextDecoder !== 'undefined') { + return new TextDecoder(impliedEncoding).decode(dataView); + } + var a = []; + var i = 0; - var periodInfo = getPeriodForStreamInfo(streamInfo); - var periodId = periodInfo.id; - var idx = dashManifestModel.getIndexForAdaptation(data, manifest, streamInfo.index); + if (impliedEncoding === 'utf-8') { + /* The following algorithm is essentially a rewrite of the UTF8.decode at + http://bannister.us/weblog/2007/simple-base64-encodedecode-javascript/ + */ - adaptations[periodId] = adaptations[periodId] || dashManifestModel.getAdaptationsForPeriod(manifest, periodInfo); + while (i < dataView.byteLength) { + var c = dataView.getUint8(i++); + if (c < 0x80) { + // 1-byte character (7 bits) + } else if (c < 0xe0) { + // 2-byte character (11 bits) + c = (c & 0x1f) << 6; + c |= (dataView.getUint8(i++) & 0x3f); + } else if (c < 0xf0) { + // 3-byte character (16 bits) + c = (c & 0xf) << 12; + c |= (dataView.getUint8(i++) & 0x3f) << 6; + c |= (dataView.getUint8(i++) & 0x3f); + } else { + // 4-byte character (21 bits) + c = (c & 0x7) << 18; + c |= (dataView.getUint8(i++) & 0x3f) << 12; + c |= (dataView.getUint8(i++) & 0x3f) << 6; + c |= (dataView.getUint8(i++) & 0x3f); + } + a.push(String.fromCharCode(c)); + } + } else { // Just map byte-by-byte (probably wrong) + while (i < dataView.byteLength) { + a.push(String.fromCharCode(dataView.getUint8(i++))); + } + } + return a.join(''); +}; - return convertAdaptationToMediaInfo(manifest, adaptations[periodId][idx]); +ISOBoxer.Utils.utf8ToByteArray = function(string) { + // Only UTF-8 encoding is supported by TextEncoder + var u, i; + if (typeof TextEncoder !== 'undefined') { + u = new TextEncoder().encode(string); + } else { + u = []; + for (i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + if (c < 0x80) { + u.push(c); + } else if (c < 0x800) { + u.push(0xC0 | (c >> 6)); + u.push(0x80 | (63 & c)); + } else if (c < 0x10000) { + u.push(0xE0 | (c >> 12)); + u.push(0x80 | (63 & (c >> 6))); + u.push(0x80 | (63 & c)); + } else { + u.push(0xF0 | (c >> 18)); + u.push(0x80 | (63 & (c >> 12))); + u.push(0x80 | (63 & (c >> 6))); + u.push(0x80 | (63 & c)); + } } + } + return u; +}; - function getAllMediaInfoForType(manifest, streamInfo, type) { - var periodInfo = getPeriodForStreamInfo(streamInfo); - var periodId = periodInfo.id; - var adaptationsForType = dashManifestModel.getAdaptationsForType(manifest, streamInfo.index, type !== 'embeddedText' ? type : 'video'); +// Method to append a box in the list of child boxes +// The 'pos' parameter can be either: +// - (number) a position index at which to insert the new box +// - (string) the type of the box after which to insert the new box +// - (object) the box after which to insert the new box +ISOBoxer.Utils.appendBox = function(parent, box, pos) { + box._offset = parent._cursor.offset; + box._root = (parent._root ? parent._root : parent); + box._raw = parent._raw; + box._parent = parent; + + if (pos === -1) { + // The new box is a sub-box of the parent but not added in boxes array, + // for example when the new box is set as an entry (see dref and stsd for example) + return; + } - var mediaArr = []; + if (pos === undefined || pos === null) { + parent.boxes.push(box); + return; + } - var data, media, idx, i, j, ln; + var index = -1, + type; - if (!adaptationsForType) return mediaArr; + if (typeof pos === "number") { + index = pos; + } else { + if (typeof pos === "string") { + type = pos; + } else if (typeof pos === "object" && pos.type) { + type = pos.type; + } else { + parent.boxes.push(box); + return; + } - adaptations[periodId] = adaptations[periodId] || dashManifestModel.getAdaptationsForPeriod(manifest, periodInfo); + for (var i = 0; i < parent.boxes.length; i++) { + if (type === parent.boxes[i].type) { + index = i + 1; + break; + } + } + } + parent.boxes.splice(index, 0, box); +}; - for (i = 0, ln = adaptationsForType.length; i < ln; i++) { - data = adaptationsForType[i]; - idx = dashManifestModel.getIndexForAdaptation(data, manifest, streamInfo.index); - media = convertAdaptationToMediaInfo(manifest, adaptations[periodId][idx]); +if (typeof exports !== 'undefined') { + exports.parseBuffer = ISOBoxer.parseBuffer; + exports.addBoxProcessor = ISOBoxer.addBoxProcessor; + exports.createFile = ISOBoxer.createFile; + exports.createBox = ISOBoxer.createBox; + exports.createFullBox = ISOBoxer.createFullBox; + exports.Utils = ISOBoxer.Utils; +} - if (type === 'embeddedText') { - var accessibilityLength = media.accessibility.length; - for (j = 0; j < accessibilityLength; j++) { - if (!media) { - continue; - } - var accessibility = media.accessibility[j]; - if (accessibility.indexOf('cea-608:') === 0) { - var value = accessibility.substring(8); - var parts = value.split(';'); - if (parts[0].substring(0, 2) === 'CC') { - for (j = 0; j < parts.length; j++) { - if (!media) { - media = convertAdaptationToMediaInfo.call(this, manifest, adaptations[periodId][idx]); - } - convertVideoInfoToEmbeddedTextInfo(media, parts[j].substring(0, 3), parts[j].substring(4)); - mediaArr.push(media); - media = null; - } - } else { - for (j = 0; j < parts.length; j++) { - // Only languages for CC1, CC2, ... - if (!media) { - media = convertAdaptationToMediaInfo.call(this, manifest, adaptations[periodId][idx]); - } - convertVideoInfoToEmbeddedTextInfo(media, 'CC' + (j + 1), parts[j]); - mediaArr.push(media); - media = null; - } - } - } else if (accessibility.indexOf('cea-608') === 0) { - // Nothing known. We interpret it as CC1=eng - convertVideoInfoToEmbeddedTextInfo(media, 'CC1', 'eng'); - mediaArr.push(media); - media = null; - } - } - } - if (media && type !== 'embeddedText') { - mediaArr.push(media); - } - } +ISOBoxer.Cursor = function(initialOffset) { + this.offset = (typeof initialOffset == 'undefined' ? 0 : initialOffset); +}; - return mediaArr; - } +var ISOFile = function(arrayBuffer) { + this._cursor = new ISOBoxer.Cursor(); + this.boxes = []; + if (arrayBuffer) { + this._raw = new DataView(arrayBuffer); + } +}; - function getStreamsInfo(manifest) { - var streams = []; - var mpd, ln, i; +ISOFile.prototype.fetch = function(type) { + var result = this.fetchAll(type, true); + return (result.length ? result[0] : null); +}; - if (!manifest) return null; +ISOFile.prototype.fetchAll = function(type, returnEarly) { + var result = []; + ISOFile._sweep.call(this, type, result, returnEarly); + return result; +}; - mpd = dashManifestModel.getMpd(manifest); - periods = dashManifestModel.getRegularPeriods(manifest, mpd); - mpd.checkTime = dashManifestModel.getCheckTime(manifest, periods[0]); - adaptations = {}; - ln = periods.length; +ISOFile.prototype.parse = function() { + this._cursor.offset = 0; + this.boxes = []; + while (this._cursor.offset < this._raw.byteLength) { + var box = ISOBox.parse(this); - for (i = 0; i < ln; i++) { - streams.push(convertPeriodToStreamInfo(manifest, periods[i])); - } + // Box could not be parsed + if (typeof box.type === 'undefined') break; - return streams; - } + this.boxes.push(box); + } + return this; +}; - function getManifestInfo(manifest) { - var mpd = dashManifestModel.getMpd(manifest); +ISOFile._sweep = function(type, result, returnEarly) { + if (this.type && this.type == type) result.push(this); + for (var box in this.boxes) { + if (result.length && returnEarly) return; + ISOFile._sweep.call(this.boxes[box], type, result, returnEarly); + } +}; - return convertMpdToManifestInfo(manifest, mpd); - } +ISOFile.prototype.write = function() { - function getInitRequest(streamProcessor, quality) { - var representation = streamProcessor.getRepresentationController().getRepresentationForQuality(quality); - return streamProcessor.getIndexHandler().getInitRequest(representation); - } + var length = 0, + i; - function getNextFragmentRequest(streamProcessor, trackInfo) { - var representation = getRepresentationForTrackInfo(trackInfo, streamProcessor.getRepresentationController()); - return streamProcessor.getIndexHandler().getNextSegmentRequest(representation); - } + for (i = 0; i < this.boxes.length; i++) { + length += this.boxes[i].getLength(false); + } - function getFragmentRequestForTime(streamProcessor, trackInfo, time, options) { - var representation = getRepresentationForTrackInfo(trackInfo, streamProcessor.getRepresentationController()); - return streamProcessor.getIndexHandler().getSegmentRequestForTime(representation, time, options); - } + var bytes = new Uint8Array(length); + this._rawo = new DataView(bytes.buffer); + this.bytes = bytes; + this._cursor.offset = 0; - function generateFragmentRequestForTime(streamProcessor, trackInfo, time) { - var representation = getRepresentationForTrackInfo(trackInfo, streamProcessor.getRepresentationController()); - return streamProcessor.getIndexHandler().generateSegmentRequestForTime(representation, time); - } + for (i = 0; i < this.boxes.length; i++) { + this.boxes[i].write(); + } - function getIndexHandlerTime(streamProcessor) { - return streamProcessor.getIndexHandler().getCurrentTime(); - } + return bytes.buffer; +}; - function setIndexHandlerTime(streamProcessor, value) { - return streamProcessor.getIndexHandler().setCurrentTime(value); - } +ISOFile.prototype.append = function(box, pos) { + ISOBoxer.Utils.appendBox(this, box, pos); +}; +var ISOBox = function() { + this._cursor = new ISOBoxer.Cursor(); +}; - function updateData(manifest, streamProcessor) { - var periodInfo = getPeriodForStreamInfo(streamProcessor.getStreamInfo()); - var mediaInfo = streamProcessor.getMediaInfo(); - var adaptation = getAdaptationForMediaInfo(mediaInfo); - var type = streamProcessor.getType(); +ISOBox.parse = function(parent) { + var newBox = new ISOBox(); + newBox._offset = parent._cursor.offset; + newBox._root = (parent._root ? parent._root : parent); + newBox._raw = parent._raw; + newBox._parent = parent; + newBox._parseBox(); + parent._cursor.offset = newBox._raw.byteOffset + newBox._raw.byteLength; + return newBox; +}; - var id, data; +ISOBox.create = function(type) { + var newBox = new ISOBox(); + newBox.type = type; + newBox.boxes = []; + return newBox; +}; - id = mediaInfo.id; - data = id ? dashManifestModel.getAdaptationForId(id, manifest, periodInfo.index) : dashManifestModel.getAdaptationForIndex(mediaInfo.index, manifest, periodInfo.index); - streamProcessor.getRepresentationController().updateData(data, adaptation, type); - } +ISOBox.prototype._boxContainers = ['dinf', 'edts', 'mdia', 'meco', 'mfra', 'minf', 'moof', 'moov', 'mvex', 'stbl', 'strk', 'traf', 'trak', 'tref', 'udta', 'vttc', 'sinf', 'schi', 'encv', 'enca']; - function getRepresentationInfoForQuality(manifest, representationController, quality) { - var representation = representationController.getRepresentationForQuality(quality); - return representation ? convertRepresentationToTrackInfo(manifest, representation) : null; - } +ISOBox.prototype._boxProcessors = {}; - function getCurrentRepresentationInfo(manifest, representationController) { - var representation = representationController.getCurrentRepresentation(); - return representation ? convertRepresentationToTrackInfo(manifest, representation) : null; - } +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Generic read/write functions - function getEvent(eventBox, eventStreams, startTime) { - var event = new _voEvent2['default'](); - var schemeIdUri = eventBox.scheme_id_uri; - var value = eventBox.value; - var timescale = eventBox.timescale; - var presentationTimeDelta = eventBox.presentation_time_delta; - var duration = eventBox.event_duration; - var id = eventBox.id; - var messageData = eventBox.message_data; - var presentationTime = startTime * timescale + presentationTimeDelta; +ISOBox.prototype._procField = function (name, type, size) { + if (this._parsing) { + this[name] = this._readField(type, size); + } + else { + this._writeField(type, size, this[name]); + } +}; - if (!eventStreams[schemeIdUri]) return null; +ISOBox.prototype._procFieldArray = function (name, length, type, size) { + var i; + if (this._parsing) { + this[name] = []; + for (i = 0; i < length; i++) { + this[name][i] = this._readField(type, size); + } + } + else { + for (i = 0; i < this[name].length; i++) { + this._writeField(type, size, this[name][i]); + } + } +}; - event.eventStream = eventStreams[schemeIdUri]; - event.eventStream.value = value; - event.eventStream.timescale = timescale; - event.duration = duration; - event.id = id; - event.presentationTime = presentationTime; - event.messageData = messageData; - event.presentationTimeDelta = presentationTimeDelta; +ISOBox.prototype._procFullBox = function() { + this._procField('version', 'uint', 8); + this._procField('flags', 'uint', 24); +}; - return event; +ISOBox.prototype._procEntries = function(name, length, fn) { + var i; + if (this._parsing) { + this[name] = []; + for (i = 0; i < length; i++) { + this[name].push({}); + fn.call(this, this[name][i]); + } + } + else { + for (i = 0; i < length; i++) { + fn.call(this, this[name][i]); } + } +}; - function getEventsFor(manifest, info, streamProcessor) { - var events = []; +ISOBox.prototype._procSubEntries = function(entry, name, length, fn) { + var i; + if (this._parsing) { + entry[name] = []; + for (i = 0; i < length; i++) { + entry[name].push({}); + fn.call(this, entry[name][i]); + } + } + else { + for (i = 0; i < length; i++) { + fn.call(this, entry[name][i]); + } + } +}; - if (info instanceof _streamingVoStreamInfo2['default']) { - events = dashManifestModel.getEventsForPeriod(manifest, getPeriodForStreamInfo(info)); - } else if (info instanceof _streamingVoMediaInfo2['default']) { - events = dashManifestModel.getEventStreamForAdaptationSet(manifest, getAdaptationForMediaInfo(info)); - } else if (info instanceof _streamingVoTrackInfo2['default']) { - events = dashManifestModel.getEventStreamForRepresentation(manifest, getRepresentationForTrackInfo(info, streamProcessor.getRepresentationController())); - } +ISOBox.prototype._procEntryField = function (entry, name, type, size) { + if (this._parsing) { + entry[name] = this._readField(type, size); + } + else { + this._writeField(type, size, entry[name]); + } +}; - return events; +ISOBox.prototype._procSubBoxes = function(name, length) { + var i; + if (this._parsing) { + this[name] = []; + for (i = 0; i < length; i++) { + this[name].push(ISOBox.parse(this)); } - - function reset() { - periods = []; - adaptations = {}; + } + else { + for (i = 0; i < length; i++) { + if (this._rawo) { + this[name][i].write(); + } else { + this.size += this[name][i].getLength(); + } } + } +}; - instance = { - initialize: initialize, - convertDataToTrack: convertRepresentationToTrackInfo, - convertDataToMedia: convertAdaptationToMediaInfo, - convertDataToStream: convertPeriodToStreamInfo, - getDataForTrack: getRepresentationForTrackInfo, - getDataForMedia: getAdaptationForMediaInfo, - getDataForStream: getPeriodForStreamInfo, - getStreamsInfo: getStreamsInfo, - getManifestInfo: getManifestInfo, - getMediaInfoForType: getMediaInfoForType, - getAllMediaInfoForType: getAllMediaInfoForType, - getCurrentRepresentationInfo: getCurrentRepresentationInfo, - getRepresentationInfoForQuality: getRepresentationInfoForQuality, - updateData: updateData, - getInitRequest: getInitRequest, - getNextFragmentRequest: getNextFragmentRequest, - getFragmentRequestForTime: getFragmentRequestForTime, - generateFragmentRequestForTime: generateFragmentRequestForTime, - getIndexHandlerTime: getIndexHandlerTime, - setIndexHandlerTime: setIndexHandlerTime, - getEventsFor: getEventsFor, - getEvent: getEvent, - setConfig: setConfig, - reset: reset, - metricsList: METRIC_LIST - }; +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Read/parse functions + +ISOBox.prototype._readField = function(type, size) { + switch (type) { + case 'uint': + return this._readUint(size); + case 'int': + return this._readInt(size); + case 'template': + return this._readTemplate(size); + case 'string': + return (size === -1) ? this._readTerminatedString() : this._readString(size); + case 'data': + return this._readData(size); + case 'utf8': + return this._readUTF8String(); + default: + return -1; + } +}; - return instance; -} +ISOBox.prototype._readInt = function(size) { + var result = null, + offset = this._cursor.offset - this._raw.byteOffset; + switch(size) { + case 8: + result = this._raw.getInt8(offset); + break; + case 16: + result = this._raw.getInt16(offset); + break; + case 32: + result = this._raw.getInt32(offset); + break; + case 64: + // Warning: JavaScript cannot handle 64-bit integers natively. + // This will give unexpected results for integers >= 2^53 + var s1 = this._raw.getInt32(offset); + var s2 = this._raw.getInt32(offset + 4); + result = (s1 * Math.pow(2,32)) + s2; + break; + } + this._cursor.offset += (size >> 3); + return result; +}; -DashAdapter.__dashjs_factory_name = 'DashAdapter'; -exports['default'] = _coreFactoryMaker2['default'].getSingletonFactory(DashAdapter); -module.exports = exports['default']; +ISOBox.prototype._readUint = function(size) { + var result = null, + offset = this._cursor.offset - this._raw.byteOffset, + s1, s2; + switch(size) { + case 8: + result = this._raw.getUint8(offset); + break; + case 16: + result = this._raw.getUint16(offset); + break; + case 24: + s1 = this._raw.getUint16(offset); + s2 = this._raw.getUint8(offset + 2); + result = (s1 << 8) + s2; + break; + case 32: + result = this._raw.getUint32(offset); + break; + case 64: + // Warning: JavaScript cannot handle 64-bit integers natively. + // This will give unexpected results for integers >= 2^53 + s1 = this._raw.getUint32(offset); + s2 = this._raw.getUint32(offset + 4); + result = (s1 * Math.pow(2,32)) + s2; + break; + } + this._cursor.offset += (size >> 3); + return result; +}; -},{"10":10,"166":166,"167":167,"169":169,"172":172,"2":2,"20":20,"41":41}],16:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -'use strict'; +ISOBox.prototype._readString = function(length) { + var str = ''; + for (var c = 0; c < length; c++) { + var char = this._readUint(8); + str += String.fromCharCode(char); + } + return str; +}; -Object.defineProperty(exports, '__esModule', { - value: true -}); +ISOBox.prototype._readTemplate = function(size) { + var pre = this._readUint(size / 2); + var post = this._readUint(size / 2); + return pre + (post / Math.pow(2, size / 2)); +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } +ISOBox.prototype._readTerminatedString = function() { + var str = ''; + while (this._cursor.offset - this._offset < this._raw.byteLength) { + var char = this._readUint(8); + if (char === 0) break; + str += String.fromCharCode(char); + } + return str; +}; -var _streamingVoFragmentRequest = _dereq_(163); +ISOBox.prototype._readData = function(size) { + var length = (size > 0) ? size : (this._raw.byteLength - (this._cursor.offset - this._offset)); + var data = new DataView(this._raw.buffer, this._cursor.offset, length); + this._cursor.offset += length; + return data; +}; -var _streamingVoFragmentRequest2 = _interopRequireDefault(_streamingVoFragmentRequest); +ISOBox.prototype._readUTF8String = function() { + var data = this._readData(); + return ISOBoxer.Utils.dataViewToString(data); +}; -var _streamingVoError = _dereq_(162); +ISOBox.prototype._parseBox = function() { + this._parsing = true; + this._cursor.offset = this._offset; -var _streamingVoError2 = _interopRequireDefault(_streamingVoError); + // return immediately if there are not enough bytes to read the header + if (this._offset + 8 > this._raw.buffer.byteLength) { + this._root._incomplete = true; + return; + } -var _streamingVoMetricsHTTPRequest = _dereq_(179); + this._procField('size', 'uint', 32); + this._procField('type', 'string', 4); -var _coreEventsEvents = _dereq_(13); + if (this.size === 1) { this._procField('largesize', 'uint', 64); } + if (this.type === 'uuid') { this._procFieldArray('usertype', 16, 'uint', 8); } -var _coreEventsEvents2 = _interopRequireDefault(_coreEventsEvents); + switch(this.size) { + case 0: + this._raw = new DataView(this._raw.buffer, this._offset, (this._raw.byteLength - this._cursor.offset + 8)); + break; + case 1: + if (this._offset + this.size > this._raw.buffer.byteLength) { + this._incomplete = true; + this._root._incomplete = true; + } else { + this._raw = new DataView(this._raw.buffer, this._offset, this.largesize); + } + break; + default: + if (this._offset + this.size > this._raw.buffer.byteLength) { + this._incomplete = true; + this._root._incomplete = true; + } else { + this._raw = new DataView(this._raw.buffer, this._offset, this.size); + } + } -var _coreEventBus = _dereq_(9); + // additional parsing + if (!this._incomplete) { + if (this._boxProcessors[this.type]) { + this._boxProcessors[this.type].call(this); + } + if (this._boxContainers.indexOf(this.type) !== -1) { + this._parseContainerBox(); + } else{ + // Unknown box => read and store box content + this._data = this._readData(); + } + } +}; -var _coreEventBus2 = _interopRequireDefault(_coreEventBus); +ISOBox.prototype._parseFullBox = function() { + this.version = this._readUint(8); + this.flags = this._readUint(24); +}; -var _coreFactoryMaker = _dereq_(10); +ISOBox.prototype._parseContainerBox = function() { + this.boxes = []; + while (this._cursor.offset - this._raw.byteOffset < this._raw.byteLength) { + this.boxes.push(ISOBox.parse(this)); + } +}; -var _coreFactoryMaker2 = _interopRequireDefault(_coreFactoryMaker); +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Write functions -var _coreDebug = _dereq_(8); +ISOBox.prototype.append = function(box, pos) { + ISOBoxer.Utils.appendBox(this, box, pos); +}; -var _coreDebug2 = _interopRequireDefault(_coreDebug); +ISOBox.prototype.getLength = function() { + this._parsing = false; + this._rawo = null; -var _streamingUtilsURLUtils = _dereq_(158); + this.size = 0; + this._procField('size', 'uint', 32); + this._procField('type', 'string', 4); -var _streamingUtilsURLUtils2 = _interopRequireDefault(_streamingUtilsURLUtils); + if (this.size === 1) { this._procField('largesize', 'uint', 64); } + if (this.type === 'uuid') { this._procFieldArray('usertype', 16, 'uint', 8); } -var _utilsSegmentsUtils = _dereq_(35); + if (this._boxProcessors[this.type]) { + this._boxProcessors[this.type].call(this); + } -var _utilsSegmentsGetter = _dereq_(34); + if (this._boxContainers.indexOf(this.type) !== -1) { + for (var i = 0; i < this.boxes.length; i++) { + this.size += this.boxes[i].getLength(); + } + } -var _utilsSegmentsGetter2 = _interopRequireDefault(_utilsSegmentsGetter); + if (this._data) { + this._writeData(this._data); + } -var SEGMENTS_UNAVAILABLE_ERROR_CODE = 1; + return this.size; +}; -function DashHandler(config) { +ISOBox.prototype.write = function() { + this._parsing = false; + this._cursor.offset = this._parent._cursor.offset; - var context = this.context; - var log = (0, _coreDebug2['default'])(context).getInstance().log; - var eventBus = (0, _coreEventBus2['default'])(context).getInstance(); - var urlUtils = (0, _streamingUtilsURLUtils2['default'])(context).getInstance(); + switch(this.size) { + case 0: + this._rawo = new DataView(this._parent._rawo.buffer, this._cursor.offset, (this.parent._rawo.byteLength - this._cursor.offset)); + break; + case 1: + this._rawo = new DataView(this._parent._rawo.buffer, this._cursor.offset, this.largesize); + break; + default: + this._rawo = new DataView(this._parent._rawo.buffer, this._cursor.offset, this.size); + } - var segmentBaseLoader = config.segmentBaseLoader; - var timelineConverter = config.timelineConverter; - var dashMetrics = config.dashMetrics; - var metricsModel = config.metricsModel; - var baseURLController = config.baseURLController; + this._procField('size', 'uint', 32); + this._procField('type', 'string', 4); - var instance = undefined, - index = undefined, - requestedTime = undefined, - isDynamic = undefined, - type = undefined, - currentTime = undefined, - earliestTime = undefined, - streamProcessor = undefined, - segmentsGetter = undefined; + if (this.size === 1) { this._procField('largesize', 'uint', 64); } + if (this.type === 'uuid') { this._procFieldArray('usertype', 16, 'uint', 8); } - function setup() { - index = -1; - currentTime = 0; - earliestTime = NaN; - eventBus.on(_coreEventsEvents2['default'].INITIALIZATION_LOADED, onInitializationLoaded, instance); - eventBus.on(_coreEventsEvents2['default'].SEGMENTS_LOADED, onSegmentsLoaded, instance); + if (this._boxProcessors[this.type]) { + this._boxProcessors[this.type].call(this); + } + + if (this._boxContainers.indexOf(this.type) !== -1) { + for (var i = 0; i < this.boxes.length; i++) { + this.boxes[i].write(); } + } - function initialize(StreamProcessor) { - streamProcessor = StreamProcessor; - type = streamProcessor.getType(); - isDynamic = streamProcessor.isDynamic(); + if (this._data) { + this._writeData(this._data); + } - segmentsGetter = (0, _utilsSegmentsGetter2['default'])(context).create(config, isDynamic); - } + this._parent._cursor.offset += this.size; - function getStreamProcessor() { - return streamProcessor; - } + return this.size; +}; - function setCurrentTime(value) { - currentTime = value; - } +ISOBox.prototype._writeInt = function(size, value) { + if (this._rawo) { + var offset = this._cursor.offset - this._rawo.byteOffset; + switch(size) { + case 8: + this._rawo.setInt8(offset, value); + break; + case 16: + this._rawo.setInt16(offset, value); + break; + case 32: + this._rawo.setInt32(offset, value); + break; + case 64: + // Warning: JavaScript cannot handle 64-bit integers natively. + // This will give unexpected results for integers >= 2^53 + var s1 = Math.floor(value / Math.pow(2,32)); + var s2 = value - (s1 * Math.pow(2,32)); + this._rawo.setUint32(offset, s1); + this._rawo.setUint32(offset + 4, s2); + break; + } + this._cursor.offset += (size >> 3); + } else { + this.size += (size >> 3); + } +}; - function getCurrentTime() { - return currentTime; - } +ISOBox.prototype._writeUint = function(size, value) { + + if (this._rawo) { + var offset = this._cursor.offset - this._rawo.byteOffset, + s1, s2; + switch(size) { + case 8: + this._rawo.setUint8(offset, value); + break; + case 16: + this._rawo.setUint16(offset, value); + break; + case 24: + s1 = (value & 0xFFFF00) >> 8; + s2 = (value & 0x0000FF); + this._rawo.setUint16(offset, s1); + this._rawo.setUint8(offset + 2, s2); + break; + case 32: + this._rawo.setUint32(offset, value); + break; + case 64: + // Warning: JavaScript cannot handle 64-bit integers natively. + // This will give unexpected results for integers >= 2^53 + s1 = Math.floor(value / Math.pow(2,32)); + s2 = value - (s1 * Math.pow(2,32)); + this._rawo.setUint32(offset, s1); + this._rawo.setUint32(offset + 4, s2); + break; + } + this._cursor.offset += (size >> 3); + } else { + this.size += (size >> 3); + } +}; - function getCurrentIndex() { - return index; - } +ISOBox.prototype._writeString = function(size, str) { + for (var c = 0; c < size; c++) { + this._writeUint(8, str.charCodeAt(c)); + } +}; - function getEarliestTime() { - return earliestTime; - } +ISOBox.prototype._writeTerminatedString = function(str) { + if (str.length === 0) { + return; + } + for (var c = 0; c < str.length; c++) { + this._writeUint(8, str.charCodeAt(c)); + } + this._writeUint(8, 0); +}; - function reset() { - segmentsGetter = null; - currentTime = 0; - earliestTime = NaN; - requestedTime = NaN; - index = -1; - isDynamic = null; - type = null; - streamProcessor = null; - eventBus.off(_coreEventsEvents2['default'].INITIALIZATION_LOADED, onInitializationLoaded, instance); - eventBus.off(_coreEventsEvents2['default'].SEGMENTS_LOADED, onSegmentsLoaded, instance); - } +ISOBox.prototype._writeTemplate = function(size, value) { + var pre = Math.floor(value); + var post = (value - pre) * Math.pow(2, size / 2); + this._writeUint(size / 2, pre); + this._writeUint(size / 2, post); +}; - function unescapeDollarsInTemplate(url) { - return url.split('$$').join('$'); +ISOBox.prototype._writeData = function(data) { + var i; + if (data instanceof Array) { + if (!Uint8Array.from) { + var typedArray = new Uint8Array(data.length); + for (i = 0; i < data.length; i++) { + typedArray[i] = data[i]; + } + data = new DataView(typedArray.buffer); + } else { + data = new DataView(Uint8Array.from(data).buffer); } + } + if (data instanceof Uint8Array) { + data = new DataView(data.buffer); + } + if (this._rawo) { + var offset = this._cursor.offset - this._rawo.byteOffset; + for (i = 0; i < data.byteLength; i++) { + this._rawo.setUint8(offset + i, data.getUint8(i)); + } + this._cursor.offset += data.byteLength; + } else { + this.size += data.byteLength; + } +}; - function replaceIDForTemplate(url, value) { - if (value === null || url.indexOf('$RepresentationID$') === -1) { - return url; - } - var v = value.toString(); - return url.split('$RepresentationID$').join(v); +ISOBox.prototype._writeUTF8String = function(string) { + var u = ISOBoxer.Utils.utf8ToByteArray(string); + if (this._rawo) { + var dataView = new DataView(this._rawo.buffer, this._cursor.offset, u.length); + for (var i = 0; i < u.length; i++) { + dataView.setUint8(i, u[i]); } + } else { + this.size += u.length; + } +}; - function setRequestUrl(request, destination, representation) { - var baseURL = baseURLController.resolve(representation.path); - var url; - var serviceLocation; +ISOBox.prototype._writeField = function(type, size, value) { + switch (type) { + case 'uint': + this._writeUint(size, value); + break; + case 'int': + this._writeInt(size, value); + break; + case 'template': + this._writeTemplate(size, value); + break; + case 'string': + if (size == -1) { + this._writeTerminatedString(value); + } else { + this._writeString(size, value); + } + break; + case 'data': + this._writeData(value); + break; + case 'utf8': + this._writeUTF8String(value); + break; + default: + break; + } +}; - if (!baseURL || destination === baseURL.url || !urlUtils.isRelative(destination)) { - url = destination; - } else { - url = baseURL.url; - serviceLocation = baseURL.serviceLocation; +// ISO/IEC 14496-15:2014 - avc1 box +ISOBox.prototype._boxProcessors['avc1'] = ISOBox.prototype._boxProcessors['encv'] = function() { + // SampleEntry fields + this._procFieldArray('reserved1', 6, 'uint', 8); + this._procField('data_reference_index', 'uint', 16); + // VisualSampleEntry fields + this._procField('pre_defined1', 'uint', 16); + this._procField('reserved2', 'uint', 16); + this._procFieldArray('pre_defined2', 3, 'uint', 32); + this._procField('width', 'uint', 16); + this._procField('height', 'uint', 16); + this._procField('horizresolution', 'template', 32); + this._procField('vertresolution', 'template', 32); + this._procField('reserved3', 'uint', 32); + this._procField('frame_count', 'uint', 16); + this._procFieldArray('compressorname', 32,'uint', 8); + this._procField('depth', 'uint', 16); + this._procField('pre_defined3', 'int', 16); + // AVCSampleEntry fields + this._procField('config', 'data', -1); +}; - if (destination) { - url += destination; - } - } +// ISO/IEC 14496-12:2012 - 8.7.2 Data Reference Box +ISOBox.prototype._boxProcessors['dref'] = function() { + this._procFullBox(); + this._procField('entry_count', 'uint', 32); + this._procSubBoxes('entries', this.entry_count); +}; - if (urlUtils.isRelative(url)) { - return false; - } +// ISO/IEC 14496-12:2012 - 8.6.6 Edit List Box +ISOBox.prototype._boxProcessors['elst'] = function() { + this._procFullBox(); + this._procField('entry_count', 'uint', 32); + this._procEntries('entries', this.entry_count, function(entry) { + this._procEntryField(entry, 'segment_duration', 'uint', (this.version === 1) ? 64 : 32); + this._procEntryField(entry, 'media_time', 'int', (this.version === 1) ? 64 : 32); + this._procEntryField(entry, 'media_rate_integer', 'int', 16); + this._procEntryField(entry, 'media_rate_fraction', 'int', 16); + }); +}; - request.url = url; - request.serviceLocation = serviceLocation; +// ISO/IEC 23009-1:2014 - 5.10.3.3 Event Message Box +ISOBox.prototype._boxProcessors['emsg'] = function() { + this._procFullBox(); + this._procField('scheme_id_uri', 'string', -1); + this._procField('value', 'string', -1); + this._procField('timescale', 'uint', 32); + this._procField('presentation_time_delta', 'uint', 32); + this._procField('event_duration', 'uint', 32); + this._procField('id', 'uint', 32); + this._procField('message_data', 'data', -1); +}; - return true; - } +// ISO/IEC 14496-12:2012 - 8.1.2 Free Space Box +ISOBox.prototype._boxProcessors['free'] = ISOBox.prototype._boxProcessors['skip'] = function() { + this._procField('data', 'data', -1); +}; - function generateInitRequest(representation, mediaType) { - var request = new _streamingVoFragmentRequest2['default'](); - var period, presentationStartTime; +// ISO/IEC 14496-12:2012 - 8.12.2 Original Format Box +ISOBox.prototype._boxProcessors['frma'] = function() { + this._procField('data_format', 'uint', 32); +}; +// ISO/IEC 14496-12:2012 - 4.3 File Type Box / 8.16.2 Segment Type Box +ISOBox.prototype._boxProcessors['ftyp'] = +ISOBox.prototype._boxProcessors['styp'] = function() { + this._procField('major_brand', 'string', 4); + this._procField('minor_version', 'uint', 32); + var nbCompatibleBrands = -1; + if (this._parsing) { + nbCompatibleBrands = (this._raw.byteLength - (this._cursor.offset - this._raw.byteOffset)) / 4; + } + this._procFieldArray('compatible_brands', nbCompatibleBrands, 'string', 4); +}; - period = representation.adaptation.period; +// ISO/IEC 14496-12:2012 - 8.4.3 Handler Reference Box +ISOBox.prototype._boxProcessors['hdlr'] = function() { + this._procFullBox(); + this._procField('pre_defined', 'uint', 32); + this._procField('handler_type', 'string', 4); + this._procFieldArray('reserved', 3, 'uint', 32); + this._procField('name', 'string', -1); +}; - request.mediaType = mediaType; - request.type = _streamingVoMetricsHTTPRequest.HTTPRequest.INIT_SEGMENT_TYPE; - request.range = representation.range; - presentationStartTime = period.start; - request.availabilityStartTime = timelineConverter.calcAvailabilityStartTimeFromPresentationTime(presentationStartTime, representation.adaptation.period.mpd, isDynamic); - request.availabilityEndTime = timelineConverter.calcAvailabilityEndTimeFromPresentationTime(presentationStartTime + period.duration, period.mpd, isDynamic); - request.quality = representation.index; - request.mediaInfo = streamProcessor.getMediaInfo(); +// ISO/IEC 14496-12:2012 - 8.1.1 Media Data Box +ISOBox.prototype._boxProcessors['mdat'] = function() { + this._procField('data', 'data', -1); +}; - if (setRequestUrl(request, representation.initialization, representation)) { - return request; - } - } +// ISO/IEC 14496-12:2012 - 8.4.2 Media Header Box +ISOBox.prototype._boxProcessors['mdhd'] = function() { + this._procFullBox(); + this._procField('creation_time', 'uint', (this.version == 1) ? 64 : 32); + this._procField('modification_time', 'uint', (this.version == 1) ? 64 : 32); + this._procField('timescale', 'uint', 32); + this._procField('duration', 'uint', (this.version == 1) ? 64 : 32); + if (!this._parsing && typeof this.language === 'string') { + // In case of writing and language has been set as a string, then convert it into char codes array + this.language = ((this.language.charCodeAt(0) - 0x60) << 10) | + ((this.language.charCodeAt(1) - 0x60) << 5) | + ((this.language.charCodeAt(2) - 0x60)); + } + this._procField('language', 'uint', 16); + if (this._parsing) { + this.language = String.fromCharCode(((this.language >> 10) & 0x1F) + 0x60, + ((this.language >> 5) & 0x1F) + 0x60, + (this.language & 0x1F) + 0x60); + } + this._procField('pre_defined', 'uint', 16); +}; - function getInitRequest(representation) { - var request; +// ISO/IEC 14496-12:2012 - 8.8.2 Movie Extends Header Box +ISOBox.prototype._boxProcessors['mehd'] = function() { + this._procFullBox(); + this._procField('fragment_duration', 'uint', (this.version == 1) ? 64 : 32); +}; - if (!representation) return null; +// ISO/IEC 14496-12:2012 - 8.8.5 Movie Fragment Header Box +ISOBox.prototype._boxProcessors['mfhd'] = function() { + this._procFullBox(); + this._procField('sequence_number', 'uint', 32); +}; - request = generateInitRequest(representation, type); +// ISO/IEC 14496-12:2012 - 8.8.11 Movie Fragment Random Access Box +ISOBox.prototype._boxProcessors['mfro'] = function() { + this._procFullBox(); + this._procField('mfra_size', 'uint', 32); // Called mfra_size to distinguish from the normal "size" attribute of a box +}; - //log("Got an initialization."); - return request; - } +// ISO/IEC 14496-12:2012 - 8.5.2.2 mp4a box (use AudioSampleEntry definition and naming) +ISOBox.prototype._boxProcessors['mp4a'] = ISOBox.prototype._boxProcessors['enca'] = function() { + // SampleEntry fields + this._procFieldArray('reserved1', 6, 'uint', 8); + this._procField('data_reference_index', 'uint', 16); + // AudioSampleEntry fields + this._procFieldArray('reserved2', 2, 'uint', 32); + this._procField('channelcount', 'uint', 16); + this._procField('samplesize', 'uint', 16); + this._procField('pre_defined', 'uint', 16); + this._procField('reserved3', 'uint', 16); + this._procField('samplerate', 'template', 32); + // ESDescriptor fields + this._procField('esds', 'data', -1); +}; - function isMediaFinished(representation) { - var period = representation.adaptation.period; - var segmentInfoType = representation.segmentInfoType; +// ISO/IEC 14496-12:2012 - 8.2.2 Movie Header Box +ISOBox.prototype._boxProcessors['mvhd'] = function() { + this._procFullBox(); + this._procField('creation_time', 'uint', (this.version == 1) ? 64 : 32); + this._procField('modification_time', 'uint', (this.version == 1) ? 64 : 32); + this._procField('timescale', 'uint', 32); + this._procField('duration', 'uint', (this.version == 1) ? 64 : 32); + this._procField('rate', 'template', 32); + this._procField('volume', 'template', 16); + this._procField('reserved1', 'uint', 16); + this._procFieldArray('reserved2', 2, 'uint', 32); + this._procFieldArray('matrix', 9, 'template', 32); + this._procFieldArray('pre_defined', 6,'uint', 32); + this._procField('next_track_ID', 'uint', 32); +}; - var isFinished = false; +// ISO/IEC 14496-30:2014 - WebVTT Cue Payload Box. +ISOBox.prototype._boxProcessors['payl'] = function() { + this._procField('cue_text', 'utf8'); +}; - var sDuration, seg, fTime; +//ISO/IEC 23001-7:2011 - 8.1 Protection System Specific Header Box +ISOBox.prototype._boxProcessors['pssh'] = function() { + this._procFullBox(); + + this._procFieldArray('SystemID', 16, 'uint', 8); + this._procField('DataSize', 'uint', 32); + this._procFieldArray('Data', this.DataSize, 'uint', 8); +}; +// ISO/IEC 14496-12:2012 - 8.12.5 Scheme Type Box +ISOBox.prototype._boxProcessors['schm'] = function() { + this._procFullBox(); + + this._procField('scheme_type', 'uint', 32); + this._procField('scheme_version', 'uint', 32); - if (index < 0) { - isFinished = false; - } else if (isDynamic || index < representation.availableSegmentsNumber) { - seg = (0, _utilsSegmentsUtils.getSegmentByIndex)(index, representation); + if (this.flags & 0x000001) { + this._procField('scheme_uri', 'string', -1); + } +}; +// ISO/IEC 14496-12:2012 - 8.6.4.1 sdtp box +ISOBox.prototype._boxProcessors['sdtp'] = function() { + this._procFullBox(); - if (seg) { - fTime = seg.presentationStartTime - period.start; - sDuration = representation.adaptation.period.duration; - log(representation.segmentInfoType + ': ' + fTime + ' / ' + sDuration); - isFinished = segmentInfoType === 'SegmentTimeline' && isDynamic ? false : fTime >= sDuration; - } - } else { - isFinished = true; - } + var sample_count = -1; + if (this._parsing) { + sample_count = (this._raw.byteLength - (this._cursor.offset - this._raw.byteOffset)); + } - return isFinished; - } + this._procFieldArray('sample_dependency_table', sample_count, 'uint', 8); +}; - function updateSegments(representation) { - return segmentsGetter.getSegments(representation, requestedTime, index, onSegmentListUpdated); - } +// ISO/IEC 14496-12:2012 - 8.16.3 Segment Index Box +ISOBox.prototype._boxProcessors['sidx'] = function() { + this._procFullBox(); + this._procField('reference_ID', 'uint', 32); + this._procField('timescale', 'uint', 32); + this._procField('earliest_presentation_time', 'uint', (this.version == 1) ? 64 : 32); + this._procField('first_offset', 'uint', (this.version == 1) ? 64 : 32); + this._procField('reserved', 'uint', 16); + this._procField('reference_count', 'uint', 16); + this._procEntries('references', this.reference_count, function(entry) { + if (!this._parsing) { + entry.reference = (entry.reference_type & 0x00000001) << 31; + entry.reference |= (entry.referenced_size & 0x7FFFFFFF); + entry.sap = (entry.starts_with_SAP & 0x00000001) << 31; + entry.sap |= (entry.SAP_type & 0x00000003) << 28; + entry.sap |= (entry.SAP_delta_time & 0x0FFFFFFF); + } + this._procEntryField(entry, 'reference', 'uint', 32); + this._procEntryField(entry, 'subsegment_duration', 'uint', 32); + this._procEntryField(entry, 'sap', 'uint', 32); + if (this._parsing) { + entry.reference_type = (entry.reference >> 31) & 0x00000001; + entry.referenced_size = entry.reference & 0x7FFFFFFF; + entry.starts_with_SAP = (entry.sap >> 31) & 0x00000001; + entry.SAP_type = (entry.sap >> 28) & 0x00000007; + entry.SAP_delta_time = (entry.sap & 0x0FFFFFFF); + } + }); +}; - function onSegmentListUpdated(representation, segments) { +// ISO/IEC 14496-12:2012 - 8.4.5.3 Sound Media Header Box +ISOBox.prototype._boxProcessors['smhd'] = function() { + this._procFullBox(); + this._procField('balance', 'uint', 16); + this._procField('reserved', 'uint', 16); +}; - representation.segments = segments; +// ISO/IEC 14496-12:2012 - 8.16.4 Subsegment Index Box +ISOBox.prototype._boxProcessors['ssix'] = function() { + this._procFullBox(); + this._procField('subsegment_count', 'uint', 32); + this._procEntries('subsegments', this.subsegment_count, function(subsegment) { + this._procEntryField(subsegment, 'ranges_count', 'uint', 32); + this._procSubEntries(subsegment, 'ranges', subsegment.ranges_count, function(range) { + this._procEntryField(range, 'level', 'uint', 8); + this._procEntryField(range, 'range_size', 'uint', 24); + }); + }); +}; - if (segments && segments.length > 0) { - earliestTime = isNaN(earliestTime) ? segments[0].presentationStartTime : Math.min(segments[0].presentationStartTime, earliestTime); - } +// ISO/IEC 14496-12:2012 - 8.5.2 Sample Description Box +ISOBox.prototype._boxProcessors['stsd'] = function() { + this._procFullBox(); + this._procField('entry_count', 'uint', 32); + this._procSubBoxes('entries', this.entry_count); +}; - if (isDynamic && isNaN(timelineConverter.getExpectedLiveEdge())) { - var lastIdx = segments.length - 1; - var lastSegment = segments[lastIdx]; - var liveEdge = lastSegment.presentationStartTime; - var metrics = metricsModel.getMetricsFor('stream'); - // the last segment is supposed to be a live edge - timelineConverter.setExpectedLiveEdge(liveEdge); - metricsModel.updateManifestUpdateInfo(dashMetrics.getCurrentManifestUpdate(metrics), { presentationStartTime: liveEdge }); - } - } +// ISO/IEC 14496-12:2015 - 8.7.7 Sub-Sample Information Box +ISOBox.prototype._boxProcessors['subs'] = function () { + this._procFullBox(); + this._procField('entry_count', 'uint', 32); + this._procEntries('entries', this.entry_count, function(entry) { + this._procEntryField(entry, 'sample_delta', 'uint', 32); + this._procEntryField(entry, 'subsample_count', 'uint', 16); + this._procSubEntries(entry, 'subsamples', entry.subsample_count, function(subsample) { + this._procEntryField(subsample, 'subsample_size', 'uint', (this.version === 1) ? 32 : 16); + this._procEntryField(subsample, 'subsample_priority', 'uint', 8); + this._procEntryField(subsample, 'discardable', 'uint', 8); + this._procEntryField(subsample, 'codec_specific_parameters', 'uint', 32); + }); + }); +}; - function updateSegmentList(representation) { +//ISO/IEC 23001-7:2011 - 8.2 Track Encryption Box +ISOBox.prototype._boxProcessors['tenc'] = function() { + this._procFullBox(); - if (!representation) { - throw new _streamingVoError2['default']('no representation'); - } + this._procField('default_IsEncrypted', 'uint', 24); + this._procField('default_IV_size', 'uint', 8); + this._procFieldArray('default_KID', 16, 'uint', 8); + }; - representation.segments = null; +// ISO/IEC 14496-12:2012 - 8.8.12 Track Fragmnent Decode Time +ISOBox.prototype._boxProcessors['tfdt'] = function() { + this._procFullBox(); + this._procField('baseMediaDecodeTime', 'uint', (this.version == 1) ? 64 : 32); +}; - updateSegments(representation); +// ISO/IEC 14496-12:2012 - 8.8.7 Track Fragment Header Box +ISOBox.prototype._boxProcessors['tfhd'] = function() { + this._procFullBox(); + this._procField('track_ID', 'uint', 32); + if (this.flags & 0x01) this._procField('base_data_offset', 'uint', 64); + if (this.flags & 0x02) this._procField('sample_description_offset', 'uint', 32); + if (this.flags & 0x08) this._procField('default_sample_duration', 'uint', 32); + if (this.flags & 0x10) this._procField('default_sample_size', 'uint', 32); + if (this.flags & 0x20) this._procField('default_sample_flags', 'uint', 32); +}; - return representation; - } +// ISO/IEC 14496-12:2012 - 8.8.10 Track Fragment Random Access Box +ISOBox.prototype._boxProcessors['tfra'] = function() { + this._procFullBox(); + this._procField('track_ID', 'uint', 32); + if (!this._parsing) { + this.reserved = 0; + this.reserved |= (this.length_size_of_traf_num & 0x00000030) << 4; + this.reserved |= (this.length_size_of_trun_num & 0x0000000C) << 2; + this.reserved |= (this.length_size_of_sample_num & 0x00000003); + } + this._procField('reserved', 'uint', 32); + if (this._parsing) { + this.length_size_of_traf_num = (this.reserved & 0x00000030) >> 4; + this.length_size_of_trun_num = (this.reserved & 0x0000000C) >> 2; + this.length_size_of_sample_num = (this.reserved & 0x00000003); + } + this._procField('number_of_entry', 'uint', 32); + this._procEntries('entries', this.number_of_entry, function(entry) { + this._procEntryField(entry, 'time', 'uint', (this.version === 1) ? 64 : 32); + this._procEntryField(entry, 'moof_offset', 'uint', (this.version === 1) ? 64 : 32); + this._procEntryField(entry, 'traf_number', 'uint', (this.length_size_of_traf_num + 1) * 8); + this._procEntryField(entry, 'trun_number', 'uint', (this.length_size_of_trun_num + 1) * 8); + this._procEntryField(entry, 'sample_number', 'uint', (this.length_size_of_sample_num + 1) * 8); + }); +}; - function updateRepresentation(representation, keepIdx) { - var hasInitialization = representation.initialization; - var hasSegments = representation.segmentInfoType !== 'BaseURL' && representation.segmentInfoType !== 'SegmentBase' && !representation.indexRange; - var error; +// ISO/IEC 14496-12:2012 - 8.3.2 Track Header Box +ISOBox.prototype._boxProcessors['tkhd'] = function() { + this._procFullBox(); + this._procField('creation_time', 'uint', (this.version == 1) ? 64 : 32); + this._procField('modification_time', 'uint', (this.version == 1) ? 64 : 32); + this._procField('track_ID', 'uint', 32); + this._procField('reserved1', 'uint', 32); + this._procField('duration', 'uint', (this.version == 1) ? 64 : 32); + this._procFieldArray('reserved2', 2, 'uint', 32); + this._procField('layer', 'uint', 16); + this._procField('alternate_group', 'uint', 16); + this._procField('volume', 'template', 16); + this._procField('reserved3', 'uint', 16); + this._procFieldArray('matrix', 9, 'template', 32); + this._procField('width', 'template', 32); + this._procField('height', 'template', 32); +}; - if (!representation.segmentDuration && !representation.segments) { - updateSegmentList(representation); - } +// ISO/IEC 14496-12:2012 - 8.8.3 Track Extends Box +ISOBox.prototype._boxProcessors['trex'] = function() { + this._procFullBox(); + this._procField('track_ID', 'uint', 32); + this._procField('default_sample_description_index', 'uint', 32); + this._procField('default_sample_duration', 'uint', 32); + this._procField('default_sample_size', 'uint', 32); + this._procField('default_sample_flags', 'uint', 32); +}; - representation.segmentAvailabilityRange = null; - representation.segmentAvailabilityRange = timelineConverter.calcSegmentAvailabilityRange(representation, isDynamic); +// ISO/IEC 14496-12:2012 - 8.8.8 Track Run Box +// Note: the 'trun' box has a direct relation to the 'tfhd' box for defaults. +// These defaults are not set explicitly here, but are left to resolve for the user. +ISOBox.prototype._boxProcessors['trun'] = function() { + this._procFullBox(); + this._procField('sample_count', 'uint', 32); + if (this.flags & 0x1) this._procField('data_offset', 'int', 32); + if (this.flags & 0x4) this._procField('first_sample_flags', 'uint', 32); + this._procEntries('samples', this.sample_count, function(sample) { + if (this.flags & 0x100) this._procEntryField(sample, 'sample_duration', 'uint', 32); + if (this.flags & 0x200) this._procEntryField(sample, 'sample_size', 'uint', 32); + if (this.flags & 0x400) this._procEntryField(sample, 'sample_flags', 'uint', 32); + if (this.flags & 0x800) this._procEntryField(sample, 'sample_composition_time_offset', (this.version === 1) ? 'int' : 'uint', 32); + }); +}; - if (representation.segmentAvailabilityRange.end < representation.segmentAvailabilityRange.start && !representation.useCalculatedLiveEdgeTime) { - error = new _streamingVoError2['default'](SEGMENTS_UNAVAILABLE_ERROR_CODE, 'no segments are available yet', { availabilityDelay: representation.segmentAvailabilityRange.start - representation.segmentAvailabilityRange.end }); - eventBus.trigger(_coreEventsEvents2['default'].REPRESENTATION_UPDATED, { sender: this, representation: representation, error: error }); - return; - } +// ISO/IEC 14496-12:2012 - 8.7.2 Data Reference Box +ISOBox.prototype._boxProcessors['url '] = ISOBox.prototype._boxProcessors['urn '] = function() { + this._procFullBox(); + if (this.type === 'urn ') { + this._procField('name', 'string', -1); + } + this._procField('location', 'string', -1); +}; - if (!keepIdx) index = -1; +// ISO/IEC 14496-30:2014 - WebVTT Source Label Box +ISOBox.prototype._boxProcessors['vlab'] = function() { + this._procField('source_label', 'utf8'); +}; - if (representation.segmentDuration) { - updateSegmentList(representation); - } +// ISO/IEC 14496-12:2012 - 8.4.5.2 Video Media Header Box +ISOBox.prototype._boxProcessors['vmhd'] = function() { + this._procFullBox(); + this._procField('graphicsmode', 'uint', 16); + this._procFieldArray('opcolor', 3, 'uint', 16); +}; - if (!hasInitialization) { - segmentBaseLoader.loadInitialization(representation); - } +// ISO/IEC 14496-30:2014 - WebVTT Configuration Box +ISOBox.prototype._boxProcessors['vttC'] = function() { + this._procField('config', 'utf8'); +}; - if (!hasSegments) { - segmentBaseLoader.loadSegments(representation, type, representation.indexRange); - } +// ISO/IEC 14496-30:2014 - WebVTT Empty Sample Box +ISOBox.prototype._boxProcessors['vtte'] = function() { + // Nothing should happen here. +}; - if (hasInitialization && hasSegments) { - eventBus.trigger(_coreEventsEvents2['default'].REPRESENTATION_UPDATED, { sender: this, representation: representation }); - } - } +},{}],11:[function(_dereq_,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; - function getIndexForSegments(time, representation, timeThreshold) { - var segments = representation.segments; - var ln = segments ? segments.length : null; +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - var idx = -1; - var epsilon, frag, ft, fd, i; +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - if (segments && ln > 0) { - for (i = 0; i < ln; i++) { - frag = segments[i]; - ft = frag.presentationStartTime; - fd = frag.duration; - epsilon = timeThreshold === undefined || timeThreshold === null ? fd / 2 : timeThreshold; - if (time + epsilon >= ft && time - epsilon < ft + fd) { - idx = frag.availabilityIdx; - break; - } - } - } +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - return idx; - } +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - function getRequestForSegment(segment) { - if (segment === null || segment === undefined) { - return null; - } +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - var request = new _streamingVoFragmentRequest2['default'](); - var representation = segment.representation; - var bandwidth = representation.adaptation.period.mpd.manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index].Representation_asArray[representation.index].bandwidth; - var url = segment.media; +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; - url = (0, _utilsSegmentsUtils.replaceTokenForTemplate)(url, 'Number', segment.replacementNumber); - url = (0, _utilsSegmentsUtils.replaceTokenForTemplate)(url, 'Time', segment.replacementTime); - url = (0, _utilsSegmentsUtils.replaceTokenForTemplate)(url, 'Bandwidth', bandwidth); - url = replaceIDForTemplate(url, representation.id); - url = unescapeDollarsInTemplate(url); +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; - request.mediaType = type; - request.type = _streamingVoMetricsHTTPRequest.HTTPRequest.MEDIA_SEGMENT_TYPE; - request.range = segment.mediaRange; - request.startTime = segment.presentationStartTime; - request.duration = segment.duration; - request.timescale = representation.timescale; - request.availabilityStartTime = segment.availabilityStartTime; - request.availabilityEndTime = segment.availabilityEndTime; - request.wallStartTime = segment.wallStartTime; - request.quality = representation.index; - request.index = segment.availabilityIdx; - request.mediaInfo = streamProcessor.getMediaInfo(); - request.adaptationIndex = representation.adaptation.index; +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; - if (setRequestUrl(request, url, representation)) { - return request; - } +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":_dereq_(25)}) + +},{"25":25}],12:[function(_dereq_,module,exports){ +var pSlice = Array.prototype.slice; +var objectKeys = _dereq_(14); +var isArguments = _dereq_(13); + +var deepEqual = module.exports = function (actual, expected, opts) { + if (!opts) opts = {}; + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (actual instanceof Date && expected instanceof Date) { + return actual.getTime() === expected.getTime(); + + // 7.3. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!actual || !expected || typeof actual != 'object' && typeof expected != 'object') { + return opts.strict ? actual === expected : actual == expected; + + // 7.4. For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected, opts); + } +} + +function isUndefinedOrNull(value) { + return value === null || value === undefined; +} + +function isBuffer (x) { + if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false; + if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { + return false; + } + if (x.length > 0 && typeof x[0] !== 'number') return false; + return true; +} + +function objEquiv(a, b, opts) { + var i, key; + if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + //~~~I've managed to break Object.keys through screwy arguments passing. + // Converting to array solves the problem. + if (isArguments(a)) { + if (!isArguments(b)) { + return false; + } + a = pSlice.call(a); + b = pSlice.call(b); + return deepEqual(a, b, opts); + } + if (isBuffer(a)) { + if (!isBuffer(b)) { + return false; } + if (a.length !== b.length) return false; + for (i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; + } + try { + var ka = objectKeys(a), + kb = objectKeys(b); + } catch (e) {//happens when one is a string literal and the other isn't + return false; + } + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key], opts)) return false; + } + return typeof a === typeof b; +} - function getSegmentRequestForTime(representation, time, options) { - var request, segment, finished; +},{"13":13,"14":14}],13:[function(_dereq_,module,exports){ +var supportsArgumentsClass = (function(){ + return Object.prototype.toString.call(arguments) +})() == '[object Arguments]'; - var idx = index; +exports = module.exports = supportsArgumentsClass ? supported : unsupported; - var keepIdx = options ? options.keepIdx : false; - var timeThreshold = options ? options.timeThreshold : null; - var ignoreIsFinished = options && options.ignoreIsFinished ? true : false; +exports.supported = supported; +function supported(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +}; - if (!representation) { - return null; - } +exports.unsupported = unsupported; +function unsupported(object){ + return object && + typeof object == 'object' && + typeof object.length == 'number' && + Object.prototype.hasOwnProperty.call(object, 'callee') && + !Object.prototype.propertyIsEnumerable.call(object, 'callee') || + false; +}; - if (requestedTime !== time) { - // When playing at live edge with 0 delay we may loop back with same time and index until it is available. Reduces verboseness of logs. - requestedTime = time; - log('Getting the request for ' + type + ' time : ' + time); - } +},{}],14:[function(_dereq_,module,exports){ +exports = module.exports = typeof Object.keys === 'function' + ? Object.keys : shim; - index = getIndexForSegments(time, representation, timeThreshold); - //Index may be -1 if getSegments needs to update. So after getSegments is called and updated then try to get index again. - updateSegments(representation); - if (index < 0) { - index = getIndexForSegments(time, representation, timeThreshold); - } +exports.shim = shim; +function shim (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} - if (index > 0) { - log('Index for ' + type + ' time ' + time + ' is ' + index); - } +},{}],15:[function(_dereq_,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; - finished = !ignoreIsFinished ? isMediaFinished(representation) : false; - if (finished) { - request = new _streamingVoFragmentRequest2['default'](); - request.action = _streamingVoFragmentRequest2['default'].ACTION_COMPLETE; - request.index = index; - request.mediaType = type; - request.mediaInfo = streamProcessor.getMediaInfo(); - log('Signal complete.', request); - } else { - segment = (0, _utilsSegmentsUtils.getSegmentByIndex)(index, representation); - request = getRequestForSegment(segment); - } +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - if (keepIdx && idx >= 0) { - index = representation.segmentInfoType === 'SegmentTimeline' && isDynamic ? index : idx; - } +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - return request; - } +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; - function generateSegmentRequestForTime(representation, time) { - var step = (representation.segmentAvailabilityRange.end - representation.segmentAvailabilityRange.start) / 2; +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; - representation.segments = null; - representation.segmentAvailabilityRange = { start: time - step, end: time + step }; - return getSegmentRequestForTime(representation, time, { keepIdx: false, ignoreIsFinished: true }); +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); } + } - function getNextSegmentRequest(representation) { - var request, segment, finished; + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + handler.apply(this, args); + } + } else if (isObject(handler)) { + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } - if (!representation || index === -1) { - return null; - } + return true; +}; - requestedTime = null; - index++; +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + var m; + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } - log('Getting the next request at index: ' + index); + return this; +}; - finished = isMediaFinished(representation); - if (finished) { - request = new _streamingVoFragmentRequest2['default'](); - request.action = _streamingVoFragmentRequest2['default'].ACTION_COMPLETE; - request.index = index; - request.mediaType = type; - request.mediaInfo = streamProcessor.getMediaInfo(); - log('Signal complete.'); - } else { - updateSegments(representation); - segment = (0, _utilsSegmentsUtils.getSegmentByIndex)(index, representation); - request = getRequestForSegment(segment); - if (!segment && isDynamic) { - /* - Sometimes when playing dynamic streams with 0 fragment delay at live edge we ask for - an index before it is available so we decrement index back and send null request - which triggers the validate loop to rerun and the next time the segment should be - available. - */ - index--; - } - } +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - return request; - } +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - function onInitializationLoaded(e) { - var representation = e.representation; - //log("Got an initialization."); - if (!representation.segments) return; + var fired = false; - eventBus.trigger(_coreEventsEvents2['default'].REPRESENTATION_UPDATED, { sender: this, representation: representation }); + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); } + } - function onSegmentsLoaded(e) { - if (e.error || type !== e.mediaType) return; + g.listener = listener; + this.on(type, g); - var fragments = e.segments; - var representation = e.representation; - var segments = []; - var count = 0; + return this; +}; - var i, len, s, seg; +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; - for (i = 0, len = fragments.length; i < len; i++) { - s = fragments[i]; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - seg = (0, _utilsSegmentsUtils.getTimeBasedSegment)(timelineConverter, isDynamic, representation, s.startTime, s.duration, s.timescale, s.media, s.mediaRange, count); + if (!this._events || !this._events[type]) + return this; - segments.push(seg); - seg = null; - count++; - } + list = this._events[type]; + length = list.length; + position = -1; - representation.segmentAvailabilityRange = { start: segments[0].presentationStartTime, end: segments[len - 1].presentationStartTime }; - representation.availableSegmentsNumber = len; + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); - onSegmentListUpdated(representation, segments); + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } - if (!representation.initialization) return; + if (position < 0) + return this; - eventBus.trigger(_coreEventsEvents2['default'].REPRESENTATION_UPDATED, { sender: this, representation: representation }); + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); } - instance = { - initialize: initialize, - getStreamProcessor: getStreamProcessor, - getInitRequest: getInitRequest, - getSegmentRequestForTime: getSegmentRequestForTime, - getNextSegmentRequest: getNextSegmentRequest, - generateSegmentRequestForTime: generateSegmentRequestForTime, - updateRepresentation: updateRepresentation, - setCurrentTime: setCurrentTime, - getCurrentTime: getCurrentTime, - getCurrentIndex: getCurrentIndex, - getEarliestTime: getEarliestTime, - reset: reset - }; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } - setup(); + return this; +}; - return instance; -} +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; -DashHandler.__dashjs_factory_name = 'DashHandler'; -var factory = _coreFactoryMaker2['default'].getClassFactory(DashHandler); -factory.SEGMENTS_UNAVAILABLE_ERROR_CODE = SEGMENTS_UNAVAILABLE_ERROR_CODE; -exports['default'] = factory; -module.exports = exports['default']; + if (!this._events) + return this; -},{"10":10,"13":13,"158":158,"162":162,"163":163,"179":179,"34":34,"35":35,"8":8,"9":9}],17:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -'use strict'; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } -Object.defineProperty(exports, '__esModule', { - value: true -}); + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } + listeners = this._events[type]; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; -var _streamingVoMetricsHTTPRequest = _dereq_(179); + return this; +}; -var _streamingModelsManifestModel = _dereq_(100); +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; -var _streamingModelsManifestModel2 = _interopRequireDefault(_streamingModelsManifestModel); +EventEmitter.listenerCount = function(emitter, type) { + var ret; + if (!emitter._events || !emitter._events[type]) + ret = 0; + else if (isFunction(emitter._events[type])) + ret = 1; + else + ret = emitter._events[type].length; + return ret; +}; -var _modelsDashManifestModel = _dereq_(22); +function isFunction(arg) { + return typeof arg === 'function'; +} -var _modelsDashManifestModel2 = _interopRequireDefault(_modelsDashManifestModel); +function isNumber(arg) { + return typeof arg === 'number'; +} -var _coreFactoryMaker = _dereq_(10); +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} -var _coreFactoryMaker2 = _interopRequireDefault(_coreFactoryMaker); +function isUndefined(arg) { + return arg === void 0; +} -var _constantsDashMetricsList = _dereq_(20); +},{}],16:[function(_dereq_,module,exports){ +exports.read = function (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) {} + + 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) +} -var MetricsList = _interopRequireWildcard(_constantsDashMetricsList); +exports.write = function (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 { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } -var _round10 = _dereq_(7); + 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 + } + } -/** - * @module DashMetrics - */ -function DashMetrics() { + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - var instance = undefined; - var context = this.context; - var manifestModel = (0, _streamingModelsManifestModel2['default'])(context).getInstance(); //TODO Need to pass this in not bake in + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - function getBandwidthForRepresentation(representationId, periodId) { - var representation; - var manifest = manifestModel.getValue(); - var period = manifest.Period_asArray[periodId]; + buffer[offset + i - d] |= s * 128 +} - representation = findRepresentation(period, representationId); +},{}],17:[function(_dereq_,module,exports){ +/* + * Copyright (c) 2016, Pierre-Anthony Lemieux + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ - if (representation === null) { - return null; - } +/** + * @module imscDoc + */ + +; +(function (imscDoc, sax, imscNames, imscStyles, imscUtils) { - return representation.bandwidth; - } /** - * - * @param {string} representationId - * @param {number} periodIdx - * @returns {*} + * Allows a client to provide callbacks to handle children of the element + * @typedef {Object} MetadataHandler + * @property {?OpenTagCallBack} onOpenTag + * @property {?CloseTagCallBack} onCloseTag + * @property {?TextCallBack} onText */ - function getIndexForRepresentation(representationId, periodIdx) { - var representationIndex; - var manifest = manifestModel.getValue(); - var period = manifest.Period_asArray[periodIdx]; - - representationIndex = findRepresentationIndex(period, representationId); - return representationIndex; - } /** - * This method returns the current max index based on what is defined in the MPD. - * - * @param {string} bufferType - String 'audio' or 'video', - * @param {number} periodIdx - Make sure this is the period index not id - * @return {number} - * @memberof module:DashMetrics - * @instance + * Called when the opening tag of an element node is encountered. + * @callback OpenTagCallBack + * @param {string} ns Namespace URI of the element + * @param {string} name Local name of the element + * @param {Object[]} attributes List of attributes, each consisting of a + * `uri`, `name` and `value` */ - function getMaxIndexForBufferType(bufferType, periodIdx) { - var maxIndex; - var manifest = manifestModel.getValue(); - var period = manifest.Period_asArray[periodIdx]; - - maxIndex = findMaxBufferIndex(period, bufferType); - return maxIndex; - } /** - * @param {MetricsList} metrics - * @returns {*} - * @memberof module:DashMetrics - * @instance + * Called when the closing tag of an element node is encountered. + * @callback CloseTagCallBack */ - function getCurrentRepresentationSwitch(metrics) { - return getCurrent(metrics, MetricsList.TRACK_SWITCH); - } /** - * @param {MetricsList} metrics - * @returns {*} - * @memberof module:DashMetrics - * @instance + * Called when a text node is encountered. + * @callback TextCallBack + * @param {string} contents Contents of the text node */ - function getLatestBufferLevelVO(metrics) { - return getCurrent(metrics, MetricsList.BUFFER_LEVEL); - } /** - * @param {MetricsList} metrics - * @returns {number} - * @memberof module:DashMetrics - * @instance + * Parses an IMSC1 document into an opaque in-memory representation that exposes + * a single method
getMediaTimeEvents()
that returns a list of time + * offsets (in seconds) of the ISD, i.e. the points in time where the visual + * representation of the document change. `metadataHandler` allows the caller to + * be called back when nodes are present in elements. + * + * @param {string} xmlstring XML document + * @param {?module:imscUtils.ErrorHandler} errorHandler Error callback + * @param {?MetadataHandler} metadataHandler Callback for elements + * @returns {Object} Opaque in-memory representation of an IMSC1 document */ - function getCurrentBufferLevel(metrics) { - var vo = getLatestBufferLevelVO(metrics); - if (vo) { - return (0, _round10.round10)(vo.level / 1000, -3); - } + imscDoc.fromXML = function (xmlstring, errorHandler, metadataHandler) { + var p = sax.parser(true, {xmlns: true}); + var estack = []; + var xmllangstack = []; + var xmlspacestack = []; + var metadata_depth = 0; + var doc = null; - return 0; - } + p.onclosetag = function (node) { - /** - * @param {MetricsList} metrics - * @returns {null|*|vo} - * @memberof module:DashMetrics - * @instance - */ - function getRequestsQueue(metrics) { - return metrics.RequestsQueue; - } + if (estack[0] instanceof Styling) { - /** - * @param {MetricsList} metrics - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getCurrentHttpRequest(metrics) { - if (metrics === null) { - return null; - } + /* flatten chained referential styling */ - var httpList = metrics.HttpList; - var currentHttpList = null; + for (var sid in estack[0].styles) { - var httpListLength, httpListLastIndex; + mergeChainedStyles(estack[0], estack[0].styles[sid], errorHandler); - if (httpList === null || httpList.length <= 0) { - return null; - } + } - httpListLength = httpList.length; - httpListLastIndex = httpListLength - 1; + } else if (estack[0] instanceof P || estack[0] instanceof Span) { - while (httpListLastIndex >= 0) { - if (httpList[httpListLastIndex].responsecode) { - currentHttpList = httpList[httpListLastIndex]; - break; - } - httpListLastIndex--; - } - return currentHttpList; - } + /* merge anonymous spans */ - /** - * @param {MetricsList} metrics - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getHttpRequests(metrics) { - if (metrics === null) { - return []; - } + if (estack[0].contents.length > 1) { - return !!metrics.HttpList ? metrics.HttpList : []; - } + var cs = [estack[0].contents[0]]; - /** - * @param {MetricsList} metrics - * @param {string} metricName - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getCurrent(metrics, metricName) { - if (metrics === null) { - return null; - } + var c; - var list = metrics[metricName]; + for (c = 1; c < estack[0].contents.length; c++) { - if (list === null) { - return null; - } + if (estack[0].contents[c] instanceof AnonymousSpan && + cs[cs.length - 1] instanceof AnonymousSpan) { - var length = list.length; + cs[cs.length - 1].text += estack[0].contents[c].text; - if (length <= 0) { - return null; - } + } else { - return list[length - 1]; - } + cs.push(estack[0].contents[c]); - /** - * @param {MetricsList} metrics - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getCurrentDroppedFrames(metrics) { - return getCurrent(metrics, MetricsList.DROPPED_FRAMES); - } + } - /** - * @param {MetricsList} metrics - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getCurrentSchedulingInfo(metrics) { - return getCurrent(metrics, MetricsList.SCHEDULING_INFO); - } + } - /** - * @param {MetricsList} metrics - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getCurrentManifestUpdate(metrics) { - return getCurrent(metrics, MetricsList.MANIFEST_UPDATE); - } + estack[0].contents = cs; - /** - * @param {MetricsList} metrics - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getCurrentDVRInfo(metrics) { - return getCurrent(metrics, MetricsList.DVR_INFO); - } + } - /** - * @param {MetricsList} metrics - * @param {string} id - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getLatestMPDRequestHeaderValueByID(metrics, id) { - var headers = {}; - var httpRequestList, httpRequest, i; + // remove redundant nested anonymous spans (9.3.3(1)(c)) - if (metrics === null) { - return null; - } + if (estack[0] instanceof Span && + estack[0].contents.length === 1 && + estack[0].contents[0] instanceof AnonymousSpan && + estack[0].text === null) { - httpRequestList = getHttpRequests(metrics); + estack[0].text = estack[0].contents[0].text; + delete estack[0].contents; - for (i = httpRequestList.length - 1; i >= 0; i--) { - httpRequest = httpRequestList[i]; + } - if (httpRequest.type === _streamingVoMetricsHTTPRequest.HTTPRequest.MPD_TYPE) { - headers = parseResponseHeaders(httpRequest._responseHeaders); - break; - } - } + } else if (estack[0] instanceof ForeignElement) { - return headers[id] === undefined ? null : headers[id]; - } + if (estack[0].node.uri === imscNames.ns_tt && + estack[0].node.local === 'metadata') { - /** - * @param {MetricsList} metrics - * @param {string} id - * @returns {*} - * @memberof module:DashMetrics - * @instance - */ - function getLatestFragmentRequestHeaderValueByID(metrics, id) { + /* leave the metadata element */ - if (metrics === null) return null; + metadata_depth--; - var httpRequest = getCurrentHttpRequest(metrics); - var headers; + } else if (metadata_depth > 0 && + metadataHandler && + 'onCloseTag' in metadataHandler) { - if (httpRequest === null || httpRequest._responseHeaders === null) return null; + /* end of child of metadata element */ - headers = parseResponseHeaders(httpRequest._responseHeaders); - return headers[id] === undefined ? null : headers[id]; - } + metadataHandler.onCloseTag(); + + } - function parseResponseHeaders(headerStr) { - var headers = {}; - if (!headerStr) { - return headers; - } - var headerPairs = headerStr.split('\r\n'); - for (var i = 0, ilen = headerPairs.length; i < ilen; i++) { - var headerPair = headerPairs[i]; - var index = headerPair.indexOf(': '); - if (index > 0) { - headers[headerPair.substring(0, index)] = headerPair.substring(index + 2); } - } - return headers; - } - function findRepresentationIndex(period, representationId) { - var index = findRepresentation(period, representationId, true); + // TODO: delete stylerefs? - if (index !== null) { - return index; - } + // maintain the xml:space stack - return -1; - } + xmlspacestack.shift(); - function findRepresentation(period, representationId, returnIndex) { - var adaptationSet, adaptationSetArray, representation, representationArray, adaptationSetArrayIndex, representationArrayIndex; + // maintain the xml:lang stack - adaptationSetArray = period.AdaptationSet_asArray; - for (adaptationSetArrayIndex = 0; adaptationSetArrayIndex < adaptationSetArray.length; adaptationSetArrayIndex = adaptationSetArrayIndex + 1) { - adaptationSet = adaptationSetArray[adaptationSetArrayIndex]; - representationArray = adaptationSet.Representation_asArray; - for (representationArrayIndex = 0; representationArrayIndex < representationArray.length; representationArrayIndex = representationArrayIndex + 1) { - representation = representationArray[representationArrayIndex]; - if (representationId === representation.id) { - if (returnIndex) { - return representationArrayIndex; - } else { - return representation; - } - } - } - } + xmllangstack.shift(); - return null; - } + // prepare for the next element - function adaptationIsType(adaptation, bufferType) { - return (0, _modelsDashManifestModel2['default'])(context).getInstance().getIsTypeOf(adaptation, bufferType); - } + estack.shift(); + }; - function findMaxBufferIndex(period, bufferType) { - var adaptationSet, adaptationSetArray, representationArray, adaptationSetArrayIndex; + p.ontext = function (str) { - if (!period || !bufferType) return -1; + if (estack[0] === undefined) { - adaptationSetArray = period.AdaptationSet_asArray; - for (adaptationSetArrayIndex = 0; adaptationSetArrayIndex < adaptationSetArray.length; adaptationSetArrayIndex = adaptationSetArrayIndex + 1) { - adaptationSet = adaptationSetArray[adaptationSetArrayIndex]; - representationArray = adaptationSet.Representation_asArray; - if (adaptationIsType(adaptationSet, bufferType)) { - return representationArray.length; - } - } + /* ignoring text outside of elements */ - return -1; - } + } else if (estack[0] instanceof Span || estack[0] instanceof P) { - instance = { - getBandwidthForRepresentation: getBandwidthForRepresentation, - getIndexForRepresentation: getIndexForRepresentation, - getMaxIndexForBufferType: getMaxIndexForBufferType, - getCurrentRepresentationSwitch: getCurrentRepresentationSwitch, - getLatestBufferLevelVO: getLatestBufferLevelVO, - getCurrentBufferLevel: getCurrentBufferLevel, - getCurrentHttpRequest: getCurrentHttpRequest, - getHttpRequests: getHttpRequests, - getCurrentDroppedFrames: getCurrentDroppedFrames, - getCurrentSchedulingInfo: getCurrentSchedulingInfo, - getCurrentDVRInfo: getCurrentDVRInfo, - getCurrentManifestUpdate: getCurrentManifestUpdate, - getLatestFragmentRequestHeaderValueByID: getLatestFragmentRequestHeaderValueByID, - getLatestMPDRequestHeaderValueByID: getLatestMPDRequestHeaderValueByID, - getRequestsQueue: getRequestsQueue - }; + /* create an anonymous span */ + + var s = new AnonymousSpan(); + + s.initFromText(doc, estack[0], str, xmlspacestack[0], errorHandler); - return instance; -} + estack[0].contents.push(s); -DashMetrics.__dashjs_factory_name = 'DashMetrics'; -exports['default'] = _coreFactoryMaker2['default'].getSingletonFactory(DashMetrics); -module.exports = exports['default']; + } else if (estack[0] instanceof ForeignElement && + metadata_depth > 0 && + metadataHandler && + 'onText' in metadataHandler) { -},{"10":10,"100":100,"179":179,"20":20,"22":22,"7":7}],18:[function(_dereq_,module,exports){ -/** - * The copyright in this software is being made available under the BSD License, - * included below. This software may be subject to other third party and contributor - * rights, including patent rights, and no such rights are granted under this license. - * - * Copyright (c) 2013, Dash Industry Forum. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation and/or - * other materials provided with the distribution. - * * Neither the name of Dash Industry Forum nor the names of its - * contributors may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -'use strict'; + /* text node within a child of metadata element */ -Object.defineProperty(exports, '__esModule', { - value: true -}); + metadataHandler.onText(str); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + } -var _streamingUtilsRequestModifier = _dereq_(156); + }; -var _streamingUtilsRequestModifier2 = _interopRequireDefault(_streamingUtilsRequestModifier); -var _voSegment = _dereq_(46); + p.onopentag = function (node) { -var _voSegment2 = _interopRequireDefault(_voSegment); + // maintain the xml:space stack -var _streamingVoError = _dereq_(162); + var xmlspace = node.attributes["xml:space"]; -var _streamingVoError2 = _interopRequireDefault(_streamingVoError); + if (xmlspace) { -var _streamingUtilsErrorHandler = _dereq_(151); + xmlspacestack.unshift(xmlspace.value); -var _streamingUtilsErrorHandler2 = _interopRequireDefault(_streamingUtilsErrorHandler); + } else { -var _coreEventsEvents = _dereq_(13); + if (xmlspacestack.length === 0) { -var _coreEventsEvents2 = _interopRequireDefault(_coreEventsEvents); + xmlspacestack.unshift("default"); -var _coreEventBus = _dereq_(9); + } else { -var _coreEventBus2 = _interopRequireDefault(_coreEventBus); + xmlspacestack.unshift(xmlspacestack[0]); -var _streamingUtilsBoxParser = _dereq_(146); + } -var _streamingUtilsBoxParser2 = _interopRequireDefault(_streamingUtilsBoxParser); + } -var _coreFactoryMaker = _dereq_(10); + /* maintain the xml:lang stack */ -var _coreFactoryMaker2 = _interopRequireDefault(_coreFactoryMaker); -var _coreDebug = _dereq_(8); + var xmllang = node.attributes["xml:lang"]; -var _coreDebug2 = _interopRequireDefault(_coreDebug); + if (xmllang) { -function SegmentBaseLoader() { + xmllangstack.unshift(xmllang.value); - var context = this.context; - var log = (0, _coreDebug2['default'])(context).getInstance().log; - var eventBus = (0, _coreEventBus2['default'])(context).getInstance(); + } else { - var instance = undefined, - errHandler = undefined, - boxParser = undefined, - requestModifier = undefined, - baseURLController = undefined; + if (xmllangstack.length === 0) { - function initialize() { - errHandler = (0, _streamingUtilsErrorHandler2['default'])(context).getInstance(); - boxParser = (0, _streamingUtilsBoxParser2['default'])(context).getInstance(); - requestModifier = (0, _streamingUtilsRequestModifier2['default'])(context).getInstance(); - } + xmllangstack.unshift(""); - function setConfig(config) { - if (config.baseURLController) { - baseURLController = config.baseURLController; - } - } + } else { - function loadInitialization(representation, loadingInfo) { - var needFailureReport = true; - var initRange = null; - var isoFile = null; - var request = new XMLHttpRequest(); - var baseUrl = baseURLController.resolve(representation.path); - var info = loadingInfo || { - url: baseUrl ? baseUrl.url : undefined, - range: { - start: 0, - end: 1500 - }, - searching: false, - bytesLoaded: 0, - bytesToLoad: 1500, - request: request - }; + xmllangstack.unshift(xmllangstack[0]); - log('Start searching for initialization.'); + } - request.onload = function () { - if (request.status < 200 || request.status > 299) return; + } - needFailureReport = false; - info.bytesLoaded = info.range.end; - isoFile = boxParser.parse(request.response); - initRange = findInitRange(isoFile); + /* process the element */ - if (initRange) { - representation.range = initRange; - representation.initialization = info.url; - eventBus.trigger(_coreEventsEvents2['default'].INITIALIZATION_LOADED, { representation: representation }); - } else { - info.range.end = info.bytesLoaded + info.bytesToLoad; - loadInitialization(representation, info); - } - }; + if (node.uri === imscNames.ns_tt) { - request.onloadend = request.onerror = function () { - if (!needFailureReport) return; - needFailureReport = false; + if (node.local === 'tt') { - errHandler.downloadError('initialization', info.url, request); - eventBus.trigger(_coreEventsEvents2['default'].INITIALIZATION_LOADED, { representation: representation }); - }; + if (doc !== null) { - sendRequest(request, info); - log('Perform init search: ' + info.url); - } + reportFatal("Two elements at (" + this.line + "," + this.column + ")"); - function loadSegments(representation, type, range, loadingInfo, callback) { - if (range && (range.start === undefined || range.end === undefined)) { - var parts = range ? range.toString().split('-') : null; - range = parts ? { start: parseFloat(parts[0]), end: parseFloat(parts[1]) } : null; - } + } - callback = !callback ? onLoaded : callback; - var needFailureReport = true; - var isoFile = null; - var sidx = null; - var hasRange = !!range; - var request = new XMLHttpRequest(); - var baseUrl = baseURLController.resolve(representation.path); - var info = { - url: baseUrl ? baseUrl.url : undefined, - range: hasRange ? range : { start: 0, end: 1500 }, - searching: !hasRange, - bytesLoaded: loadingInfo ? loadingInfo.bytesLoaded : 0, - bytesToLoad: 1500, - request: request - }; + doc = new TT(); - request.onload = function () { - if (request.status < 200 || request.status > 299) return; + doc.initFromNode(node, errorHandler); - var extraBytes = info.bytesToLoad; - var loadedLength = request.response.byteLength; + estack.unshift(doc); - needFailureReport = false; - info.bytesLoaded = info.range.end - info.range.start; - isoFile = boxParser.parse(request.response); - sidx = isoFile.getBox('sidx'); + } else if (node.local === 'head') { - if (!sidx || !sidx.isComplete) { - if (sidx) { - info.range.start = sidx.offset || info.range.start; - info.range.end = info.range.start + (sidx.size || extraBytes); - } else if (loadedLength < info.bytesLoaded) { - // if we have reached a search limit or if we have reached the end of the file we have to stop trying to find sidx - callback(null, representation, type); - return; - } else { - var lastBox = isoFile.getLastBox(); + if (!(estack[0] instanceof TT)) { + reportFatal("Parent of element is not at (" + this.line + "," + this.column + ")"); + } - if (lastBox && lastBox.size) { - info.range.start = lastBox.offset + lastBox.size; - info.range.end = info.range.start + extraBytes; - } else { - info.range.end += extraBytes; + if (doc.head !== null) { + reportFatal("Second element at (" + this.line + "," + this.column + ")"); } - } - loadSegments(representation, type, info.range, info, callback); - } else { - var ref = sidx.references; - var loadMultiSidx, segments; - if (ref !== null && ref !== undefined && ref.length > 0) { - loadMultiSidx = ref[0].reference_type === 1; - } + doc.head = new Head(); - if (loadMultiSidx) { - log('Initiate multiple SIDX load.'); - info.range.end = info.range.start + sidx.size; - - var j, len, ss, se, r; - var segs = []; - var count = 0; - var offset = (sidx.offset || info.range.start) + sidx.size; - var tmpCallback = function tmpCallback(result) { - if (result) { - segs = segs.concat(result); - count++; - - if (count >= len) { - callback(segs, representation, type); - } - } else { - callback(null, representation, type); - } - }; - - for (j = 0, len = ref.length; j < len; j++) { - ss = offset; - se = offset + ref[j].referenced_size - 1; - offset = offset + ref[j].referenced_size; - r = { start: ss, end: se }; - loadSegments(representation, null, r, info, tmpCallback); - } - } else { - log('Parsing segments from SIDX.'); - segments = getSegmentsForSidx(sidx, info); - callback(segments, representation, type); - } - } - }; + estack.unshift(doc.head); - request.onloadend = request.onerror = function () { - if (!needFailureReport) return; + } else if (node.local === 'styling') { - needFailureReport = false; - errHandler.downloadError('SIDX', info.url, request); - callback(null, representation, type); - }; + if (!(estack[0] instanceof Head)) { + reportFatal("Parent of element is not at (" + this.line + "," + this.column + ")"); + } - sendRequest(request, info); - log('Perform SIDX load: ' + info.url); - } + if (doc.head.styling !== null) { + reportFatal("Second element at (" + this.line + "," + this.column + ")"); + } - function reset() { - errHandler = null; - boxParser = null; - requestModifier = null; - log = null; - } + doc.head.styling = new Styling(); - function getSegmentsForSidx(sidx, info) { + estack.unshift(doc.head.styling); - var refs = sidx.references; - var len = refs.length; - var timescale = sidx.timescale; - var time = sidx.earliest_presentation_time; - var start = info.range.start + sidx.offset + sidx.first_offset + sidx.size; - var segments = []; - var segment, end, duration, size; + } else if (node.local === 'style') { - for (var i = 0; i < len; i++) { - duration = refs[i].subsegment_duration; - size = refs[i].referenced_size; + var s; - segment = new _voSegment2['default'](); - segment.duration = duration; - segment.media = info.url; - segment.startTime = time; - segment.timescale = timescale; - end = start + size - 1; - segment.mediaRange = start + '-' + end; - segments.push(segment); - time += duration; - start += size; - } + if (estack[0] instanceof Styling) { - return segments; - } + s = new Style(); - function findInitRange(isoFile) { - var ftyp = isoFile.getBox('ftyp'); - var moov = isoFile.getBox('moov'); + s.initFromNode(node, errorHandler); - var initRange = null; - var start, end; + /* ignore